How to add calendar events in Android?
how do I programmatically add an event to the user's calendar?
Which calendar?
Is there a common API they all share?
No, no more than there is a "common API they all share" for Windows calendar apps. There are some common data formats (e.g., iCalendar) and Internet protocols (e.g., CalDAV), but no common API. Some calendar apps don't even offer an API.
If there are specific calendar applications you wish to integrate with, contact their developers and determine if they offer an API. So, for example, the Calendar application from the Android open source project, that Mayra cites, offers no documented and supported APIs. Google has even explicitly told developers to not use the techniques outlined in the tutorial Mayra cites.
Another option is for you to add events to the Internet calendar in question. For example, the best way to add events to the Calendar application from the Android open source project is to add the event to the user's Google Calendar via the appropriate GData APIs.
UPDATE
Android 4.0 (API Level 14) added a CalendarContract
ContentProvider
.
Case insensitive comparison NSString
Alternate solution for swift:
To make both UpperCase:
e.g:
if ("ABcd".uppercased() == "abcD".uppercased()){
}
or to make both LowerCase:
e.g:
if ("ABcd".lowercased() == "abcD".lowercased()){
}
SQL Server: the maximum number of rows in table
Largest table I've encountered on SQL Server 8 on Windows2003 was 799 million with 5 columns. But whether or not it's good will is to be measured against the SLA and usage case - e.g. load 50-100,000,000 records and see if it still works.
JQuery html() vs. innerHTML
To answer your question:
.html()
will just call .innerHTML
after doing some checks for nodeTypes and stuff. It also uses a try/catch
block where it tries to use innerHTML
first and if that fails, it'll fallback gracefully to jQuery's .empty()
+ append()
Twitter bootstrap progress bar animation on page load
While Tats_innit's answer has a nice touch to it, I had to do it a bit differently since I have more than one progress bar on the page.
here's my solution:
JSfiddle: http://jsfiddle.net/vacNJ/
HTML (example):
<div class="progress progress-success">
<div class="bar" style="float: left; width: 0%; " data-percentage="60"></div>
</div>
<div class="progress progress-success">
<div class="bar" style="float: left; width: 0%; " data-percentage="50"></div>
</div>
<div class="progress progress-success">
<div class="bar" style="float: left; width: 0%; " data-percentage="40"></div>
</div>
?
JavaScript:
setTimeout(function(){
$('.progress .bar').each(function() {
var me = $(this);
var perc = me.attr("data-percentage");
var current_perc = 0;
var progress = setInterval(function() {
if (current_perc>=perc) {
clearInterval(progress);
} else {
current_perc +=1;
me.css('width', (current_perc)+'%');
}
me.text((current_perc)+'%');
}, 50);
});
},300);
@Tats_innit: Using setInterval() to dynamically recalc the progress is a nice solution, thx mate! ;)
EDIT:
A friend of mine wrote a nice jquery plugin for custom twitter bootstrap progress bars.
Here's a demo:
http://minddust.github.com/bootstrap-progressbar/
Here's the Github repo:
https://github.com/minddust/bootstrap-progressbar
What's the difference between using CGFloat and float?
As @weichsel stated, CGFloat is just a typedef for either float
or double
. You can see for yourself by Command-double-clicking on "CGFloat" in Xcode — it will jump to the CGBase.h header where the typedef is defined. The same approach is used for NSInteger and NSUInteger as well.
These types were introduced to make it easier to write code that works on both 32-bit and 64-bit without modification. However, if all you need is float
precision within your own code, you can still use float
if you like — it will reduce your memory footprint somewhat. Same goes for integer values.
I suggest you invest the modest time required to make your app 64-bit clean and try running it as such, since most Macs now have 64-bit CPUs and Snow Leopard is fully 64-bit, including the kernel and user applications. Apple's 64-bit Transition Guide for Cocoa is a useful resource.
How to add external library in IntelliJ IDEA?
I've used this process to attach a 3rd party Jar to an Android project in IDEA.
- Copy the Jar to your libs/ directory
- Open Project Settings (Ctrl Alt Shift S)
- Under the Project Settings panel on the left, choose Modules
- On the larger right pane, choose the Dependencies tab
- Press the Add... button on the far right of the screen (if you have a smaller
screen like me, you may have to drag resize to the right in order to
see it)
- From the dropdown of Add options, choose "Library". A "Choose
Libraries" dialog will appear.
- Press "New Library..."
- Choose a suitable title for the library
- Press "Attach Classes..."
- Choose the Jar from your libs/ directory, and press OK to dismiss
The library should now be recognised.
Is there a way to crack the password on an Excel VBA Project?
Tom - I made a schoolboy error initially as I didn't watch the byte size and instead I copied and pasted from the "CMG" set up to the subsequent entry. This was two different text sizes between the two files, though, and I lost the VBA project just as Stewbob warned.
Using HxD, there is a counter tracking how much file you're selecting. Copy starting from CMG until the counter reads 8F (hex for 143) and likewise when pasting into the locked file - I ended up with twice the number of "..." at the end of the paste, which looked odd somehow and felt almost unnatural, but it worked.
I don't know if it is crucial, but I made sure I shut both the hex editor and excel down before reopening the file in Excel. I then had to go through the menus to open the VB Editor, into VBProject Properties and entered in the 'new' password to unlock the code.
I hope this helps.
How do you access the element HTML from within an Angular attribute directive?
So actually, my comment that you should do a console.log(el.nativeElement)
should have pointed you in the right direction, but I didn't expect the output to be just a string representing the DOM Element
.
What you have to do to inspect it in the way it helps you with your problem, is to do a console.log(el)
in your example, then you'll have access to the nativeElement
object and will see a property called innerHTML
.
Which will lead to the answer to your original question:
let myCurrentContent:string = el.nativeElement.innerHTML; // get the content of your element
el.nativeElement.innerHTML = 'my new content'; // set content of your element
Update for better approach:
Since it's the accepted answer and web workers are getting more important day to day (and it's considered best practice anyway) I want to add this suggestion by Mark Rajcok here.
The best way to manipulate DOM Elements
programmatically is using the Renderer:
constructor(private _elemRef: ElementRef, private _renderer: Renderer) {
this._renderer.setElementProperty(this._elemRef.nativeElement, 'innerHTML', 'my new content');
}
Edit
Since Renderer
is deprecated now, use Renderer2 instead with setProperty
Update:
This question with its answer explained the console.log
behavior.
Which means that console.dir(el.nativeElement)
would be the more direct way of accessing the DOM Element
as an "inspectable" Object in your console for this situation.
Hope this helped.
Create a button with rounded border
For implementing the rounded border button with a border color use this
OutlineButton(
child: new Text("Button Text"),borderSide: BorderSide(color: Colors.blue),
onPressed: null,
shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(20.0))
),
Instagram API: How to get all user media?
Instagram developer console has provided the solution for it. https://www.instagram.com/developer/endpoints/
To use this in PHP, here is the code snippet,
/**
**
** Add this code snippet after your first curl call
** assume the response of the first call is stored in $userdata
** $access_token have your access token
*/
$maximumNumberOfPost = 33; // it can be 20, depends on your instagram application
$no_of_images = 50 // Enter the number of images you want
if ($no_of_images > $maximumNumberOfPost) {
$ImageArray = [];
$next_url = $userdata->pagination->next_url;
while ($no_of_images > $maximumNumberOfPost) {
$originalNumbersOfImage = $no_of_images;
$no_of_images = $no_of_images - $maximumNumberOfPost;
$next_url = str_replace("count=" . $originalNumbersOfImage, "count=" . $no_of_images, $next_url);
$chRepeat = curl_init();
curl_setopt_array($chRepeat, [
CURLOPT_URL => $next_url,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer $access_token"
],
CURLOPT_RETURNTRANSFER => true
]);
$userRepeatdata = curl_exec($chRepeat);
curl_close($chRepeat);
if ($userRepeatdata) {
$userRepeatdata = json_decode($userRepeatdata);
$next_url = $userRepeatdata->pagination->next_url;
if (isset($userRepeatdata->data) && $userRepeatdata->data) {
$ImageArray = $userRepeatdata->data;
}
}
}
}
How to maintain a Unique List in Java?
I do not know how efficient this is, However worked for me in a simple context.
List<int> uniqueNumbers = new ArrayList<>();
public void AddNumberToList(int num)
{
if(!uniqueNumbers .contains(num)) {
uniqueNumbers .add(num);
}
}
Difference between clustered and nonclustered index
A comparison of a non-clustered index with a clustered index with an example
As an example of a non-clustered index, let’s say that we have a non-clustered index on the EmployeeID column. A non-clustered index will store both the value of the
EmployeeID
AND a pointer to the row in the Employee table where that value is actually stored. But a clustered index, on the other hand, will actually store the row data for a particular EmployeeID – so if you are running a query that looks for an EmployeeID of 15, the data from other columns in the table like
EmployeeName, EmployeeAddress, etc
. will all actually be stored in the leaf node of the clustered index itself.
This means that with a non-clustered index extra work is required to follow that pointer to the row in the table to retrieve any other desired values, as opposed to a clustered index which can just access the row directly since it is being stored in the same order as the clustered index itself. So, reading from a clustered index is generally faster than reading from a non-clustered index.
how much memory can be accessed by a 32 bit machine?
No your concepts are not right. And to set it right you need the answer to the question that you incorrectly answered:
What is meant by 32bit or 64 bit machine?
The answer to the question is "something significant in the CPU is 32bit or 64 bit". So the question is what is that something significant? Lot of people say the width of data bus that determine whether the machine is 32bit or 64 bit. But none of the latest 32 bit processors have 32 bit or 64 bit wide data buses. most 32 bit systems will have 36 bit at least to support more RAM. Most 64 bit processors have no more than 48bit wide data bus because that is hell lot of memory already.
So according to me a 32 bit or 64 bit machine is determined by the size of its general purpose registers used in computation or "the natural word size" used by the computer.
Note that a 32 bit OS is a different thing. You can have a 32 bit OS running on 64 bit computer. Additionally, you can have 32 bit application running on 64 bit OS. If you do not understand the difference, post another question.
So the maximum amount of RAM a processor can address is 2^(width of data bus in bits), given that the proper addressing mode is switched on in the processor.
Further note, there is nothing stopping someone to introduce a multiplex between data Bus and memory banks, that will select a bank and then address the RAM (in two steps). This way you can address even more RAM. But that is impractical, and highly inefficient.
Beginner question: returning a boolean value from a function in Python
Ignoring the refactoring issues, you need to understand functions and return values. You don't need a global at all. Ever. You can do this:
def rps():
# Code to determine if player wins
if player_wins:
return True
return False
Then, just assign a value to the variable outside this function like so:
player_wins = rps()
It will be assigned the return value (either True or False) of the function you just called.
After the comments, I decided to add that idiomatically, this would be better expressed thus:
def rps():
# Code to determine if player wins, assigning a boolean value (True or False)
# to the variable player_wins.
return player_wins
pw = rps()
This assigns the boolean value of player_wins
(inside the function) to the pw
variable outside the function.
How can I extract a number from a string in JavaScript?
_x000D_
_x000D_
function justNumbers(string)
{
var numsStr = string.replace(/[^0-9]/g,'');
return parseInt(numsStr);
}
console.log(justNumbers('abcdefg12hijklmnop'));
_x000D_
_x000D_
_x000D_
You can do a function like this
function justNumbers(string)
{
var numsStr = string.replace(/[^0-9]/g,'');
return parseInt(numsStr);
}
remember: if the number has a zero in front of it, the int wont have it
Variables declared outside function
When Python parses a function, it notes when a variable assignment is made. When there is an assignment, it assumes by default that that variable is a local variable. To declare that the assignment refers to a global variable, you must use the global
declaration.
When you access a variable in a function, its value is looked up using the LEGB scoping rules.
So, the first example
x = 1
def inc():
x += 5
inc()
produces an UnboundLocalError
because Python determined x
inside inc
to be a local variable,
while accessing x
works in your second example
def inc():
print x
because here, in accordance with the LEGB rule, Python looks for x
in the local scope, does not find it, then looks for it in the extended scope, still does not find it, and finally looks for it in the global scope successfully.
Node.js global variables
The other solutions that use the GLOBAL keyword are a nightmare to maintain/readability (+namespace pollution and bugs) when the project gets bigger. I've seen this mistake many times and had the hassle of fixing it.
Use a JavaScript file and then use module exports.
Example:
File globals.js
var Globals = {
'domain':'www.MrGlobal.com';
}
module.exports = Globals;
Then if you want to use these, use require.
var globals = require('globals'); // << globals.js path
globals.domain // << Domain.
How to use getJSON, sending data with post method?
I just used post and an if:
data = getDataObjectByForm(form);
var jqxhr = $.post(url, data, function(){}, 'json')
.done(function (response) {
if (response instanceof Object)
var json = response;
else
var json = $.parseJSON(response);
// console.log(response);
// console.log(json);
jsonToDom(json);
if (json.reload != undefined && json.reload)
location.reload();
$("body").delay(1000).css("cursor", "default");
})
.fail(function (jqxhr, textStatus, error) {
var err = textStatus + ", " + error;
console.log("Request Failed: " + err);
alert("Fehler!");
});
Converting datetime.date to UTC timestamp in Python
the question is a little confused. timestamps are not UTC - they're a Unix thing. the date might be UTC? assuming it is, and if you're using Python 3.2+, simple-date makes this trivial:
>>> SimpleDate(date(2011,1,1), tz='utc').timestamp
1293840000.0
if you actually have the year, month and day you don't need to create the date
:
>>> SimpleDate(2011,1,1, tz='utc').timestamp
1293840000.0
and if the date is in some other timezone (this matters because we're assuming midnight without an associated time):
>>> SimpleDate(date(2011,1,1), tz='America/New_York').timestamp
1293858000.0
[the idea behind simple-date is to collect all python's date and time stuff in one consistent class, so you can do any conversion. so, for example, it will also go the other way:
>>> SimpleDate(1293858000, tz='utc').date
datetime.date(2011, 1, 1)
]
Oracle select most recent date record
select *
from (select
staff_id, site_id, pay_level, date,
rank() over (partition by staff_id order by date desc) r
from owner.table
where end_enrollment_date is null
)
where r = 1
List all virtualenv
If you are using virtualenv
or Python 3's built in venv
the above answers might not work.
If you are on Linux, just locate
the activate
script that is always present inside a env.
locate -b '\activate' | grep "/home"
This will grab all Python virtual environments present inside your home directory.
See Demo Here
How to have multiple conditions for one if statement in python
I would use
def example(arg1, arg2, arg3):
if arg1 == 1 and arg2 == 2 and arg3 == 3:
print("Example Text")
The and
operator is identical to the logic gate with the same name; it will return 1 if and only if all of the inputs are 1. You can also use or
operator if you want that logic gate.
EDIT: Actually, the code provided in your post works fine with me. I don't see any problems with that. I think that this might be a problem with your Python, not the actual language.
Using an Alias in a WHERE clause
SELECT A.identifier
, A.name
, TO_NUMBER(DECODE( A.month_no
, 1, 200803
, 2, 200804
, 3, 200805
, 4, 200806
, 5, 200807
, 6, 200808
, 7, 200809
, 8, 200810
, 9, 200811
, 10, 200812
, 11, 200701
, 12, 200702
, NULL)) as MONTH_NO
, TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
FROM table_a A, table_b B
WHERE .identifier = B.identifier
HAVING MONTH_NO > UPD_DATE
How to insert image in mysql database(table)?
I tried all above solution and fail, it just added a null file to the DB.
However, I was able to get it done by moving the image(fileName.jpg
) file first in to below folder(in my case) C:\ProgramData\MySQL\MySQL Server 5.7\Uploads
and then I executed below command and it works for me,
INSERT INTO xx_BLOB(ID,IMAGE) VALUES(1,LOAD_FILE('C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/fileName.jpg'));
Hope this helps.
How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download
I researched online and saw that the Response.End()
always throws an exception.
Replace this: HttpContext.Current.Response.End();
With this:
HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
HttpContext.Current.Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.
Sublime Text 3 how to change the font size of the file sidebar?
If you want to change the font size then simply follow.
Preferences-> Default File preferences.
After clicking on default file preferences, new Tab will open with name of Default File Type.Sublime-options
After find Font properties like font Courier New 12
we (recommend to use CTRL+F) then change size of it. Click save and instantly you can see the changes.
ORDER BY using Criteria API
You need to create an alias for the mother.kind
. You do this like so.
Criteria c = session.createCriteria(Cat.class);
c.createAlias("mother.kind", "motherKind");
c.addOrder(Order.asc("motherKind.value"));
return c.list();
How to make a phone call programmatically?
If you end up with a SecurityException (and the call does not work), You should consider requesting the user permission to make a call as this is considered a dangerous permission:
ActivityCompat.requestPermissions(
activity,
new String[] {Manifest.permission.CALL_PHONE},
1
);
Note this has nothing to do with the manifest permission (that you must have as well)
How do I use cx_freeze?
I'm really not sure what you're doing to get that error, it looks like you're trying to run cx_Freeze on its own, without arguments. So here is a short step-by-step guide on how to do it in windows (Your screenshot looks rather like the windows command line, so I'm assuming that's your platform)
Write your setup.py file. Your script above looks correct so it should work, assuming that your script exists.
Open the command line (Start
-> Run
-> "cmd"
)
Go to the location of your setup.py file and run python setup.py build
Notes:
There may be a problem with the name of your script. "Main.py" contains upper case letters, which might cause confusion since windows' file names are not case sensitive, but python is. My approach is to always use lower case for scripts to avoid any conflicts.
Make sure that python is on your PATH (read http://docs.python.org/using/windows.html)1
Make sure are are looking at the new cx_Freeze documentation. Google often seems to bring up the old docs.
removing html element styles via javascript
Remove removeProperty
_x000D_
_x000D_
var el=document.getElementById("id");
el.style.removeProperty('display')
console.log("display removed"+el.style["display"])
console.log("color "+el.style["color"])
_x000D_
<div id="id" style="display:block;color:red">s</div>
_x000D_
_x000D_
_x000D_
How to determine tables size in Oracle
Here is a query, you can run it in SQL Developer (or SQL*Plus):
SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
FROM DBA_SEGMENTS DS
WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES)
GROUP BY DS.TABLESPACE_NAME,
SEGMENT_NAME;
javax.naming.NoInitialContextException - Java
We need to specify the INITIAL_CONTEXT_FACTORY, PROVIDER_URL, USERNAME, PASSWORD etc. of JNDI to create an InitialContext
.
In a standalone application, you can specify that as below
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://ldap.wiz.com:389");
env.put(Context.SECURITY_PRINCIPAL, "joeuser");
env.put(Context.SECURITY_CREDENTIALS, "joepassword");
Context ctx = new InitialContext(env);
But if you are running your code in a Java EE container, these values will be fetched by the container and used to create an InitialContext
as below
System.getProperty(Context.PROVIDER_URL);
and
these values will be set while starting the container as JVM arguments.
So if you are running the code in a container, the following will work
InitialContext ctx = new InitialContext();
window.location.reload with clear cache
reload()
is supposed to accept an argument which tells it to do a hard reload, ie, ignoring the cache:
location.reload(true);
I can't vouch for its reliability, you may want to investigate this further.
How to make html table vertically scrollable
Here's my solution (in Spring with Thymeleaf and jQuery):
html:
<!DOCTYPE html>
<html
xmlns:th="http://www.thymeleaf.org"
xmlns:tiles="http://www.thymeleaf.org">
<body>
<div id="objects" th:fragment="ObjectList">
<br/>
<div id='cap'>
<span>Objects</span>
</div>
<div id="hdr">
<div>
<div class="Cell">Name</div>
<div class="Cell">Type</div>
</div>
</div>
<div id="bdy">
<div th:each="object : ${objectlist}">
<div class="Cell" th:text="${object.name}">name</div>
<div class="Cell" th:text="${object.type}">type</div>
</div>
</div>
</div>
</body>
</html>
css:
@CHARSET "UTF-8";
#cap span {
display: table-caption;
border:2px solid;
font-size: 200%;
padding: 3px;
}
#hdr {
display:block;
padding:0px;
margin-left:0;
border:2px solid;
}
#bdy {
display:block;
padding:0px;
margin-left:0;
border:2px solid;
}
#objects #bdy {
height:300px;
overflow-y: auto;
}
#hdr div div{
margin-left:-3px;
margin-right:-3px;
text-align: right;
}
#hdr div:first-child {
text-align: left;
}
#bdy div div {
margin-left:-3px;
margin-right:-3px;
text-align: right;
}
#bdy div div:first-child {
text-align: left;
}
.Cell
{
display: table-cell;
border: solid;
border-width: thin;
padding-left: 5px;
padding-right: 5px;
}
javascript:
$(document).ready(function(){
var divs = ['#objects'];
divs.forEach(function(div)
{
if ($(div).length > 0)
{
var widths = [];
var totalWidth = 0;
$(div+' #hdr div div').each(function() {
widths.push($(this).width())
});
$(div+' #bdy div div').each(function() {
var col = $(this).index();
if ( $(this).width() > widths[col] )
{
widths[col] = $(this).width();
}
});
$(div+' #hdr div div').each(function() {
var newWidth = widths[$(this).index()]+5;
$(this).css("width", newWidth);
totalWidth += $(this).outerWidth();
});
$(div+' #bdy div div').each(function() {
$(this).css("width", widths[$(this).index()]+5);
});
$(div+' #hdr').css("width", totalWidth);
$(div+' #bdy').css("width", totalWidth+($(div+' #bdy').css('overflow-y')=='auto'?15:0));
}
})
});
How to enable/disable bluetooth programmatically in android
Here is a bit more robust way of doing this, also handling the return values of enable()\disable()
methods:
public static boolean setBluetooth(boolean enable) {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
boolean isEnabled = bluetoothAdapter.isEnabled();
if (enable && !isEnabled) {
return bluetoothAdapter.enable();
}
else if(!enable && isEnabled) {
return bluetoothAdapter.disable();
}
// No need to change bluetooth state
return true;
}
And add the following permissions into your manifest file:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
But remember these important points:
This is an asynchronous call: it will return immediately, and clients
should listen for ACTION_STATE_CHANGED to be notified of subsequent
adapter state changes. If this call returns true, then the adapter
state will immediately transition from STATE_OFF to STATE_TURNING_ON,
and some time later transition to either STATE_OFF or STATE_ON. If
this call returns false then there was an immediate problem that will
prevent the adapter from being turned on - such as Airplane mode, or
the adapter is already turned on.
UPDATE:
Ok, so how to implement bluetooth listener?:
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
switch (state) {
case BluetoothAdapter.STATE_OFF:
// Bluetooth has been turned off;
break;
case BluetoothAdapter.STATE_TURNING_OFF:
// Bluetooth is turning off;
break;
case BluetoothAdapter.STATE_ON:
// Bluetooth is on
break;
case BluetoothAdapter.STATE_TURNING_ON:
// Bluetooth is turning on
break;
}
}
}
};
And how to register/unregister the receiver? (In your Activity
class)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
// Register for broadcasts on BluetoothAdapter state change
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, filter);
}
@Override
public void onStop() {
super.onStop();
// ...
// Unregister broadcast listeners
unregisterReceiver(mReceiver);
}
Oracle SQL Developer and PostgreSQL
I got the list of databases to populate by putting my username in the Username field (no password) and clicking "Choose Database". Doesn't work with a blank Username field, I can only connect to my user database that way.
(This was with SQL Developer 4.0.0.13, Postgres.app 9.3.0.0, and postgresql-9.3-1100.jdbc41.jar, FWIW.)
Pretty printing XML with javascript
You can get pretty formatted xml with xml-beautify
var prettyXmlText = new XmlBeautify().beautify(xmlText,
{indent: " ",useSelfClosingElement: true});
indent:indent pattern like white spaces
useSelfClosingElement: true=>use self-closing element when empty element.
JSFiddle
Original(Before)
<?xml version="1.0" encoding="utf-8"?><example version="2.0">
<head><title>Original aTitle</title></head>
<body info="none" ></body>
</example>
Beautified(After)
<?xml version="1.0" encoding="utf-8"?>
<example version="2.0">
<head>
<title>Original aTitle</title>
</head>
<body info="none" />
</example>
What do parentheses surrounding an object/function/class declaration mean?
A few considerations on the subject:
The parenthesis:
The browser (engine/parser) associates the keyword function with
[optional name]([optional parameters]){...code...}
So in an expression like function(){}() the last parenthesis makes no sense.
Now think at
name=function(){} ; name() !?
Yes, the first pair of parenthesis force the anonymous function to turn into a variable (stored expression) and the second launches evaluation/execution, so ( function(){} )() makes sense.
The utility: ?
For executing some code on load and isolate the used variables from the rest of the page especially when name conflicts are possible;
Replace eval("string") with
(new Function("string"))()
Wrap long code for " =?: " operator like:
result = exp_to_test ? (function(){... long_code ...})() : (function(){...})();
Entity framework self referencing loop detected
I know this is an old question but here is the solution I found to a very similar coding issue in my own code:
var response = ApiDB.Persons.Include(y => y.JobTitle).Include(b => b.Discipline).Include(b => b.Team).Include(b => b.Site).OrderBy(d => d.DisplayName).ToArray();
foreach (var person in response)
{
person.JobTitle = new JobTitle()
{
JobTitle_ID = person.JobTitle.JobTitle_ID,
JobTitleName = person.JobTitle.JobTitleName,
PatientInteraction = person.JobTitle.PatientInteraction,
Active = person.JobTitle.Active,
IsClinical = person.JobTitle.IsClinical
};
}
Since the person object contains everything from the person table and the job title object contains a list of persons with that job title, the database kept self referencing. I thought disabling proxy creation and lazy loading would fix this but unfortunately it didn't.
For the that aren't able to do that, try the solution above. Explicitly creating a new object for each object that self references, but leave out the list of objects or object that goes back to the previous entity will fix it since disabling lazy loading does not appear to work for me.
Java Round up Any Number
Assuming a as double and we need a rounded number with no decimal place . Use Math.round() function.
This goes as my solution .
double a = 0.99999;
int rounded_a = (int)Math.round(a);
System.out.println("a:"+rounded_a );
Output :
a:1
How can I convert ticks to a date format?
private void button1_Click(object sender, EventArgs e)
{
long myTicks = 633896886277130000;
DateTime dtime = new DateTime(myTicks);
MessageBox.Show(dtime.ToString("MMMM d, yyyy"));
}
Gives
September 27, 2009
Is that what you need?
I don't see how that format is necessarily easy to work with in SQL queries, though.
Setting up Eclipse with JRE Path
You should specify where Eclipse should find your JDK in the file eclipse.ini. Specifically, the following parameter (note that it is 2 separate lines in the ini file):
-vm
C:\Java\JDK\1.8\bin\javaw.exe
or wherever your javaw.exe happens to be.
Note: The format of the ini file is very particular; make sure to consult https://wiki.eclipse.org/Eclipse.ini to ensure you get it exactly right
Row numbers in query result using Microsoft Access
MS-Access doesn't support ROW_NUMBER(). Use TOP 1:
SELECT TOP 1 *
FROM [MyTable]
ORDER BY [MyIdentityCOlumn]
If you need the 15th row - MS-Access has no simple, built-in, way to do this. You can simulate the rownumber by using reverse nested ordering to get this:
SELECT TOP 1 *
FROM (
SELECT TOP 15 *
FROM [MyTable]
ORDER BY [MyIdentityColumn] ) t
ORDER BY [MyIdentityColumn] DESC
JavaScript: function returning an object
I would take those directions to mean:
function makeGamePlayer(name,totalScore,gamesPlayed) {
//should return an object with three keys:
// name
// totalScore
// gamesPlayed
var obj = { //note you don't use = in an object definition
"name": name,
"totalScore": totalScore,
"gamesPlayed": gamesPlayed
}
return obj;
}
Can ordered list produce result that looks like 1.1, 1.2, 1.3 (instead of just 1, 2, 3, ...) with css?
this is proper code if you want to first child li resize of other css.
<style>
li.title {
font-size: 20px;
counter-increment: ordem;
color:#0080B0;
}
.my_ol_class {
counter-reset: my_ol_class;
padding-left: 30px !important;
}
.my_ol_class li {
display: block;
position: relative;
}
.my_ol_class li:before {
counter-increment: my_ol_class;
content: counter(ordem) "." counter(my_ol_class) " ";
position: absolute;
margin-right: 100%;
right: 10px; /* space between number and text */
}
li.title ol li{
font-size: 15px;
color:#5E5E5E;
}
</style>
in html file.
<ol>
<li class="title"> <p class="page-header list_title">Acceptance of Terms. </p>
<ol class="my_ol_class">
<li>
<p>
my text 1.
</p>
</li>
<li>
<p>
my text 2.
</p>
</li>
</ol>
</li>
</ol>
How to initialize an array of custom objects
I had to create an array of a predefined type, and I successfully did as follows:
[System.Data.DataColumn[]]$myitems = ([System.Data.DataColumn]("col1"),
[System.Data.DataColumn]("col2"), [System.Data.DataColumn]("col3"))
What is the reason and how to avoid the [FIN, ACK] , [RST] and [RST, ACK]
Here is a rough explanation of the concepts.
[ACK]
is the acknowledgement that the previously sent data packet was received.
[FIN]
is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN
).
So, suppose
- host A sends a data packet to host B
- and then host B wants to close the connection.
- Host B (depending on timing) can respond with
[FIN,ACK]
indicating that it received the sent packet and wants to close the session.
- Host A should then respond with a
[FIN,ACK]
indicating that it received the termination request (the ACK
part) and that it too will close the connection (the FIN
part).
However, if host A wants to close the session after sending the packet, it would only send a [FIN]
packet (nothing to acknowledge) but host B would respond with [FIN,ACK]
(acknowledges the request and responds with FIN
).
Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST]
instead of the usual [FIN,ACK]
. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.
You can find a more detailed and comprehensive explanation here.
Sum values in foreach loop php
In your case IF you want to go with foreach loop than
$sum = 0;
foreach($group as $key => $value) {
$sum += $value;
}
echo $sum;
But if you want to go with direct sum of array than look on below for your solution :
$total = array_sum($group);
for only sum of array looping is time wasting.
http://php.net/manual/en/function.array-sum.php
array_sum — Calculate the sum of values in an array
<?php
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";
$b = array("a" => 1.2, "b" => 2.3, "c" => 3.4);
echo "sum(b) = " . array_sum($b) . "\n";
?>
The above example will output:
sum(a) = 20
sum(b) = 6.9
Difference between Git and GitHub
Simply put, Git is a version control system that lets you manage and keep track of your source code history. GitHub is a cloud-based hosting service that lets you manage Git repositories. If you have open-source projects that use Git, then GitHub is designed to help you better manage them.
What is the C++ function to raise a number to a power?
In C++ the "^" operator is a bitwise OR. It does not work for raising to a power. The x << n is a left shift of the binary number which is the same as multiplying x by 2 n number of times and that can only be used when raising 2 to a power. The POW function is a math function that will work generically.
Parse a URI String into Name-Value Collection
PLAIN Java 11
Given the URL to analyse:
URL url = new URL("https://google.com.ua/oauth/authorize?client_id=SS&response_type=code&scope=N_FULL&access_type=offline&redirect_uri=http://localhost/Callback");
This solution collects a list of pairs:
List<Map.Entry<String, String>> list = Pattern.compile("&")
.splitAsStream(url.getQuery())
.map(s -> Arrays.copyOf(s.split("=", 2), 2))
.map(o -> Map.entry(decode(o[0]), decode(o[1])))
.collect(Collectors.toList());
This solution on the other hand collects a map (given that in a url there can be more parameters with same name but different values).
Map<String, List<String>> list = Pattern.compile("&")
.splitAsStream(url.getQuery())
.map(s -> Arrays.copyOf(s.split("=", 2), 2))
.collect(groupingBy(s -> decode(s[0]), mapping(s -> decode(s[1]), toList())));
Both the solutions must use an utility function to properly decode the parameters.
private static String decode(final String encoded) {
return Optional.ofNullable(encoded)
.map(e -> URLDecoder.decode(e, StandardCharsets.UTF_8))
.orElse(null);
}
JSON and XML comparison
I found this article at digital bazaar really interesting. Quoting their quotations from Norm:
About JSON pros:
If all you want to pass around are atomic values or lists or hashes of
atomic values, JSON has many of the advantages of XML: it’s
straightforwardly usable over the Internet, supports a wide variety of
applications, it’s easy to write programs to process JSON, it has few
optional features, it’s human-legible and reasonably clear, its design
is formal and concise, JSON documents are easy to create, and it uses
Unicode. ...
About XML pros:
XML deals remarkably well with the full richness of unstructured
data. I’m not worried about the future of XML at all even if its death
is gleefully celebrated by a cadre of web API designers.
And I can’t resist tucking an "I told you so!" token away in my
desk. I look forward to seeing what the JSON folks do when they are
asked to develop richer APIs. When they want to exchange less well
strucured data, will they shoehorn it into JSON? I see occasional
mentions of a schema language for JSON, will other languages follow?
...
I personally agree with Norm. I think that most attacks to XML come from Web Developers for typical applications, and not really from integration developers. But that's my opinion! ;)
Output of git branch in tree like fashion
The following example shows commit parents as well:
git log --graph --all \
--format='%C(cyan dim) %p %Cred %h %C(white dim) %s %Cgreen(%cr)%C(cyan dim) <%an>%C(bold yellow)%d%Creset'
Getting the last argument passed to a shell script
There is a much more concise way to do this. Arguments to a bash script can be brought into an array, which makes dealing with the elements much simpler. The script below will always print the last argument passed to a script.
argArray=( "$@" ) # Add all script arguments to argArray
arrayLength=${#argArray[@]} # Get the length of the array
lastArg=$((arrayLength - 1)) # Arrays are zero based, so last arg is -1
echo ${argArray[$lastArg]}
Sample output
$ ./lastarg.sh 1 2 buckle my shoe
shoe
Can I redirect the stdout in python into some sort of string buffer?
This method restores sys.stdout even if there's an exception. It also gets any output before the exception.
import io
import sys
real_stdout = sys.stdout
fake_stdout = io.BytesIO() # or perhaps io.StringIO()
try:
sys.stdout = fake_stdout
# do what you have to do to create some output
finally:
sys.stdout = real_stdout
output_string = fake_stdout.getvalue()
fake_stdout.close()
# do what you want with the output_string
Tested in Python 2.7.10 using io.BytesIO()
Tested in Python 3.6.4 using io.StringIO()
Bob, added for a case if you feel anything from the modified / extended code experimentation might get interesting in any sense, otherwise feel free to delete it
Ad informandum ... a few remarks from extended experimentation during finding some viable mechanics to "grab" outputs, directed by numexpr.print_versions()
directly to the <stdout>
( upon a need to clean GUI and collecting details into debugging-report )
# THIS WORKS AS HELL: as Bob Stein proposed years ago:
# py2 SURPRISEDaBIT:
#
import io
import sys
#
real_stdout = sys.stdout # PUSH <stdout> ( store to REAL_ )
fake_stdout = io.BytesIO() # .DEF FAKE_
try: # FUSED .TRY:
sys.stdout.flush() # .flush() before
sys.stdout = fake_stdout # .SET <stdout> to use FAKE_
# ----------------------------------------- # + do what you gotta do to create some output
print 123456789 # +
import numexpr # +
QuantFX.numexpr.__version__ # + [3] via fake_stdout re-assignment, as was bufferred + "late" deferred .get_value()-read into print, to finally reach -> real_stdout
QuantFX.numexpr.print_versions() # + [4] via fake_stdout re-assignment, as was bufferred + "late" deferred .get_value()-read into print, to finally reach -> real_stdout
_ = os.system( 'echo os.system() redir-ed' )# + [1] via real_stdout + "late" deferred .get_value()-read into print, to finally reach -> real_stdout, if not ( _ = )-caught from RET-d "byteswritten" / avoided from being injected int fake_stdout
_ = os.write( sys.stderr.fileno(), # + [2] via stderr + "late" deferred .get_value()-read into print, to finally reach -> real_stdout, if not ( _ = )-caught from RET-d "byteswritten" / avoided from being injected int fake_stdout
b'os.write() redir-ed' )# *OTHERWISE, if via fake_stdout, EXC <_io.BytesIO object at 0x02C0BB10> Traceback (most recent call last):
# ----------------------------------------- # ? io.UnsupportedOperation: fileno
#''' ? YET: <_io.BytesIO object at 0x02C0BB10> has a .fileno() method listed
#>>> 'fileno' in dir( sys.stdout ) -> True ? HAS IT ADVERTISED,
#>>> pass; sys.stdout.fileno -> <built-in method fileno of _io.BytesIO object at 0x02C0BB10>
#>>> pass; sys.stdout.fileno()-> Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# io.UnsupportedOperation: fileno
# ? BUT REFUSES TO USE IT
#'''
finally: # == FINALLY:
sys.stdout.flush() # .flush() before ret'd back REAL_
sys.stdout = real_stdout # .SET <stdout> to use POP'd REAL_
sys.stdout.flush() # .flush() after ret'd back REAL_
out_string = fake_stdout.getvalue() # .GET string from FAKE_
fake_stdout.close() # <FD>.close()
# +++++++++++++++++++++++++++++++++++++ # do what you want with the out_string
#
print "\n{0:}\n{1:}{0:}".format( 60 * "/\\",# "LATE" deferred print the out_string at the very end reached -> real_stdout
out_string #
)
'''
PASS'd:::::
...
os.system() redir-ed
os.write() redir-ed
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
123456789
'2.5'
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Numexpr version: 2.5
NumPy version: 1.10.4
Python version: 2.7.13 |Anaconda 4.0.0 (32-bit)| (default, May 11 2017, 14:07:41) [MSC v.1500 32 bit (Intel)]
AMD/Intel CPU? True
VML available? True
VML/MKL version: Intel(R) Math Kernel Library Version 11.3.1 Product Build 20151021 for 32-bit applications
Number of threads used by default: 4 (out of 4 detected cores)
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
>>>
EXC'd :::::
...
os.system() redir-ed
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
123456789
'2.5'
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Numexpr version: 2.5
NumPy version: 1.10.4
Python version: 2.7.13 |Anaconda 4.0.0 (32-bit)| (default, May 11 2017, 14:07:41) [MSC v.1500 32 bit (Intel)]
AMD/Intel CPU? True
VML available? True
VML/MKL version: Intel(R) Math Kernel Library Version 11.3.1 Product Build 20151021 for 32-bit applications
Number of threads used by default: 4 (out of 4 detected cores)
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
Traceback (most recent call last):
File "<stdin>", line 9, in <module>
io.UnsupportedOperation: fileno
'''
composer laravel create project
- Create project
- Open: Root (htdocs)\
- Press: Shift + Open command windows here
- Type:
php composer.phar create-project --prefer-dist
laravel/laravel lar-project "5.7.*"
Using CSS for a fade-in effect on page load
Looking forward to Web Animations in 2020.
_x000D_
_x000D_
async function moveToPosition(el, durationInMs) {
return new Promise((resolve) => {
const animation = el.animate([{
opacity: '0'
},
{
transform: `translateY(${el.getBoundingClientRect().top}px)`
},
], {
duration: durationInMs,
easing: 'ease-in',
iterations: 1,
direction: 'normal',
fill: 'forwards',
delay: 0,
endDelay: 0
});
animation.onfinish = () => resolve();
});
}
async function fadeIn(el, durationInMs) {
return new Promise((resolve) => {
const animation = el.animate([{
opacity: '0'
},
{
opacity: '0.5',
offset: 0.5
},
{
opacity: '1',
offset: 1
}
], {
duration: durationInMs,
easing: 'linear',
iterations: 1,
direction: 'normal',
fill: 'forwards',
delay: 0,
endDelay: 0
});
animation.onfinish = () => resolve();
});
}
async function fadeInSections() {
for (const section of document.getElementsByTagName('section')) {
await fadeIn(section, 200);
}
}
window.addEventListener('load', async() => {
await moveToPosition(document.getElementById('headerContent'), 500);
await fadeInSections();
await fadeIn(document.getElementsByTagName('footer')[0], 200);
});
_x000D_
body,
html {
height: 100vh;
}
header {
height: 20%;
}
.text-center {
text-align: center;
}
.leading-none {
line-height: 1;
}
.leading-3 {
line-height: .75rem;
}
.leading-2 {
line-height: .25rem;
}
.bg-black {
background-color: rgba(0, 0, 0, 1);
}
.bg-gray-50 {
background-color: rgba(249, 250, 251, 1);
}
.pt-12 {
padding-top: 3rem;
}
.pt-2 {
padding-top: 0.5rem;
}
.text-lightGray {
color: lightGray;
}
.container {
display: flex;
/* or inline-flex */
justify-content: space-between;
}
.container section {
padding: 0.5rem;
}
.opacity-0 {
opacity: 0;
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="Web site created using create-snowpack-app" />
<link rel="stylesheet" type="text/css" href="./assets/syles/index.css" />
</head>
<body>
<header class="bg-gray-50">
<div id="headerContent">
<h1 class="text-center leading-none pt-2 leading-2">Hello</h1>
<p class="text-center leading-2"><i>Ipsum lipmsum emus tiris mism</i></p>
</div>
</header>
<div class="container">
<section class="opacity-0">
<h2 class="text-center"><i>ipsum 1</i></h2>
<p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
</section>
<section class="opacity-0">
<h2 class="text-center"><i>ipsum 2</i></h2>
<p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
</section>
<section class="opacity-0">
<h2 class="text-center"><i>ipsum 3</i></h2>
<p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
</section>
</div>
<footer class="opacity-0">
<h1 class="text-center leading-3 text-lightGray"><i>dictum non ultricies eu, dapibus non tellus</i></h1>
<p class="text-center leading-3"><i>Ipsum lipmsum emus tiris mism</i></p>
</footer>
</body>
</html>
_x000D_
_x000D_
_x000D_
Count Rows in Doctrine QueryBuilder
To count items after some number of items (offset), $qb->setFirstResults() cannot be applied in this case, as it works not as a condition of query, but as an offset of query result for a range of items selected (i. e. setFirstResult cannot be used togather with COUNT at all). So to count items, which are left I simply did the following:
//in repository class:
$count = $qb->select('count(p.id)')
->from('Products', 'p')
->getQuery()
->getSingleScalarResult();
return $count;
//in controller class:
$count = $this->em->getRepository('RepositoryBundle')->...
return $count-$offset;
Anybody knows more clean way to do it?
Refresh Page C# ASP.NET
I think this should do the trick (untested):
Page.Response.Redirect(Page.Request.Url.ToString(), true);
Resolving instances with ASP.NET Core DI from within ConfigureServices
The IServiceCollection
interface is used for building a dependency injection container. After it's fully built, it gets composed to an IServiceProvider
instance which you can use to resolve services. You can inject an IServiceProvider
into any class. The IApplicationBuilder
and HttpContext
classes can provide the service provider as well, via their ApplicationServices
or RequestServices
properties respectively.
IServiceProvider
defines a GetService(Type type)
method to resolve a service:
var service = (IFooService)serviceProvider.GetService(typeof(IFooService));
There are also several convenience extension methods available, such as serviceProvider.GetService<IFooService>()
(add a using
for Microsoft.Extensions.DependencyInjection
).
Resolving services inside the startup class
Injecting dependencies
The runtime's hosting service provider can inject certain services into the constructor of the Startup
class, such as IConfiguration
,
IWebHostEnvironment
(IHostingEnvironment
in pre-3.0 versions), ILoggerFactory
and IServiceProvider
. Note that the latter is an instance built by the hosting layer and contains only the essential services for starting up an application.
The ConfigureServices()
method does not allow injecting services, it only accepts an IServiceCollection
argument. This makes sense because ConfigureServices()
is where you register the services required by your application. However you can use services injected in the startup's constructor here, for example:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// Use Configuration here
}
Any services registered in ConfigureServices()
can then be injected into the Configure()
method; you can add an arbitrary number of services after the IApplicationBuilder
parameter:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IFooService>();
}
public void Configure(IApplicationBuilder app, IFooService fooService)
{
fooService.Bar();
}
Manually resolving dependencies
If you need to manually resolve services, you should preferably use the ApplicationServices
provided by IApplicationBuilder
in the Configure()
method:
public void Configure(IApplicationBuilder app)
{
var serviceProvider = app.ApplicationServices;
var hostingEnv = serviceProvider.GetService<IHostingEnvironment>();
}
It is possible to pass and directly use an IServiceProvider
in the constructor of your Startup
class, but as above this will contain a limited subset of services, and thus has limited utility:
public Startup(IServiceProvider serviceProvider)
{
var hostingEnv = serviceProvider.GetService<IWebHostEnvironment>();
}
If you must resolve services in the ConfigureServices()
method, a different approach is required. You can build an intermediate IServiceProvider
from the IServiceCollection
instance which contains the services which have been registered up to that point:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IFooService, FooService>();
// Build the intermediate service provider
var sp = services.BuildServiceProvider();
// This will succeed.
var fooService = sp.GetService<IFooService>();
// This will fail (return null), as IBarService hasn't been registered yet.
var barService = sp.GetService<IBarService>();
}
Please note:
Generally you should avoid resolving services inside the ConfigureServices()
method, as this is actually the place where you're configuring the application services. Sometimes you just need access to an IOptions<MyOptions>
instance. You can accomplish this by binding the values from the IConfiguration
instance to an instance of MyOptions
(which is essentially what the options framework does):
public void ConfigureServices(IServiceCollection services)
{
var myOptions = new MyOptions();
Configuration.GetSection("SomeSection").Bind(myOptions);
}
Manually resolving services (aka Service Locator) is generally considered an anti-pattern. While it has its use-cases (for frameworks and/or infrastructure layers), you should avoid it as much as possible.
Erasing elements from a vector
Use the remove/erase idiom:
std::vector<int>& vec = myNumbers; // use shorter name
vec.erase(std::remove(vec.begin(), vec.end(), number_in), vec.end());
What happens is that remove
compacts the elements that differ from the value to be removed (number_in
) in the beginning of the vector
and returns the iterator to the first element after that range. Then erase
removes these elements (whose value is unspecified).
How do I count a JavaScript object's attributes?
var miobj = [
{"padreid":"0", "sw":"0", "dtip":"UNO", "datos":[]},
{"padreid":"1", "sw":"0", "dtip":"DOS", "datos":[]}
];
alert(miobj.length) //=== 2
but
alert(miobj[0].length) //=== undefined
this function is very good
Object.prototype.count = function () {
var count = 0;
for(var prop in this) {
if(this.hasOwnProperty(prop))
count = count + 1;
}
return count;
}
alert(miobj.count()) // === 2
alert(miobj[0].count()) // === 4
JavaScript for handling Tab Key press
Having following html:
<!-- note that not all browsers focus on links when Tab is pressed -->
<a href="http://example.com">Link</a>
<input type="text" placeholder="Some input" />
<a href="http://example.com">Another Link</a>
<textarea>...</textarea>
You can get to active link with:
// event listener for keyup
function checkTabPress(e) {
"use strict";
// pick passed event or global event object if passed one is empty
e = e || event;
var activeElement;
if (e.keyCode == 9) {
// Here read the active selected link.
activeElement = document.activeElement;
// If HTML element is an anchor <a>
if (activeElement.tagName.toLowerCase() == 'a')
// get it's hyperlink
alert(activeElement.href);
}
}
var body = document.querySelector('body');
body.addEventListener('keyup', checkTabPress);
Here is working example.
Ruby on Rails: Clear a cached page
If you're doing fragment caching, you can manually break the cache by updating your cache key, like so:
Version #1
<% cache ['cool_name_for_cache_key', 'v1'] do %>
Version #2
<% cache ['cool_name_for_cache_key', 'v2'] do %>
Or you can have the cache automatically reset based on the state of a non-static object, such as an ActiveRecord object, like so:
<% cache @user_object do %>
With this ^ method, any time the user object is updated, the cache will automatically be reset.
Simple way to get element by id within a div tag?
In HTML ids should be unique. I suggest you change your code to something like this:
<div id="div1" >
<input type="text" name="edit1" id="edit1" />
<input type="text" name="edit2" id="edit2" />
</div>
<div id="div2" >
<input type="text" name="edit1" id="edit3" />
<input type="text" name="edit2" id="edit4" />
</div>
deleted object would be re-saved by cascade (remove deleted object from associations)
I also ran into this error on a badly designed database, where there was a Person
table with a one2many relationship with a Code
table and an Organization
table with a one2many relationship with the same Code
table. The Code could apply to both an Organization and Or a Person depending on situation. Both the Person object and the Organization object were set to Cascade=All delete orphans.
What became of this overloaded use of the Code table however was that neither the Person nor the Organization could cascade delete because there was always another collection that had a reference to it. So no matter how it was deleted in the Java code out of whatever referencing collections or objects the delete would fail. The only way to get it to work was to delete it out of the collection I was trying to save then delete it out of the Code table directly then save the collection. That way there was no reference to it.
How to sum all column values in multi-dimensional array?
For example, you can pluck all fields from a result like this below.
I am picking out the 'balance' from an array and save to a variable
$kii = $user->pluck('balance');
then on the next line u can sum like this:
$sum = $kii->sum();
Hope it helps.
How do I enable the column selection mode in Eclipse?
You can enable and disable column editing mode via the keyboard shortcut ALT-SHIFT-A
.
Once enabled you can then use either the mouse to select a block of text, or the keyboard using SHIFT
(like a normal keyboard select, except the selection will now be in a block).
If you've changed your default font for text editing, entering column editing mode will probably change your screen font to the default column editing font (which is probably different to your changed font. To change the font when in column editing mode, go to the menu and select Window -> Preferences
, then in the tree on the left hand side, pick General -> Appearance -> Colors and Fonts
, and then pick Basic -> Text Editor Block Selection Font
on the right hand side tree. You can then select the font to be consistent with your "not in column editing mode" font.
Django TemplateDoesNotExist?
Hi guys I found a new solution. Actually it is defined in another template so instead of defining TEMPLATE_DIRS yourself, put your directory path name at their:
print variable and a string in python
'''
If the python version you installed is 3.6.1, you can print strings and a variable through
a single line of code.
For example the first string is "I have", the second string is "US
Dollars" and the variable, **card.price** is equal to 300, we can write
the code this way:
'''
print("I have", card.price, "US Dollars")
#The print() function outputs strings to the screen.
#The comma lets you concatenate and print strings and variables together in a single line of code.
What is the incentive for curl to release the library for free?
I'm Daniel Stenberg.
I made curl
I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.
I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.
Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.
Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.
Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.
At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.
Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.
Why do I still work on curl?
Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?
- I can't speak for my fellow project team members. We all participate in this for our own reasons.
- I think it's still the right thing to do. I'm proud of what we've accomplished and I truly want to make the world a better place and I think curl does its little part in this.
- There are still bugs to fix and features to add!
- curl is free but my time is not. I still have a job and someone still has to pay someone for me to get paid every month so that I can put food on the table for my family. I charge customers and companies to help them with curl. You too can get my help for a fee, which then indirectly helps making sure that curl continues to evolve, remain free and the kick-ass product it is.
- curl was my spare time project for twenty years before I started working with it full time. I've had great jobs and worked on awesome projects. I've been in a position of luxury where I could continue to work on curl on my spare time and keep shipping a quality product for free. My work on curl has given me friends, boosted my career and taken me to places I would not have been at otherwise.
- I would not do it differently if I could back and do it again.
Am I proud of what we've done?
Yes. So insanely much.
But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.
We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.
Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.
For real?
Yeah. For real.
Do I ever get tired? Is it ever done?
Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.
But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.
curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.
How to tell if browser/tab is active
You would use the focus
and blur
events of the window:
var interval_id;
$(window).focus(function() {
if (!interval_id)
interval_id = setInterval(hard_work, 1000);
});
$(window).blur(function() {
clearInterval(interval_id);
interval_id = 0;
});
To Answer the Commented Issue of "Double Fire" and stay within jQuery ease of use:
$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
// do work
break;
case "focus":
// do work
break;
}
}
$(this).data("prevType", e.type);
})
Click to view Example Code Showing it working (JSFiddle)
How to change values in a tuple?
I´m late to the game but I think the simplest, resource-friendliest and fastest way (depending on the situation),
is to overwrite the tuple itself. Since this would remove the need for the list & variable creation and is archived in one line.
new = 24
t = (1, 2, 3)
t = (t[0],t[1],new)
>>> (1, 2, 24)
But: This is only handy for rather small tuples and also limits you to a fixed tuple value, nevertheless, this is the case for tuples most of the time anyway.
So in this particular case it would look like this:
new = '200'
t = ('275', '54000', '0.0', '5000.0', '0.0')
t = (new, t[1], t[2], t[3], t[4])
>>> ('200', '54000', '0.0', '5000.0', '0.0')
How to dynamically add a class to manual class names?
Depending on how many dynamic classes you need to add as your project grows it's probably worth checking out the classnames utility by JedWatson on GitHub. It allows you to represent your conditional classes as an object and returns those that evaluate to true.
So as an example from its React documentation:
render () {
var btnClass = classNames({
'btn': true,
'btn-pressed': this.state.isPressed,
'btn-over': !this.state.isPressed && this.state.isHovered
});
return <button className={btnClass}>I'm a button!</button>;
}
Since React triggers a re-render when there is a state change, your dynamic class names are handled naturally and kept up to date with the state of your component.
Last Key in Python Dictionary
It seems like you want to do that:
dict.keys()[-1]
dict.keys()
returns a list of your dictionary's keys. Once you got the list, the -1 index allows you getting the last element of a list.
Since a dictionary is unordered*, it's doesn't make sense to get the last key of your dictionary.
Perhaps you want to sort them before. It would look like that:
sorted(dict.keys())[-1]
Note:
In Python 3, the code is
list(dict)[-1]
*Update:
This is no longer the case. Dictionary keys are officially ordered as of Python 3.7 (and unofficially in 3.6).
ORA-12154 could not resolve the connect identifier specified
I had this error in Visual Studio 2013, with an SSIS project. I set Project, Properties, Debugging, Run64BitRuntime = false and then the SSIS package ran. However, when I deployed the package to the server I had to set the value to true (Server is 64 bit Windows 2012 / Sql 2014 ).
I think the reasoning behind this is that Visual Studio is a 32 bit application.
JSON.stringify output to div in pretty print way
My proposal is based on:
- replace each '\n' (newline) with a <br>
- replace each space with
_x000D_
_x000D_
var x = { "data": { "x": "1", "y": "1", "url": "http://url.com" }, "event": "start", "show": 1, "id": 50 };_x000D_
_x000D_
_x000D_
document.querySelector('#newquote').innerHTML = JSON.stringify(x, null, 6)_x000D_
.replace(/\n( *)/g, function (match, p1) {_x000D_
return '<br>' + ' '.repeat(p1.length);_x000D_
});
_x000D_
<div id="newquote"></div>
_x000D_
_x000D_
_x000D_
.NET Events - What are object sender & EventArgs e?
Manually cast the sender to the type of your custom control, and then use it to delete or disable etc. Eg, something like this:
private void myCustomControl_Click(object sender, EventArgs e)
{
((MyCustomControl)sender).DoWhatever();
}
The 'sender' is just the object that was actioned (eg clicked).
The event args is subclassed for more complex controls, eg a treeview, so that you can know more details about the event, eg exactly where they clicked.
lodash: mapping array to object
It can also solve without using any lodash function like this:
let paramsVal = [
{ name: 'foo', input: 'bar' },
{ name: 'baz', input: 'zle' }
];
let output = {};
paramsVal.forEach(({name, input})=>{
output[name] = input;
})
console.log(output);
Check if table exists and if it doesn't exist, create it in SQL Server 2008
Declare @Username varchar(20)
Set @Username = 'Mike'
if not exists
(Select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'tblEmp')
Begin
Create table tblEmp (ID int primary key, Name varchar(50))
Print (@Username + ' Table created successfully')
End
Else
Begin
Print (@Username + ' : this Table Already exists in the database')
End
What is the facade design pattern?
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design.
The Facade design pattern is a structural pattern as it defines a manner for creating relationships between classes or entities. The facade design pattern is used to define a simplified interface to a more complex subsystem.
The facade pattern is ideal when working with a large number of interdependent classes, or with classes that require the use of multiple methods, particularly when they are complicated to use or difficult to understand. The facade class is a "wrapper" that contains a set of members that are easily understood and simple to use. These members access the subsystem on behalf of the facade user, hiding the implementation details.
The facade design pattern is particularly useful when wrapping subsystems that are poorly designed but cannot be refactored because the source code is unavailable or the existing interface is widely used. Sometimes you may decide to implement more than one facade to provide subsets of functionality for different purposes.
One example use of the facade pattern is for integrating a web site with a business application. The existing software may include large amounts of business logic that must be accessed in a particular manner. The web site may require only limited access to this business logic. For example, the web site may need to show whether an item for sale has reached a limited level of stock. The IsLowStock method of the facade class could return a Boolean value to indicate this. Behind the scenes, this method could be hiding the complexities of processing the current physical stock, incoming stock, allocated items and the low stock level for each item.
C#: Limit the length of a string?
The only reason I can see the purpose in this is for DB storage. If so, why not let the DB handle it and then push the exception upstream to be dealt with at the presentation layer?
Powershell: Get FQDN Hostname
I have the following add.. I need to separate out the dns suffix from the hostname.. and I only "know" the servers alias shortname... and want to know what the dns suffix is
#example:
#serveralias: MyAppServer.us.fred.com
#actualhostname: server01.us.fred.com
#I "know": "MyAppServer" .. I pass this on as an env var called myjumpbox .. this could also be $env:computername
$forname = $env:myjumpbox
$fqdn = [System.Net.Dns]::GetHostByName($forname).Hostname
$shortname = $fqdn.split('.')[0]
$domainname = $fqdn -split $fqdn.split('.')[0]+"."
$dnssuf = $domainname[1]
" name parts are- alias: " + $forname + " actual hostname: " + $shortname + " suffix: " + $dnssuf
#returns
name parts are- alias: MyAppServer actual hostname: server01 suffix: us.fred.com
How to allow remote access to my WAMP server for Mobile(Android)
I assume you are using windows. Open the command prompt and type ipconfig
and find out your local address (on your pc) it should look something like 192.168.1.13
or 192.168.0.5
where the end digit is the one that changes. It should be next to IPv4 Address.
If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13
If you have a virtual host then you will need root to edit the hosts file.
If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.
See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.
Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).
If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow
to allow,deny
in the httpd.conf
file. You can access this by the WAMP menu.
To eliminate possible causes of the issue for now set your config file to
<Directory />
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
<RequireAll>
Require all granted
</RequireAll>
</Directory>
As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.
Config file that fixed the problem:
https://gist.github.com/samvaughton/6790739
Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.
Understanding dispatch_async
All of the DISPATCH_QUEUE_PRIORITY_X queues are concurrent queues (meaning they can execute multiple tasks at once), and are FIFO in the sense that tasks within a given queue will begin executing using "first in, first out" order. This is in comparison to the main queue (from dispatch_get_main_queue()), which is a serial queue (tasks will begin executing and finish executing in the order in which they are received).
So, if you send 1000 dispatch_async() blocks to DISPATCH_QUEUE_PRIORITY_DEFAULT, those tasks will start executing in the order you sent them into the queue. Likewise for the HIGH, LOW, and BACKGROUND queues. Anything you send into any of these queues is executed in the background on alternate threads, away from your main application thread. Therefore, these queues are suitable for executing tasks such as background downloading, compression, computation, etc.
Note that the order of execution is FIFO on a per-queue basis. So if you send 1000 dispatch_async() tasks to the four different concurrent queues, evenly splitting them and sending them to BACKGROUND, LOW, DEFAULT and HIGH in order (ie you schedule the last 250 tasks on the HIGH queue), it's very likely that the first tasks you see starting will be on that HIGH queue as the system has taken your implication that those tasks need to get to the CPU as quickly as possible.
Note also that I say "will begin executing in order", but keep in mind that as concurrent queues things won't necessarily FINISH executing in order depending on length of time for each task.
As per Apple:
https://developer.apple.com/library/content/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html
A concurrent dispatch queue is useful when you have multiple tasks that can run in parallel. A concurrent queue is still a queue in that it dequeues tasks in a first-in, first-out order; however, a concurrent queue may dequeue additional tasks before any previous tasks finish. The actual number of tasks executed by a concurrent queue at any given moment is variable and can change dynamically as conditions in your application change. Many factors affect the number of tasks executed by the concurrent queues, including the number of available cores, the amount of work being done by other processes, and the number and priority of tasks in other serial dispatch queues.
Basically, if you send those 1000 dispatch_async() blocks to a DEFAULT, HIGH, LOW, or BACKGROUND queue they will all start executing in the order you send them. However, shorter tasks may finish before longer ones. Reasons behind this are if there are available CPU cores or if the current queue tasks are performing computationally non-intensive work (thus making the system think it can dispatch additional tasks in parallel regardless of core count).
The level of concurrency is handled entirely by the system and is based on system load and other internally determined factors. This is the beauty of Grand Central Dispatch (the dispatch_async() system) - you just make your work units as code blocks, set a priority for them (based on the queue you choose) and let the system handle the rest.
So to answer your above question: you are partially correct. You are "asking that code" to perform concurrent tasks on a global concurrent queue at the specified priority level. The code in the block will execute in the background and any additional (similar) code will execute potentially in parallel depending on the system's assessment of available resources.
The "main" queue on the other hand (from dispatch_get_main_queue()) is a serial queue (not concurrent). Tasks sent to the main queue will always execute in order and will always finish in order. These tasks will also be executed on the UI Thread so it's suitable for updating your UI with progress messages, completion notifications, etc.
How do I use Safe Area Layout programmatically?
I'm using this instead of add leading and trailing margin constraints to the layoutMarginsGuide:
UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
yourView.translatesAutoresizingMaskIntoConstraints = NO;
[NSLayoutConstraint activateConstraints:@[
[safe.trailingAnchor constraintEqualToAnchor:yourView.trailingAnchor],
[yourView.leadingAnchor constraintEqualToAnchor:safe.leadingAnchor],
[yourView.topAnchor constraintEqualToAnchor:safe.topAnchor],
[safe.bottomAnchor constraintEqualToAnchor:yourView.bottomAnchor]
]];
Please also check the option for lower version of ios 11 from Krunal's answer.
Convert a JSON String to a HashMap
try this code :
Map<String, String> params = new HashMap<String, String>();
try
{
Iterator<?> keys = jsonObject.keys();
while (keys.hasNext())
{
String key = (String) keys.next();
String value = jsonObject.getString(key);
params.put(key, value);
}
}
catch (Exception xx)
{
xx.toString();
}
C - casting int to char and append char to char
You can use itoa function to convert the integer to a string.
You can use strcat function to append characters in a string at the end of another string.
If you want to convert a integer to a character, just do the following -
int a = 65;
char c = (char) a;
Note that since characters are smaller in size than integer, this casting may cause a loss of data. It's better to declare the character variable as unsigned
in this case (though you may still lose data).
To do a light reading about type conversion, go here.
If you are still having trouble, comment on this answer.
Edit
Go here for a more suitable example of joining characters.
Also some more useful link is given below -
- http://www.cplusplus.com/reference/clibrary/cstring/strncat/
- http://www.cplusplus.com/reference/clibrary/cstring/strcat/
Second Edit
char msg[200];
int msgLength;
char rankString[200];
........... // Your message has arrived
msgLength = strlen(msg);
itoa(rank, rankString, 10); // I have assumed rank is the integer variable containing the rank id
strncat( msg, rankString, (200 - msgLength) ); // msg now contains previous msg + id
// You may loose some portion of id if message length + id string length is greater than 200
Third Edit
Go to this link. Here you will find an implementation of itoa
. Use that instead.
Error: Tablespace for table xxx exists. Please DISCARD the tablespace before IMPORT
Trying to drop the tablespace can give you other errors. For me, I got the following error:
DROP TABLESPACE `tablename`
Error Code: 1478. Table storage engine 'InnoDB' does not support the create option 'TABLESPACE or LOGFILE GROUP'
My solution was to drop the database. This will remove any tablespaces related to it and allow you to create the tables again.
Access the css ":after" selector with jQuery
You can't manipulate :after
, because it's not technically part of the DOM and therefore is inaccessible by any JavaScript. But you can add a new class with a new :after
specified.
CSS:
.pageMenu .active.changed:after {
/* this selector is more specific, so it takes precedence over the other :after */
border-top-width: 22px;
border-left-width: 22px;
border-right-width: 22px;
}
JS:
$('.pageMenu .active').toggleClass('changed');
UPDATE: while it's impossible to directly modify the :after
content, there are ways to read and/or override it using JavaScript. See "Manipulating CSS pseudo-elements using jQuery (e.g. :before and :after)" for a comprehensive list of techniques.
Android getText from EditText field
EditText txt = (EditText)findviewbyid(R.id.txt);
Editable str = txt.getText().toString();
Toast toast = Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG);
toast.show();
Merging Cells in Excel using C#
This solves the issue in the appropriate way
// Merge a row
ws.Cell("B2").Value = "Merged Row(1) of Range (B2:D3)";
ws.Range("B2:D3").Row(1).Merge();
Trying to get PyCharm to work, keep getting "No Python interpreter selected"
If you are using Ubuntu, Python has already been downloaded on your PC.
so, go to -> ctrl + alt + s -> search interpreter
-> go to project interpreter
than select Python 3.6
in the dropdown menu.
Edit: If there is no Python interpreter in drop-down menu, you should click the gear icon that on the right of the drop-down menu --> add
--> select an interpreter
.
(on PyCharm 2018.2.4 Community Edition)
How to execute a program or call a system command from Python
Here are my two cents: In my view, this is the best practice when dealing with external commands...
These are the return values from the execute method...
pass, stdout, stderr = execute(["ls","-la"],"/home/user/desktop")
This is the execute method...
def execute(cmdArray,workingDir):
stdout = ''
stderr = ''
try:
try:
process = subprocess.Popen(cmdArray,cwd=workingDir, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1)
except OSError:
return [False, '', 'ERROR : command(' + ' '.join(cmdArray) + ') could not get executed!']
for line in iter(process.stdout.readline, b''):
try:
echoLine = line.decode("utf-8")
except:
echoLine = str(line)
stdout += echoLine
for line in iter(process.stderr.readline, b''):
try:
echoLine = line.decode("utf-8")
except:
echoLine = str(line)
stderr += echoLine
except (KeyboardInterrupt,SystemExit) as err:
return [False,'',str(err)]
process.stdout.close()
returnCode = process.wait()
if returnCode != 0 or stderr != '':
return [False, stdout, stderr]
else:
return [True, stdout, stderr]
Angular.js: How does $eval work and why is it different from vanilla eval?
From the test,
it('should allow passing locals to the expression', inject(function($rootScope) {
expect($rootScope.$eval('a+1', {a: 2})).toBe(3);
$rootScope.$eval(function(scope, locals) {
scope.c = locals.b + 4;
}, {b: 3});
expect($rootScope.c).toBe(7);
}));
We also can pass locals for evaluation expression.
How to delete columns in numpy.array
Removing Matrix columns that contain NaN.
This is a lengthy answer, but hopefully easy to follow.
def column_to_vector(matrix, i):
return [row[i] for row in matrix]
import numpy
def remove_NaN_columns(matrix):
import scipy
import math
from numpy import column_stack, vstack
columns = A.shape[1]
#print("columns", columns)
result = []
skip_column = True
for column in range(0, columns):
vector = column_to_vector(A, column)
skip_column = False
for value in vector:
# print(column, vector, value, math.isnan(value) )
if math.isnan(value):
skip_column = True
if skip_column == False:
result.append(vector)
return column_stack(result)
### test it
A = vstack(([ float('NaN'), 2., 3., float('NaN')], [ 1., 2., 3., 9]))
print("A shape", A.shape, "\n", A)
B = remove_NaN_columns(A)
print("B shape", B.shape, "\n", B)
A shape (2, 4)
[[ nan 2. 3. nan]
[ 1. 2. 3. 9.]]
B shape (2, 2)
[[ 2. 3.]
[ 2. 3.]]
Getting next element while cycling through a list
After thinking this through carefully, I think this is the best way. It lets you step off in the middle easily without using break
, which I think is important, and it requires minimal computation, so I think it's the fastest. It also doesn't require that li
be a list or tuple. It could be any iterator.
from itertools import cycle
li = [0, 1, 2, 3]
running = True
licycle = cycle(li)
# Prime the pump
nextelem = next(licycle)
while running:
thiselem, nextelem = nextelem, next(licycle)
I'm leaving the other solutions here for posterity.
All of that fancy iterator stuff has its place, but not here. Use the % operator.
li = [0, 1, 2, 3]
running = True
while running:
for idx, elem in enumerate(li):
thiselem = elem
nextelem = li[(idx + 1) % len(li)]
Now, if you intend to infinitely cycle through a list, then just do this:
li = [0, 1, 2, 3]
running = True
idx = 0
while running:
thiselem = li[idx]
idx = (idx + 1) % len(li)
nextelem = li[idx]
I think that's easier to understand than the other solution involving tee
, and probably faster too. If you're sure the list won't change size, you can squirrel away a copy of len(li)
and use that.
This also lets you easily step off the ferris wheel in the middle instead of having to wait for the bucket to come down to the bottom again. The other solutions (including yours) require you check running
in the middle of the for
loop and then break
.
Linking to an external URL in Javadoc?
Javadocs don't offer any special tools for external links, so you should just use standard html:
See <a href="http://groversmill.com/">Grover's Mill</a> for a history of the
Martian invasion.
or
@see <a href="http://groversmill.com/">Grover's Mill</a> for a history of
the Martian invasion.
Don't use {@link ...}
or {@linkplain ...}
because these are for links to the javadocs of other classes and methods.
How to output numbers with leading zeros in JavaScript?
NOTE: Potentially outdated. ECMAScript 2017 includes String.prototype.padStart
.
You'll have to convert the number to a string since numbers don't make sense with leading zeros. Something like this:
function pad(num, size) {
num = num.toString();
while (num.length < size) num = "0" + num;
return num;
}
Or, if you know you'd never be using more than X number of zeros, this might be better. This assumes you'd never want more than 10 digits.
function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
}
If you care about negative numbers you'll have to strip the -
and read it.
Handle file download from ajax post
This is a 3 years old question but I had the same problem today. I looked your edited solution but I think that it can sacrifice the performance because it has to make a double request. So if anyone needs another solution that doesn't imply to call the service twice then this is the way I did it:
<form id="export-csv-form" method="POST" action="/the/path/to/file">
<input type="hidden" name="anyValueToPassTheServer" value="">
</form>
This form is just used to call the service and avoid to use a window.location(). After that you just simply have to make a form submit from jquery in order to call the service and get the file. It's pretty simple but this way you can make a download using a POST. I now that this could be easier if the service you're calling is a GET, but that's not my case.
How to retrieve form values from HTTPPOST, dictionary or?
You could have your controller action take an object which would reflect the form input names and the default model binder will automatically create this object for you:
[HttpPost]
public ActionResult SubmitAction(SomeModel model)
{
var value1 = model.SimpleProp1;
var value2 = model.SimpleProp2;
var value3 = model.ComplexProp1.SimpleProp1;
...
... return something ...
}
Another (obviously uglier) way is:
[HttpPost]
public ActionResult SubmitAction()
{
var value1 = Request["SimpleProp1"];
var value2 = Request["SimpleProp2"];
var value3 = Request["ComplexProp1.SimpleProp1"];
...
... return something ...
}
Send data from javascript to a mysql database
JavaScript, as defined in your question, can't directly work with MySql. This is because it isn't running on the same computer.
JavaScript runs on the client side (in the browser), and databases usually exist on the server side. You'll probably need to use an intermediate server-side language (like PHP, Java, .Net, or a server-side JavaScript stack like Node.js) to do the query.
Here's a tutorial on how to write some code that would bind PHP, JavaScript, and MySql together, with code running both in the browser, and on a server:
http://www.w3schools.com/php/php_ajax_database.asp
And here's the code from that page. It doesn't exactly match your scenario (it does a query, and doesn't store data in the DB), but it might help you start to understand the types of interactions you'll need in order to make this work.
In particular, pay attention to these bits of code from that article.
Bits of Javascript:
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
Bits of PHP code:
mysql_select_db("ajax_demo", $con);
$result = mysql_query($sql);
// ...
$row = mysql_fetch_array($result)
mysql_close($con);
Also, after you get a handle on how this sort of code works, I suggest you use the jQuery JavaScript library to do your AJAX calls. It is much cleaner and easier to deal with than the built-in AJAX support, and you won't have to write browser-specific code, as jQuery has cross-browser support built in. Here's the page for the jQuery AJAX API documentation.
The code from the article
HTML/Javascript code:
<html>
<head>
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
PHP code:
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ajax_demo", $con);
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup
In iOS 5, the Manifest.mbdx file was eliminated. For the purpose of this article, it was redundant anyway, because the domain and path are in Manifest.mbdb and the ID hash can be generated with SHA1.
Here is my update of galloglass's code so it works with backups of iOS 5 devices. The only changes are elimination of process_mbdx_file() and addition of a few lines in process_mbdb_file().
Tested with backups of an iPhone 4S and an iPad 1, both with plenty of apps and files.
#!/usr/bin/env python
import sys
import hashlib
mbdx = {}
def getint(data, offset, intsize):
"""Retrieve an integer (big-endian) and new offset from the current offset"""
value = 0
while intsize > 0:
value = (value<<8) + ord(data[offset])
offset = offset + 1
intsize = intsize - 1
return value, offset
def getstring(data, offset):
"""Retrieve a string and new offset from the current offset into the data"""
if data[offset] == chr(0xFF) and data[offset+1] == chr(0xFF):
return '', offset+2 # Blank string
length, offset = getint(data, offset, 2) # 2-byte length
value = data[offset:offset+length]
return value, (offset + length)
def process_mbdb_file(filename):
mbdb = {} # Map offset of info in this file => file info
data = open(filename).read()
if data[0:4] != "mbdb": raise Exception("This does not look like an MBDB file")
offset = 4
offset = offset + 2 # value x05 x00, not sure what this is
while offset < len(data):
fileinfo = {}
fileinfo['start_offset'] = offset
fileinfo['domain'], offset = getstring(data, offset)
fileinfo['filename'], offset = getstring(data, offset)
fileinfo['linktarget'], offset = getstring(data, offset)
fileinfo['datahash'], offset = getstring(data, offset)
fileinfo['unknown1'], offset = getstring(data, offset)
fileinfo['mode'], offset = getint(data, offset, 2)
fileinfo['unknown2'], offset = getint(data, offset, 4)
fileinfo['unknown3'], offset = getint(data, offset, 4)
fileinfo['userid'], offset = getint(data, offset, 4)
fileinfo['groupid'], offset = getint(data, offset, 4)
fileinfo['mtime'], offset = getint(data, offset, 4)
fileinfo['atime'], offset = getint(data, offset, 4)
fileinfo['ctime'], offset = getint(data, offset, 4)
fileinfo['filelen'], offset = getint(data, offset, 8)
fileinfo['flag'], offset = getint(data, offset, 1)
fileinfo['numprops'], offset = getint(data, offset, 1)
fileinfo['properties'] = {}
for ii in range(fileinfo['numprops']):
propname, offset = getstring(data, offset)
propval, offset = getstring(data, offset)
fileinfo['properties'][propname] = propval
mbdb[fileinfo['start_offset']] = fileinfo
fullpath = fileinfo['domain'] + '-' + fileinfo['filename']
id = hashlib.sha1(fullpath)
mbdx[fileinfo['start_offset']] = id.hexdigest()
return mbdb
def modestr(val):
def mode(val):
if (val & 0x4): r = 'r'
else: r = '-'
if (val & 0x2): w = 'w'
else: w = '-'
if (val & 0x1): x = 'x'
else: x = '-'
return r+w+x
return mode(val>>6) + mode((val>>3)) + mode(val)
def fileinfo_str(f, verbose=False):
if not verbose: return "(%s)%s::%s" % (f['fileID'], f['domain'], f['filename'])
if (f['mode'] & 0xE000) == 0xA000: type = 'l' # symlink
elif (f['mode'] & 0xE000) == 0x8000: type = '-' # file
elif (f['mode'] & 0xE000) == 0x4000: type = 'd' # dir
else:
print >> sys.stderr, "Unknown file type %04x for %s" % (f['mode'], fileinfo_str(f, False))
type = '?' # unknown
info = ("%s%s %08x %08x %7d %10d %10d %10d (%s)%s::%s" %
(type, modestr(f['mode']&0x0FFF) , f['userid'], f['groupid'], f['filelen'],
f['mtime'], f['atime'], f['ctime'], f['fileID'], f['domain'], f['filename']))
if type == 'l': info = info + ' -> ' + f['linktarget'] # symlink destination
for name, value in f['properties'].items(): # extra properties
info = info + ' ' + name + '=' + repr(value)
return info
verbose = True
if __name__ == '__main__':
mbdb = process_mbdb_file("Manifest.mbdb")
for offset, fileinfo in mbdb.items():
if offset in mbdx:
fileinfo['fileID'] = mbdx[offset]
else:
fileinfo['fileID'] = "<nofileID>"
print >> sys.stderr, "No fileID found for %s" % fileinfo_str(fileinfo)
print fileinfo_str(fileinfo, verbose)
How to support different screen size in android
Beginning with Android 3.2 (API level 13), size groups (folders small, normal, large, xlarge) are deprecated in favor of a new technique for managing screen sizes based on the available screen width.
There are different resource configurations that you can specify based on the space available for your layout:
1)
Smallest Width - The fundamental size of a screen, as indicated by the shortest dimension of the available screen area.
Qualifier Value: sw'dp value'dp
Eg. res/sw600dp/layout.xml -> will be used for all screen sizes bigger or equal to 600dp. This does not take the device orientation into account.
2)
Available Screen Width - Specifies a minimum available width in dp units at which the resources should be used.
Qualifier Value: w'dp value'dp
Eg. res/w600dp/layout.xml -> will be used for all screens, which width is greater than or equal to 600dp.
3)
Available Screen Height - Specifies a minimum screen height in dp units at which the resources should be used.
Qualifier Value: h'dp value'dp
Eg. res/h600dp/layout.xml -> will be used for all screens, which height is greater than or equal to 600dp.
So at the end your folder structure might look like this:
res/layout/layout.xml -> for handsets (smaller than 600dp available width)
res/layout-sw600dp/layout.xml -> for 7” tablets (600dp wide and bigger)
res/layout-sw720dp/layout.xml -> for 10” tablets (720dp wide and bigger)
For more information please read the official documentation:
https://developer.android.com/guide/practices/screens_support.html#DeclaringTabletLayouts
Forgot Oracle username and password, how to retrieve?
Go to SQL command line:-
type:
sql>connect / as sysdba;
then type:
sql>desc dba_users;
then type:
sql>select username,password from dba_users;
If sysdba
doesn't work then try connecting with username:scott and password: Tiger
You will be able to see all users with passwords.
Probably you might find your's.
Hope this helps
Nullable property to entity field, Entity Framework through Code First
In Ef .net core there are two options that you can do; first with data annotations:
public class Blog
{
public int BlogId { get; set; }
[Required]
public string Url { get; set; }
}
Or with fluent api:
class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.IsRequired(false)//optinal case
.IsRequired()//required case
;
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
There are more details here
How to get full path of a file?
Beside "readlink -f" , another commonly used command:
$find /the/long/path/but/I/can/use/TAB/to/auto/it/to/ -name myfile
/the/long/path/but/I/can/use/TAB/to/auto/it/to/myfile
$
This also give the full path and file name at console
Off-topic: This method just gives relative links, not absolute. The readlink -f
command is the right one.
Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work
Personally, to deal with empty responses, I use in my Integration Tests the MockMvcResponse object like this :
MockMvcResponse response = RestAssuredMockMvc.given()
.webAppContextSetup(webApplicationContext)
.when()
.get("/v1/ticket");
assertThat(response.mockHttpServletResponse().getStatus()).isEqualTo(HttpStatus.NO_CONTENT.value());
and in my controller I return empty response in a specific case like this :
return ResponseEntity.noContent().build();
get current url in twig template?
{{ path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) }}
If you want to read it into a view variable:
{% set currentPath = path(app.request.attributes.get('_route'),
app.request.attributes.get('_route_params')) %}
The app
global view variable contains all sorts of useful shortcuts, such as app.session
and app.security.token.user
, that reference the services you might use in a controller.
Can Mockito stub a method without regard to the argument?
when(
fooDao.getBar(
any(Bazoo.class)
)
).thenReturn(myFoo);
or (to avoid null
s):
when(
fooDao.getBar(
(Bazoo)notNull()
)
).thenReturn(myFoo);
Don't forget to import matchers (many others are available):
For Mockito 2.1.0 and newer:
import static org.mockito.ArgumentMatchers.*;
For older versions:
import static org.mockito.Matchers.*;
What is the difference between .*? and .* regular expressions?
On greedy vs non-greedy
Repetition in regex by default is greedy: they try to match as many reps as possible, and when this doesn't work and they have to backtrack, they try to match one fewer rep at a time, until a match of the whole pattern is found. As a result, when a match finally happens, a greedy repetition would match as many reps as possible.
The ?
as a repetition quantifier changes this behavior into non-greedy, also called reluctant (in e.g. Java) (and sometimes "lazy"). In contrast, this repetition will first try to match as few reps as possible, and when this doesn't work and they have to backtrack, they start matching one more rept a time. As a result, when a match finally happens, a reluctant repetition would match as few reps as possible.
References
Example 1: From A to Z
Let's compare these two patterns: A.*Z
and A.*?Z
.
Given the following input:
eeeAiiZuuuuAoooZeeee
The patterns yield the following matches:
Let's first focus on what A.*Z
does. When it matched the first A
, the .*
, being greedy, first tries to match as many .
as possible.
eeeAiiZuuuuAoooZeeee
\_______________/
A.* matched, Z can't match
Since the Z
doesn't match, the engine backtracks, and .*
must then match one fewer .
:
eeeAiiZuuuuAoooZeeee
\______________/
A.* matched, Z still can't match
This happens a few more times, until finally we come to this:
eeeAiiZuuuuAoooZeeee
\__________/
A.* matched, Z can now match
Now Z
can match, so the overall pattern matches:
eeeAiiZuuuuAoooZeeee
\___________/
A.*Z matched
By contrast, the reluctant repetition in A.*?Z
first matches as few .
as possible, and then taking more .
as necessary. This explains why it finds two matches in the input.
Here's a visual representation of what the two patterns matched:
eeeAiiZuuuuAoooZeeee
\__/r \___/r r = reluctant
\____g____/ g = greedy
Example: An alternative
In many applications, the two matches in the above input is what is desired, thus a reluctant .*?
is used instead of the greedy .*
to prevent overmatching. For this particular pattern, however, there is a better alternative, using negated character class.
The pattern A[^Z]*Z
also finds the same two matches as the A.*?Z
pattern for the above input (as seen on ideone.com). [^Z]
is what is called a negated character class: it matches anything but Z
.
The main difference between the two patterns is in performance: being more strict, the negated character class can only match one way for a given input. It doesn't matter if you use greedy or reluctant modifier for this pattern. In fact, in some flavors, you can do even better and use what is called possessive quantifier, which doesn't backtrack at all.
References
Example 2: From A to ZZ
This example should be illustrative: it shows how the greedy, reluctant, and negated character class patterns match differently given the same input.
eeAiiZooAuuZZeeeZZfff
These are the matches for the above input:
Here's a visual representation of what they matched:
___n
/ \ n = negated character class
eeAiiZooAuuZZeeeZZfff r = reluctant
\_________/r / g = greedy
\____________/g
Related topics
These are links to questions and answers on stackoverflow that cover some topics that may be of interest.
One greedy repetition can outgreed another
How to Apply Mask to Image in OpenCV?
You don't apply a binary mask to an image. You (optionally) use a binary mask in a processing function call to tell the function which pixels of the image you want to process. If I'm completely misinterpreting your question, you should add more detail to clarify.
How to print a dictionary line by line in Python?
You have a nested structure, so you need to format the nested dictionary too:
for key, car in cars.items():
print(key)
for attribute, value in car.items():
print('{} : {}'.format(attribute, value))
This prints:
A
color : 2
speed : 70
B
color : 3
speed : 60
How to center a subview of UIView
I would use:
child.center = CGPointMake(parent.bounds.height / 2, parent.bounds.width / 2)
This is simple, short, and sweet. If you use @Hejazi's answer above and parent.center
is set to anything other than (0,0)
your subview will not be centered!
Detect if the app was launched/opened from a push notification
Yes, you can detect by this method in appDelegate:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
/* your Code*/
}
For local Notification:
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification
{
/* your Code*/
}
Android: How do I get string from resources using its name?
If you wannt get it inside an activity or fragmnet, then:
getContext().getResources().getString(R.string.string_name);
If you want to get it from a class outside of activity or fragment where you don't have the activity context then use application context:
getApplicationContext().getResources().getString(R.string.string_name);
How to delete columns in a CSV file?
Use of Pandas module will be much easier.
import pandas as pd
f=pd.read_csv("test.csv")
keep_col = ['day','month','lat','long']
new_f = f[keep_col]
new_f.to_csv("newFile.csv", index=False)
And here is short explanation:
>>>f=pd.read_csv("test.csv")
>>> f
day month year lat long
0 1 4 2001 45 120
1 2 4 2003 44 118
>>> keep_col = ['day','month','lat','long']
>>> f[keep_col]
day month lat long
0 1 4 45 120
1 2 4 44 118
>>>
How to ignore files/directories in TFS for avoiding them to go to central source repository?
For VS2015 and VS2017
Works with TFS (on-prem) or VSO (Visual Studio Online - the Azure-hosted offering)
The NuGet documentation provides instructions on how to accomplish this and I just followed them successfully for Visual Studio 2015 & Visual Studio 2017 against VSTS (Azure-hosted TFS). Everything is fully updated as of Nov 2016 Aug 2018.
I recommend you follow NuGet's instructions but just to recap what I did:
- Make sure your
packages
folder is not committed to TFS. If it is, get it out of there.
- Everything else we create below goes into the same folder that your
.sln
file exists in unless otherwise specified (NuGet's instructions aren't completely clear on this).
- Create a
.nuget
folder. You can use Windows Explorer to name it .nuget.
for it to successfully save as .nuget
(it automatically removes the last period) but directly trying to name it .nuget
may not work (you may get an error or it may change the name, depending on your version of Windows).
Or name the directory nuget, and open the parent directory in command line prompt. type. ren nuget .nuget
- Inside of that folder, create a
NuGet.config
file and add the following contents and save it:
NuGet.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<solution>
<add key="disableSourceControlIntegration" value="true" />
</solution>
</configuration>
- Go back in your
.sln
's folder and create a new text file and name it .tfignore
(if using Windows Explorer, use the same trick as above and name it .tfignore.
)
- Put the following content into that file:
.tfignore:
# Ignore the NuGet packages folder in the root of the repository.
# If needed, prefix 'packages' with additional folder names if it's
# not in the same folder as .tfignore.
packages
# include package target files which may be required for msbuild,
# again prefixing the folder name as needed.
!packages/*.targets
- Save all of this, commit it to TFS, then close & re-open Visual Studio and the Team Explorer should no longer identify the packages folder as a pending check-in.
- Copy/pasted via Windows Explorer the
.tfignore
file and .nuget
folder to all of my various solutions and committed them and I no longer have the packages
folder trying to sneak into my source control repo!
Further Customization
While not mine, I have found this .tfignore
template by sirkirby to be handy. The example in my answer covers the Nuget packages
folder but this template includes some other things as well as provides additional examples that can be useful if you wish to customize this further.
Grep regex NOT containing string
grep
matches, grep -v
does the inverse. If you need to "match A but not B" you usually use pipes:
grep "${PATT}" file | grep -v "${NOTPATT}"
How to install a plugin in Jenkins manually
The accepted answer is accurate, but make sure that you also install all necessary dependencies as well. Installing using the CLI or web seems to take care of this, but my plugins were not showing up in the browser or using java -jar jenkins-cli.jar -s http://localhost:8080 list-plugins
until I also installed the dependencies.
writing to existing workbook using xlwt
openpyxl
# -*- coding: utf-8 -*-
import openpyxl
file = 'sample.xlsx'
wb = openpyxl.load_workbook(filename=file)
# Seleciono la Hoja
ws = wb.get_sheet_by_name('Hoja1')
# Valores a Insertar
ws['A3'] = 42
ws['A4'] = 142
# Escribirmos en el Fichero
wb.save(file)
Preventing twitter bootstrap carousel from auto sliding on page load
I think maybe you should go to check the official instruction about carousel, for me, i have not found answer above, because of multiple versions of bootstrap, I'm using b4-alpha and i want the autoplay effect stop.
$(document).ready({
pause:true,
interval:false
});
this script does not make any effect while mouse leave that page, exactly carousel area. go to official definition and find those :
So you will find why.if carousel page onmouseover event triggered, page will pause, while mouse out of that page, it'll resume again.
So, if you want a page stop forever and rotate manually, you can just set data-interval='false'
.
Calculating powers of integers
No, there is not something as short as a**b
Here is a simple loop, if you want to avoid doubles:
long result = 1;
for (int i = 1; i <= b; i++) {
result *= a;
}
If you want to use pow
and convert the result in to integer, cast the result as follows:
int result = (int)Math.pow(a, b);
Python: Remove division decimal
When a number as a decimal it is usually a float
in Python.
If you want to remove the decimal and keep it an integer (int
). You can call the int()
method on it like so...
>>> int(2.0)
2
However, int
rounds down so...
>>> int(2.9)
2
If you want to round to the nearest integer you can use round
:
>>> round(2.9)
3.0
>>> round(2.4)
2.0
And then call int()
on that:
>>> int(round(2.9))
3
>>> int(round(2.4))
2
Difference between Constructor and ngOnInit
constructor() is the default method in the Component life cycle and is used for dependency injection. Constructor is a Typescript Feature.
ngOnInit() is called after the constructor and ngOnInit is called after the first ngOnChanges.
i.e.:
Constructor() --> ngOnChanges() --> ngOnInit()
as mentioned above ngOnChanges()
is called when an input or output binding value changes.
How to run vbs as administrator from vbs?
This is the universal and best solution for this:
If WScript.Arguments.Count <> 1 Then WScript.Quit 1
RunAsAdmin
Main
Sub RunAsAdmin()
Set Shell = CreateObject("WScript.Shell")
Set Env = Shell.Environment("VOLATILE")
If Shell.Run("%ComSpec% /C ""NET FILE""", 0, True) <> 0 Then
Env("CurrentDirectory") = Shell.CurrentDirectory
ArgsList = ""
For i = 1 To WScript.Arguments.Count
ArgsList = ArgsList & """ """ & WScript.Arguments(i - 1)
Next
CreateObject("Shell.Application").ShellExecute WScript.FullName, """" & WScript.ScriptFullName & ArgsList & """", , "runas", 5
WScript.Sleep 100
Env.Remove("CurrentDirectory")
WScript.Quit
End If
If Env("CurrentDirectory") <> "" Then Shell.CurrentDirectory = Env("CurrentDirectory")
End Sub
Sub Main()
'Your code here!
End Sub
Advantages:
1) The parameter injection is not possible.
2) The number of arguments does not change after the elevation to administrator and then you can check them before you elevate yourself.
3) You know for real and immediately if the script runs as an administrator. For example, if you call it from a control panel uninstallation entry, the RunAsAdmin function will not run unnecessarily because in that case you are already an administrator. Same thing if you call it from a script already elevated to administrator.
4) The window is kept at its current size and position, as it should be.
5) The current directory doesn't change after obtained administrative privileges.
Disadvantages: Nobody
isPrime Function for Python Language
def is_prime(n):
if (n==2 or n==3): return True
if(n<=1 or n%2==0 or n%3==0 ): return False
for i in range(6,int((n**0.5)) + 2,6):
if(n%(i-1)==0 or n%(i+1)==0):
return False
return True
PHPExcel auto size column width
If you need to do that on multiple sheets, and multiple columns in each sheet, here is how you can iterate through all of them:
// Auto size columns for each worksheet
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$objPHPExcel->setActiveSheetIndex($objPHPExcel->getIndex($worksheet));
$sheet = $objPHPExcel->getActiveSheet();
$cellIterator = $sheet->getRowIterator()->current()->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(true);
/** @var PHPExcel_Cell $cell */
foreach ($cellIterator as $cell) {
$sheet->getColumnDimension($cell->getColumn())->setAutoSize(true);
}
}
NodeJS w/Express Error: Cannot GET /
Where is your get method for "/"?
Also you cant serve static html directly in Express.First you need to configure it.
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set("view options", {layout: false}); //This one does the trick for rendering static html
app.engine('html', require('ejs').renderFile);
app.use(app.router);
});
Now add your get method.
app.get('/', function(req, res) {
res.render('default.htm');
});
C# Iterating through an enum? (Indexing a System.Array)
You can cast that Array to different types of Arrays:
myEnum[] values = (myEnum[])Enum.GetValues(typeof(myEnum));
or if you want the integer values:
int[] values = (int[])Enum.GetValues(typeof(myEnum));
You can iterate those casted arrays of course :)
Inserting an image with PHP and FPDF
You can use $pdf->GetX()
and $pdf->GetY()
to get current cooridnates and use them to insert image.
$pdf->Image($image1, 5, $pdf->GetY(), 33.78);
or even
$pdf->Image($image1, 5, null, 33.78);
(ALthough in first case you can add a number to create a bit of a space)
$pdf->Image($image1, 5, $pdf->GetY() + 5, 33.78);
How to mock private method for testing using PowerMock?
A generic solution that will work with any testing framework (if your class is non-final
) is to manually create your own mock.
- Change your private method to protected.
- In your test class extend the class
- override the previously-private method to return whatever constant you want
This doesn't use any framework so its not as elegant but it will always work: even without PowerMock. Alternatively, you can use Mockito to do steps #2 & #3 for you, if you've done step #1 already.
To mock a private method directly, you'll need to use PowerMock as shown in the other answer.
CSS - make div's inherit a height
The Problem
When an element is floated, its parent no longer contains it because the float is removed from the flow. The floated element is out of the natural flow, so all block elements will render as if the floated element is not even there, so a parent container will not fully expand to hold the floated child element.
Take a look at the following article to get a better idea of how the CSS Float property works:
The Mystery Of The CSS Float Property
A Potential Solution
Now, I think the following article resembles what you're trying to do. Take a look at it and see if you can solve your problem.
Equal Height Columns with Cross-Browser CSS
I hope this helps.
How do I implement a callback in PHP?
With PHP 5.3, you can now do this:
function doIt($callback) { $callback(); }
doIt(function() {
// this will be done
});
Finally a nice way to do it. A great addition to PHP, because callbacks are awesome.
Change marker size in Google maps V3
This answer expounds on John Black's helpful answer, so I will repeat some of his answer content in my answer.
The easiest way to resize a marker seems to be leaving argument 2, 3, and 4 null and scaling the size in argument 5.
var pinIcon = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FFFF00",
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(42, 68)
);
As an aside, this answer to a similar question asserts that defining marker size in the 2nd argument is better than scaling in the 5th argument. I don't know if this is true.
Leaving arguments 2-4 null works great for the default google pin image, but you must set an anchor explicitly for the default google pin shadow image, or it will look like this:
The bottom center of the pin image happens to be collocated with the tip of the pin when you view the graphic on the map. This is important, because the marker's position property (marker's LatLng position on the map) will automatically be collocated with the visual tip of the pin when you leave the anchor (4th argument) null
. In other words, leaving the anchor null ensures the tip points where it is supposed to point.
However, the tip of the shadow is not located at the bottom center. So you need to set the 4th argument explicitly to offset the tip of the pin shadow so the shadow's tip will be colocated with the pin image's tip.
By experimenting I found the tip of the shadow should be set like this: x is 1/3 of size and y is 100% of size.
var pinShadow = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
null,
null,
/* Offset x axis 33% of overall size, Offset y axis 100% of overall size */
new google.maps.Point(40, 110),
new google.maps.Size(120, 110));
to give this:
Input and Output binary streams using JERSEY?
I had to return a rtf file and this worked for me.
// create a byte array of the file in correct format
byte[] docStream = createDoc(fragments);
return Response
.ok(docStream, MediaType.APPLICATION_OCTET_STREAM)
.header("content-disposition","attachment; filename = doc.rtf")
.build();
gridview data export to excel in asp.net
Something else to check is make sure viewstate is on (I just solved this yesterday). If you don't have viewstate on, the gridview will be blank until you load it again.
How to add a scrollbar to an HTML5 table?
This is technique I have used on a number of occasions. It is originally based on this fiddle with a number of modifications. It is also fluid and column widths can be fixed by adding a width style to the <th>
.
_x000D_
_x000D_
/* this is for the main container of the table, also sets the height of the fixed header row */_x000D_
.headercontainer {_x000D_
position: relative;_x000D_
border: 1px solid #222;_x000D_
padding-top: 37px;_x000D_
background: #000;_x000D_
}_x000D_
/* this is for the data area that is scrollable */_x000D_
.tablecontainer {_x000D_
overflow-y: auto;_x000D_
height: 200px;_x000D_
background: #fff;_x000D_
}_x000D_
_x000D_
/* remove default cell borders and ensures table width 100% of its container*/_x000D_
.tablecontainer table {_x000D_
border-spacing: 0;_x000D_
width:100%;_x000D_
}_x000D_
_x000D_
/* add a thin border to the left of cells, but not the first */_x000D_
.tablecontainer td + td {_x000D_
border-left:1px solid #eee; _x000D_
}_x000D_
_x000D_
/* cell padding and bottom border */_x000D_
.tablecontainer td, th {_x000D_
border-bottom:1px solid #eee;_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
/* make the default header height 0 and make text invisible */_x000D_
.tablecontainer th {_x000D_
height: 0px;_x000D_
padding-top: 0;_x000D_
padding-bottom: 0;_x000D_
line-height: 0;_x000D_
visibility: hidden;_x000D_
white-space: nowrap;_x000D_
}_x000D_
_x000D_
/* reposition the divs in the header cells and place in the blank area of the headercontainer */_x000D_
.tablecontainer th div{_x000D_
visibility: visible;_x000D_
position: absolute;_x000D_
background: #000;_x000D_
color: #fff;_x000D_
padding: 9px 10px;_x000D_
top: 0;_x000D_
margin-left: -10px;_x000D_
line-height: normal;_x000D_
border-left: 1px solid #222;_x000D_
}_x000D_
/* prevent the left border from above appearing in first div header */_x000D_
th:first-child div{_x000D_
border: none;_x000D_
}_x000D_
_x000D_
/* alternate colors for rows */_x000D_
.tablecontainer tbody tr:nth-child(even){_x000D_
background-color: #ddd;_x000D_
}
_x000D_
<div class="headercontainer">_x000D_
<div class="tablecontainer">_x000D_
<table>_x000D_
<thead>_x000D_
<tr>_x000D_
<th>_x000D_
Table attribute name_x000D_
<div>Table attribute name</div>_x000D_
</th>_x000D_
<th>_x000D_
Value_x000D_
<div>Value</div>_x000D_
</th>_x000D_
<th>_x000D_
Description_x000D_
<div>Description</div>_x000D_
</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>align</td>_x000D_
<td>left, center, right</td>_x000D_
<td>Not supported in HTML5. Deprecated in HTML 4.01. Specifies the alignment of a table according to surrounding text</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>bgcolor</td>_x000D_
<td>rgb(x,x,x), #xxxxxx, colorname</td>_x000D_
<td>Not supported in HTML5. Deprecated in HTML 4.01. Specifies the background color for a table</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>border</td>_x000D_
<td>1,""</td>_x000D_
<td>Specifies whether the table cells should have borders or not</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>cellpadding</td>_x000D_
<td>pixels</td>_x000D_
<td>Not supported in HTML5. Specifies the space between the cell wall and the cell content</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>cellspacing</td>_x000D_
<td>pixels</td>_x000D_
<td>Not supported in HTML5. Specifies the space between cells</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>frame</td>_x000D_
<td>void, above, below, hsides, lhs, rhs, vsides, box, border</td>_x000D_
<td>Not supported in HTML5. Specifies which parts of the outside borders that should be visible</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>rules</td>_x000D_
<td>none, groups, rows, cols, all</td>_x000D_
<td>Not supported in HTML5. Specifies which parts of the inside borders that should be visible</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>summary</td>_x000D_
<td>text</td>_x000D_
<td>Not supported in HTML5. Specifies a summary of the content of a table</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>width</td>_x000D_
<td>pixels, %</td>_x000D_
<td>Not supported in HTML5. Specifies the width of a table</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Also as a JSFiddle
How to solve java.lang.NoClassDefFoundError?
Don't use test classes outside the module
I do not have a solution, just another flavour of the "present at compilation, absent at run time" case.
I was trying to use a very convenient method from a JUnit test class from another test class which resides in a different module. That's a no-no, since test code is not part of the packaged jar, but I didn't realize because it appears visible for the user class from within Eclipse.
My solution was to place the method in a existing utilities class that is part of the production code.