from http://www.vmware.com/products/player/faqs.html:
How does VMware Player compare to VMware Workstation? VMware Player enables you to quickly and easily create and run virtual machines. However, VMware Player lacks many powerful features, remote connections to vSphere, drag and drop upload to vSphere, multiple Snapshots and Clones, and much more.
Not being able to revert snapshots it's a big no for me.
For razor you can use: culture, value
@String.Format(new CultureInfo("sv-SE"), @Model.value)
You can use %%~nf
to get the filename only as described in the reference for for
:
@echo off
for /R "C:\Users\Admin\Ordner" %%f in (*.flv) do (
echo %%~nf
)
pause
The following options are available:
Variable with modifier Description %~I Expands %I which removes any surrounding quotation marks (""). %~fI Expands %I to a fully qualified path name. %~dI Expands %I to a drive letter only. %~pI Expands %I to a path only. %~nI Expands %I to a file name only. %~xI Expands %I to a file extension only. %~sI Expands path to contain short names only. %~aI Expands %I to the file attributes of file. %~tI Expands %I to the date and time of file. %~zI Expands %I to the size of file. %~$PATH:I Searches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, this modifier expands to the empty string.
We can do that with two way:
1- First create a new object and replicate the structure of the existing one by iterating
over its properties and copying them on the primitive level.
let user = {
name: "John",
age: 30
};
let clone = {}; // the new empty object
// let's copy all user properties into it
for (let key in user) {
clone[key] = user[key];
}
// now clone is a fully independant clone
clone.name = "Pete"; // changed the data in it
alert( user.name ); // still John in the original object
2- Second we can use the method Object.assign for that
let user = { name: "John" };
let permissions1 = { canView: true };
let permissions2 = { canEdit: true };
// copies all properties from permissions1 and permissions2 into user
Object.assign(user, permissions1, permissions2);
-Another example
let user = {
name: "John",
age: 30
};
let clone = Object.assign({}, user);
It copies all properties of user into the empty object and returns it. Actually, the same as the loop, but shorter.
But Object.assign() not create a deep clone
let user = {
name: "John",
sizes: {
height: 182,
width: 50
}
};
let clone = Object.assign({}, user);
alert( user.sizes === clone.sizes ); // true, same object
// user and clone share sizes
user.sizes.width++; // change a property from one place
alert(clone.sizes.width); // 51, see the result from the other one
To fix that, we should use the cloning loop that examines each value of user[key] and, if it’s an object, then replicate its structure as well. That is called a “deep cloning”.
There’s a standard algorithm for deep cloning that handles the case above and more complex cases, called the Structured cloning algorithm. In order not to reinvent the wheel, we can use a working implementation of it from the JavaScript library lodash the method is called _.cloneDeep(obj).
You can use this simple method
function reloadFrame(iFrame) {
iFrame.parentNode.replaceChild(iFrame.cloneNode(), iFrame);
}
There is an option “unlimited scrollback buffer” which you can find under Preferences > Profiles > Terminal
or you can just pump up number of lines that you want to have in history in the same place.
Convert your x-axis data from text to datetime.datetime
, use datetime.strptime
:
>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
datetime.datetime(2012, 5, 31, 19, 0)
This is an example of how to plot data once you have an array of datetimes:
import matplotlib.pyplot as plt
import datetime
import numpy as np
x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)
plt.plot(x,y)
plt.show()
To set flashdata you need to redirect controller function
$this->session->set_flashdata('message_name', 'This is test message');
//redirect to some function
redirect("controller/function_name");
//echo in view or controller
$this->session->flashdata('message_name');
How about this one ? Simple and straightforward.
def is_list_sorted(al):
llength =len(al)
for i in range (llength):
if (al[i-1] > al[i]):
print(al[i])
print(al[i+1])
print('Not sorted')
return -1
else :
print('sorted')
return true
I agree with Justin, and the WhiteSpace CHAR can be referenced using ASCII codes here Character number 32 represents a white space, Therefore:
string.Empty.PadRight(totalLength, (char)32);
An alternative approach: Create all spaces manually within a custom method and call it:
private static string GetSpaces(int totalLength)
{
string result = string.Empty;
for (int i = 0; i < totalLength; i++)
{
result += " ";
}
return result;
}
And call it in your code to create white spaces: GetSpaces(14);
Authentication is the process of verifying the proclaimed identity.
Usually followed by authorization, which is the approval that you can do this and that.
Use count(d.ertek)
or count(d.id)
instead of count(d)
. This can be happen when you have composite primary key at your entity.
A credit card number is not a bunch of random numbers. There is a formula for checking if it is correct.
After a quick Google search I found this JavaScript which will check a credit card number to be valid.
http://javascript.internet.com/forms/credit-card-number-validation.html
URL Broken: Internet archive: http://web.archive.org/web/20100129174150/http://javascript.internet.com/forms/credit-card-number-validation.html?
<!-- TWO STEPS TO INSTALL CREDIT CARD NUMBER VALIDATION:
1. Copy the code into the HEAD of your HTML document
2. Add the last code into the BODY of your HTML document -->
<!-- STEP ONE: Paste this code into the HEAD of your HTML document -->
<HEAD>
<script type="text/javascript">
<!--
/* This script and many more are available free online at
The JavaScript Source!! http://javascript.internet.com
Created by: David Leppek :: https://www.azcode.com/Mod10
Basically, the algorithm takes each digit, from right to left and muliplies each second
digit by two. If the multiple is two-digits long (i.e.: 6 * 2 = 12) the two digits of
the multiple are then added together for a new number (1 + 2 = 3). You then add up the
string of numbers, both unaltered and new values and get a total sum. This sum is then
divided by 10 and the remainder should be zero if it is a valid credit card. Hense the
name Mod 10 or Modulus 10.
*/
function Mod10(ccNumb) { // v2.0
var valid = "0123456789" // Valid digits in a credit card number
var len = ccNumb.length; // The length of the submitted cc number
var iCCN = parseInt(ccNumb); // Integer of ccNumb
var sCCN = ccNumb.toString(); // String of ccNumb
sCCN = sCCN.replace (/^\s+|\s+$/g,''); // Strip spaces
var iTotal = 0; // Integer total set at zero
var bNum = true; // By default assume it is a number
var bResult = false; // By default assume it is NOT a valid cc
var temp; // Temporary variable for parsing string
var calc; // Used for calculation of each digit
// Determine if the ccNumb is in fact all numbers
for (var j=0; j<len; j++) {
temp = "" + sCCN.substring(j, j+1);
if (valid.indexOf(temp) == "-1"){
bNum = false;
}
}
// If it is NOT a number, you can either alert to the fact, or just pass a failure
if (!bNum) {
/* alert("Not a Number"); */
bResult = false;
}
// Determine if it is the proper length
if ((len == 0) && (bResult)) { // Nothing, the field is blank AND passed above # check
bResult = false;
}
else { // ccNumb is a number and the proper length - let's
// see if it is a valid card number
if (len >= 15) { // 15 or 16 for Amex or V/MC
for (var i=len;i>0;i--) { // LOOP through the digits of the card
calc = parseInt(iCCN) % 10; // Right most digit
calc = parseInt(calc); // Assure it is an integer
iTotal += calc; // Running total of the card number as we loop - Do Nothing to first digit
i--; // Decrement the count - move to the next digit in the card
iCCN = iCCN / 10; // Subtracts right most digit from ccNumb
calc = parseInt(iCCN) % 10; // NEXT right most digit
calc = calc *2; // multiply the digit by two
// Instead of some screwy method of converting 16 to a string
// and then parsing 1 and 6 and then adding them to make 7,
// I use a simple switch statement to change the value
// of calc2 to 7 if 16 is the multiple.
switch(calc) {
case 10: calc = 1; break; // 5*2=10 & 1+0 = 1
case 12: calc = 3; break; // 6*2=12 & 1+2 = 3
case 14: calc = 5; break; // 7*2=14 & 1+4 = 5
case 16: calc = 7; break; // 8*2=16 & 1+6 = 7
case 18: calc = 9; break; // 9*2=18 & 1+8 = 9
default: calc = calc; // 4*2= 8 & 8 = 8 - the same for all lower numbers
}
iCCN = iCCN / 10; // Subtracts right most digit from ccNum
iTotal += calc; // Running total of the card number as we loop
} // END OF LOOP
if ((iTotal%10)==0){ // Check to see if the sum Mod 10 is zero
bResult = true; // This IS (or could be) a valid credit card number.
}
else {
bResult = false; // This could NOT be a valid credit card number
}
}
}
// Change alert to on-page display or other indication as needed.
if (bResult) {
alert("This IS a valid Credit Card Number!");
}
if (!bResult) {
alert("This is NOT a valid Credit Card Number!");
}
return bResult; // Return the results
}
// -->
</script>
</HEAD>
<!-- STEP TWO: Copy this code into the BODY of your HTML document -->
<BODY>
<div align="center">
<form name="Form1">
<table width="50%" border="0" cellspacing="0" cellpadding="5">
<tr>
<td width="50%" align="right">Credit Card Number: </td>
<td width="50%">
<input name="CreditCard" type="text" value="4012888888881881" size="18" maxlength="16" style="border: 1px solid #000098; padding: 3px;">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="button" name="Button" style="color: #fff; background: #000098; font-weight:bold; border: solid 1px #000;" value="TEST CARD NUMBER" onClick="return Mod10(document.Form1.CreditCard.value);">
</td>
</tr>
</table>
</form>
</div>
<p><center>
<font face="arial, helvetica" size"-2">Free JavaScripts provided<br>
by <a href="http://javascriptsource.com">The JavaScript Source</a></font>
</center><p>
<!-- Script Size: 4.97 KB -->
it clears stdin
buffer before reading. From the man page:
For output streams, fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function. For input streams, fflush() discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application.
Note: This is Linux-specific, using fflush()
on input streams is undefined by the standard, however, most implementations behave the same as in Linux.
If you have problems with accessing to the path, maybe you need to put this:
$root = $_SERVER['DOCUMENT_ROOT'];
$path = "/cv/";
// Open the folder
$dir_handle = @opendir($root . $path) or die("Unable to open $path");
If you are using PHP version 5.3 or higher you can do the following:
$host= gethostname();
$ip = gethostbyname($host);
This works well when you are running a stand-alone script, not running through the web server.
WITH CTE AS (
SELECT
rownum = ROW_NUMBER() OVER (ORDER BY columns_to_order_by),
value
FROM table
)
SELECT
curr.value - prev.value
FROM CTE cur
INNER JOIN CTE prev on prev.rownum = cur.rownum - 1
This is an old question, anyway today the best practice is by using Object.defineProperty
const object1 = {};
Object.defineProperty(object1, 'property1', {
value: 42,
writable: false
});
object1.property1 = 77;
// throws an error in strict mode
console.log(object1.property1);
// expected output: 42
The org.apache.commons.text.StringSubstitutor helper class from Apache Commons Text provides named variable substitution
Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String resolved = new StringSubstitutor(valuesMap).replace("The ${animal} jumped over the ${target}.");
System.out.println(resolved); // The quick brown fox jumped over the lazy dog.
In our codebase; we typically declare enums in the class that they belong to.
So for your Fruit example, We would have a Fruit class, and inside that an Enum called Fruits.
Referencing it in the code looks like this: Fruit.Fruits.Apple, Fruit.Fruits.Pear
, etc.
Constants follow along the same line, where they either get defined in the class to which they're relevant (so something like Fruit.ORANGE_BUSHEL_SIZE
); or if they apply system-wide (i.e. an equivalent "null value" for ints) in a class named "ConstantManager" (or equivalent; like ConstantManager.NULL_INT
). (side note; all our constants are in upper case)
As always, your coding standards probably differ from mine; so YMMV.
Can you make and edit a collection of objects from an enum? Yes.
If you do not care about the order, use EnumSet
, an implementation of Set
.
enum Animal{ DOG , CAT , BIRD , BAT ; }
Set<Animal> flyingAnimals = EnumSet.of( BIRD , BAT );
Set<Animal> featheredFlyingAnimals = flyingAnimals.clone().remove( BAT ) ;
If you care about order, use a List
implementation such as ArrayList
. For example, we can create a list of a person’s preference in choosing a pet, in the order of their most preferred.
List< Animal > favoritePets = new ArrayList<>() ;
favoritePets.add( CAT ) ; // This person prefers cats over dogs…
favoritePets.add( DOG ) ; // …but would accept either.
// This person would not accept a bird nor a bat.
For a non-modifiable ordered list, use List.of
.
List< Animal > favoritePets = List.of( CAT , DOG ) ; // This person prefers cats over dogs, but would accept either. This person would not accept a bird nor a bat.
The Answer (EnumSet
) by Amit Deshpande and the Answer (.values
) by Marko Topolnik are both correct. Here is a bit more info.
Enum.values
The .values()
method is an implicitly declared method on Enum
, added by the compiler. It produces a crude array rather than a Collection
. Certainly usable.
Special note about documentation: Being unusual as an implicitly declared method, the .values()
method is not listed among the methods on the Enum
class. The method is defined in the Java Language Specification, and is mentioned in the doc for Enum.valueOf
.
EnumSet
– Fast & SmallThe upsides to EnumSet
include:
To quote the class doc:
Enum sets are represented internally as bit vectors. This representation is extremely compact and efficient. The space and time performance of this class should be good enough to allow its use as a high-quality, typesafe alternative to traditional int-based "bit flags." Even bulk operations (such as containsAll and retainAll) should run very quickly if their argument is also an enum set.
Given this enum:
enum Animal
{
DOG , CAT , BIRD , BAT ;
}
Make an EnumSet
in one line.
Set<Animal> allAnimals = EnumSet.allOf( Animal.class );
Dump to console.
System.out.println( "allAnimals : " + allAnimals );
allAnimals : [DOG, CAT, BIRD, BAT]
Make a set from a subset of the enum objects.
Set<Animal> flyingAnimals = EnumSet.of( BIRD , BAT );
Look at the class doc to see many ways to manipulate the collection including adding or removing elements.
Set<Animal> featheredFlyingAnimals =
EnumSet.copyOf( flyingAnimals ).remove( BAT );
The doc promises the Iterator for EnumSet is in natural order, the order in which the values of the enum were originally declared.
To quote the class doc:
The iterator returned by the iterator method traverses the elements in their natural order (the order in which the enum constants are declared).
Frankly, given this promise, I'm confused why this is not a SortedSet
. But, oh well, good enough. We can create a List
from the Set
if desired. Pass any Collection
to constructor of ArrayList
and that collection’s Iterator
is automatically called on your behalf.
List<Animal> list = new ArrayList<>( allAnimals );
Dump to console.
System.out.println("list : " + list );
When run.
list : [DOG, CAT, BIRD, BAT]
In Java 10 and later, you can conveniently create a non-modifiable List
by passing the EnumSet
. The order of the new list will be in the iterator order of the EnumSet
. The iterator order of an EnumSet
is the order in which the element objects of the enum were defined on that enum.
List< Animal > nonModList = List.copyOf( allAnimals ) ; // Or pass Animals.values()
Investigate what is your EOL, \n or \r\n. Then replace .*#region.*\r\n
with nothing in regexpr mode.
It's been more than 10 years and not sure if anyone still finding this question or answer relevant.
But a quick workaround is just to wrap the asp control
within a html container
<div id="myElement" style="display: inline-block">
<asp:TextBox ID="textBox1" runat="server"></asp:TextBox>
</div>
Whenever the Javascript Event
is triggered, if it needs to be an event by the asp control
, just wrap the asp control
around the div
container.
<div id="testG">
<asp:Button ID="Button2" runat="server" CssClass="btn" Text="Activate" />
</div>
The jQuery Code is below:
$(document).ready(function () {
$("#testG").click(function () {
$("#myElement").css("display", "none");
});
});
You can use the u
button to undo the last modification. (And Ctrl+R to redo it).
Read more about it at: http://vim.wikia.com/wiki/Undo_and_Redo
If you are still getting that error after installing the 64 bit JRE, it means that the JVM running Gurobi package is still using the 32 bit JRE.
Check that you have updated the PATH and JAVA_HOME globally and in the command shell that you are using. (Maybe you just need to exit and restart it.)
Check that your command shell runs the right version of Java by running "java -version" and checking that it says it is a 64bit JRE.
If you are launching the example via a wrapper script / batch file, make sure that the script is using the right JRE. Modify as required ...
Here is another solution (only relevant declarations listed):
.text span {
display:inline-block;
margin-right:100%;
}
When the margin is expressed in percentage, that percentage is taken from the width of the parent node, so 100% means as wide as the parent, which results in the next element getting "pushed" to a new line.
Thank you drifty0pine!
The first solution, it´s works!
[a relative link](../../some/dir/filename.md)
[Link to file in another dir on same drive](/another/dir/filename.md)
[Link to file in another dir on a different drive](/D:/dir/filename.md)
but I had need put more ../
until the folder where was my file, like this:
[FileToOpen](../../../../folderW/folderX/folderY/folderZ/FileToOpen.txt)
I just started yesterday on Windows 7 and was facing the same problem. The easiest solution, I found and is working for me is to use the low config device in the emulator. I used Nexus One instead of Nexus 7 and select the snapshot for the device in Android Virtual Device.
And, also important is to leave open the emulator. It works both in Eclipse and Android Studio.
In a window, it says snapshot does not generally work when RAM is more than ~700. So, selecting a lower configured one easily help to test Hello World and then for developing your application. Later, we can test on a high-end device.
For me, virtualization support does not work as my hardware does not support it.
@media (max-width: @iphone-screen) {
background-attachment:inherit;
background-size:cover;
-webkit-background-size:cover;
}
override func viewWillAppear(animated: Bool) {
self.tableView.tableFooterView = UIView(frame: CGRect.zeroRect)
/// OR
self.tableView.tableFooterView = UIView()
}
If you want to add SSL in your test environment, then you can use mkcert
. Below I mentioned the GitHub URL.
https://github.com/FiloSottile/mkcert
And also below I mentioned sample nginx configuration for reverse proxy.
server {
listen 80;
server_name test.local;
return 301 https://test.local$request_uri;
}
server {
listen 443 ssl;
server_name test.local;
ssl_certificate /etc/nginx/ssl/test.local.pem;
ssl_certificate_key /etc/nginx/ssl/test.local-key.pem;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Client-Verify SUCCESS;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_pass http://localhost:3000;
proxy_redirect off;
proxy_buffering off;
}
}
Note: I know this is a hack, but it was useful for Angular 1.2 and earlier that didn't provide a simple mechanism.
The validation kicks in on the change event, so some things like changing the values programmatically won't trigger it. But triggering the change event will trigger the validation. For example, with jQuery:
$('#formField1, #formField2').trigger('change');
to make it as globally reuse function using jquery
HTML
<select class="select_location">
<option value="http://localhost.com/app/page1.html">Page 1</option>
<option value="http://localhost.com/app/page2.html">Page 2</option>
<option value="http://localhost.com/app/page3.html">Page 3</option>
</select>
Javascript using jquery
$('.select_location').on('change', function(){
window.location = $(this).val();
});
now you will able to reuse this function by adding .select_location class to any Select element class
I realize this question was asked nearly 7 years ago but it's still a top Google search result for certain keywords regarding importing excel data with C#, so I wanted to provide an alternative based on some recent tech developments.
Importing Excel data has become such a common task to my everyday duties, that I've streamlined the process and documented the method on my blog: best way to read excel file in c#.
I use NPOI because it can read/write Excel files without Microsoft Office installed and it doesn't use COM+ or any interops. That means it can work in the cloud!
But the real magic comes from pairing up with NPOI Mapper from Donny Tian because it allows me to map the Excel columns to properties in my C# classes without writing any code. It's beautiful.
Here is the basic idea:
I create a .net class that matches/maps the Excel columns I'm interested in:
class CustomExcelFormat
{
[Column("District")]
public int District { get; set; }
[Column("DM")]
public string FullName { get; set; }
[Column("Email Address")]
public string EmailAddress { get; set; }
[Column("Username")]
public string Username { get; set; }
public string FirstName
{
get
{
return Username.Split('.')[0];
}
}
public string LastName
{
get
{
return Username.Split('.')[1];
}
}
}
Notice, it allows me to map based on column name if I want to!
Then when I process the excel file all I need to do is something like this:
public void Execute(string localPath, int sheetIndex)
{
IWorkbook workbook;
using (FileStream file = new FileStream(localPath, FileMode.Open, FileAccess.Read))
{
workbook = WorkbookFactory.Create(file);
}
var importer = new Mapper(workbook);
var items = importer.Take<CustomExcelFormat>(sheetIndex);
foreach(var item in items)
{
var row = item.Value;
if (string.IsNullOrEmpty(row.EmailAddress))
continue;
UpdateUser(row);
}
DataContext.SaveChanges();
}
Now, admittedly, my code does not modify the Excel file itself. I am instead saving the data to a database using Entity Framework (that's why you see "UpdateUser" and "SaveChanges" in my example). But there is already a good discussion on SO about how to save/modify a file using NPOI.
Untested. Modify to suit:
$form = $('#my-form');
$rows = $form.find('.person-input-row');
$('button#add-new').click(function() {
$rows.find(':first').clone().insertAfter($rows.find(':last'));
$justInserted = $rows.find(':last');
$justInserted.hide();
$justInserted.find('input').val(''); // it may copy values from first one
$justInserted.slideDown(500);
});
This is better than copying innerHTML because you will lose all attached events etc.
The best way to do it is:
return this.StatusCode(StatusCodes.Status418ImATeapot, "Error message");
'StatusCodes' has every kind of return status and you can see all of them in this link https://httpstatuses.com/
Once you choose your StatusCode, return it with a message.
In the code of the button that saves the changes to the database eg the update button, add the following lines of code:
MyDataGridView.DataSource = MyTableBindingSource
MyDataGridView.Update()
MyDataGridView.RefreshEdit()
public static boolean isNumeric(String string) {
if (string == null || string.isEmpty()) {
return false;
}
int i = 0;
int stringLength = string.length();
if (string.charAt(0) == '-') {
if (stringLength > 1) {
i++;
} else {
return false;
}
}
if (!Character.isDigit(string.charAt(i))
|| !Character.isDigit(string.charAt(stringLength - 1))) {
return false;
}
i++;
stringLength--;
if (i >= stringLength) {
return true;
}
for (; i < stringLength; i++) {
if (!Character.isDigit(string.charAt(i))
&& string.charAt(i) != '.') {
return false;
}
}
return true;
}
Via the page Git Submodule Tutorial:
To remove a submodule you need to:
.gitmodules
file..gitmodules
changes:git add .gitmodules
.git/config
.git rm --cached path_to_submodule
(no trailing slash)..git
directory:rm -rf .git/modules/path_to_submodule
git commit -m "Removed submodule <name>"
rm -rf path_to_submodule
See also: alternative steps below.
.block1 {_x000D_
color: red;_x000D_
width: 100px;_x000D_
border: 1px solid green;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.block2 {_x000D_
color: blue;_x000D_
width: 70px;_x000D_
border: 2px solid black;_x000D_
position: absolute;_x000D_
top: 0px;_x000D_
right: 0px;_x000D_
}
_x000D_
<div class='block1'>_x000D_
<p>text</p>_x000D_
<p>text2</p>_x000D_
<div class='block2'>block2</div>_x000D_
</div>
_x000D_
Should do it. Assuming you don't need it to flow.
If you are using pdo, it will look like
$sql = "UPDATE users SET firstname = :firstname, lastname = :lastname WHERE id= :id";
$query = $this->pdo->prepare($sql);
$result = $query->execute(array(':firstname' => $firstname, ':lastname' => $lastname, ':id' => $id));
For this purpose you need to match the location in your apache or any other service you are using
If you are using apache then in httpd.conf file.
<LocationMatch "/your_relative_path">
ProxyPass absolute_path_of_your_application/your_relative_path
ProxyPassReverse absolute_path_of_your_application/your_relative_path
</LocationMatch>
Go to Xcode
-> Project Settings
You can find the way to go to derived Data
If you need the result to be timezone-aware, you can use the replace()
method of datetime
objects. This preserves timezone, so you can do
>>> from django.utils import timezone
>>> now = timezone.now()
>>> now
datetime.datetime(2018, 8, 30, 14, 15, 43, 726252, tzinfo=<UTC>)
>>> now.replace(hour=0, minute=0, second=0, microsecond=0)
datetime.datetime(2018, 8, 30, 0, 0, tzinfo=<UTC>)
Note that this returns a new datetime object -- now
remains unchanged.
You should not map score to player. You should map player (or his name) to score:
Map<Player, Integer> player2score = new HashMap<Player, Integer>();
Then add players to map: int score = .... Player player = new Player(); player.setName("John"); // etc. player2score.put(player, score);
In this case the task is trivial:
int score = player2score.get(player);
The easiest way to do so is using jQuery and animate.css animation library.
Javascript
/* --- Show DIV --- */
$( '.example' ).removeClass( 'fadeOutRight' ).show().addClass( 'fadeInRight' );
/* --- Hide DIV --- */
$( '.example' ).removeClass( 'fadeInRight' ).addClass( 'fadeOutRight' );
HTML
<div class="example">Some text over here.</div>
Easy enough to implement. Just don't forget to include the animate.css file in the header :)
Go to File -> Settings -> Editor -> Auto Import -> Java and make the below things:
Select Insert imports on paste value to All
Do tick mark on Add unambigious imports on the fly option and "Optimize imports on the fly*
if anyone want to add a value inside loop then you can use this its working 100%
{% set ftotal= {'total': 0} %}
{%- for pe in payment_entry -%}
{% if ftotal.update({'total': ftotal.total + 5}) %}{% endif %}
{%- endfor -%}
{{ftotal.total}}
output = 5
This method Appends the specified element to the end of this list.
add(E e) //append element to the end of the arraylist.
This method Inserts the specified element at the specified position in this list.
void add(int index, E element) //inserts element at the given position in the array list.
This method Replaces the element at the specified position in this list with the specified element.
set(int index, E element) //Replaces the element at the specified position in this list with the specified element.
Edit 2018: Please look into Object getters and setters and Proxies. Old answer below:
a quick and easy solution goes like this:
var something=999;
var something_cachedValue=something;
function doStuff() {
if(something===something_cachedValue) {//we want it to match
setTimeout(doStuff, 50);//wait 50 millisecnds then recheck
return;
}
something_cachedValue=something;
//real action
}
doStuff();
Specify the maxrecursion option at the end of the query:
...
from EmployeeTree
option (maxrecursion 0)
That allows you to specify how often the CTE can recurse before generating an error. Maxrecursion 0 allows infinite recursion.
With Named arguments:
@Html.ActionLink(linkText: "TestTab", actionName: "TestAction", controllerName: "TestController", routeValues: null, htmlAttributes: new { target = "_blank"})
Download the latest build from https://github.com/macvim-dev/macvim/releases
Expand the archive.
Put MacVim.app into /Applications/
.
Done.
It's /public_html/stats/*
.
$ ~/myrepo> ls public_html/stats/
bar baz foo
$ ~/myrepo> cat .gitignore
public_html/stats/*
$ ~/myrepo> git status
# On branch master
#
# Initial commit
#
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# .gitignore
nothing added to commit but untracked files present (use "git add" to track)
$ ~/myrepo>
I believe that you will have to drop the foreign key constraints first. Then update all of the appropriate tables and remap them as they were.
ALTER TABLE [dbo.Details_tbl] DROP CONSTRAINT [FK_Details_tbl_User_tbl];
-- Perform more appropriate alters
ALTER TABLE [dbo.Details_tbl] ADD FOREIGN KEY (FK_Details_tbl_User_tbl)
REFERENCES User_tbl(appId);
-- Perform all appropriate alters to bring the key constraints back
However, unless memory is a really big issue, I would keep the identity as an INT. Unless you are 100% positive that your keys will never grow past the TINYINT restraints. Just a word of caution :)
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
Method overriding is when a child class redefines the same method as a parent class, with the same parameters. For example, the standard Java class java.util.LinkedHashSet
extends java.util.HashSet
. The method add()
is overridden in LinkedHashSet
. If you have a variable that is of type HashSet
, and you call its add()
method, it will call the appropriate implementation of add()
, based on whether it is a HashSet
or a LinkedHashSet
. This is called polymorphism.
Method overloading is defining several methods in the same class, that accept different numbers and types of parameters. In this case, the actual method called is decided at compile-time, based on the number and types of arguments. For instance, the method System.out.println()
is overloaded, so that you can pass ints as well as Strings, and it will call a different version of the method.
Try this so you don't need to worry about where your logs are:
dmesg -T | egrep -i 'killed process'
-T
- readable timestamps
So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]
To receive arbitrary Json in Spring-Boot, you can simply use Jackson's JsonNode
. The appropriate converter is automatically configured.
@PostMapping(value="/process")
public void process(@RequestBody com.fasterxml.jackson.databind.JsonNode payload) {
System.out.println(payload);
}
These samples work well. You can check section and then return a height to show or hide section. Don't forget to extend your viewcontroller from UITableViewDelegate
.
Objective-C
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
if (section == 0)
{
// to hide footer for section 0
return 0.0;
}
else
{
// show footer for every section except section 0
return HEIGHT_YOU_WANT;
}
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
UIView *footerView = [[UIView alloc] init];
footerView.backgroundColor = [UIColor blackColor];
return footerView;
}
Swift
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerView = UIView()
footerView.backgroundColor = UIColor.black
return footerView
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == 0 {
// to hide footer for section 0
return 0.0
} else {
// show footer for every section except section 0
return HEIGHT_YOU_WANT
}
}
Using a jquery plugin I have adapted it to my needs adding customized options and creating a new plugin. You can find it here: https://github.com/david-dlc-cerezo/jquery-clearField
An example of a simple usage:
<script src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script src='http://code.jquery.com/ui/1.10.3/jquery-ui.js'></script>
<script src='src/jquery.clearField.js'></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="css/jquery.clearField.css">
<table>
<tr>
<td><input name="test1" id="test1" clas="test" type='text'></td>
<td>Empty</td>
</tr>
<tr>
<td><input name="test2" id="test2" clas="test" type='text' value='abc'></td>
<td>Not empty</td>
</tr>
</table>
<script>
$('.test').clearField();
</script>
Obtaining something like this:
You can access the namespace's dictionary with vars():
>>> import argparse
>>> args = argparse.Namespace()
>>> args.foo = 1
>>> args.bar = [1,2,3]
>>> d = vars(args)
>>> d
{'foo': 1, 'bar': [1, 2, 3]}
You can modify the dictionary directly if you wish:
>>> d['baz'] = 'store me'
>>> args.baz
'store me'
Yes, it is okay to access the __dict__ attribute. It is a well-defined, tested, and guaranteed behavior.
I'm sure this isn't a great answer, since it modifies the string it's looping over, but it seems to work alright:
import string
for chr in your_string:
if chr == ' ':
your_string = your_string.replace(' ', '_')
elif chr not in string.ascii_letters or chr not in string.digits:
your_string = your_string.replace(chr, '')
TL;DR:
SOLUTION (1)
import numpy as np
main_list = np.setdiff1d(list_2,list_1)
# yields the elements in `list_2` that are NOT in `list_1`
SOLUTION (2) You want a sorted list
def setdiff_sorted(array1,array2,assume_unique=False):
ans = np.setdiff1d(array1,array2,assume_unique).tolist()
if assume_unique:
return sorted(ans)
return ans
main_list = setdiff_sorted(list_2,list_1)
EXPLANATIONS:
(1) You can use NumPy's setdiff1d
(array1
,array2
,assume_unique
=False
).
assume_unique
asks the user IF the arrays ARE ALREADY UNIQUE.
If False
, then the unique elements are determined first.
If True
, the function will assume that the elements are already unique AND function will skip determining the unique elements.
This yields the unique values in array1
that are not in array2
. assume_unique
is False
by default.
If you are concerned with the unique elements (based on the response of Chinny84), then simply use (where assume_unique=False
=> the default value):
import numpy as np
list_1 = ["a", "b", "c", "d", "e"]
list_2 = ["a", "f", "c", "m"]
main_list = np.setdiff1d(list_2,list_1)
# yields the elements in `list_2` that are NOT in `list_1`
(2)
For those who want answers to be sorted, I've made a custom function:
import numpy as np
def setdiff_sorted(array1,array2,assume_unique=False):
ans = np.setdiff1d(array1,array2,assume_unique).tolist()
if assume_unique:
return sorted(ans)
return ans
To get the answer, run:
main_list = setdiff_sorted(list_2,list_1)
SIDE NOTES:
(a) Solution 2 (custom function setdiff_sorted
) returns a list (compared to an array in solution 1).
(b) If you aren't sure if the elements are unique, just use the default setting of NumPy's setdiff1d
in both solutions A and B. What can be an example of a complication? See note (c).
(c) Things will be different if either of the two lists is not unique.
Say list_2
is not unique: list2 = ["a", "f", "c", "m", "m"]
. Keep list1
as is: list_1 = ["a", "b", "c", "d", "e"]
Setting the default value of assume_unique
yields ["f", "m"]
(in both solutions). HOWEVER, if you set assume_unique=True
, both solutions give ["f", "m", "m"]
. Why? This is because the user ASSUMED that the elements are unique). Hence, IT IS BETTER TO KEEP assume_unique
to its default value. Note that both answers are sorted.
I use superagent
, which is simliar to jQuery.
Here is the docs
And the demo like:
var sa = require('superagent');
sa.post('url')
.send({key: value})
.end(function(err, res) {
//TODO
});
Try this to see how you can create a object from strings.
var firstName = "xx";
var lastName = "xy";
var phone = "xz";
var adress = "x1";
var obj = {"firstName":firstName, "lastName":lastName, "phone":phone, "address":adress};
console.log(obj);
Make sure you are not using the same element Id / class elsewhere, for an element unrelated to the modal component.
That is.. if you are identifying your buttons which trigger the modal popups using the class name 'myModal', ensure that there are no unrelated elements having that same class name.
As we don't know what are the names of your activities classes, let's call your current activity Activity1, and the one you wish to open - Activity2 (these are the names of the classes)
First you need to define an intent that will be sent to Activity2:
Intent launchActivity2 = new Intent(Activity1.this, Activity2.class);
Then, you can simply launch the activity by running:
startActivity(launchActivity2 );
The documentation for Gerrit, in particular the "Push changes" section, explains that you push to the "magical refs/for/'branch'
ref using any Git client tool".
The following image is taken from the Intro to Gerrit. When you push to Gerrit, you do git push gerrit HEAD:refs/for/<BRANCH>
. This pushes your changes to the staging area (in the diagram, "Pending Changes"). Gerrit doesn't actually have a branch called <BRANCH>
; it lies to the git client.
Internally, Gerrit has its own implementation for the Git and SSH stacks. This allows it to provide the "magical" refs/for/<BRANCH>
refs.
When a push request is received to create a ref in one of these namespaces Gerrit performs its own logic to update the database, and then lies to the client about the result of the operation. A successful result causes the client to believe that Gerrit has created the ref, but in reality Gerrit hasn’t created the ref at all. [Link - Gerrit, "Gritty Details"].
After a successful patch (i.e, the patch has been pushed to Gerrit, [putting it into the "Pending Changes" staging area], reviewed, and the review has passed), Gerrit pushes the change from the "Pending Changes" into the "Authoritative Repository", calculating which branch to push it into based on the magic it did when you pushed to refs/for/<BRANCH>
. This way, successfully reviewed patches can be pulled directly from the correct branches of the Authoritative Repository
.
I think you may be overthinking this.
My approach is simple.
Enclose you page with a div tag:
<div id="mydiv">
<!-- you page here -->
</div>
In your javascript:
var html=document.getElementById('mydiv').innerHTML;
html = html.replace(/this/g,"that");
document.getElementById('mydiv').innerHTML=html;
You should be able to find your command with a ps
variant like:
ps -ef
ps -fubob # if your job's user ID is bob.
Then, once located, it should be a simple matter to use kill
to kill the process (permissions permitting).
If you're talking about getting rid of jobs in the at
queue (that aren't running yet), you can use atq
to list them and atrm
to get rid of them.
Update
If your popover is going to have a selector that is consistent then you can make use of selector
property of popover constructor.
var popOverSettings = {
placement: 'bottom',
container: 'body',
html: true,
selector: '[rel="popover"]', //Sepcify the selector here
content: function () {
return $('#popover-content').html();
}
}
$('body').popover(popOverSettings);
Other ways:
Mutation Event
/Mutation Observer
to identify if a particular element has been inserted on to the ul
or an element.var popOverSettings = { //Save the setting for later use as well
placement: 'bottom',
container: 'body',
html: true,
//content:" <div style='color:red'>This is your div content</div>"
content: function () {
return $('#popover-content').html();
}
}
$('ul').on('DOMNodeInserted', function () { //listed for new items inserted onto ul
$(event.target).popover(popOverSettings);
});
$("button[rel=popover]").popover(popOverSettings);
$('.pop-Add').click(function () {
$('ul').append("<li class='project-name'> <a>project name 2 <button class='pop-function' rel='popover'></button> </a> </li>");
});
But it is not recommended to use DOMNodeInserted Mutation Event for performance issues as well as support. This has been deprecated as well. So your best bet would be to save the setting and bind after you update with new element.
Another recommended way is to use MutationObserver instead of MutationEvent according to MDN, but again support in some browsers are unknown and performance a concern.
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
// create an observer instance
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
$(mutation.addedNodes).popover(popOverSettings);
});
});
// configuration of the observer:
var config = {
attributes: true,
childList: true,
characterData: true
};
// pass in the target node, as well as the observer options
observer.observe($('ul')[0], config);
This should work. I converted the date to unix time via strtotime.
foreach ($originalArray as $key => $part) {
$sort[$key] = strtotime($part['datetime']);
}
array_multisort($sort, SORT_DESC, $originalArray);
One-liner version would be using multiple array methods:
array_multisort(array_map('strtotime',array_column($originalArray,'datetime')),
SORT_DESC,
$originalArray);
Here is a YUI compressor script (Byuic) that finds all the js and css down a path and compresses /(optionally) obfuscates them. Nice to integrate into a build process.
Delete .android folder cache files, Also delete the build folder manually from a directory and open android studio and run again.
Referencing the Rails documents we see that there are a few ways to link to images from css. Just go to section 2.3.2.
First, make sure your css file has the .scss extension if it's a sass file.
Next, you can use the ruby method, which is really ugly:
#logo { background: url(<%= asset_data_uri 'logo.png' %>) }
Or you can use the specific form that is nicer:
image-url("rails.png") returns url(/assets/rails.png)
image-path("rails.png") returns "/assets/rails.png"
Lastly, you can use the general form:
asset-url("rails.png") returns url(/assets/rails.png)
asset-path("rails.png") returns "/assets/rails.png"
The error is happening because you (or whoever designed this table) have a bunch of dates in VARCHAR
. Why are you (or whoever designed this table) storing dates as strings? Do you (or whoever designed this table) also store salary and prices and distances as strings?
To find the values that are causing issues (so you (or whoever designed this table) can fix them):
SELECT GRADUATION_DATE FROM mydb
WHERE ISDATE(GRADUATION_DATE) = 0;
Bet you have at least one row. Fix those values, and then FIX THE TABLE. Or ask whoever designed the table to FIX THE TABLE. Really nicely.
ALTER TABLE mydb ALTER COLUMN GRADUATION_DATE DATE;
Now you don't have to worry about the formatting - you can always format as YYYYMMDD
or YYYY-MM-DD
on the client, or using CONVERT
in SQL. When you have a valid date as a string literal, you can use:
SELECT CONVERT(CHAR(10), '20120101', 120);
...but this is better done on the client (if at all).
There's a popular term - garbage in, garbage out. You're never going to be able to convert to a date (never mind convert to a string in a specific format) if your data type choice (or the data type choice of whoever designed the table) inherently allows garbage into your table. Please fix it. Or ask whoever designed the table (again, really nicely) to fix it.
when we run application in eclipse apk generate is sign by default Keystore which is provided by android .
But if you want to upload your application on play store you need to create your own keystore. Eclipse already provides GUI interface to create new keystore. And you also can create keystore through command line.
default alias is
androiddebugkey
You have to pass the -np
/--no-parent
option to wget
(in addition to -r
/--recursive
, of course), otherwise it will follow the link in the directory index on my site to the parent directory. So the command would look like this:
wget --recursive --no-parent http://example.com/configs/.vim/
To avoid downloading the auto-generated index.html
files, use the -R
/--reject
option:
wget -r -np -R "index.html*" http://example.com/configs/.vim/
In my case, my array was multidimensional, potentially with arrays as values. So I created this recursive function to blow apart the array completely:
function array2csv($array, &$title, &$data) {
foreach($array as $key => $value) {
if(is_array($value)) {
$title .= $key . ",";
$data .= "" . ",";
array2csv($value, $title, $data);
} else {
$title .= $key . ",";
$data .= '"' . $value . '",';
}
}
}
Since the various levels of my array didn't lend themselves well to a the flat CSV format, I created a blank column with the sub-array's key to serve as a descriptive "intro" to the next level of data. Sample output:
agentid fname lname empid totals sales leads dish dishnet top200_plus top120 latino base_packages
G-adriana ADRIANA EUGENIA PALOMO PAIZ 886 0 19 0 0 0 0 0
You could easily remove that "intro" (descriptive) column, but in my case I had repeating column headers, i.e. inbound_leads, in each sub-array, so that gave me a break/title preceding the next section. Remove:
$title .= $key . ",";
$data .= "" . ",";
after the is_array() to compact the code further and remove the extra column.
Since I wanted both a title row and data row, I pass two variables into the function and upon completion of the call to the function, terminate both with PHP_EOL:
$title .= PHP_EOL;
$data .= PHP_EOL;
Yes, I know I leave an extra comma, but for the sake of brevity, I didn't handle it here.
People say you can't and I understand you may be frustrated when asking a question and getting such an answer.
If you really want it to show in UTF-8 instead of US ASCII then you need to do it in two steps.
First:
iconv -f us-ascii -t utf-16 yourfile > youfileinutf16.*
Second:
iconv -f utf-16le -t utf-8 yourfileinutf16 > yourfileinutf8.*
Then if you do a file -i
, you'll see the new character set is UTF-8.
var anchor = angular.element('<a/>');
anchor.css({display: 'none'}); // Make sure it's not visible
angular.element(document.body).append(anchor); // Attach to document
anchor.attr({
href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
target: '_blank',
download: 'filename.csv'
})[0].click();
anchor.remove(); // Clean it up afterwards
This code works both Mozilla and chrome
In order to get around the Enable Macro prompt I suggest
Application.AutomationSecurity = msoAutomationSecurityForceDisable
Be sure to return it to default when you are done
Application.AutomationSecurity = msoAutomationSecurityLow
A reminder that the .SaveAs
function contains all optional arguments.I recommend removing CreatBackup:= False
as it is not necessary.
The most interesting way I think is to create an object of the workbook and access the .SaveAs
property that way. I have not tested it but you are never using Workbooks.Open
rendering Application.AutomationSecurity
inapplicable. Possibly saving resources and time as well.
That said I was able to execute the following without any notifications on Excel 2013 windows 10.
Option Explicit
Sub Convert()
OptimizeVBA (True)
'function to set all the things you want to set, but hate keying in
Application.AutomationSecurity = msoAutomationSecurityForceDisable
'this should stop those pesky enable prompts
ChDir "F:\VBA Macros\Stack Overflow Questions\When changing type xlsm to
xlsx stop popup"
Workbooks.Open ("Book1.xlsm")
ActiveWorkbook.SaveAs Filename:= _
"F:\VBA Macros\Stack Overflow Questions\When changing type xlsm to xlsx_
stop popup\Book1.xlsx" _
, FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close
Application.AutomationSecurity = msoAutomationSecurityLow
'make sure you set this up when done
Kill ("F:\VBA Macros\Stack Overflow Questions\When changing type xlsm_
to xlsx stop popup\Book1.xlsx") 'clean up
OptimizeVBA (False)
End Sub
Function OptimizeVBA(ByRef Status As Boolean)
If Status = True Then
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.DisplayAlerts = False
Application.EnableEvents = False
Else
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.DisplayAlerts = True
Application.EnableEvents = True
End If
End Function
try this instead and because it needs root privileges use sudo
sudo service tomcat7 status
Here was an answer baked into the default ASP.NET MVC 5 project I believe that accomplishes my styling goals nicely in the UI. Form submit using pure javascript to some containing form.
@using (Html.BeginForm("Logout", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
<a href="javascript:document.getElementById('logoutForm').submit()">
<span>Sign out</span>
</a>
}
The fully shown use case is a logout dropdown in the navigation bar of a web app.
@using (Html.BeginForm("Logout", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
<div class="dropdown">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span class="ma-nav-text ma-account-name">@User.Identity.Name</span>
<i class="material-icons md-36 text-inverse">person</i>
</button>
<ul class="dropdown-menu dropdown-menu-right ma-dropdown-tray">
<li>
<a href="javascript:document.getElementById('logoutForm').submit()">
<i class="material-icons">system_update_alt</i>
<span>Sign out</span>
</a>
</li>
</ul>
</div>
}
As many have stated more or less correctly what reference and primitive types are, one might be interested that we have some more relevant types in Java. Here is the complete lists of types in java (as far as I am aware of (JDK 11)).
Describes a value (and not a type).
11
Describes a concrete type which instances extend Object (interface, class, enum, array). Furthermore TypeParameter is actually a reference type!
Integer
Note: The difference between primitive and reference type makes it necessary to rely on boxing to convert primitives in Object instances and vise versa.
Note2: A type parameter describes a type having an optional lower or upper bound and can be referenced by name within its context (in contrast to the wild card type). A type parameter typically can be applied to parameterized types (classes/interfaces) and methods. The parameter type defines a type identifier.
Expresses an unknown type (like any in TypeScript) that can have a lower or upper bound by using super or extend.
? extends List<String>
? super ArrayList<String>
Nothingness. No value/instance possible.
void method();
The only representation is 'null'. It is used especially during type interference computations. Null is a special case logically belonging to any type (can be assigned to any variable of any type) but is actual not considered an instance of any type (e.g. (null instanceof Object) == false).
null
A union type is a type that is actual a set of alternative types. Sadly in Java it only exists for the multi catch statement.
catch(IllegalStateException | IOException e) {}
A type that is compatibile to multiple types. Since in Java a class has at most one super class (Object has none), interference types allow only the first type to be a class and every other type must be an interface type.
void method(List<? extends List<?> & Comparable> comparableList) {}
The type is unknown. That is the case for certain Lambda definitions (not enclosed in brackets, single parameter).
list.forEach(element -> System.out.println(element.toString)); //element is of unknown type
Unknown type introduced by a variable declaration spotting the 'var' keyword.
var variable = list.get(0);
You have broken version of RVM. Ubuntu does something to RVM that produces lots of errors, the only safe way of fixing for now is to:
sudo apt-get --purge remove ruby-rvm
sudo rm -rf /usr/share/ruby-rvm /etc/rvmrc /etc/profile.d/rvm.sh
open new terminal and validate environment is clean from old RVM settings (should be no output):
env | grep rvm
if there was output, try to open new terminal, if it does not help then restart your computer.
\curl -L https://get.rvm.io |
bash -s stable --ruby --autolibs=enable --auto-dotfiles
If you find you need some hand-holding, take a look at Installing Ruby on Ubuntu 12.04, which gives a bit more explanation.
If you want to match the two words in either order, use:
gci C:\Logs| select-string -pattern '(VendorEnquiry.*Failed)|(Failed.*VendorEnquiry)'
If Failed always comes after VendorEnquiry on the line, just use:
gci C:\Logs| select-string -pattern '(VendorEnquiry.*Failed)'
l=[[0]*(L) for _ in range(W)]
Will be faster than:
l = [[0 for x in range(L)] for y in range(W)]
Use character classes: [ \t]
If you right click on any result of "Edit Top 200 Rows" query in SSMS you will see the option "Pane -> SQL". It then shows the SQL Query that was run, which you can edit as you wish.
In SMSS 2012 and 2008, you can use Ctrl+3 to quickly get there.
Something like this?
public static T ConvertValue<T>(string value)
{
return (T)Convert.ChangeType(value, typeof(T));
}
You can then use it like this:
int val = ConvertValue<int>("42");
Edit:
You can even do this more generic and not rely on a string
parameter provided the type U
implements IConvertible
- this means you have to specify two type parameters though:
public static T ConvertValue<T,U>(U value) where U : IConvertible
{
return (T)Convert.ChangeType(value, typeof(T));
}
I considered catching the InvalidCastException
exception that might be raised by Convert.ChangeType()
- but what would you return in this case? default(T)
? It seems more appropriate having the caller deal with the exception.
You can do it with IE 'sometimes' as I have done this for an internal application on an intranet which is IE only. Try the following:
function GetComputerName() {
try {
var network = new ActiveXObject('WScript.Network');
// Show a pop up if it works
alert(network.computerName);
}
catch (e) { }
}
It may or may not require some specific security setting setup in IE as well to allow the browser to access the ActiveX object.
Here is a link to some more info on WScript: More Information
element.remove()
The DOM is organized in a tree of nodes, where each node has a value, along with a list of references to its child nodes. So element.parentNode.removeChild(element)
mimics exactly what is happening internally: First you go the parent node, then remove the reference to the child node.
As of DOM4, a helper function is provided to do the same thing: element.remove()
. This works in 96% of browsers (as of 2020), but not IE 11. If you need to support older browsers, you can:
int countRow = dt.Rows.Count;
int countCol = dt.Columns.Count;
for (int iCol = 0; iCol < countCol; iCol++)
{
DataColumn col = dt.Columns[iCol];
for (int iRow = 0; iRow < countRow; iRow++)
{
object cell = dt.Rows[iRow].ItemArray[iCol];
}
}
npm ws was the answer for me. I found it less intrusive and more straight forward. With it was also trivial to mix websockets with rest services. Shared simple code on this post.
var WebSocketServer = require("ws").Server;
var http = require("http");
var express = require("express");
var port = process.env.PORT || 5000;
var app = express();
app.use(express.static(__dirname+ "/../"));
app.get('/someGetRequest', function(req, res, next) {
console.log('receiving get request');
});
app.post('/somePostRequest', function(req, res, next) {
console.log('receiving post request');
});
app.listen(80); //port 80 need to run as root
console.log("app listening on %d ", 80);
var server = http.createServer(app);
server.listen(port);
console.log("http server listening on %d", port);
var userId;
var wss = new WebSocketServer({server: server});
wss.on("connection", function (ws) {
console.info("websocket connection open");
var timestamp = new Date().getTime();
userId = timestamp;
ws.send(JSON.stringify({msgType:"onOpenConnection", msg:{connectionId:timestamp}}));
ws.on("message", function (data, flags) {
console.log("websocket received a message");
var clientMsg = data;
ws.send(JSON.stringify({msg:{connectionId:userId}}));
});
ws.on("close", function () {
console.log("websocket connection close");
});
});
console.log("websocket server created");
I've just checked and i have the same code as you and it works perferctly. The only difference is how i fill my List for the params :
I use a : ArrayList<BasicNameValuePair> params
and fill it this way :
params.add(new BasicNameValuePair("apikey", apikey);
I do not use any JSONObject to send params to the webservices.
Are you obliged to use the JSONObject ?
Every time you call itr2.next() you are getting a distinct value. Not the same value. You should only call this once in the loop.
Iterator<String> itr2 = keys.iterator();
while(itr2.hasNext()){
String v = itr2.next();
System.out.println("Key: "+v+" ,value: "+m.get(v));
}
Check to make sure there is a film release date; if the date is missing you will not be able to format on a non-object.
if ($info['Film_Release']){ //check if the date exists
$dateFromDB = $info['Film_Release'];
$newDate = DateTime::createFromFormat("l dS F Y", $dateFromDB);
$newDate = $newDate->format('d/m/Y');
} else {
$newDate = "none";
}
or
$newDate = ($info['Film_Release']) ? DateTime::createFromFormat("l dS F Y", $info['Film_Release'])->format('d/m/Y'): "none"
I believe that if you download the offline ISO image file, and use that to install Visual Studio Express, you won't have to register.
Go here and find the link that says "All - Offline Install ISO image file". Click on it to expand it, select your language, and then click "Download".
Otherwise, it's possible that online registration is simply down for a while, as the error message indicates. You have 30 days before it expires, so give it a few days before starting to panic.
Try this simpler one,
cp /home/ankur/folder/file{1,2} /home/ankur/dest
If you want to copy all the 10 files then run this command,
cp ~/Desktop/{xyz,file{1,2},next,files,which,are,not,similer} foo-bar
Not only is the boolean datatype missing in Oracle's SQL (not PL/SQL), but they also have no clear recommendation about what to use instead. See this thread on asktom. From recommending CHAR(1) 'Y'/'N'
they switch to NUMBER(1) 0/1
when someone points out that 'Y'/'N'
depends on the English language, while e.g. German programmers might use 'J'/'N'
instead.
The worst thing is that they defend this stupid decision just like they defend the ''=NULL
stupidity.
Adding
SQLNET.ALLOWED_LOGON_VERSION_SERVER = 8
is the perfect solution sql.ora directory ..\product\12.1.0\dbhome_1\NETWORK\ADMIN
I have used the extremely handy app_offline.htm trick to shut down/update sites in the past without any issues.
Be sure that you are actually placing the "app_offline.htm" file in the "root" of the website that you have configured within IIS.
Also ensure that the file is named exactly as it should be: app_offline.htm
Other than that, there should be no other changes to IIS that you should need to make since the processing of this file (with this specific name) is handled by the ASP.NET runtime rather than IIS itself (for IIS v6).
Be aware, however, that although placing this file in the root of your site will force the application to "shut down" and display the content of the "app_offline.htm" file itself, any existing requests will still get the real website served up to them. Only new requests will get the app_offline.htm content.
If you're still having issues, try the following links for further info:
App_Offline.htm and working around the "IE Friendly Errors" feature
Will app_offline.htm stop current requests or just new requests?
$(window).scroll(function () {
var Bottom = $(window).height() + $(window).scrollTop() >= $(document).height();
if(Bottom )
{
$('#div').hide();
}
});
Try,
public class Sent
{
public int MsgID;
public string Content;
public int Status;
}
public class Messages
{
public int MsgID;
public string Content;
}
List<Sent> SentList = new List<Sent>() { new Sent() { MsgID = 1, Content = "aaa", Status = 0 }, new Sent() { MsgID = 3, Content = "ccc", Status = 0 } };
List<Messages> MsgList = new List<Messages>() { new Messages() { MsgID = 1, Content = "aaa" }, new Messages() { MsgID = 2, Content = "bbb" }, new Messages() { MsgID = 3, Content = "ccc" }, new Messages() { MsgID = 4, Content = "ddd" }, new Messages() { MsgID = 5, Content = "eee" }};
int [] sentMsgIDs = SentList.Select(v => v.MsgID).ToArray();
List<Messages> result1 = MsgList.Where(o => !sentMsgIDs.Contains(o.MsgID)).ToList<Messages>();
Hope it should help.
canvas.toDataURL
is not working if the original image URL (either relative or absolute) does not belong to the same domain as the web page. Tested from a bookmarklet and a simple javascript in the web page containing the images.
Have a look to David Walsh working example. Put the html and images on your own web server, switch original image to relative or absolute URL, change to an external image URL. Only the first two cases are working.
From JQuery Documentation
The jqXHR objects returned by $.ajax()
as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax()
request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:
jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, refer to deferred.done()
for implementation details.
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
An alternative construct to the error callback option, the .fail()
method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.
jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { });
(added in jQuery 1.6)
An alternative construct to the complete callback option, the .always()
method replaces the deprecated .complete()
method.
In response to a successful request, the function's arguments are the same as those of .done()
: data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail()
: the jqXHR object, textStatus, and errorThrown. Refer to deferred.always()
for implementation details.
jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});
Incorporates the functionality of the .done()
and .fail()
methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then()
for implementation details.
Deprecation Notice: The
jqXHR.success()
,jqXHR.error()
, andjqXHR.complete()
callbacks are removed as of jQuery 3.0. You can usejqXHR.done()
,jqXHR.fail()
, andjqXHR.always()
instead.
In Python 3, /
is float division
In Python 2, /
is integer division (assuming int
inputs)
In both 2 and 3, //
is integer division
(To get float division in Python 2 requires either of the operands be a float, either as 20.
or float(20)
)
I found another solution in this link
SELECT MIN (tbl_name) AS tbl_name, PK, column_list
FROM
(
SELECT ' source_table ' as tbl_name, S.PK, S.column_list
FROM source_table AS S
UNION ALL
SELECT 'destination_table' as tbl_name, D.PK, D.column_list
FROM destination_table AS D
) AS alias_table
GROUP BY PK, column_list
HAVING COUNT(*) = 1
ORDER BY PK
Change directory to tomcat/bin directory in cmd prompt
cd C:\Program Files\Apache Software Foundation\Tomcat 8.0\bin
Run the below command to start:
On Linux: >startup.sh
On Windows: >startup.bat
Run these commands to stop
On Linux: shutdown.sh
On Windows: shutdown.bat
Scikit learn introduced a delicious new method called export_text
in version 0.21 (May 2019) to extract the rules from a tree. Documentation here. It's no longer necessary to create a custom function.
Once you've fit your model, you just need two lines of code. First, import export_text
:
from sklearn.tree import export_text
Second, create an object that will contain your rules. To make the rules look more readable, use the feature_names
argument and pass a list of your feature names. For example, if your model is called model
and your features are named in a dataframe called X_train
, you could create an object called tree_rules
:
tree_rules = export_text(model, feature_names=list(X_train.columns))
Then just print or save tree_rules
. Your output will look like this:
|--- Age <= 0.63
| |--- EstimatedSalary <= 0.61
| | |--- Age <= -0.16
| | | |--- class: 0
| | |--- Age > -0.16
| | | |--- EstimatedSalary <= -0.06
| | | | |--- class: 0
| | | |--- EstimatedSalary > -0.06
| | | | |--- EstimatedSalary <= 0.40
| | | | | |--- EstimatedSalary <= 0.03
| | | | | | |--- class: 1
In batch you could do it like this:
@echo off
setlocal EnableDelayedExpansion
set "string_list=str1 str2 str3 ... str10"
for %%s in (%string_list%) do (
set "var=%%sxyz"
svn co "!var!"
)
If you don't need the variable !var!
elsewhere in the loop, you could simplify that to
@echo off
setlocal
set "string_list=str1 str2 str3 ... str10"
for %%s in (%string_list%) do svn co "%%sxyz"
However, like C.B. I'd prefer PowerShell if at all possible:
$string_list = 'str1', 'str2', 'str3', ... 'str10'
$string_list | ForEach-Object {
$var = "${_}xyz" # alternatively: $var = $_ + 'xyz'
svn co $var
}
Again, this could be simplified if you don't need $var
elsewhere in the loop:
$string_list = 'str1', 'str2', 'str3', ... 'str10'
$string_list | ForEach-Object { svn co "${_}xyz" }
If you are a Photoshop guy, you can also use:
#some-element {
background-color: hsla(170, 50%, 45%, 0.9); // **0.9 is the opacity range from 0 - 1**
}
#some-element {
background-color: rgba(170, 190, 45, 0.9); // **0.9 is the opacity range from 0 - 1**
}
Declare the variable as a string.
example :
public string dateOfBirth ;
then assign a value like :
dateOfBirth = ((DateTime)(datetimevaluefromDB)).ToShortDateString();
$scope.actions.data.concat is not a function
same problem with me but i solve the problem by
$scope.actions.data = [].concat($scope.actions.data , data)
First you need to know the exact name of the INDEX (Unique key in this case) to delete or update it.
INDEX names are usually same as column names. In case of more than one INDEX applied on a column, MySQL automatically suffixes numbering to the column names to create unique INDEX names.
For example if 2 indexes are applied on a column named customer_id
customer_id
itself.customer_id_2
and so on.SHOW INDEX FROM <table_name>
as suggested by @Amr
ALTER TABLE <table_name> DROP INDEX <index_name>;
The basic one, ask tasklist to filter its output and only show the indicated process id information
tasklist /fi "pid eq 4444"
To only get the process name, the line must be splitted
for /f "delims=," %%a in ('
tasklist /fi "pid eq 4444" /nh /fo:csv
') do echo %%~a
In this case, the list of processes is retrieved without headers (/nh
) in csv format (/fo:csv
). The commas are used as token delimiters and the first token in the line is the image name
note: In some windows versions (one of them, my case, is the spanish windows xp version), the pid filter in the tasklist does not work. In this case, the filter over the list of processes must be done out of the command
for /f "delims=," %%a in ('
tasklist /fo:csv /nh ^| findstr /b /r /c:"[^,]*,\"4444\","
') do echo %%~a
This will generate the task list and filter it searching for the process id in the second column of the csv output.
edited: alternatively, you can suppose what has been made by the team that translated the OS to spanish. I don't know what can happen in other locales.
tasklist /fi "idp eq 4444"
Rather than abusing plot
or annotate
, which will be inefficient for many lines, you can use matplotlib.collections.LineCollection
:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")
# Takes list of lines, where each line is a sequence of coordinates
l1 = [(70, 100), (70, 250)]
l2 = [(70, 90), (90, 200)]
lc = LineCollection([l1, l2], color=["k","blue"], lw=2)
plt.gca().add_collection(lc)
plt.show()
It takes a list of lines [l1, l2, ...]
, where each line is a sequence of N coordinates (N can be more than two).
The standard formatting keywords are available, accepting either a single value, in which case the value applies to every line, or a sequence of M values
, in which case the value for the ith line is values[i % M]
.
try this:
ren "File 1-1" "File 1 - %date:/=-% %time::=-%"
Dim pos, arr, val
arr=Array(1,2,4,5)
val = 4
pos=Application.Match(val, arr, False)
if not iserror(pos) then
Msgbox val & " is at position " & pos
else
Msgbox val & " not found!"
end if
Updated to show using Match (with .Index) to find a value in a dimension of a two-dimensional array:
Dim arr(1 To 10, 1 To 2)
Dim x
For x = 1 To 10
arr(x, 1) = x
arr(x, 2) = 11 - x
Next x
Debug.Print Application.Match(3, Application.Index(arr, 0, 1), 0)
Debug.Print Application.Match(3, Application.Index(arr, 0, 2), 0)
EDIT: it's worth illustrating here what @ARich pointed out in the comments - that using Index()
to slice an array has horrible performance if you're doing it in a loop.
In testing (code below) the Index() approach is almost 2000-fold slower than using a nested loop.
Sub PerfTest()
Const VAL_TO_FIND As String = "R1800:C8"
Dim a(1 To 2000, 1 To 10)
Dim r As Long, c As Long, t
For r = 1 To 2000
For c = 1 To 10
a(r, c) = "R" & r & ":C" & c
Next c
Next r
t = Timer
Debug.Print FindLoop(a, VAL_TO_FIND), Timer - t
' >> 0.00781 sec
t = Timer
Debug.Print FindIndex(a, VAL_TO_FIND), Timer - t
' >> 14.18 sec
End Sub
Function FindLoop(arr, val) As Boolean
Dim r As Long, c As Long
For r = 1 To UBound(arr, 1)
For c = 1 To UBound(arr, 2)
If arr(r, c) = val Then
FindLoop = True
Exit Function
End If
Next c
Next r
End Function
Function FindIndex(arr, val)
Dim r As Long
For r = 1 To UBound(arr, 1)
If Not IsError(Application.Match(val, Application.Index(arr, r, 0), 0)) Then
FindIndex = True
Exit Function
End If
Next r
End Function
keep it simple. Most modern browsers support a maxlength attribute on a text area (IE included), so simply add that attribute in code-behind. No JS, no Jquery, no inheritance, custom code, no fuss, no muss.
VB.Net:
fld_description.attributes("maxlength") = 255
C#
fld_description.Attributes["maxlength"] = 255
The Date
object is used to work with dates and times.
Date objects are created with new Date()
.
var date= new Date();
function myFunction() {
var currentTime = new Date();
Logger.log(currentTime);
}
Not with the HTML file control, no. A flash file uploader can do that for you though. You could use some client-side code to check for the PDF extension after they select, but you cannot directly control what they can select.
Create a UNIQUE
constraint on your subs_email
column, if one does not already exist:
ALTER TABLE subs ADD UNIQUE (subs_email)
Use INSERT ... ON DUPLICATE KEY UPDATE
:
INSERT INTO subs
(subs_name, subs_email, subs_birthday)
VALUES
(?, ?, ?)
ON DUPLICATE KEY UPDATE
subs_name = VALUES(subs_name),
subs_birthday = VALUES(subs_birthday)
You can use the VALUES(col_name) function in the UPDATE clause to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE - dev.mysql.com
If you do not have an LDF file then:
1) put the MDF in the C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\
2) In ssms, go to Databases -> Attach
and add the MDF file. It will not let you add it this way but it will tell you the database name contained within.
3) Make sure the user you are running ssms.exe as has acccess to this MDF file.
4) Now that you know the DbName, run
EXEC sp_attach_single_file_db @dbname = 'DbName',
@physname = N'C:\Program Files\Microsoft SQL Server\MSSQL13.SQLEXPRESS\MSSQL\DATA\yourfile.mdf';
Reference: https://dba.stackexchange.com/questions/12089/attaching-mdf-without-ldf
You can try this:
/*iPad landscape oriented styles */
@media only screen and (device-width:768px)and (orientation:landscape){
.yourstyle{
}
}
/*iPad Portrait oriented styles */
@media only screen and (device-width:768px)and (orientation:portrait){
.yourstyle{
}
}
Droid Explorer http://de.codeplex.com/releases/view/612392
Window Apps:
Explorer:
SQLite Manager:
If you're removing the path for Python 3 specifically, I found it in ~/.zprofile
and ~/.zshrc.
Xcode 8 beta 2 • Swift 3
let myString = "Hello World"
let myRange = myString.startIndex..<myString.index(myString.startIndex, offsetBy: 5)
let mySubString = myString.substring(with: myRange) // Hello
Xcode 7 • Swift 2.0
let myString = "Hello World"
let myRange = Range<String.Index>(start: myString.startIndex, end: myString.startIndex.advancedBy(5))
let mySubString = myString.substringWithRange(myRange) // Hello
or simply
let myString = "Hello World"
let myRange = myString.startIndex..<myString.startIndex.advancedBy(5)
let mySubString = myString.substringWithRange(myRange) // Hello
How about:
String numbers = text.substring(text.length() - 7);
That assumes that there are 7 characters at the end, of course. It will throw an exception if you pass it "12345". You could address that this way:
String numbers = text.substring(Math.max(0, text.length() - 7));
or
String numbers = text.length() <= 7 ? text : text.substring(text.length() - 7);
Note that this still isn't doing any validation that the resulting string contains numbers - and it will still throw an exception if text
is null.
Pass your Image URL: Try this:
private Bitmap getBitmap(String url)
{
File file=fileCache.getFile(url);
Bitmap bm = decodeFile(file);
if(bm!=null)
return bm;
try {
Bitmap bitmap=null;
URL ImageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)ImageUrl.openConnection();
conn.setConnectTimeout(50000);
conn.setReadTimeout(50000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(file);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(file);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
private Bitmap decodeFile(File file){
try {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(file),null,opt);
final int REQUIRED_SIZE=70;
int width_tmp=opt.outWidth, height_tmp=opt.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
BitmapFactory.Options opte = new BitmapFactory.Options();
opte.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(file), null, opte);
} catch (FileNotFoundException e) {}
return null;
}
Create Class Utils:
public class Utils {
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
}
A fixed number can't be set for port, heroku assigns it dynamically using process.env.PORT
. But you can add them both, like this process.env.PORT || 5000
. Heroku will use the first one, and your localhost will use the second one.
You can even add your call back function. Look at the code below
app.listen(process.env.PORT || 5000, function() {
console.log("Server started.......");
});
on my quest to do this with entitie, i stumbled over here, just hitting back to post what i've found out...
when using EF4, "a sql's" datetime column can be filled from .NET's DateTime using BitConverter.
EntitieObj.thetime = BitConverter.GetBytes(DateTime.Now.ToBinary());
also Fakrudeen's link brought me further... thank you.
To replace from the right:
def replace_right(source, target, replacement, replacements=None):
return replacement.join(source.rsplit(target, replacements))
In use:
>>> replace_right("asd.asd.asd.", ".", ". -", 1)
'asd.asd.asd. -'
You can use LambdaEqualityComparer:
var distinctValues
= myCustomerList.Distinct(new LambdaEqualityComparer<OurType>((c1, c2) => c1.CustomerId == c2.CustomerId));
public class LambdaEqualityComparer<T> : IEqualityComparer<T>
{
public LambdaEqualityComparer(Func<T, T, bool> equalsFunction)
{
_equalsFunction = equalsFunction;
}
public bool Equals(T x, T y)
{
return _equalsFunction(x, y);
}
public int GetHashCode(T obj)
{
return obj.GetHashCode();
}
private readonly Func<T, T, bool> _equalsFunction;
}
If you are using SQL Express (which you are), then your login credentials are .\SQLEXPRESS
Here is the connectionString in the web config file which you can add:
<connectionStrings>
<add connectionString="Server=localhost\SQLEXPRESS;Database=yourDBName;Initial Catalog= yourDBName;Integrated Security=true" name="nametoCallBy" providerName="System.Data.SqlClient"/>
</connectionStrings>
Place is just above the system.web tag.
Then you can call it by:
connString = ConfigurationManager.ConnectionStrings["nametoCallBy"].ConnectionString;
Python lists are mutable objects and here:
plot_data = [[]] * len(positions)
you are repeating the same list len(positions)
times.
>>> plot_data = [[]] * 3
>>> plot_data
[[], [], []]
>>> plot_data[0].append(1)
>>> plot_data
[[1], [1], [1]]
>>>
Each list in your list is a reference to the same object. You modify one, you see the modification in all of them.
If you want different lists, you can do this way:
plot_data = [[] for _ in positions]
for example:
>>> pd = [[] for _ in range(3)]
>>> pd
[[], [], []]
>>> pd[0].append(1)
>>> pd
[[1], [], []]
Applying the full_extent()
function in an answer by @Joe 3 years later from here, you can get exactly what the OP was looking for. Alternatively, you can use Axes.get_tightbbox()
which gives a little tighter bounding box
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from matplotlib.transforms import Bbox
def full_extent(ax, pad=0.0):
"""Get the full extent of an axes, including axes labels, tick labels, and
titles."""
# For text objects, we need to draw the figure first, otherwise the extents
# are undefined.
ax.figure.canvas.draw()
items = ax.get_xticklabels() + ax.get_yticklabels()
# items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label]
items += [ax, ax.title]
bbox = Bbox.union([item.get_window_extent() for item in items])
return bbox.expanded(1.0 + pad, 1.0 + pad)
# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')
ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')
# Save the full figure...
fig.savefig('full_figure.png')
# Save just the portion _inside_ the second axis's boundaries
extent = full_extent(ax2).transformed(fig.dpi_scale_trans.inverted())
# Alternatively,
# extent = ax.get_tightbbox(fig.canvas.renderer).transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)
I'd post a pic but I lack the reputation points
ADD following -
It's works for me.
You need to use the library project located at: ANDROID-SDK-DIRECTORY/extras/google/google_play_services/libproject
This will fix your first issue.
I'm not sure about your second, but it may be a side effect of the first. I am still trying to get the map working in my own app :)
You can't have multiple actions with the same name. You could add a parameter to one method and that would be valid. For example:
public ActionResult Index(int i)
{
Some Code--Some Code---Some Code
return View();
}
There are a few ways to do to have actions that differ only by request verb. My favorite and, I think, the easiest to implement is to use the AttributeRouting package. Once installed simply add an attribute to your method as follows:
[GET("Resources")]
public ActionResult Index()
{
return View();
}
[POST("Resources")]
public ActionResult Create()
{
return RedirectToAction("Index");
}
In the above example the methods have different names but the action name in both cases is "Resources". The only difference is the request verb.
The package can be installed using NuGet like this:
PM> Install-Package AttributeRouting
If you don't want the dependency on the AttributeRouting packages you could do this by writing a custom action selector attribute.
TO answer your question: no, MySQL does not support Table-typed variables in the same manner that SQL Server (http://msdn.microsoft.com/en-us/library/ms188927.aspx) provides. Oracle provides similar functionality but calls them Cursor types instead of table types (http://docs.oracle.com/cd/B12037_01/appdev.101/b10807/13_elems012.htm).
Depending your needs you can simulate table/cursor-typed variables in MySQL using temporary tables in a manner similar to what is provided by both Oracle and SQL Server.
However, there is an important difference between the temporary table approach and the table/cursor-typed variable approach and it has a lot of performance implications (this is the reason why Oracle and SQL Server provide this functionality over and above what is provided with temporary tables).
Specifically: table/cursor-typed variables allow the client to collate multiple rows of data on the client side and send them up to the server as input to a stored procedure or prepared statement. What this eliminates is the overhead of sending up each individual row and instead pay that overhead once for a batch of rows. This can have a significant impact on overall performance when you are trying to import larger quantities of data.
A possible work-around:
What you may want to try is creating a temporary table and then using a LOAD DATA (http://dev.mysql.com/doc/refman/5.1/en/load-data.html) command to stream the data into the temporary table. You could then pass them name of the temporary table into your stored procedure. This will still result in two calls to the database server, but if you are moving enough rows there may be a savings there. Of course, this is really only beneficial if you are doing some kind of logic inside the stored procedure as you update the target table. If not, you may just want to LOAD DATA directly into the target table.
For those of you trying to figure out how to actually remove the styling from the element only, without removing the css from the files, this solution works with jquery:
$('.selector').removeAttr('style');
If you are using two DateTime objects, one to store the date the other the time, you could do the following:
var date = new DateTime(2016,6,28);
var time = new DateTime(1,1,1,13,13,13);
var combinedDateTime = date.AddTicks(time.TimeOfDay.Ticks);
An example of this can be found here
[x+1 if x >= 45 else x+5 for x in l]
And for a reward, here is the comment, I wrote to remember this the first time I did this error:
Python's conditional expression is
a if C else b
and can't be used as:[a for i in items if C else b]
The right form is:
[a if C else b for i in items]
Even though there is a valid form:
[a for i in items if C]
But that isn't the same as that is how you filter by
C
, but they can be combined:[a if tC else b for i in items if fC]
Connects to both Office 365 and Exchange Online in one easy to use script.
REMINDER: You must have the following installed in order to manage Office 365 via PowerShell.
Microsoft Online Services Sign-in Assistant: http://go.microsoft.com/fwlink/?LinkId=286152
Azure AD Module for Windows PowerShell 32 bit - http://go.microsoft.com/fwlink/p/?linkid=236298 64 bit - http://go.microsoft.com/fwlink/p/?linkid=236297
MORE INFORMATION FOUND HERE: http://technet.microsoft.com/en-us/library/hh974317.aspx
For future visitors: In the new HttpClient
(Angular 4.3+), the response
object is JSON by default, so you don't need to do response.json().data
anymore. Just use response
directly.
Example (modified from the official documentation):
import { HttpClient } from '@angular/common/http';
@Component(...)
export class YourComponent implements OnInit {
// Inject HttpClient into your component or service.
constructor(private http: HttpClient) {}
ngOnInit(): void {
this.http.get('https://api.github.com/users')
.subscribe(response => console.log(response));
}
}
Don't forget to import it and include the module under imports in your project's app.module.ts:
...
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
// Include it under 'imports' in your application module after BrowserModule.
HttpClientModule,
...
],
...
It works well - you must put unchecked in the checkbox "Enable Just My Code" as highlighted in below image:
You simply need to enclose your SELECT
statements in parentheses to indicate that they are subqueries:
SET cityLat = (SELECT cities.lat FROM cities WHERE cities.id = cityID);
Alternatively, you can use MySQL's SELECT ... INTO
syntax. One advantage of this approach is that both cityLat
and cityLng
can be assigned from a single table-access:
SELECT lat, lng INTO cityLat, cityLng FROM cities WHERE id = cityID;
However, the entire procedure can be replaced with a single self-joined SELECT
statement:
SELECT b.*, HAVERSINE(a.lat, a.lng, b.lat, b.lng) AS dist
FROM cities AS a, cities AS b
WHERE a.id = cityID
ORDER BY dist
LIMIT 10;
You can hit the key q (for quit) and it should take you to the prompt.
Please see this link.
Thanks for @bkurzius's answer and this update is for Charles 3.10+. (The reason is here)
Install Charles Root Certificate on a Mobile Device or Remote Browser...
, and just follow the instruction. (use the Android's browser to download and install the certificate.)A couple of quick extensions on what has already been said...
An id
must be unique, but you can use the same id to make different styles more specific.
For example, given this HTML extract:
<div id="sidebar">
<h2>Heading</h2>
<ul class="menu">
...
</ul>
</div>
<div id="content">
<h2>Heading</h2>
...
</div>
<div id="footer">
<ul class="menu">
...
</ul>
</div>
You could apply different styles with these:
#sidebar h2
{ ... }
#sidebar .menu
{ ... }
#content h2
{ ... }
#footer .menu
{ ... }
Another useful thing to know: you can have multiple classes on an element, by space-delimiting them...
<ul class="main menu">...</ul>
<ul class="other menu">...</ul>
Which allows you to have common styling in .menu
with specific styles using .main.menu
and .sub.menu
.menu
{ ... }
.main.menu
{ ... }
.other.menu
{ ... }
The format specifers matter: "%s" says that the next string is a narrow string ("ascii" and typically 8 bits per character). "%S" means wide char string. Mixing the two will give "undefined behaviour", which includes printing garbage, just one character or nothing.
One character is printed because wide chars are, for example, 16 bits wide, and the first byte is non-zero, followed by a zero byte -> end of string in narrow strings. This depends on byte-order, in a "big endian" machine, you'd get no string at all, because the first byte is zero, and the next byte contains a non-zero value.
There's many forms of timeout, are you after the connection timeout, request timeout or time to live (time before TCP connection stops).
The default TimeToLive on Firefox is 115s (network.http.keep-alive.timeout)
The default connection timeout on Firefox is 250s (network.http.connection-retry-timeout)
The default request timeout for Firefox is 30s (network.http.pipelining.read-timeout).
The time it takes to do an HttpRequest depends on if a connection has been made this has to be within 250s which I'm guessing you're not after. You're probably after the request timeout which I think is 30,000ms (30s) so to conclude I'd say it's timing out with a connection time out that's why you got a response back after ~150s though I haven't really tested this.
For Mac OS X, save your CSV file in "Windows Comma Separated (.csv)" format.
You are looking for -H
option in gnu grep.
find . -name '*bills*' -exec grep -H "put" {} \;
-H, --with-filename
Print the filename for each match.
.compare()
returns an integer, which is a measure of the difference between the two strings.
0
indicates that the two strings compare as equal. operator==
simply returns a boolean, indicating whether the strings are equal or not.
If you don't need the extra detail, you may as well just use ==
.
The function takes a pointer to an arbitrary type and returns one such.
You can call a stored procedure using SqlQuery
(See here)
// Prepare the query
var query = context.Functions.SqlQuery(
"EXEC [dbo].[GetFunctionByID] @p1",
new SqlParameter("p1", 200));
// add NoTracking() if required
// Fetch the results
var result = query.ToList();
You could use a little javascript to calculate the darker and lighter color using the rgb().
Fiddle : Not really nice, but it is just for illustration.
What it essentially does is sets a color and selects 20 colors with the same amount (compared to one another) of rgb only with 10 apart.
for (var i=-10; i < $('.row:eq(0) .block').length/2 ; i++) {
var r = 91;
var g = 192;
var b = 222;
$('.row:eq(1) .block:eq('+(i+10)+')').css('background' , color(r+(i*10),g+(i*10),b+ (i*10)) );
};
Now you can do df['column'].dt.date
Note that for datetime objects, if you don't see the hour when they're all 00:00:00, that's not pandas. That's iPython notebook trying to make things look pretty.
These are class stereotypes used in analysis.
boundary classes are ones at the boundary of the system - the classes that you or other systems interact with
entity classes classes are your typical business entities like "person" and "bank account"
control classes implement some business logic or other
Using union will help in this case.
You can also use join on a condition that always returns true and is not related to data in these tables.See below
select tmd .name,tbc.goals from tblMadrid tmd join tblBarcelona tbc on 1=1;
You may want to also look into using Task
instead of background workers.
The easiest way to do this is in your example is Task.Run(InitializationThread);
.
There are several benefits to using tasks instead of background workers. For example, the new async/await features in .net 4.5 use Task
for threading. Here is some documentation about Task
https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task
You should check the EOF after reading from file.
fscanf_s // read from file
while(condition) // check EOF
{
fscanf_s // read from file
}
i don't see any for loop to initalize the variables.you can do something like this.
for(i=0;i<50;i++){
/* Code which is necessary with a simple if statement*/
}
Perfectly described here https://www.smashingmagazine.com/2014/05/moving-git-repository-new-server/
First, we have to fetch all of the remote branches and tags from the existing repository to our local index:
git fetch origin
We can check for any missing branches that we need to create a local copy of:
git branch -a
Let’s use the SSH-cloned URL of our new repository to create a new remote in our existing local repository:
git remote add new-origin [email protected]:manakor/manascope.git
Now we are ready to push all local branches and tags to the new remote named new-origin:
git push --all new-origin
git push --tags new-origin
Let’s make new-origin the default remote:
git remote rm origin
Rename new-origin to just origin, so that it becomes the default remote:
git remote rename new-origin origin
Would I just override the drawRect method?
Yes:
- (void)drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddEllipseInRect(ctx, rect);
CGContextSetFillColor(ctx, CGColorGetComponents([[UIColor blueColor] CGColor]));
CGContextFillPath(ctx);
}
Also, would it be okay to change the frame of that view within the class itself?
Ideally not, but you could.
Or do I need to change the frame from a different class?
I'd let the parent control that.
For those who still can't make this work, make sure that the overflowed element is displayed before using the jQuery function.
Example:
$('#elem').show();
$('#elem').scrollTop(0);
In case you want to hide and show an element, depending on whether it is already visible or not, you can use
toggle instead of .hide()
and .show()
$('elem').toggle();
If your array is not guaranteed to be populated from index zero, you can use Array.prototype.find()
:
var elements = []
elements[1] = 'foo'
elements[2] = 'bar'
var first = function(element) { return !!element }
var gotcha = elements.find(first)
console.log(a[0]) // undefined
console.log(gotcha) // 'foo'
Maybe your solutions works with ints, but It Doesnt work for me with dictionarys.
In one hand, remove() has not worked for me. But maybe it works with basic Types. I guess the code bellow is also the way to remove items from objects list.
In the other hand, 'del' has not worked properly either. In my case, using python 3.6: when I try to delete an element from a list in a 'for' bucle with 'del' command, python changes the index in the process and bucle stops prematurely before time. It only works if You delete element by element in reversed order. In this way you dont change the pending elements array index when you are going through it
Then, Im used:
c = len(list)-1
for element in (reversed(list)):
if condition(element):
del list[c]
c -= 1
print(list)
where 'list' is like [{'key1':value1'},{'key2':value2}, {'key3':value3}, ...]
Also You can do more pythonic using enumerate:
for i, element in enumerate(reversed(list)):
if condition(element):
del list[(i+1)*-1]
print(list)
A simple solution is to do this formula:
A1*7+DATE(A2,1,1)
If it returns a Wednesday, simply change the formula to:
(A1*7+DATE(A2,1,1))-2
This will only work for dates within one calendar year.
you should disable Instant Run android studio Settings.
File>Settings>Build,Execution, Deployment>Instant Run unCheck all options shown there.
Note: White screen Issue due to Instant Run is only for Debug builds,this Issue will not appear on release builds.
Pscp.exe is painfully slow.
Uploading files using WinSCP is like 10 times faster.
So, to do that from command line, first you got to add the winscp.com
file to your %PATH%. It's not a top-level domain, but an executable .com
file, which is located in your WinSCP installation directory.
Then just issue a simple command and your file will be uploaded much faster putty ever could:
WinSCP.com /command "open sftp://username:[email protected]:22" "put your_large_file.zip /var/www/somedirectory/" "exit"
And make sure your check the synchronize folders feature, which is basically what rsync
does, so you won't ever want to use pscp.exe again.
WinSCP.com /command "help synchronize"
Read this for detail :
// 1 define a function pointer and initialize to NULL
int (TMyClass::*pt2ConstMember)(float, char, char) const = NULL;
// C++
class TMyClass
{
public:
int DoIt(float a, char b, char c){ cout << "TMyClass::DoIt"<< endl; return a+b+c;};
int DoMore(float a, char b, char c) const
{ cout << "TMyClass::DoMore" << endl; return a-b+c; };
/* more of TMyClass */
};
pt2ConstMember = &TMyClass::DoIt; // note: <pt2Member> may also legally point to &DoMore
// Calling Function using Function Pointer
(*this.*pt2ConstMember)(12, 'a', 'b');
As funny as it may seem, the easiest way I found to save my 180MB spreadsheet into a UTF8 CSV file was to select the cells into Excel, copy them and to paste the content of the clipboard into SublimeText.
The problem is that for reasons of optimization the switch statement in C++ does not work on anything but primitive types, and you can only compare them with compile time constants.
Presumably the reason for the restriction is that the compiler is able to apply some form of optimization compiling the code down to one cmp instruction and a goto where the address is computed based on the value of the argument at runtime. Since branching and and loops don't play nicely with modern CPUs, this can be an important optimization.
To go around this, I am afraid you will have to resort to if statements.
We can use ng-src
but when ng-src's value
became null
, ''
or undefined
, ng-src
will not work.
So just use ng-if
for this case:
http://jsfiddle.net/Hx7B9/299/
<div ng-app>
<div ng-controller="AppCtrl">
<a href='#'><img ng-src="{{link}}" ng-if="!!link"/></a>
<button ng-click="changeLink()">Change Image</button>
</div>
</div>
This is a little faster (and looks nicer)
np.argmax(aa>5)
Since argmax
will stop at the first True
("In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.") and doesn't save another list.
In [2]: N = 10000
In [3]: aa = np.arange(-N,N)
In [4]: timeit np.argmax(aa>N/2)
100000 loops, best of 3: 52.3 us per loop
In [5]: timeit np.where(aa>N/2)[0][0]
10000 loops, best of 3: 141 us per loop
In [6]: timeit np.nonzero(aa>N/2)[0][0]
10000 loops, best of 3: 142 us per loop
If you are using Matplotlib and are trying to get good figures in a LaTeX document, save as an EPS. Specifically, try something like this after running the commands to plot the image:
plt.savefig('destination_path.eps', format='eps')
I have found that EPS files work best and the dpi
parameter is what really makes them look good in a document.
To specify the orientation of the figure before saving, simply call the following before the plt.savefig
call, but after creating the plot (assuming you have plotted using an axes with the name ax
):
ax.view_init(elev=elevation_angle, azim=azimuthal_angle)
Where elevation_angle
is a number (in degrees) specifying the polar angle (down from vertical z axis) and the azimuthal_angle
specifies the azimuthal angle (around the z axis).
I find that it is easiest to determine these values by first plotting the image and then rotating it and watching the current values of the angles appear towards the bottom of the window just below the actual plot. Keep in mind that the x, y, z, positions appear by default, but they are replaced with the two angles when you start to click+drag+rotate the image.
If you are using a third party library called apache commons-lang, the following solution can be useful:
Use StringUtils
class of apache commons-lang :
int i = 5;
StringUtils.leftPad(String.valueOf(i), 3, "0"); // --> "005"
As StringUtils.leftPad()
is faster than String.format()
What Arne said - you can't reliably style select boxes and have them look anything like consistent across browsers.
Uniform: https://github.com/pixelmatrix/uniform is a javascript solution which gives you good graphic control over your form elements - it's still Javascript, but it's about as nice as javascript gets for solving this problem.
It means you're passing the variable by reference.
In fact, in a declaration of a type, it means reference, just like:
int x = 42;
int& y = x;
declares a reference to x
, called y
.
This version should work:
DELETE WorkRecord2
FROM WorkRecord2
INNER JOIN Employee ON EmployeeRun=EmployeeNo
Where Company = '1' AND Date = '2013-05-06'
Bootstrap people use .hidden
class on <td>
.
I have Mac OS and I open Launchpad
and select docker
application.
from reset
tab click on restart
.
A little late, but here's a regex I found that returns 0 matches for empty or white spaces:
/^(?!\s*$).+/
You can test this out at regex101
There are 3 ways to pass data from Parent to Children
Through Children Router Resolver if you have to receive different data
this.data = this.route.snaphsot.data['dataFromResolver'];
Through Parent Router Resolver if your have to receive the same data from parent
this.data = this.route.parent.snaphsot.data['dataFromResolver'];
Note1: You can read about resolver here. There is also an example of resolver and how to register the resolver into the module and then retrieve data from resolver into the component. The resolver registration is the same on the parent and child.
Note2: You can read about ActivatedRoute here to be able to get data from router
Deadlock is a common problem in multiprocessing/multiprogramming problems in OS. Say there are two processes P1, P2 and two globally shareable resource R1, R2 and in critical section both resources need to be accessed
Initially, the OS assigns R1 to process P1 and R2 to process P2. As both processes are running concurrently they may start executing their code but the PROBLEM arises when a process hits the critical section. So process R1 will wait for process P2 to release R2 and vice versa... So they will wait for forever (DEADLOCK CONDITION).
A small ANALOGY...
Your Mother(OS),
You(P1),
Your brother(P2),
Apple(R1),
Knife(R2),
critical section(cutting apple with knife).Your mother gives you the apple and the knife to your brother in the beginning.
Both are happy and playing(Executing their codes).
Anyone of you wants to cut the apple(critical section) at some point.
You don't want to give the apple to your brother.
Your brother doesn't want to give the knife to you.
So both of you are going to wait for a long very long time :)
I use a trigger as a workaround to set a datetime field to NOW() for new inserts:
CREATE TRIGGER `triggername` BEFORE INSERT ON `tablename`
FOR EACH ROW
SET NEW.datetimefield = NOW()
it should work for updates too
Answers by Johan & Leonardo involve converting to a timestamp field. Although this is probably ok for the use case presented in the question (storing RegisterDate and LastVisitDate), it is not a universal solution. See datetime vs timestamp question.
RewriteCond %{HTTP_HOST} ^!example.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
This starts with the HTTP_HOST
variable, which contains just the domain name portion of the incoming URL (example.com
). Assuming the domain name does not contain a www.
and matches your domain name exactly, then the RewriteRule comes into play. The pattern ^(.*)$
will match everything in the REQUEST_URI
, which is the resource requested in the HTTP request (foo/blah/index.html
). It stores this in a back reference, which is then used to rewrite the URL with the new domain name (one that starts with www
).
[NC]
indicates case-insensitive pattern matching, [R=301]
indicates an external redirect using code 301 (resource moved permanently), and [L]
stops all further rewriting, and redirects immediately.
To follow these instructions in Windows make sure you have installed Git for Windows. In Windows, I like to use Git Bash so that it feels more like Linux.
First, we want to create a special Sublime Text project so that we can specify special project settings we want set whenever Git calls the editor, to make things easier when editing in Git. For example, I normally set my ruler to 120 chars in most projects, but for Git commit messages I want it to be 72 characters so that it fits nicely in a terminal when you call git log
or git lg
.
Open Sublime Text and go to menu "File" ? "New Window" to create a new anonymous project. Go to menu "Project" ? "Save Project As..." and choose a place to save it. In Linux I saved it in my Linux home directory with the file name .gitconfig.sublime-project
. Its path is therefore: ~/.gitconfig.sublime-project
. In Windows also save it in your home directory, for example: C:\Users\MY_USER_NAME\.gitconfig.sublime-project
Now go to menu "Project" ? "Edit Project" to edit the project settings. Paste the following and save the settings. Make any further edits for your project settings if desired.
{
// For folder settings help see here: https://www.sublimetext.com/docs/3/projects.html
"folders":
[
],
"settings":
{
// Disables horizontal scrolling if enabled.
// May be set to true, false, or "auto", where it will be disabled for
// source code, and otherwise enabled.
"word_wrap": false,
// Set to a value other than 0 to force wrapping at that column rather than the
// window width
"wrap_width": 0,
// Columns in which to display vertical rulers
"rulers": [72, 50], //72 is recommended by git for commit message content, and 50 for commit titles
// The number of spaces a tab is considered equal to
"tab_size": 4,
// Set to true to insert spaces when tab is pressed
"translate_tabs_to_spaces": true,
},
"build_systems":
[
]
}
Now we need to set the editor to be used by Git, by editing the .gitconfig
file.
Your user copy of this will be located in ~/.gitconfig
. Open this file and add the following lines. Be sure to use the proper path name to the Git project you just created above! I'm using ~/.gitconfig.sublime-project
.
[core]
editor = subl --project ~/.gitconfig.sublime-project --wait
The --wait
is important, as it forces Git to wait until you close the file before it continues on. The --project
line is important to tell Sublime Text which project you want opened whenever Git opens Sublime Text.
Per @digitaldreamer's answer above (https://stackoverflow.com/a/2596835/4561887), "subl
can be replaced by the full path of the executable but [the alias subl
] is usually available when [Sublime is] correctly installed."
For Windows, first read the Linux instructions for background information. Now we will do something almost identical.
(OPTIONAL: create a subl
alias for use in Git Bash):
Open up a text editor (for example, Notepad, Notepad++, Sublime Text, Geany, etc.), and create a file called ".bash_profile" in your home directory. Its path will therefore be: C:\Users\MY_USER_NAME\.bash_profile
. Save the following into it:
alias subl="/c/Program\ Files/Sublime\ Text\ 3/subl.exe"
This creates a Git Bash alias called subl
that we can now use in Git Bash for Windows, to easily open Sublime Text. This step isn't required, but it's useful for general Git Bash use. Now you can call subl .
, for instance, in Git Bash to open up a new Sublime Text project in your current directory.
(MANDATORY):
Edit the .gitconfig
file found in your home directory: C:\Users\MY_USER_NAME\.gitconfig
, by adding the following to it. Notice the subtle changes from the Linux instructions above:
[core]
editor = 'C:/Program Files/Sublime Text 3/subl.exe' --project ~/.gitconfig.sublime-project --wait
/
NOT \
to separate folders in the path name! (Thanks VonC for helping me see this).subl
alias we made for Git Bash above doesn't work here, so you can't use it like we did in the Linux example, instead you must specify the whole path as shown above.~
symbol, however, does still work here to get to your Windows home directory.This gives you syntax highlighting for git commit
messages, as well as access to other Git commands such as git blame
(which I use frequently in Sublime Text) or git commit
(which I don't use in Sublime Text since I'd prefer the command-line for general Git flow, as I've mentioned in my comments below this answer).
To install a package: First, ensure “Package Control” is installed. Next, press Ctrl + Shift + P (same as Tools ? Command Palette) and type all or part of “Package Control: Install Package”, then press Enter. In the search box that comes up, search for the package "Git" and hit Enter on it, or click on it, to automatically install it.
Once installed, Ctrl + Shift + P then searching for "git" will bring up Git commands you can use internally inside Sublime Text now, such as git blame
.
Now when you call git commit
, for instance, as normal from the command-line, Sublime Text will open up into the .gitconfig.sublime-project
we created above, with that project's settings! As you type a paragraph you'll notice it extends past the ruler we set since soft word-wrap is off. To force hard wrap via auto-inserted hard-returns at the end of each line, put your cursor on the long line you want auto-wrapped and press Alt + Q. It will now hard-wrap/hard-fold at 72 characters, which is what we set in the project settings' "rulers" parameter above.
Now, save your commit message with Ctrl + S, and exit (to complete your git commit
) with Ctrl + Shift + W.
Done!
Not yet, but the New NIO (JSR 203) will have support for these common operations.
In the meantime, there are a few things to keep in mind.
File.renameTo generally works only on the same file system volume. I think of this as the equivalent to a "mv" command. Use it if you can, but for general copy and move support, you'll need to have a fallback.
When a rename doesn't work you will need to actually copy the file (deleting the original with File.delete if it's a "move" operation). To do this with the greatest efficiency, use the FileChannel.transferTo or FileChannel.transferFrom methods. The implementation is platform specific, but in general, when copying from one file to another, implementations avoid transporting data back and forth between kernel and user space, yielding a big boost in efficiency.
If you're on a page and this does not work:
$page_object = get_queried_object();
$page_id = get_queried_object_id();
you can try to build the permalink manually with PHP so you can lookup the post ID:
// get or make permalink
$url = !empty(get_the_permalink()) ? get_the_permalink() : (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$permalink = strtok($url, '?');
// get post_id using url/permalink
$post_id = url_to_postid($url);
// want the post or postmeta? use get_post() or get_post_meta()
$post = get_post($post_id);
$postmeta = get_post_meta($post_id);
It may not catch every possible permalink (especially since I'm stripping out the query string), but you can modify it to fit your use case.
That is okay for removing of data connections by using VBA as follows:
Sub deleteConn()
Dim xlBook As Workbook
Dim Cn As WorkbookConnection
Dim xlSheet As Worksheet
Dim Qt As QueryTable
Set xlBook = ActiveWorkbook
For Each Cn In xlBook.Connections
Debug.Print VarType(Cn)
Cn.Delete
Next Cn
For Each xlSheet In xlBook.Worksheets
For Each Qt In xlSheet.QueryTables
Debug.Print Qt.Name
Qt.Delete
Next Qt
Next xlSheet
End Sub
The preferred approach should be:
Double.valueOf(d).longValue()
From the Double (Java Platform SE 7) documentation:
Double.valueOf(d)
Returns a
Double
instance representing the specifieddouble
value. If a newDouble
instance is not required, this method should generally be used in preference to the constructorDouble(double)
, as this method is likely to yield significantly better space and time performance by caching frequently requested values.
public IList<Splitting> get(Guid companyId, long customrId) {
var res=from c in Customers_data_source
where c.CustomerId = customrId && c.CompanyID == companyId
from s in Splittings_data_srouce
where s.CustomerID = c.CustomerID
select s;
return res.ToList();
}
So, when using gcc, I like:
#define DBGI(expr) ({int g2rE3=expr; fprintf(stderr, "%s:%d:%s(): ""%s->%i\n", __FILE__, __LINE__, __func__, #expr, g2rE3); g2rE3;})
Because it can be inserted into code.
Suppose you're trying to debug
printf("%i\n", (1*2*3*4*5*6));
720
Then you can change it to:
printf("%i\n", DBGI(1*2*3*4*5*6));
hello.c:86:main(): 1*2*3*4*5*6->720
720
And you can get an analysis of what expression was evaluated to what.
It's protected against the double-evaluation problem, but the absence of gensyms does leave it open to name-collisions.
However it does nest:
DBGI(printf("%i\n", DBGI(1*2*3*4*5*6)));
hello.c:86:main(): 1*2*3*4*5*6->720
720
hello.c:86:main(): printf("%i\n", DBGI(1*2*3*4*5*6))->4
So I think that as long as you avoid using g2rE3 as a variable name, you'll be OK.
Certainly I've found it (and allied versions for strings, and versions for debug levels etc) invaluable.