I used the following psd that I derived from http://www.teehanlax.com/blog/?p=447
http://www.chrisandtennille.com/pictures/backbutton.psd
I then just created a custom UIView that I use in the customView property of the toolbar item.
Works well for me.
Edit: As pointed out by PrairieHippo, maralbjo found that using the following, simple code did the trick (requires custom image in bundle) should be combined with this answer. So here is additional code:
// Creates a back button instead of default behaviour (displaying title of previous screen)
UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back_arrow.png"]
style:UIBarButtonItemStyleBordered
target:self
action:@selector(backAction)];
tipsDetailViewController.navigationItem.leftBarButtonItem = backButton;
[backButton release];
This one might be good
function addDayswithdate($date,$days){
$date = strtotime("+".$days." days", strtotime($date));
return date("Y-m-d", $date);
}
A tidyverse way to count the number of nulls in every column of a dataframe:
library(tidyverse)
library(purrr)
df %>%
map_df(function(x) sum(is.na(x))) %>%
gather(feature, num_nulls) %>%
print(n = 100)
Here is what made the error disappear for me:
Close eclipse, open up a terminal window and run:
$ mvn clean eclipse:clean eclipse:eclipse
Are you using Maven? If so,
To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.
And then clean
Edit 1:
If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.
Edit 2:
You can also try going into the folder where you have all your projects and delete the .metadata
for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.
With Swift 5 and iOS 12, according to your needs, you may use one of the two following ways to find the difference between two dates in days.
Calendar
's dateComponents(_:from:to:)
methodimport Foundation
let calendar = Calendar.current
let startDate = calendar.date(from: DateComponents(year: 2010, month: 11, day: 22))!
let endDate = calendar.date(from: DateComponents(year: 2015, month: 5, day: 1))!
let dateComponents = calendar.dateComponents([Calendar.Component.day], from: startDate, to: endDate)
print(dateComponents) // prints: day: 1621 isLeapMonth: false
print(String(describing: dateComponents.day)) // prints: Optional(1621)
DateComponentsFormatter
's string(from:to:)
methodimport Foundation
let calendar = Calendar.current
let startDate = calendar.date(from: DateComponents(year: 2010, month: 11, day: 22))!
let endDate = calendar.date(from: DateComponents(year: 2015, month: 5, day: 1))!
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.allowedUnits = [NSCalendar.Unit.day]
let elapsedTime = formatter.string(from: startDate, to: endDate)
print(String(describing: elapsedTime)) // prints: Optional("1,621 days")
SELECT SUBDATE(NOW(),1);
where now() function returs current date and time of system in Timestamp...
you can use:
SELECT SUBDATE(CURDATE(),1)
Programmatically: Run time
You can do programmatically using setTypeface():
textView.setTypeface(null, Typeface.NORMAL); // for Normal Text
textView.setTypeface(null, Typeface.BOLD); // for Bold only
textView.setTypeface(null, Typeface.ITALIC); // for Italic
textView.setTypeface(null, Typeface.BOLD_ITALIC); // for Bold and Italic
XML: Design Time
You can set in XML as well:
android:textStyle="normal"
android:textStyle="normal|bold"
android:textStyle="normal|italic"
android:textStyle="bold"
android:textStyle="bold|italic"
Hope this will help
Summved
If you use different windows user, your SSH key and git settings will be independent.
If this is not an option for you, then your friend should add your SSH key to her Github account.
Although, previous solution will keep you pushing as yourself, but it will allow you to push into her repo. If you don't want this and work in different folder on the same pc, you can setup username and email locally inside a folder with git by removing -g
flag of the config command:
git config user.name her_username
git config user.email her_email
Alternatively, if you push over https
protocol, Github will prompt for username/password every time (unless you use a password manager).
To get the position look at the OnMouseMove event. The MouseEventArgs will give you the x an y positions...
protected override void OnMouseMove(MouseEventArgs mouseEv)
To set the mouse position use the Cursor.Position property.
http://msdn.microsoft.com/en-us/library/system.windows.forms.cursor.position.aspx
Another way of initializing an array of structs is to initialize the array members explicitly. This approach is useful and simple if there aren't too many struct and array members.
Use the typedef
specifier to avoid re-using the struct
statement everytime you declare a struct variable:
typedef struct
{
double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
}Body;
Then declare your array of structs. Initialization of each element goes along with the declaration:
Body bodies[n] = {{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0},
{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0},
{{0,0,0}, {0,0,0}, {0,0,0}, 0, 1.0}};
To repeat, this is a rather simple and straightforward solution if you don't have too many array elements and large struct members and if you, as you stated, are not interested in a more dynamic approach. This approach can also be useful if the struct members are initialized with named enum-variables (and not just numbers like the example above) whereby it gives the code-reader a better overview of the purpose and function of a structure and its members in certain applications.
First of all, you should use none of them. You are using wrapper
type, which should rarely be used in case you have a primitive type.
So, you should use boolean
rather.
Further, we initialize the boolean
variable to false
to hold an initial default value which is false. In case you have declared it as instance variable, it will automatically be initialized to false
.
But, its completely upto you, whether you assign a default value or not. I rather prefer to initialize them at the time of declaration.
But if you are immediately assigning to your variable, then you can directly assign a value to it, without having to define a default
value.
So, in your case I would use it like this: -
boolean isMatch = email1.equals (email2);
This is a revised solution that will also work for modal windows rendered using a Grails template, where you can have the same modal template called multiple times (with different values) in the same body. This thread helped me immensely, so I thought I'd share it in case other Grails users found their way here.
For those who are curious, the accepted solution didn't work for me because I am rendering a table; each row has a button that opens a modal window with more details about the record. This led to multiple printSection divs being created and printed on top of each other. Therefore I had to revise the js to clean up the div after it was done printing.
I added this CSS directly to my modal gsp, but adding it to the parent has the same effect.
<style type="text/css">
@media screen {
#printSection {
display: none;
}
}
@media print {
body > *:not(#printSection) {
display: none;
}
#printSection, #printSection * {
visibility: visible;
}
#printSection {
position:absolute;
left:0;
top:0;
}
}
</style>
Adding it to the site-wide CSS killed the print functionality in other parts of the site. I got this from ComFreak's accepted answer (based on Bennett McElwee answer), but it is revised using ':not' functionality from fanfavorite's answer on Print <div id=printarea></div> only? . I opted for 'display' rather than 'visibility' because my invisible body content was creating extra blank pages, which was unacceptable to my users.
And this to my javascript, revised from ComFreak's accepted answer to this question.
function printDiv(div) {
// Create and insert new print section
var elem = document.getElementById(div);
var domClone = elem.cloneNode(true);
var $printSection = document.createElement("div");
$printSection.id = "printSection";
$printSection.appendChild(domClone);
document.body.insertBefore($printSection, document.body.firstChild);
window.print();
// Clean up print section for future use
var oldElem = document.getElementById("printSection");
if (oldElem != null) { oldElem.parentNode.removeChild(oldElem); }
//oldElem.remove() not supported by IE
return true;
}
I had no need for appending elements, so I removed that aspect and changed the function to specifically print a div.
And the modal template. This prints the modal header & body and excludes the footer, where the buttons were located.
<div class="modal-content">
<div id="print-me"> <!-- This is the div that is cloned and printed -->
<div class="modal-header">
<!-- HEADER CONTENT -->
</div>
<div class="modal-body">
<!-- BODY CONTENT -->
</div>
</div>
<div class="modal-footer">
<!-- This is where I specify the div to print -->
<button type="button" class="btn btn-default" onclick="printDiv('print-me')">Print</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
I hope that helps someone!
Simply by "unpacking" the list in the print function argument and using a newline (\n) as separator.
print(*lst, sep='\n')
lst = ['foo', 'bar', 'spam', 'egg']
print(*lst, sep='\n')
foo
bar
spam
egg
the simple way I believe is to import it then export it, using the certificate manager in Windows Management Console.
In most cases simply switching the virtual machine network adapter to bridged mode is enough to make the guest machine accessible from outside.
Sometimes it's possible for the guest machine to not automatically receive an IP which matches the host's IP range after switching to bridged mode (even after rebooting the guest machine). This is often caused by a malfunctioning or badly configured DHCP on the host network.
For example, if the host IP is 192.168.1.1
the guest machine needs to have an IP in the format 192.168.1.*
where only the last group of numbers is allowed to be different from the host IP.
You can use a terminal (shell) and type ifconfig
(ipconfig
for Windows guests) to check what IP is assigned to the guest machine and change it if required.
If the host and guest IPs do not match simply setting a static IP for the guest machine explicitly should resolve the issue.
You'll have to create a custom object for that. Your custom object will contain two values:
Not sure if there already is a CLR-provided data type that has that, but at least the TimeZone component is already available.
Use compact
function view($view)
{
$ms = Person::where('name', '=', 'Foo Bar')->first();
$persons = Person::order_by('list_order', 'ASC')->get();
return View::make('users', compact('ms','persons'));
}
This happens because $cOTLdata
is not null but the index 'char_data'
does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.
To check whether the index exists or not you can use isset():
isset($cOTLdata['char_data'])
Which means the line should look something like this:
$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).
Here is how to set variables in the package from code -
using Microsoft.SqlServer.Dts.Runtime;
private void Execute_Package()
{
string pkgLocation = @"c:\test.dtsx";
Package pkg;
Application app;
DTSExecResult pkgResults;
Variables vars;
app = new Application();
pkg = app.LoadPackage(pkgLocation, null);
vars = pkg.Variables;
vars["A_Variable"].Value = "Some value";
pkgResults = pkg.Execute(null, vars, null, null, null);
if (pkgResults == DTSExecResult.Success)
Console.WriteLine("Package ran successfully");
else
Console.WriteLine("Package failed");
}
From 6.11. Boolean operations:
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.
The key phrasing here that I think you are misunderstanding is "interpreted as false" or "interpreted as true". This does not mean that any of those values are identical to True or False, or even equal to True or False.
The expression '/bla/bla/bla'
will be treated as true where a Boolean expression is expected (like in an if
statement), but the expressions '/bla/bla/bla' is True
and '/bla/bla/bla' == True
will evaluate to False for the reasons in Ignacio's answer.
Namenode enters into safemode when there is shortage of memory. As a result the HDFS becomes readable only. That means one can not create any additional directory or file in the HDFS. To come out of the safemode, the following command is used:
hadoop dfsadmin -safemode leave
If you are using cloudera manager:
go to >>Actions>>Leave Safemode
But it doesn't always solve the problem. The complete solution lies in making some space in the memory. Use the following command to check your memory usage.
free -m
If you are using cloudera, you can also check if the HDFS is showing some signs of bad health. It probably must be showing some memory issue related to the namenode. Allot more memory by following the options available. I am not sure what commands to use for the same if you are not using cloudera manager but there must be a way. Hope it helps! :)
I was able to get what I needed using Martinho Fernandes' solution below. The code is:
var test = "My cow always gives milk";
var testRE = test.match("cow(.*)milk");
alert(testRE[1]);
You'll notice that I am alerting the testRE variable as an array. This is because testRE is returning as an array, for some reason. The output from:
My cow always gives milk
Changes into:
always gives
You get this error, despite everything being in line, because of a conflict caused by one of the packages that are currently loaded in your R environment.
So, to solve this issue, detach all the packages that are not needed from the R environment. For example, when I had the same issue, I did the following:
detach(package:neuralnet)
bottom line: detach all the libraries no longer needed for execution... and the problem will be solved.
string GetString(RichTextBox rtb)
{
var textRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
return textRange.Text;
}
Yahoo is very easy to use and provides customized data. Use the following page to learn more.
finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT=pder=.csv
WARNING - there are a few tutorials out there on the web that show you how to do this, but the region where you put in the stock symbols causes an error if you use it as posted. You will get a "MISSING FORMAT VALUE". The tutorials I found omits the commentary around GOOG.
Example URL for GOOG: http://download.finance.yahoo.com/d/quotes.csv?s=%40%5EDJI,GOOG&f=nsl1op&e=.csv
A span is an inline formatting element that does NOT have a line feed above or below.
A p is a block element that HAS an implied line feed above and below.
The match attribute indicates on which parts the template transformation is going to be applied. In that particular case the "/" means the root of the xml document. The value you have to provide into the match attribute should be XPath expression. XPath is the language you have to use to refer specific parts of the target xml file.
To gain a meaningful understanding of what else you can put into match attribute you need to understand what xpath is and how to use it. I suggest yo look at links I've provided for youat the bottom of the answer.
Could I write "table" or any other html tag instead of "/" ?
Yes you can. But this depends what exactly you are trying to do. if your target xml file contains HMTL elements and you are triyng to apply this xsl:template on them it makes sense to use table, div or anithing else.
Here a few links:
sorry for answering in old thread but may my code helps other in future.i was in same scenario that when check box will be checked then few selected inputs fields will be enable other wise disabled.
$("[id*='chkAddressChange']").click(function () {
var checked = $(this).is(':checked');
if (checked) {
$('.DisabledInputs').removeAttr('disabled');
} else {
$('.DisabledInputs').attr('disabled', 'disabled');
}
});
If you want to dynamically change it, I prefer using SqlConnectionStringBuilder .
It allows you to convert ConnectionString i.e. a string into class Object, All the connection string properties will become its Member.
In this case the real advantage would be that you don't have to worry about If the ConnectionTimeout string part is already exists in the connection string or not?
Also as it creates an Object and its always good to assign value in object rather than manipulating string.
Here is the code sample:
var sscsb = new SqlConnectionStringBuilder(_dbFactory.Database.ConnectionString);
sscsb.ConnectTimeout = 30;
var conn = new SqlConnection(sscsb.ConnectionString);
Be careful with the "Range(...)" without first qualifying a Worksheet because it will use the currently Active worksheet to make the copy from. It's best to fully qualify both sheets. Please give this a shot (please change "Sheet1" with the copy worksheet):
EDIT: edited for pasting values only based on comments below.
Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
Dim copySheet As Worksheet
Dim pasteSheet As Worksheet
Set copySheet = Worksheets("Sheet1")
Set pasteSheet = Worksheets("Sheet2")
copySheet.Range("A3:E3").Copy
pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
use an unsigned long long (i.e. a 64 bit unit) to represent the system time:
typedef unsigned long long u64;
u64 u64useconds;
struct timeval tv;
gettimeofday(&tv,NULL);
u64useconds = (1000000*tv.tv_sec) + tv.tv_usec;
The other answers to this question seem to hit it spot on. Now how would you figure this out for yourself without stack overflow? Check out IPython, an interactive Python shell that has tab auto-complete.
> ipython
import Python 2.5 (r25:51908, Nov 6 2007, 16:54:01)
Type "copyright", "credits" or "license" for more information.
IPython 0.8.2.svn.r2750 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
In [1]: import datetime
In [2]: now=datetime.datetime.now()
In [3]: now.
press tab a few times and you'll be prompted with the members of the "now" object:
now.__add__ now.__gt__ now.__radd__ now.__sub__ now.fromordinal now.microsecond now.second now.toordinal now.weekday
now.__class__ now.__hash__ now.__reduce__ now.astimezone now.fromtimestamp now.min now.strftime now.tzinfo now.year
now.__delattr__ now.__init__ now.__reduce_ex__ now.combine now.hour now.minute now.strptime now.tzname
now.__doc__ now.__le__ now.__repr__ now.ctime now.isocalendar now.month now.time now.utcfromtimestamp
now.__eq__ now.__lt__ now.__rsub__ now.date now.isoformat now.now now.timetuple now.utcnow
now.__ge__ now.__ne__ now.__setattr__ now.day now.isoweekday now.replace now.timetz now.utcoffset
now.__getattribute__ now.__new__ now.__str__ now.dst now.max now.resolution now.today now.utctimetuple
and you'll see that now.year is a member of the "now" object.
Alternately, you could do a Text to Columns with space as the delimiter.
I'd personally suggest using a different unit of measurement than px
. I don't think that pixels have much relevance in terms of print; ideally you'd use:
I'm sure there are others, and one excellent article about print-css can be found here: Going to Print, by Eric Meyer.
Also for openCV in python you can do:
img = cv2.imread('myImage.jpg')
height, width, channels = img.shape
if (object is IBlah)
or
IBlah myTest = originalObject as IBlah
if (myTest != null)
I'm not sure that is the problem but what worked for me is calling mVideoView.start();
inside the mVideoView.setOnPreparedListener
event callback.
For example:
Uri uriVideo = Uri.parse(<your link here>);
MediaController mediaController = new MediaController(mContext);
mediaController.setAnchorView(mVideoView);
mVideoView.setMediaController(mediaController);
mVideoView.setVideoURI(uriVideo);
mVideoView.requestFocus();
mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
@Override
public void onPrepared(MediaPlayer mp)
{
mVideoViewPeekItem.start();
}
});
I also wondered that long time ago. I searched a bit in my history and I think that this post: http://lists.mysql.com/internals/34919 represents the semi-official position of MySQL (before Oracle's intervention ;))
In short:
this limitation stems only from the way in which this feature is currently implemented in the server and there are no other reasons for its existence.
So their explanation is "because it is implemented like this". Doesn't sound very scientific. I guess it all comes from some old code. This is suggested in the thread above: "carry-over from when only the first timestamp field was auto-set/update".
Cheers!
As far as I am aware, simply opening the file in write mode without append mode will erase the contents of the file.
ofstream file("filename.txt"); // Without append
ofstream file("filename.txt", ios::app); // with append
The first one will place the position bit at the beginning erasing all contents while the second version will place the position bit at the end-of-file bit and write from there.
One option not mentioned in other posts is Helios. It is built by spotify and does not try to do too much.
If you just need to await
to avoid nesting code:
let json;
await new Promise(done => $.getJSON('https://***', async function (data) {
json = data;
done();
}));
You want the 'change' event handler, instead of 'click'.
$('#mySelect').change(function(){
var value = $(this).val();
});
To set the default using PHP and JavaScript:
State: <select id="State">
<option value="" selected disabled hidden></option>
<option value="Andhra Pradesh">Andhra Pradesh</option>
<option value="Andaman and Nicobar Islands">Andaman and Nicobar Islands</option>
.
.
<option value="West Bengal">West Bengal</option>
</select>
<?php
if(isset($_GET['State'])){
echo <<<heredoc
<script>
document.getElementById("State").querySelector('option[value="{$_GET['State']}"]').selected = true;
</script>
heredoc;
}
?>
Try to make your css more specific so that the new (green) style is more specific than the previous one, so that it worked for me!
For example, you might use in css:
button:active {/*your style here*/}
Instead of (probably not working):
.active {/*style*/} (.active is not a pseudo-class)
Hope it helps!
It seems impossible to prevent spinners from appearing in Opera. As a temporary workaround, you can make room for the spinners. As far as I can tell, the following CSS adds just enough padding, only in Opera:
noindex:-o-prefocus,
input[type=number] {
padding-right: 1.2em;
}
Get text from a dropdown multiple
var texts = [];
$('#list :selected').each(function(){
texts.push($(this).text());
});
texts now contains a list of selected text
A hashtable is the traditional implementation of a simple "Dictionary". If you don't care about speed or size, just google for it. There are many freely available implementations.
here's the first one I saw -- at a glance, it looks ok to me. (it's pretty basic. If you really want it to hold an unlimited amount of data, then you'll need to add some logic to "realloc" the table memory as it grows.)
good luck!
Now show it using jquery show element function just above your ajax.
$('#example_load').show();
$.ajax({
type: "POST",
data: {},
url: '/url',
success: function(){
// Now hide the load element
$('#example_load').hide();
}
});
For SQL Server 2012 Management Studio, this file has moved. It is now located at:
C:\Users\<username>\AppData\Roaming\Microsoft\
SQL Server Management Studio\11.0\SqlStudio.bin
Try the sql server management studio (version 2008 or earlier) from Microsoft. Download it from here. Not sure about the license, but it seems to be free if you download the EXPRESS EDITION.
You might also be able to use later editions of SSMS. For 2016, you will need to install an extension.
If you have the option you can copy the sdf file to a different machine which you are allowed to pollute with additional software.
Update: comment from Nick Westgate in nice formatting
The steps are not all that intuitive:
- Open SQL Server Management Studio, or if it's running select File -> Connect Object Explorer...
- In the Connect to Server dialog change Server type to SQL Server Compact Edition
- From the Database file dropdown select < Browse for more...>
- Open your SDF file.
.NET Framework and .NET Core are both frameworks.
.NET Standard is a standard (in other words, a specification).
You can make an executable project (like a console application, or ASP.NET application) with .NET Framework and .NET Core, but not with .NET Standard.
With .NET Standard you can make only a class library project that cannot be executed standalone and should be referenced by another .NET Core or .NET Framework executable project.
I use something like this:
if schema_id('newSchema') is null
exec('create schema newSchema');
The advantage is if you have this code in a long sql-script you can always execute it with the other code, and its short.
for existing repository
type in terminal
$ heroku git:remote -a example
public static string XmlEscape(string unescaped)
{
XmlDocument doc = new XmlDocument();
XmlNode node = doc.CreateElement("root");
node.InnerText = unescaped;
return node.InnerXml;
}
public static string XmlUnescape(string escaped)
{
XmlDocument doc = new XmlDocument();
XmlNode node = doc.CreateElement("root");
node.InnerXml = escaped;
return node.InnerText;
}
create attribute name is "price_screen_tab_name
". and access using this simple formula.
<?php $_product = $this->getProduct(); ?>
<?php echo $_product->getData('price_screen_tab_name');?>
The "0x" counts towards the eight character count. You need "%#010x"
.
Note that #
does not append the 0x to 0 - the result will be 0000000000
- so you probably actually should just use "0x%08x"
anyway.
SOLVED! I register to stockoverflow just to share to you the only solution (at least in ASP.NET/IE/FF/Chrome) that works! The idea is to replace innerHTML value of a div by its current innerHTML value.
Here is the HTML snippet:
<div class="content-2" id="divGranite">
<h2>Granite Purchase</h2>
<IFRAME runat="server" id="frameGranite" src="Jobs-granite.aspx" width="820px" height="300px" frameborder="0" seamless ></IFRAME>
</div>
And my Javascript code:
function refreshGranite() {
var iframe = document.getElementById('divGranite')
iframe.innerHTML = iframe.innerHTML;
}
Hope this helps.
dot -Tps input.dot > output.eps
dot -Tpng input.dot > output.png
PostScript output seems always there. I am not sure if dot has PNG output by default. This may depend on how you have built it.
You can try this:
string sql = "UPDATE Customer SET City = @City WHERE CustomerId = @CustomerId";
conn.Execute(sql, customerEntity);
If you already have your line of text in a variable $LINE, then you should be able to say
for L in $LINE; do
echo $L;
done
They are called the Positional Parameters.
3.4.1 Positional Parameters
A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell’s arguments when it is invoked, and may be reassigned using the set builtin command. Positional parameter N may be referenced as ${N}, or as $N when N consists of a single digit. Positional parameters may not be assigned to with assignment statements. The set and shift builtins are used to set and unset them (see Shell Builtin Commands). The positional parameters are temporarily replaced when a shell function is executed (see Shell Functions).
When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces.
I recently made this python program to convert Decimal to Hexadecimal, please check this out. This is my first Answer in stack overflow .
decimal = int(input("Enter the Decimal no that you want to convert to Hexadecimal : "))
intact = decimal
hexadecimal = ''
dictionary = {1:'1',2:'2',3:'3',4:'4',5:'5',6:'6',7:'7',8:'8',9:'9',10:'A',11:'B',12:'C',13:'D',14:'E',15:'F'}
while(decimal!=0):
c = decimal%16
hexadecimal = dictionary[c] + hexadecimal
decimal = int(decimal/16)
print(f"{intact} is {hexadecimal} in Hexadecimal")
When you Execute this code this will give output as:
Enter the Decimal no that you want to convert to Hexadecimal : 2766
2766 is ACE in Hexadecimal
axios.get
accepts a request config as the second parameter (not query string params).
You can use the params
config option to set query string params as follows:
axios.get('/api', {
params: {
foo: 'bar'
}
});
One user control can't be applied to it ownself. So open another winform and the one will appear in the toolbox.
Instead of trying to learn vim, use a different easier editor (like nano, for example). As much as I like vim, I do not think using it in this case is the solution. It takes dedication and time to master it.
git config core.editor "nano"
What kind of processing are you trying to do? You can do XmlDocument doc = new XmlDocument();
followed by doc.Load(filename)
. Then the XML document can be parsed in memory.
Read here for more information on XmlDocument:
Thanks Jim Lewis for his great answer and I would like to illustrate this solution by my function in Swift:
func getRandomLocation(forLocation location: CLLocation, withOffsetKM offset: Double) -> CLLocation {
let latDistance = (Double(arc4random()) / Double(UInt32.max)) * offset * 2.0 - offset
let longDistanceMax = sqrt(offset * offset - latDistance * latDistance)
let longDistance = (Double(arc4random()) / Double(UInt32.max)) * longDistanceMax * 2.0 - longDistanceMax
let lat: CLLocationDegrees = location.coordinate.latitude + latDistance / 110.574
let lng: CLLocationDegrees = location.coordinate.longitude + longDistance / (111.320 * cos(lat / .pi / 180))
return CLLocation(latitude: lat, longitude: lng)
}
In this function to convert distance I use following formulas:
latDistance / 110.574
longDistance / (111.320 * cos(lat / .pi / 180))
I think this sample explains the difference between the styles:
james@bodacious-wired:~$cat test.py
#!/usr/bin/env python
class MyClass:
element1 = "Hello"
def __init__(self):
self.element2 = "World"
obj = MyClass()
print dir(MyClass)
print "--"
print dir(obj)
print "--"
print obj.element1
print obj.element2
print MyClass.element1 + " " + MyClass.element2
james@bodacious-wired:~$./test.py
['__doc__', '__init__', '__module__', 'element1']
--
['__doc__', '__init__', '__module__', 'element1', 'element2']
--
Hello World
Hello
Traceback (most recent call last):
File "./test.py", line 17, in <module>
print MyClass.element2
AttributeError: class MyClass has no attribute 'element2'
element1 is bound to the class, element2 is bound to an instance of the class.
just for development in windows
$Env:NODE_TLS_REJECT_UNAUTHORIZED=0
Current date is in yyyy-mm-dd
format. You can convert it into yyyymmdd
format using substring
function:
select substr(current date,1,4)||substr(current date,6,2)||substr(currentdate,9,2)
Your head should include the preload rel as follows:
<head>
...
<link rel="preload" as="font" href="/somefolder/font-one.woff2">
<link rel="preload" as="font" href="/somefolder/font-two.woff2">
</head>
This way woff2 will be preloaded by browsers that support preload, and all the fallback formats will load as they normally do.
And your css font face should look similar to to this
@font-face {
font-family: FontOne;
src: url(../somefolder/font-one.eot);
src: url(../somefolder/font-one.eot?#iefix) format('embedded-opentype'),
url(../somefolder/font-one.woff2) format('woff2'), //Will be preloaded
url(../somefolder/font-one.woff) format('woff'),
url(../somefolder/font-one.ttf) format('truetype'),
url(../somefolder/font-one.svg#svgFontName) format('svg');
}
@font-face {
font-family: FontTwo;
src: url(../somefolder/font-two.eot);
src: url(../somefolder/font-two.eot?#iefix) format('embedded-opentype'),
url(../somefolder/font-two.woff2) format('woff2'), //Will be preloaded
url(../somefolder/font-two.woff) format('woff'),
url(../somefolder/font-two.ttf) format('truetype'),
url(../somefolder/font-two.svg#svgFontName) format('svg');
}
Generalizing on martinedwards and others' ideas, you can glue a bunch of columns together (not just a pair) by adjusting padding of even and odd column children. Adding this definition of a class, .no-gutter
, and placing it on your .row
element
.row.no-gutter > [class*='col-']:nth-child(2n+1) {
padding-right: 0;
}
.row.no-gutter > [class*='col-']:nth-child(2n) {
padding-left: 0;
}
Or in SCSS:
.no-gutter {
> [class*='col-'] {
&:nth-child(2n+1) {
padding-right: 0;
}
&:nth-child(2n) {
padding-left: 0;
}
}
}
Download http://download.cnet.com/Free-Desktop-Timer/3000-2350_4-75415517.html
Then add a button or something on the form and inside its event, just open this app ie:
{
Process.Start(@"C:\Program Files (x86)\Free Desktop Timer\DesktopTimer");
}
I had a nice time creating an Custom Attribute for this:
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public sealed class DecimalPrecisionAttribute : Attribute
{
public DecimalPrecisionAttribute(byte precision, byte scale)
{
Precision = precision;
Scale = scale;
}
public byte Precision { get; set; }
public byte Scale { get; set; }
}
using it like this
[DecimalPrecision(20,10)]
public Nullable<decimal> DeliveryPrice { get; set; }
and the magic happens at model creation with some reflection
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
foreach (Type classType in from t in Assembly.GetAssembly(typeof(DecimalPrecisionAttribute)).GetTypes()
where t.IsClass && t.Namespace == "YOURMODELNAMESPACE"
select t)
{
foreach (var propAttr in classType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.GetCustomAttribute<DecimalPrecisionAttribute>() != null).Select(
p => new { prop = p, attr = p.GetCustomAttribute<DecimalPrecisionAttribute>(true) }))
{
var entityConfig = modelBuilder.GetType().GetMethod("Entity").MakeGenericMethod(classType).Invoke(modelBuilder, null);
ParameterExpression param = ParameterExpression.Parameter(classType, "c");
Expression property = Expression.Property(param, propAttr.prop.Name);
LambdaExpression lambdaExpression = Expression.Lambda(property, true,
new ParameterExpression[]
{param});
DecimalPropertyConfiguration decimalConfig;
if (propAttr.prop.PropertyType.IsGenericType && propAttr.prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
MethodInfo methodInfo = entityConfig.GetType().GetMethods().Where(p => p.Name == "Property").ToList()[7];
decimalConfig = methodInfo.Invoke(entityConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
}
else
{
MethodInfo methodInfo = entityConfig.GetType().GetMethods().Where(p => p.Name == "Property").ToList()[6];
decimalConfig = methodInfo.Invoke(entityConfig, new[] { lambdaExpression }) as DecimalPropertyConfiguration;
}
decimalConfig.HasPrecision(propAttr.attr.Precision, propAttr.attr.Scale);
}
}
}
the first part is to get all classes in the model (my custom attribute is defined in that assembly so i used that to get the assembly with the model)
the second foreach gets all properties in that class with the custom attribute, and the attribute itself so i can get the precision and scale data
after that i have to call
modelBuilder.Entity<MODEL_CLASS>().Property(c=> c.PROPERTY_NAME).HasPrecision(PRECISION,SCALE);
so i call the modelBuilder.Entity() by reflection and store it in the entityConfig variable then i build the "c => c.PROPERTY_NAME" lambda expression
After that, if the decimal is nullable i call the
Property(Expression<Func<TStructuralType, decimal?>> propertyExpression)
method (i call this by the position in the array, it's not ideal i know, any help will be much appreciated)
and if it's not nullable i call the
Property(Expression<Func<TStructuralType, decimal>> propertyExpression)
method.
Having the DecimalPropertyConfiguration i call the HasPrecision method.
I've already had the proxies set as described above and it was working until today. Then it turned out that now I need "http://" in front of my proxy address: "http://{proxyURL}:{proxyPort}". Then it finally worked.
I had the following
document.getElementById("search-button") != null
which worked fine in all browsers except ie8. ( I didnt check ie6 or ie7)
I changed it to
document.getElementById("searchBtn") != null
and updated the id attribute on the field in my html and it now works in ie8
<label>
display:none
or visibility:hidden
since such will impact accessibility)+
/* HIDE RADIO */
[type=radio] {
position: absolute;
opacity: 0;
width: 0;
height: 0;
}
/* IMAGE STYLES */
[type=radio] + img {
cursor: pointer;
}
/* CHECKED STYLES */
[type=radio]:checked + img {
outline: 2px solid #f00;
}
_x000D_
<label>
<input type="radio" name="test" value="small" checked>
<img src="http://placehold.it/40x60/0bf/fff&text=A">
</label>
<label>
<input type="radio" name="test" value="big">
<img src="http://placehold.it/40x60/b0f/fff&text=B">
</label>
_x000D_
Don't forget to add a class to your labels and in CSS use that class instead.
Here's an advanced version using the <i>
element and the :after
pseudo:
body{color:#444;font:100%/1.4 sans-serif;}
/* CUSTOM RADIO & CHECKBOXES
http://stackoverflow.com/a/17541916/383904 */
.rad,
.ckb{
cursor: pointer;
user-select: none;
-webkit-user-select: none;
-webkit-touch-callout: none;
}
.rad > input,
.ckb > input{ /* HIDE ORG RADIO & CHECKBOX */
position: absolute;
opacity: 0;
width: 0;
height: 0;
}
/* RADIO & CHECKBOX STYLES */
/* DEFAULT <i> STYLE */
.rad > i,
.ckb > i{
display: inline-block;
vertical-align: middle;
width: 16px;
height: 16px;
border-radius: 50%;
transition: 0.2s;
box-shadow: inset 0 0 0 8px #fff;
border: 1px solid gray;
background: gray;
}
/* CHECKBOX OVERWRITE STYLES */
.ckb > i {
width: 25px;
border-radius: 3px;
}
.rad:hover > i{ /* HOVER <i> STYLE */
box-shadow: inset 0 0 0 3px #fff;
background: gray;
}
.rad > input:checked + i{ /* (RADIO CHECKED) <i> STYLE */
box-shadow: inset 0 0 0 3px #fff;
background: orange;
}
/* CHECKBOX */
.ckb > input + i:after{
content: "";
display: block;
height: 12px;
width: 12px;
margin: 2px;
border-radius: inherit;
transition: inherit;
background: gray;
}
.ckb > input:checked + i:after{ /* (RADIO CHECKED) <i> STYLE */
margin-left: 11px;
background: orange;
}
_x000D_
<label class="rad">
<input type="radio" name="rad1" value="a">
<i></i> Radio 1
</label>
<label class="rad">
<input type="radio" name="rad1" value="b" checked>
<i></i> Radio 2
</label>
<br>
<label class="ckb">
<input type="checkbox" name="ckb1" value="a" checked>
<i></i> Checkbox 1
</label>
<label class="ckb">
<input type="checkbox" name="ckb2" value="b">
<i></i> Checkbox 2
</label>
_x000D_
//Fields
String myID;
int myversion = 0;
myversion = Integer.valueOf(android.os.Build.VERSION.SDK);
if (myversion < 23) {
TelephonyManager mngr = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
myID= mngr.getDeviceId();
}
else
{
myID =
Settings.Secure.getString(getApplicationContext().getContentResolver(),
Settings.Secure.ANDROID_ID);
}
Yes, Secure.ANDROID_ID is unique for each device.
Alternatively to count columns, count the separators between columns. I find this to be a good balance of brevity and ease to remember. Of course, this won't work if your data include the column separator.
head -n1 myfile.txt | grep -o " " | wc -l
Uses head -n1
to grab the first line of the file.
Uses grep -o
to to count all the spaces, and output each space found on a new line. Uses wc -l
to count the number of lines.
The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.
For example:
char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;
execvp(cmd, argv); //This will run "ls -la" as if it were a command
If you want to check or validate a specific UUID version, here are the corresponding regexes.
Note that the only difference is the version number, which is explained in
4.1.3. Version
chapter of UUID 4122 RFC.
The version number is the first character of the third group : [VERSION_NUMBER][0-9A-F]{3}
:
UUID v1 :
/^[0-9A-F]{8}-[0-9A-F]{4}-[1][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
UUID v2 :
/^[0-9A-F]{8}-[0-9A-F]{4}-[2][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
UUID v3 :
/^[0-9A-F]{8}-[0-9A-F]{4}-[3][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
UUID v4 :
/^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
UUID v5 :
/^[0-9A-F]{8}-[0-9A-F]{4}-[5][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
The compiler is telling you that there are problems starting at line 122 in the middle of that strange FBI-CIA warning message. That message is not valid C++ code and is NOT commented out so of course it will cause compiler errors. Try removing that entire message.
Also, I agree with In silico: you should always tell us what you tried and exactly what error messages you got.
It depends on (a) how attached you are to the number 7 as opposed to, say, Lemons, and (b) whether any of your file names contain newlines (and whether you're willing to rename them if they do).
There are many ways to deal with it, but some of them are:
mplayer Lemon*.mp3
find . -name 'Lemon*.mp3' -exec mplayer {} ';'
i=0
for mp3 in *.mp3
do
i=$((i+1))
[ $i = 7 ] && mplayer "$mp3"
done
for mp3 in *.mp3
do
case "$mp3" in
(Lemon*) mplayer "$mp3";;
esac
done
i=0
find . -name *.mp3 |
while read mp3
do
i=$((i+1))
[ $i = 7 ] && mplayer "$mp3"
done
The read
loop doesn't work if file names contain newlines; the others work correctly even with newlines in the names (let alone spaces). For my money, if you have file names containing a newline, you should rename the file without the newline. Using the double quotes around the file name is key to the loops working correctly.
If you have GNU find
and GNU xargs
(or FreeBSD (*BSD?), or Mac OS X), you can also use the -print0
and -0
options, as in:
find . -name 'Lemon*.mp3' -print0 | xargs -0 mplayer
This works regardless of the contents of the name (the only two characters that cannot appear in a file name are slash and NUL, and the slash causes no problems in a file path, so using NUL as the name delimiter covers everything). However, if you need to filter out the first 6 entries, you need a program that handles 'lines' ended by NUL instead of newline...and I'm not sure there are any.
The first is by far the simplest for the specific case on hand; however, it may not generalize to cover your other scenarios that you've not yet listed.
An alternative way to get only one character.
$str = 'abcdefghij';
echo $str{5};
I would particularly not use this, but for the purpose of education. We can use that to answer the question:
$newString = '';
for ($i = 0; $i < 5; $i++) {
$newString .= $str{$i};
}
echo $newString;
For anyone using that. Bear in mind curly brace syntax for accessing array elements and string offsets is deprecated from PHP 7.4
More information: https://wiki.php.net/rfc/deprecate_curly_braces_array_access
Slide up/down with alpha animation with a few note
slide_up.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="@integer/activity_transition_time"
>
<translate
android:fromYDelta="100%p"
android:toYDelta="0"/>
<alpha
android:fromAlpha="0.5"
android:toAlpha="1"/>
</set>
slide_down.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="@integer/activity_transition_time"
>
<translate
android:fromYDelta="0"
android:toYDelta="100%p"/>
<alpha
android:fromAlpha="1"
android:toAlpha="0.5"/>
</set>
no_animation.xml
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="@integer/activity_transition_time"
android:fromYDelta="0"
android:toYDelta="0"/>
First Activity
startActivity(new Intent(this, SecondActivity.class));
overridePendingTransition(R.anim.slide_up, R.anim.no_animation); // remember to put it after startActivity, if you put it to above, animation will not working
// document say if we don't want animation we can put 0. However, if we put 0 instead of R.anim.no_animation, the exist activity will become black when animate
Second Activity
finish();
overridePendingTransition(R.anim.no_animation, R.anim.slide_down);
Done
MORE
I try to make the slide animation like iOS animation when present a View Model (like this https://www.youtube.com/watch?v=deZobvh2064) but failed.
Looking at iOS present animation you will see: The animation from bottom with alpha (about 50%) then it go very fast then slower, the animation time is about > 500ms (I use trim video tools for count the animation time https://www.kapwing.com/trim-video so it can not exactly 100%)
Then I try to apply to android.
To make alpha I use <alpha>
and success.
To make animation start faster than slower I use android:interpolator="a decelerate interpolator"
but it almost failed.
There are 3 default decelerate interpolator
in Android
@android:interpolator/decelerate_quad
-> factor = 1
@android:interpolator/decelerate_cubic
-> factor = 1.5
@android:interpolator/decelerate_quint
_> factor = 2.5
(higher factor <=> animation start more faster from start and more slower at end)
Here is a good tutorial http://cogitolearning.co.uk/2013/10/android-animations-tutorial-5-more-on-interpolators/ for understand it
I tried 3 above I can not achieve like iOS, the animation can not start faster like iOS. Then I create a custom decelerateInterpolator wiht factor = 3 like
<?xml version="1.0" encoding="utf-8"?>
<decelerateInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
android:factor="3" />
and I increase the duration time from 500 -> 750
. It working well (very similar to iOS). However, it only working well in some device, in some device the animation is quite slow. Later on, I know that animation may different on different device (eg: some device will faster and some device will slower) so I can not make it the animation similar in all Android device. Therefore I don't use interpolator
. I don't know if my testing is exactly 100% or not but I hope this experience help
Perhaps not relevant if you're looking to do this ONLY using ansible. But it's much easier for me to have a function in my .bash_profile
and then run _check_machine host1 host2
function _check_machine() {
echo 'hostname,num_physical_procs,cores_per_procs,memory,Gen,RH Release,bios_hp_power_profile,bios_intel_qpi_link_power_management,bios_hp_power_regulator,bios_idle_power_state,bios_memory_speed,'
hostlist=$1
for h in `echo $hostlist | sed 's/ /\n/g'`;
do
echo $h | grep -qE '[a-zA-Z]'
[ $? -ne 0 ] && h=plabb$h
echo -n $h,
ssh root@$h 'grep "^physical id" /proc/cpuinfo | sort -u | wc -l; grep "^cpu cores" /proc/cpuinfo |sort -u | awk "{print \$4}"; awk "{print \$2/1024/1024; exit 0}" /proc/meminfo; /usr/sbin/dmidecode | grep "Product Name"; cat /etc/redhat-release; /etc/facter/bios_facts.sh;' | sed 's/Red at Enterprise Linux Server release //g; s/.*=//g; s/\tProduct Name: ProLiant BL460c //g; s/-//g' | sed 's/Red Hat Enterprise Linux Server release //g; s/.*=//g; s/\tProduct Name: ProLiant BL460c //g; s/-//g' | tr "\n" ","
echo ''
done
}
E.g.
$ _machine_info '10 20 1036'
hostname,num_physical_procs,cores_per_procs,memory,Gen,RH Release,bios_hp_power_profile,bios_intel_qpi_link_power_management,bios_hp_power_regulator,bios_idle_power_state,bios_memory_speed,
plabb10,2,4,47.1629,G6,5.11 (Tikanga),Maximum_Performance,Disabled,HP_Static_High_Performance_Mode,No_CStates,1333MHz_Maximum,
plabb20,2,4,47.1229,G6,6.6 (Santiago),Maximum_Performance,Disabled,HP_Static_High_Performance_Mode,No_CStates,1333MHz_Maximum,
plabb1036,2,12,189.12,Gen8,6.6 (Santiago),Custom,Disabled,HP_Static_High_Performance_Mode,No_CStates,1333MHz_Maximum,
$
Needless to say function won't work for you as it is. You need to update it appropriately.
var yearStart = 2000;
var yearEnd = 2040;
var arr = [];
for (var i = yearStart; i <= yearEnd; i++) {
arr.push(i);
}
Given this route
app.get('/hi/:param1', function(req,res){} );
and given this URL
http://www.google.com/hi/there?qs1=you&qs2=tube
You will have:
req.query
{
qs1: 'you',
qs2: 'tube'
}
req.params
{
param1: 'there'
}
What @dmckee said.
It's not difficult to write your own bespoke footnote-queuing code. What you need to do is:
\footnote
to add a footnote macro to your queue;If this is interesting, I show some code that does this.
Break
Break forces a loop to exit immediately.
Continue
This does the opposite of break. Instead of terminating the loop, it immediately loops again, skipping the rest of the code.
Add CultureInfo.InvariantCulture
as an argument:
using System.Globalization;
...
var dateTime = new DateTime(2016,8,16);
dateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
Will return:
"16/08/2016"
I think my solution is more simple with default functionality.
http://jsfiddle.net/salt/wbpb0zoy/1/
$("a.popover-ajax").each(function(){_x000D_
$(this).popover({_x000D_
trigger:"focus",_x000D_
placement: function (context, source) {_x000D_
var obj = $(source);_x000D_
$.get(obj.data("url"),function(d) {_x000D_
$(context).html( d.titles[0].title)_x000D_
}); _x000D_
},_x000D_
html:true,_x000D_
content:"loading"_x000D_
});_x000D_
});
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<ul class="list-group">_x000D_
<li class="list-group-item"><a href="#" data-url="https://tr.instela.com/api/v2/list?op=today" class="popover-ajax">Cras justo odio</a></li>_x000D_
<li class="list-group-item"><a href="#" data-url="https://tr.instela.com/api/v2/list?op=today" class="popover-ajax">Dapibus ac facilisis in</a></li>_x000D_
<li class="list-group-item"><a href="#" data-url="https://tr.instela.com/api/v2/list?op=today" class="popover-ajax">Morbi leo risus</a></li>_x000D_
<li class="list-group-item"><a href="#" data-url="https://tr.instela.com/api/v2/list?op=today" class="popover-ajax">Porta ac consectetur ac</a></li>_x000D_
<li class="list-group-item"><a href="#" data-url="https://tr.instela.com/api/v2/list?op=today" class="popover-ajax">Vestibulum at eros</a></li>_x000D_
</ul>
_x000D_
You technically have two options when speaking of ISO dates.
In general, if you're filtering specifically on Date values alone OR looking to persist date in a neutral fashion. Microsoft recommends using the language neutral format of ymd
or y-m-d
. Which are both valid ISO formats.
Note that the form '2007-02-12' is considered language-neutral only for the data types DATE, DATETIME2, and DATETIMEOFFSET.
Because of this, your safest bet is to persist/filter based on the always netural ymd
format.
The code:
select convert(char(10), getdate(), 126) -- ISO YYYY-MM-DD
select convert(char(8), getdate(), 112) -- ISO YYYYMMDD (safest)
Easiest way:
private String millisToDate(long millis){
return DateFormat.getDateInstance(DateFormat.SHORT).format(millis);
//You can use DateFormat.LONG instead of SHORT
}
import 'package:flutter/material.dart';
void main() => runApp(DestiniApp());
class DestiniApp extends StatefulWidget {
@override
_DestiniAppState createState() => _DestiniAppState();
}
class _DestiniAppState extends State<DestiniApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: SafeArea(
child: Scaffold(
appBar: AppBar(
backgroundColor: Color.fromRGBO(245, 0, 87, 1),
title: Text(
"Landing Page Bankground Image",
),
),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: ExactAssetImage("images/appBack.jpg"),
fit: BoxFit.cover
),
),
),
),
),
);
}
}
I investigate i knew that the jquery script need to load in order that why it not worked in your case. Because $ symbol mentioned in code not understand unless you load Jquery 1.9.1 at first. Load like follows
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/css/toastr.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/js/toastr.js"></script>
Then it will work fine
Tips from 2020:
From Flask 1.0, it defaults to enable multiple threads (source), you don't need to do anything, just upgrade it with:
$ pip install -U flask
If you are using flask run
instead of app.run()
with older versions, you can control the threaded behavior with a command option (--with-threads/--without-threads
):
$ flask run --with-threads
It's same as app.run(threaded=True)
Are you sure your processor supports Intel Virtualization (VT-x) or AMD Virtualization (AMD-V)?
Here you can find Hardware-Assisted Virtualization Detection Tool ( http://www.microsoft.com/downloads/en/details.aspx?FamilyID=0ee2a17f-8538-4619-8d1c-05d27e11adb2&displaylang=en) which will tell you if your hardware supports VT-x.
Alternatively you can find your processor here: http://ark.intel.com/Default.aspx. All AMD processors since 2006 supports Virtualization.
you're executing this code from command line therefore if
conditions is true and x
is set. Compare:
>>> if False:
y = 42
>>> y
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
y
NameError: name 'y' is not defined
Create an element which shows the left part of the bar (the round part), also create an element for the right part. For the actual progress bar, create a third element with a repeating background and a width which depends on the actual progress. Put it all on top of the background image (containing the empty progress bar).
But I suppose you already knew that...
Edit: When creating a progress bar which do not use textual backgrounds. You can use the border-radius
to get the round effect, as shown by Rikudo Sennin and RoToRa!
Create the Java code that can receive an argument as a command line argument.
class TestCode{
public static void main(String args[]){
System.out.println("first argument is: "+args[0]);
}
}
Run the program without arguments (press F6).
In the Output window, at the bottom, click the double yellow arrow (or the yellow button) to open a Run dialog.
If the argument you need to pass is testArgument
, then here in this window pass the argument as application.args=testArgument
.
This will give the output as follows in the same Output window:
first argument is: testArgument
For Maven, the instructions are similar, but change the exec.args
property instead:
exec.args=-classpath %classpath package.ClassName PARAM1 PARAM2 PARAM3
Note: Use single quotes for string parameters that contain spaces.
In my case and while installing VS 2015 on Windows7 64x SP1, I experienced the same so tried to cancel and download/install the KBKB2999226 separately and for some reason the standalone update installer also get stuck searching for updates.
From menu select: File->Invalidate Catches/Restart...
than in opened dialog select: "Invalidate and Restart" and wait to restart android studio.
You can get the multiple element by id by identifying what element it is. For example
<div id='id'></div>
<div id='id'></div>
<div id='id'></div>
I assume if you are using jQuery you can select all them all by
$("div#id")
. This will get you array of elements you loop them based on your logic.
If you don't use prioritized tasks, this is actually pretty simple if you're using Redis. To get the task counts:
redis-cli -h HOST -p PORT -n DATABASE_NUMBER llen QUEUE_NAME
But, prioritized tasks use a different key in redis, so the full picture is slightly more complicated. The full picture is that you need to query redis for every priority of task. In python (and from the Flower project), this looks like:
PRIORITY_SEP = '\x06\x16'
DEFAULT_PRIORITY_STEPS = [0, 3, 6, 9]
def make_queue_name_for_pri(queue, pri):
"""Make a queue name for redis
Celery uses PRIORITY_SEP to separate different priorities of tasks into
different queues in Redis. Each queue-priority combination becomes a key in
redis with names like:
- batch1\x06\x163 <-- P3 queue named batch1
There's more information about this in Github, but it doesn't look like it
will change any time soon:
- https://github.com/celery/kombu/issues/422
In that ticket the code below, from the Flower project, is referenced:
- https://github.com/mher/flower/blob/master/flower/utils/broker.py#L135
:param queue: The name of the queue to make a name for.
:param pri: The priority to make a name with.
:return: A name for the queue-priority pair.
"""
if pri not in DEFAULT_PRIORITY_STEPS:
raise ValueError('Priority not in priority steps')
return '{0}{1}{2}'.format(*((queue, PRIORITY_SEP, pri) if pri else
(queue, '', '')))
def get_queue_length(queue_name='celery'):
"""Get the number of tasks in a celery queue.
:param queue_name: The name of the queue you want to inspect.
:return: the number of items in the queue.
"""
priority_names = [make_queue_name_for_pri(queue_name, pri) for pri in
DEFAULT_PRIORITY_STEPS]
r = redis.StrictRedis(
host=settings.REDIS_HOST,
port=settings.REDIS_PORT,
db=settings.REDIS_DATABASES['CELERY'],
)
return sum([r.llen(x) for x in priority_names])
If you want to get an actual task, you can use something like:
redis-cli -h HOST -p PORT -n DATABASE_NUMBER lrange QUEUE_NAME 0 -1
From there you'll have to deserialize the returned list. In my case I was able to accomplish this with something like:
r = redis.StrictRedis(
host=settings.REDIS_HOST,
port=settings.REDIS_PORT,
db=settings.REDIS_DATABASES['CELERY'],
)
l = r.lrange('celery', 0, -1)
pickle.loads(base64.decodestring(json.loads(l[0])['body']))
Just be warned that deserialization can take a moment, and you'll need to adjust the commands above to work with various priorities.
Remove this from #info
:
margin-left:auto;
Add this for your header:
#info p {
text-align: center;
}
Do you need the fixed width etc.? I removed the in my opinion not necessary stuff and centered the header with text-align
.
Sample
http://jsfiddle.net/Vc8CB/
Your selector looks for the descendant of a input:radio[name=cols]
element that has the id of newcol
(well the value of that variable).
Try this instead (since you're selecting by ID anyway):
$('#' + newcol).prop('checked',true);
Here is a demo: http://jsfiddle.net/jasper/n8CdM/1/
Also, as of jQuery 1.6 the perferred method of altering a property is .prop()
: http://api.jquery.com/prop
In case you don't have a current or long running process to track, you can use /usr/bin/time
.
This is not the same as Bash time
(as you will see).
Eg
# /usr/bin/time -f "%M" echo
2028
This is "Maximum resident set size of the process during its lifetime, in Kilobytes" (quoted from the man page). That is, the same as RES in top
et al.
There are a lot more you can get from /usr/bin/time
.
# /usr/bin/time -v echo
Command being timed: "echo"
User time (seconds): 0.00
System time (seconds): 0.00
Percent of CPU this job got: 0%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.00
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 1988
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 0
Minor (reclaiming a frame) page faults: 77
Voluntary context switches: 1
Involuntary context switches: 0
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0
DateFormat date = new SimpleDateFormat("dd/MMM/yyyy");
Date date1 = new Date();
System.out.println(date.format(date1));
You can try out wsdl validator http://docs.wso2.org/wiki/display/ESB451/WSDL+Validator
A reason for this could be Skype as well! If you use the default XAMPP settings, they both would run on the same port (80). You can:
I know this thread is bit old.
But I'm going to post this anyway hoping it might help someone.
We can store fields of any Object to shared preference by serializing the object to String.
Here I have used GSON
for storing any object to shared preference.
Save Object to Preference :
public static void saveObjectToSharedPreference(Context context, String preferenceFileName, String serializedObjectKey, Object object) {
SharedPreferences sharedPreferences = context.getSharedPreferences(preferenceFileName, 0);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
final Gson gson = new Gson();
String serializedObject = gson.toJson(object);
sharedPreferencesEditor.putString(serializedObjectKey, serializedObject);
sharedPreferencesEditor.apply();
}
Retrieve Object from Preference:
public static <GenericClass> GenericClass getSavedObjectFromPreference(Context context, String preferenceFileName, String preferenceKey, Class<GenericClass> classType) {
SharedPreferences sharedPreferences = context.getSharedPreferences(preferenceFileName, 0);
if (sharedPreferences.contains(preferenceKey)) {
final Gson gson = new Gson();
return gson.fromJson(sharedPreferences.getString(preferenceKey, ""), classType);
}
return null;
}
Note :
Remember to add compile 'com.google.code.gson:gson:2.6.2'
to dependencies
in your gradle.
Example :
//assume SampleClass exists
SampleClass mObject = new SampleObject();
//to store an object
saveObjectToSharedPreference(context, "mPreference", "mObjectKey", mObject);
//to retrive object stored in preference
mObject = getSavedObjectFromPreference(context, "mPreference", "mObjectKey", SampleClass.class);
As @Sharp_Edge pointed out in comments, the above solution does not work with List
.
A slight modification to the signature of getSavedObjectFromPreference()
- from Class<GenericClass> classType
to Type classType
will make this solution generalized. Modified function signature,
public static <GenericClass> GenericClass getSavedObjectFromPreference(Context context, String preferenceFileName, String preferenceKey, Type classType)
For invoking,
getSavedObjectFromPreference(context, "mPreference", "mObjectKey", (Type) SampleClass.class)
Happy Coding!
You can use an OFFSET
in a LIMIT
command:
SELECT * FROM aTable LIMIT 1 OFFSET 99
in case your table has 100 rows this return the last row without relying on a primary_key
So why don't you simply use a key-value literal?
var params = {
'slide0001.html': 'Looking Ahead',
'slide0002.html': 'Forecase',
...
};
return params['slide0001.html']; // returns: Looking Ahead
Everything you need is in the npm-folders
documentation. I don't want to start my Win notebook now so I cannot verify it, but you should only change prefix
to C:\Program Files\nodejs
in your config file. If you want to change it globally for all users, edit the C:\Program Files\nodejs\npmrc
file, otherwise create/edit C:\Users\{username}\.npmrc
.
But this change will probably have some side effects, so read this discussion first. I don't think it's a good idea.
Inspired by sverrir-sigmundarson's comment:
def time_to_sec(time_str):
return sum(x * int(t) for x, t in zip([1, 60, 3600], reversed(time_str.split(":"))))
You should use this example with AUTHID CURRENT_USER :
CREATE OR REPLACE PROCEDURE Create_sequence_for_tab (VAR_TAB_NAME IN VARCHAR2)
AUTHID CURRENT_USER
IS
SEQ_NAME VARCHAR2 (100);
FINAL_QUERY VARCHAR2 (100);
COUNT_NUMBER NUMBER := 0;
cur_id NUMBER;
BEGIN
SEQ_NAME := 'SEQ_' || VAR_TAB_NAME;
SELECT COUNT (*)
INTO COUNT_NUMBER
FROM USER_SEQUENCES
WHERE SEQUENCE_NAME = SEQ_NAME;
DBMS_OUTPUT.PUT_LINE (SEQ_NAME || '>' || COUNT_NUMBER);
IF COUNT_NUMBER = 0
THEN
--DBMS_OUTPUT.PUT_LINE('DROP SEQUENCE ' || SEQ_NAME);
-- EXECUTE IMMEDIATE 'DROP SEQUENCE ' || SEQ_NAME;
-- ELSE
SELECT 'CREATE SEQUENCE COMPTABILITE.' || SEQ_NAME || ' START WITH ' || ROUND (DBMS_RANDOM.VALUE (100000000000, 999999999999), 0) || ' INCREMENT BY 1'
INTO FINAL_QUERY
FROM DUAL;
DBMS_OUTPUT.PUT_LINE (FINAL_QUERY);
cur_id := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.parse (cur_id, FINAL_QUERY, DBMS_SQL.v7);
DBMS_SQL.CLOSE_CURSOR (cur_id);
-- EXECUTE IMMEDIATE FINAL_QUERY;
END IF;
COMMIT;
END;
/
You can do it as Billy Moat told you, wrap your <img>
and <h1>
in a <div>
and use float: left;
to float your image to the left, set the <div>
width
and than set a line-height
for your h1
and use <div style="clear: float;"></div>
to clear your floating elements.
var $whatever = $('#whatever');
var ending_right = ($(window).width() - ($whatever.offset().left + $whatever.outerWidth()));
Reference: .outerWidth()
I ended up fixing our Ubuntu 18.04 / Apache 2.4.29 / PHP 7.2 install for Chrome 80 by installing mod_headers:
a2enmod headers
Adding the following directive to our Apache VirtualHost configurations:
Header edit Set-Cookie ^(.*)$ "$1; Secure; SameSite=None"
And restarting Apache:
service apache2 restart
In reviewing the docs (http://www.balkangreenfoundation.org/manual/en/mod/mod_headers.html) I noticed the "always" condition has certain situations where it does not work from the same pool of response headers. Thus not using "always" is what worked for me with PHP but the docs suggest that if you want to cover all your bases you could add the directive both with and without "always". I have not tested that.
Another option is to check if it is equal to @""
with isEqualToString:
like so:
if ([myString isEqualToString:@""]) {
NSLog(@"myString IS empty!");
} else {
NSLog(@"myString IS NOT empty, it is: %@", myString);
}
Since SSRS utilizes VB, you can do the following:
=Today() 'returns date only
If you were to use:
=Now() 'returns date and current timestamp
FASTER: Bitwise instead of modulus.
select * from MEN where (id&1)=0;
Random question: Do you actually use uppercase table names? Usually uppercase is reserved for keywords. (By convention)
You can try ES6 Modules in Google Chrome Beta (61) / Chrome Canary.
Reference Implementation of ToDo MVC by Paul Irish - https://paulirish.github.io/es-modules-todomvc/
I've basic demo -
//app.js
import {sum} from './calc.js'
console.log(sum(2,3));
//calc.js
let sum = (a,b) => { return a + b; }
export {sum};
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<h1>ES6</h1>
<script src="app.js" type="module"></script>
</body>
</html>
Hope it helps!
Using table
:
library(magrittr)
myvec %>% unique %>% '['(1) %>% table %>% as.data.frame %>%
setNames(c("name","number_of_distinct_orders"))
# name number_of_distinct_orders
# 1 Amy 2
# 2 Dave 1
# 3 Jack 3
# 4 Larry 1
# 5 Tom 2
A straightforward solution with complete explanation.
var dayOfYear = function(date) {
const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
const [yyyy, mm, dd] = date.split('-').map(Number);
// Checks if February has 29 days
const isLeap = (year) => new Date(year, 1, 29).getDate() === 29;
// If it's a leap year, changes 28 to 29
if (isLeap(yyyy)) daysInMonth[1] = 29;
let daysBeforeMonth = 0;
// Slice the array and exclude the current Month
for (const i of daysInMonth.slice(0, mm - 1)) {
daysBeforeMonth += i;
}
return daysBeforeMonth + dd;
};
console.log(dayOfYear('2020-1-3'));
console.log(dayOfYear('2020-2-1'));
_x000D_
Thymeleaf 3 now:
Display a constant:
<script th:inline="javascript"> var MY_URL = /*[[${T(com.xyz.constants.Fruits).cheery}]]*/ ""; </script>
Display a variable:
var message = [[${message}]];
Or in a comment to have a valid JavaScript code when you open your template file in a static manner (without executing it at a server).
Thymeleaf calls this: JavaScript natural templates
var message = /*[[${message}]]*/ "";
Thymeleaf will ignore everything we have written after the comment and before the semicolon.
More info: http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining
The best option: os.system('pause')
<-- this will actually display a message saying 'press any key to continue' whereas adding just raw_input('')
will print no message, just the cursor will be available.
not related to answer:
os.system("some cmd command")
is a really great command as the command can execute any batch file/cmd commands.
You can use this dummy plugin:
mvn archetype:generate -DgroupId=org.eclipse.m2e -DartifactId=lifecycle-mapping -Dversion=1.0.0 -DarchetypeArtifactId=maven-archetype-mojo
After generating the project install/deploy it.
Work 100%. maybe not relation to creator answer but i share it for users have a problem with export mysql query to excel with phpexcel. Good Luck.
require('../phpexcel/PHPExcel.php');
require('../phpexcel/PHPExcel/Writer/Excel5.php');
$filename = 'userReport'; //your file name
$objPHPExcel = new PHPExcel();
/*********************Add column headings START**********************/
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'username')
->setCellValue('B1', 'city_name');
/*********************Add data entries START**********************/
//get_result_array_from_class**You can replace your sql code with this line.
$result = $get_report_clas->get_user_report();
//set variable for count table fields.
$num_row = 1;
foreach ($result as $value) {
$user_name = $value['username'];
$c_code = $value['city_name'];
$num_row++;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$num_row, $user_name )
->setCellValue('B'.$num_row, $c_code );
}
/*********************Autoresize column width depending upon contents START**********************/
foreach(range('A','B') as $columnID) {
$objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
}
$objPHPExcel->getActiveSheet()->getStyle('A1:B1')->getFont()->setBold(true);
//Make heading font bold
/*********************Add color to heading START**********************/
$objPHPExcel->getActiveSheet()
->getStyle('A1:B1')
->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
->getStartColor()
->setARGB('99ff99');
$objPHPExcel->getActiveSheet()->setTitle('userReport'); //give title to sheet
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment;Filename=$filename.xls");
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
OK. After trying out some error handling, I figured out how to solve the issue I was having.
Here's an example of how to make this work (let me know if there's something I'm missing) :
SET XACT_ABORT OFF ; -- > really important to set that to OFF
BEGIN
DECLARE @Any_error int
DECLARE @SSQL varchar(4000)
BEGIN TRANSACTION
INSERT INTO Table1(Value1) VALUES('Value1')
SELECT @Any_error = @@ERROR
IF @Any_error<> 0 AND @Any_error<>2627 GOTO ErrorHandler
INSERT INTO Table1(Value1) VALUES('Value1')
SELECT @Any_error = @@ERROR
IF @Any_error<> 0 AND @Any_error<>2627 GOTO ErrorHandler
INSERT INTO Table1(Value1) VALUES('Value2')
SELECT @Any_error = @@ERROR
IF @Any_error<> 0 AND @Any_error<>2627 GOTO ErrorHandler
ErrorHandler:
IF @Any_error = 0 OR @Any_error=2627
BEGIN
PRINT @ssql
COMMIT TRAN
END
ELSE
BEGIN
PRINT @ssql
ROLLBACK TRAN
END
END
As a result of the above Transaction, Table1 will have the following values Value1, Value2.
2627 is the error code for Duplicate Key by the way.
Thank you all for the prompt reply and helpful suggestions.
var x = 1234567;
x.toString().length;
This process will also work forFloat Number
and for Exponential number
also.
I had an issue uploading images to my React JS project. I was trying to use the file-loader to load the images; I was also using Babel-loader in my react.
I used the following settings in the webpack:
{test: /\.(jpe?g|png|gif|svg)$/i, loader: "file-loader?name=app/images/[name].[ext]"},
This helped load my images, but the images loaded were kind of corrupted. Then after some research I came to know that file-loader has a bug of corrupting the images when babel-loader is installed.
Hence, to work around the issue I tried to use URL-loader which worked perfectly for me.
I updated my webpack with the following settings
{test: /\.(jpe?g|png|gif|svg)$/i, loader: "url-loader?name=app/images/[name].[ext]"},
I then used the following command to import the images
import img from 'app/images/GM_logo_2.jpg'
<div className="large-8 columns">
<img style={{ width: 300, height: 150 }} src={img} />
</div>
#!/usr/bin/env python
import pandas as pd
# Make example dataframe
df = pd.DataFrame([(1, 'Germany'),
(2, 'France'),
(3, 'Indonesia'),
(4, 'France'),
(5, 'France'),
(6, 'Germany'),
(7, 'UK'),
],
columns=['groupid', 'country'],
index=['a', 'b', 'c', 'd', 'e', 'f', 'g'])
# What you're looking for
values = df['country'].value_counts().keys().tolist()
counts = df['country'].value_counts().tolist()
Now, print(df['country'].value_counts())
gives:
France 3
Germany 2
UK 1
Indonesia 1
and print(values)
gives:
['France', 'Germany', 'UK', 'Indonesia']
and print(counts)
gives:
[3, 2, 1, 1]
There is a nice form plugin that allows you to send an HTML form asynchroniously.
$(document).ready(function() {
$('#myForm1').ajaxForm();
});
or
$("select").change(function(){
$('#myForm1').ajaxSubmit();
});
to submit the form immediately
For me it worked
public static long getUniqueLongFromString (String value){
return UUID.nameUUIDFromBytes(value.getBytes()).getMostSignificantBits();
}
fcntl()
has always worked reliably for me. In any case, here is the function I use to enable/disable blocking on a socket:
#include <fcntl.h>
/** Returns true on success, or false if there was an error */
bool SetSocketBlockingEnabled(int fd, bool blocking)
{
if (fd < 0) return false;
#ifdef _WIN32
unsigned long mode = blocking ? 0 : 1;
return (ioctlsocket(fd, FIONBIO, &mode) == 0) ? true : false;
#else
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1) return false;
flags = blocking ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK);
return (fcntl(fd, F_SETFL, flags) == 0) ? true : false;
#endif
}
Groovy maps can be used with the property
property, so you can just do:
def x = mymap.likes
If the key you are looking for (for example 'likes.key'
) contains a dot itself, then you can use the syntax:
def x = mymap.'likes.key'
Update 3: As other answers point out as well, the npm ci
command got introduced in npm 5.7.0 as additional way to achieve fast and reproducible builds in the CI context. See the documentation and npm blog for further information.
Update 2: The issue to update and clarify the documentation is GitHub issue #18103.
Update 1: The behaviour that was described below got fixed in npm 5.4.2: the currently intended behaviour is outlined in GitHub issue #17979.
Original answer: The behaviour of package-lock.json
was changed in npm 5.1.0 as discussed in issue #16866. The behaviour that you observe is apparently intended by npm as of version 5.1.0.
That means that package.json
can override package-lock.json
whenever a newer version is found for a dependency in package.json
. If you want to pin your dependencies effectively, you now must specify the versions without a prefix, e.g., you need to write them as 1.2.0
instead of ~1.2.0
or ^1.2.0
. Then the combination of package.json
and package-lock.json
will yield reproducible builds. To be clear: package-lock.json
alone no longer locks the root level dependencies!
Whether this design decision was good or not is arguable, there is an ongoing discussion resulting from this confusion on GitHub in issue #17979. (In my eyes it is a questionable decision; at least the name lock
doesn't hold true any longer.)
One more side note: there is also a restriction for registries that don’t support immutable packages, such as when you pull packages directly from GitHub instead of npmjs.org. See this documentation of package locks for further explanation.
Probably the face_cascade
is empty. You can check if the variable is empty or not by typing following command:
face_cascade.empty()
If it is empty you will get True
and this means your file is not available in the path you mentioned.
Try to add complete path of xml file as follows:
r'D:\folder Name\haarcascade_frontalface_default.xml'
Using your code, this is how I would do it. I know an answer was chosen, just giving additional options.
data = json.loads('{"lat":444, "lon":555}')
ret = ''
for j in data:
ret = ret+" "+data[j]
return ret
When you use for in this manor you get the key of the object, not the value, so you can get the value, by using the key as an index.
If you are using dataset to bind in a Grid, you can add the row after you fill in the sql data adapter:
adapter.Fill(ds);
ds.Tables(0).Rows.Add();
<%@ page import = "java.util.Map" %>
Map<String, String[]> parameters = request.getParameterMap();
for(String parameter : parameters.keySet()) {
if(parameter.toLowerCase().startsWith("question")) {
String[] values = parameters.get(parameter);
//your code here
}
}
In [30]: pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
Out[30]:
0 1
1 2
2 3
3 4
4 NaN
dtype: float64
A task is something you want done.
A thread is one of the many possible workers which performs that task.
In .NET 4.0 terms, a Task represents an asynchronous operation. Thread(s) are used to complete that operation by breaking the work up into chunks and assigning to separate threads.
1> Add this namspace. using Newtonsoft.Json.Linq;
2> use this source code.
JObject joResponse = JObject.Parse(response);
JObject ojObject = (JObject)joResponse["response"];
JArray array= (JArray)ojObject ["chats"];
int id = Convert.ToInt32(array[0].toString());
If you are using command line use python -m compileall <argument>
to compile python code to python binary code.
Ex: python -m compileall -x ./*
Or, You can use this code to compile your library into byte-code.
import compileall
import os
lib_path = "your_lib_path"
build_path = "your-dest_path"
compileall.compile_dir(lib_path, force=True, legacy=True)
def moveToNewLocation(cu_path):
for file in os.listdir(cu_path):
if os.path.isdir(os.path.join(cu_path, file)):
compile(os.path.join(cu_path, file))
elif file.endswith(".pyc"):
dest = os.path.join(build_path, cu_path ,file)
os.makedirs(os.path.dirname(dest), exist_ok=True)
os.rename(os.path.join(cu_path, file), dest)
moveToNewLocation(lib_path)
look at ? docs.python.org for detailed documentation
Read C# Split String Examples - Dot Net Pearls and the solution can be something like:
var results = yourString.Split(new string[] { "is Marco and" }, StringSplitOptions.None);
In my case, none of the code above with bundle-operate
works; Here is my decision (I don't know if it is proper code or not, but it works in my case):
public class DialogMessageType extends DialogFragment {
private static String bodyText;
public static DialogMessageType addSomeString(String temp){
DialogMessageType f = new DialogMessageType();
bodyText = temp;
return f;
};
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String[] choiseArray = {"sms", "email"};
String title = "Send text via:";
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(title).setItems(choiseArray, itemClickListener);
builder.setCancelable(true);
return builder.create();
}
DialogInterface.OnClickListener itemClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case 0:
prepareToSendCoordsViaSMS(bodyText);
dialog.dismiss();
break;
case 1:
prepareToSendCoordsViaEmail(bodyText);
dialog.dismiss();
break;
default:
break;
}
}
};
[...]
}
public class SendObjectActivity extends FragmentActivity {
[...]
DialogMessageType dialogMessageType = DialogMessageType.addSomeString(stringToSend);
dialogMessageType.show(getSupportFragmentManager(),"dialogMessageType");
[...]
}
https://github.com/quartzjer/js0n
Ugliest interface possible, but does what you ask. Zero allocations.
http://zserge.com/jsmn.html Another zero-allocation approach.
The solutions posted above all do dynamic memory allocation, hence will be inevitably end up slower at some point, depending on the data structure - and will be dangerous to include in a heap constrained environment like an embedded system.
Benchmarks of vjson, rapidjson and sajson here : http://chadaustin.me/2013/01/json-parser-benchmarking/ if you are interested in that sort of thing.
And to answer your "writer" part of the question i doubt that you could beat an efficient
printf("{%s:%s}",name,value)
implementation with any library - assuming your printf/sprintf implementation itself is lightweight of course.
EDIT: actually let me take that back, RapidJson allows on-stack allocation only through its MemoryPoolAllocator and actually makes this a default for its GenericReader. I havent done the comparison but i would expect it to be more robust than anything else listed here. It also doesnt have any dependencies, and it doesnt throw exceptions which probably makes it ultimately suitable for embedded. Fully header based lib so, easy to include anywhere.
A weak entity is the entity which can't be fully identified by its own attributes and takes the foreign key as an attribute (generally it takes the primary key of the entity it is related to) in conjunction.
Examples
The existence of rooms is entirely dependent on the existence of a hotel. So room can be seen as the weak entity of the hotel.
Another example is the
bank account of a particular bank has no existence if the bank doesn't exist anymore.
I couldn't be more concise than this. For all your other needs and information, Google is your friend.
Alex' comment looks good but I was still confused with using range. The following worked for me while working on a for condition using length within range.
{% for i in range(0,(nums['list_users_response']['list_users_result']['users'])| length) %}
<li> {{ nums['list_users_response']['list_users_result']['users'][i]['user_name'] }} </li>
{% endfor %}
Given decimal d=12.345; the expressions d.ToString("C") or String.Format("{0:C}", d) yield $12.35 - note that the current culture's currency settings including the symbol are used.
Note that "C" uses number of digits from current culture. You can always override default to force necessary precision with C{Precision specifier}
like String.Format("{0:C2}", 5.123d)
.
I dont know about a one-line FTP server, but if you do
python -m SimpleHTTPServer
It'll run an HTTP server on 0.0.0.0:8000, serving files out of the current directory. If you're looking for a way to quickly get files off a linux box with a web browser, you cant beat it.
Stuzor and hexcodes solution worked for me as well. However, if you do want the latest connector you have to download another product. From the oracle website:
Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows (see http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html).
I like array_replace
(or array_replace_recursive
).
$cloned = array_replace([], $YOUR_ARRAY);
It works like Object.assign
from JavaScript.
$original = [ 'foo' => 'bar', 'fiz' => 'baz' ];
$cloned = array_replace([], $original);
$clonedWithReassignment = array_replace([], $original, ['foo' => 'changed']);
$clonedWithNewValues = array_replace([], $original, ['add' => 'new']);
$original['new'] = 'val';
will result in
// original:
{"foo":"bar","fiz":"baz","new":"val"}
// cloned:
{"foo":"bar","fiz":"baz"}
// cloned with reassignment:
{"foo":"changed","fiz":"baz"}
// cloned with new values:
{"foo":"bar","fiz":"baz","add":"new"}
This is probably the shortest example that came to my mind:
list($first) = explode("/", $mystring);
1) list()
will automatically assign string until "/"
if delimiter is found
2) if delimiter "/"
is not found then the whole string will be assigned
...and if you get really obsessed with performance, you may add extra parameter to explode explode("/", $mystring, 2)
which limits maximum of the returned elements.
If you use IIS Express via Visual Studio instead of the builtin ASP.net host, you can achieve this.
'hg forget
' is just shorthand for 'hg remove -Af
'. From the 'hg remove
' help:
...and -Af can be used to remove files from the next revision without deleting them from the working directory.
Bottom line: 'remove
' deletes the file from your working copy on disk (unless you uses -Af
) and 'forget
' doesn't.
Fullname with only one whitespace:
^[a-zA-Z'\-\pL]+(?:(?! {2})[a-zA-Z'\-\pL ])*[a-zA-Z'\-\pL]+$
The ports
section will publish ports on the host. Docker will setup a forward for a specific port from the host network into the container. By default this is implemented with a userspace proxy process (docker-proxy
) that listens on the first port, and forwards into the container, which needs to listen on the second point. If the container is not listening on the destination port, you will still see something listening on the host, but get a connection refused if you try to connect to that host port, from the failed forward into your container.
Note, the container must be listening on all network interfaces since this proxy is not running within the container's network namespace and cannot reach 127.0.0.1 inside the container. The IPv4 method for that is to configure your application to listen on 0.0.0.0
.
Also note that published ports do not work in the opposite direction. You cannot connect to a service on the host from the container by publishing a port. Instead you'll find docker errors trying to listen to the already-in-use host port.
Expose is documentation. It sets metadata on the image, and when running, on the container too. Typically you configure this in the Dockerfile with the EXPOSE
instruction, and it serves as documentation for the users running your image, for them to know on which ports by default your application will be listening. When configured with a compose file, this metadata is only set on the container. You can see the exposed ports when you run a docker inspect
on the image or container.
There are a few tools that rely on exposed ports. In docker, the -P
flag will publish all exposed ports onto ephemeral ports on the host. There are also various reverse proxies that will default to using an exposed port when sending traffic to your application if you do not explicitly set the container port.
Other than those external tools, expose has no impact at all on the networking between containers. You only need a common docker network, and connecting to the container port, to access one container from another. If that network is user created (e.g. not the default bridge network named bridge
), you can use DNS to connect to the other containers.
Just like you would for any other variable, you just set it
alert(data.ID);
data.ID = "bar"; //dot notation
alert(data.ID);
data.userID = 123456;
data["address"] = "123 some street"; //bracket notation
You can't actually do the job quite right with toLowerCase
, either on a string or in a character. The problem is that there are variant glyphs in either upper or lower case, and depending on whether you uppercase or lowercase your glyphs may or may not be preserved. It's not even clear what you mean when you say that two variants of a lower-case glyph are compared ignoring case: are they or are they not the same? (Note that there are also mixed-case glyphs: \u01c5, \u01c8, \u01cb, \u01f2
or ?, ?, ?, ?, but any method suggested here will work on those as long as they should count as the same as their fully upper or full lower case variants.)
There is an additional problem with using Char
: there are some 80 code points not representable with a single Char
that are upper/lower case variants (40 of each), at least as detected by Java's code point upper/lower casing. You therefore need to get the code points and change the case on these.
But code points don't help with the variant glyphs.
Anyway, here's a complete list of the glyphs that are problematic due to variants, showing how they fare against 6 variant methods:
toLowerCase
toUpperCase
toLowerCase
toUpperCase
equalsIgnoreCase
toLowerCase(toUpperCase)
(or vice versa)For these methods, S
means that the variants are treated the same as each other, D
means the variants are treated as different from each other.
Behavior Unicode Glyphs
=========== ================================== =========
1 2 3 4 5 6 Upper Lower Var Up Var Lo Vr Lo2 U L u l l2
- - - - - - ------ ------ ------ ------ ------ - - - - -
D D D D S S \u0049 \u0069 \u0130 \u0131 I i I i
S D S D S S \u004b \u006b \u212a K k K
D S D S S S \u0053 \u0073 \u017f S s ?
D S D S S S \u039c \u03bc \u00b5 ? µ µ
S D S D S S \u00c5 \u00e5 \u212b Å å Å
D S D S S S \u0399 \u03b9 \u0345 \u1fbe ? ? ? ?
D S D S S S \u0392 \u03b2 \u03d0 ? ß ?
D S D S S S \u0395 \u03b5 \u03f5 ? e ?
D D D D S S \u0398 \u03b8 \u03f4 \u03d1 T ? ? ?
D S D S S S \u039a \u03ba \u03f0 ? ? ?
D S D S S S \u03a0 \u03c0 \u03d6 ? p ?
D S D S S S \u03a1 \u03c1 \u03f1 ? ? ?
D S D S S S \u03a3 \u03c3 \u03c2 S s ?
D S D S S S \u03a6 \u03c6 \u03d5 F f ?
S D S D S S \u03a9 \u03c9 \u2126 O ? ?
D S D S S S \u1e60 \u1e61 \u1e9b ? ? ?
Complicating this still further is that there is no way to get the Turkish I's right (i.e. the dotted versions are different than the undotted versions) unless you know you're in Turkish; none of these methods give correct behavior and cannot unless you know the locale (i.e. non-Turkish: i
and I
are the same ignoring case; Turkish, not).
Overall, using toUpperCase
gives you the closest approximation, since you have only five uppercase variants (or four, not counting Turkish).
You can also try to specifically intercept those five troublesome cases and call toUpperCase(toLowerCase(c))
on them alone. If you choose your guards carefully (just toUpperCase
if c < 0x130 || c > 0x212B
, then work through the other alternatives) you can get only a ~20% speed penalty for characters in the low range (as compared to ~4x if you convert single characters to strings and equalsIgnoreCase
them) and only about a 2x penalty if you have a lot in the danger zone. You still have the locale problem with dotted I
, but otherwise you're in decent shape. Of course if you can use equalsIgnoreCase
on a larger string, you're better off doing that.
Here is sample Scala code that does the job:
def elevateCase(c: Char): Char = {
if (c < 0x130 || c > 0x212B) Character.toUpperCase(c)
else if (c == 0x130 || c == 0x3F4 || c == 0x2126 || c >= 0x212A)
Character.toUpperCase(Character.toLowerCase(c))
else Character.toUpperCase(c)
}
Alright, it's the usual "super()
cannot be used with an old-style class".
However, the important point is that the correct test for "is this a new-style instance (i.e. object)?" is
>>> class OldStyle: pass
>>> instance = OldStyle()
>>> issubclass(instance.__class__, object)
False
and not (as in the question):
>>> isinstance(instance, object)
True
For classes, the correct "is this a new-style class" test is:
>>> issubclass(OldStyle, object) # OldStyle is not a new-style class
False
>>> issubclass(int, object) # int is a new-style class
True
The crucial point is that with old-style classes, the class of an instance and its type are distinct. Here, OldStyle().__class__
is OldStyle
, which does not inherit from object
, while type(OldStyle())
is the instance
type, which does inherit from object
. Basically, an old-style class just creates objects of type instance
(whereas a new-style class creates objects whose type is the class itself). This is probably why the instance OldStyle()
is an object
: its type()
inherits from object
(the fact that its class does not inherit from object
does not count: old-style classes merely construct new objects of type instance
). Partial reference: https://stackoverflow.com/a/9699961/42973.
PS: The difference between a new-style class and an old-style one can also be seen with:
>>> type(OldStyle) # OldStyle creates objects but is not itself a type
classobj
>>> isinstance(OldStyle, type)
False
>>> type(int) # A new-style class is a type
type
(old-style classes are not types, so they cannot be the type of their instances).
It's simple as:
$('#action').val("1");
#action
is hidden input field id.
Just some other formatting options:
printf("name: %s\targs: %s\tvalue %d\tarraysize %d\n",
a, b, c, d);
printf("name: %s\targs: %s\tvalue %d\tarraysize %d\n",
a, b, c, d);
printf("name: %s\t" "args: %s\t" "value %d\t" "arraysize %d\n",
very_long_name_a, very_long_name_b, very_long_name_c, very_long_name_d);
You can add variations on the theme. The idea is that the printf()
conversion speficiers and the respective variables are all lined up "nicely" (for some values of "nicely").
You can use dateutil.parser.parse
(install with python -m pip install python-dateutil
) to parse strings into datetime objects.
dateutil.parser.parse
will attempt to guess the format of your string, if you know the exact format in advance then you can use datetime.strptime
which you supply a format string to (see Brent Washburne's answer).
from dateutil.parser import parse
a = "2012-10-09T19:00:55Z"
b = parse(a)
print(b.weekday())
# 1 (equal to a Tuesday)
If you have multiple ports to allow in Centos 7 FIrewalld then we can use the following command.
#firewall-cmd --add-port={port number/tcp,port number/tcp} --permanent
#firewall-cmd --reload
And check the Port opened or not after reloading the firewall.
#firewall-cmd --list-port
For other configuration [Linuxwindo.com][1]
Thanks, @droidev for the solution. If anyone looking for Kotlin solution, refer this:
class LinearLayoutManagerWithSmoothScroller: LinearLayoutManager {
constructor(context: Context) : this(context, VERTICAL,false)
constructor(context: Context, orientation: Int, reverseValue: Boolean) : super(context, orientation, reverseValue)
override fun smoothScrollToPosition(recyclerView: RecyclerView?, state: RecyclerView.State?, position: Int) {
super.smoothScrollToPosition(recyclerView, state, position)
val smoothScroller = TopSnappedSmoothScroller(recyclerView?.context)
smoothScroller.targetPosition = position
startSmoothScroll(smoothScroller)
}
private class TopSnappedSmoothScroller(context: Context?) : LinearSmoothScroller(context){
var mContext = context
override fun computeScrollVectorForPosition(targetPosition: Int): PointF? {
return LinearLayoutManagerWithSmoothScroller(mContext as Context)
.computeScrollVectorForPosition(targetPosition)
}
override fun getVerticalSnapPreference(): Int {
return SNAP_TO_START
}
}
}
I figured that the DJANGO_SETTINGS_MODULE had to be set some way, so I looked at the documentation (link updated) and found:
export DJANGO_SETTINGS_MODULE=mysite.settings
Though that is not enough if you are running a server on heroku, you need to specify it there, too. Like this:
heroku config:set DJANGO_SETTINGS_MODULE=mysite.settings --account <your account name>
In my specific case I ran these two and everything worked out:
export DJANGO_SETTINGS_MODULE=nirla.settings
heroku config:set DJANGO_SETTINGS_MODULE=nirla.settings --account personal
Edit
I would also like to point out that you have to re-do this every time you close or restart your virtual environment. Instead, you should automate the process by going to venv/bin/activate and adding the line: set DJANGO_SETTINGS_MODULE=mysite.settings
to the bottom of the code. From now on every time you activate the virtual environment, you will be using that app's settings.
I don't know if anyone else has this same problem, but my project's properties had "Configuration Properties" -> C/C++ -> "Debug Information Format"
set to "None", and when I switched it back to the default "Program Database (/Zi)", that stopped the project from recompiling every time.
I know this is an old posting -- and Gus basically answered it. But in my experience, JQuery has since changed their code for importing from the CDN - so I thought I would go ahead and post their latest code for importing from the CDN:
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
Here's an easy jQuery way:
var el = $('#yourid .yourclass');
el.html(el.html().replace(/Old Text/ig, "New Text"));
You can also make use of array#forEach()
method like this:
const cars = [{ make: 'audi', model: 'r8', year: '2012' }, { make: 'audi', model: 'rs5', year: '2013' }, { make: 'ford', model: 'mustang', year: '2012' }, { make: 'ford', model: 'fusion', year: '2015' }, { make: 'kia', model: 'optima', year: '2012' }];_x000D_
_x000D_
let newcars = {}_x000D_
_x000D_
cars.forEach(car => {_x000D_
newcars[car.make] ? // check if that array exists or not in newcars object_x000D_
newcars[car.make].push({model: car.model, year: car.year}) // just push_x000D_
: (newcars[car.make] = [], newcars[car.make].push({model: car.model, year: car.year})) // create a new array and push_x000D_
})_x000D_
_x000D_
console.log(newcars);
_x000D_
If you are sure your JSON is safely under your control (not user input) then you can simply evaluate the JSON. Eval accepts all quote types as well as unquoted property names.
var str = "{'a':1}";
var myObject = (0, eval)('(' + str + ')');
The extra parentheses are required due to how the eval parser works. Eval is not evil when it is used on data you have control over. For more on the difference between JSON.parse and eval() see JSON.parse vs. eval()
The main difference between these two is that ConcurrentHashMap
will lock only portion of the data which are being updated while other portion of data can be accessed by other threads. However, Collections.synchronizedMap()
will lock all the data while updating, other threads can only access the data when the lock is released. If there are many update operations and relative small amount of read operations, you should choose ConcurrentHashMap
.
Also one other difference is that ConcurrentHashMap
will not preserve the order of elements in the Map passed in. It is similar to HashMap
when storing data. There is no guarantee that the element order is preserved. While Collections.synchronizedMap()
will preserve the elements order of the Map passed in. For example, if you pass a TreeMap
to ConcurrentHashMap
, the elements order in the ConcurrentHashMap
may not be the same as the order in the TreeMap
, but Collections.synchronizedMap()
will preserve the order.
Furthermore, ConcurrentHashMap
can guarantee that there is no ConcurrentModificationException
thrown while one thread is updating the map and another thread is traversing the iterator obtained from the map. However, Collections.synchronizedMap()
is not guaranteed on this.
There is one post which demonstrate the differences of these two and also the ConcurrentSkipListMap
.
If you can't put value on buttons. I have just a rough solution. Put a hidden field. And when one of the buttons are clicked before submitting, populate the value of hidden field with like say 1 when first button clicked and 2 if second one is clicked. and in submit page check for the value of this hidden field to determine which one is clicked.
I have used this before and I think in order to make sure credential persist and in a best secure way is
ConfigurationManager
classSecureString
classCryptography
namespace.This link will be of great help I hope : Click here
chmod 774 filename
Note: The file with name 'filename' that has the bash script has no extension
By invoking its toString()
method.
Returns a string containing the characters in this sequence in the same order as this sequence. The length of the string will be the length of this sequence.
to add the original reference:
You can get the number of arguments from the special parameter $#
. Value of 0 means "no arguments". $#
is read-only.
When used in conjunction with shift
for argument processing, the special parameter $#
is decremented each time Bash Builtin shift
is executed.
see Bash Reference Manual in section 3.4.2 Special Parameters:
"The shell treats several parameters specially. These parameters may only be referenced"
and in this section for keyword $# "Expands to the number of positional parameters in decimal."
On Ubuntu, it's straight forward, clicking Help > Edit Custom VM Options . The IDE asks whether to create for you a file, click OK.
An empty studio64.vmoptions file is create and paste the following variables:
-Xms128m
-Xmx4096m
-XX:MaxPermSize=1024m
-XX:ReservedCodeCacheSize=200m
-XX:+UseCompressedOops
Restart the IDE, the Max Heap Size is increased to: 4,062M
see in the link :
http://www.coderanch.com/t/304851/JDBC/java/Java-date-MySQL-date-conversion
The following code just solved the problem:
java.util.Date dt = new java.util.Date();
java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(dt);
This 'currentTime' was inserted into the column whose type was DateTime and it was successful.
Let me expand a bit on a VonC's very comprehensive answer:
First, if I remember it correctly, the fact that Git by default doesn't create merge commits in the fast-forward case has come from considering single-branch "equal repositories", where mutual pull is used to sync those two repositories (a workflow you can find as first example in most user's documentation, including "The Git User's Manual" and "Version Control by Example"). In this case you don't use pull to merge fully realized branch, you use it to keep up with other work. You don't want to have ephemeral and unimportant fact when you happen to do a sync saved and stored in repository, saved for the future.
Note that usefulness of feature branches and of having multiple branches in single repository came only later, with more widespread usage of VCS with good merging support, and with trying various merge-based workflows. That is why for example Mercurial originally supported only one branch per repository (plus anonymous tips for tracking remote branches), as seen in older revisions of "Mercurial: The Definitive Guide".
Second, when following best practices of using feature branches, namely that feature branches should all start from stable version (usually from last release), to be able to cherry-pick and select which features to include by selecting which feature branches to merge, you are usually not in fast-forward situation... which makes this issue moot. You need to worry about creating a true merge and not fast-forward when merging a very first branch (assuming that you don't put single-commit changes directly on 'master'); all other later merges are of course in non fast-forward situation.
HTH
There are two ways of looking at github content, the "raw" way and the "Web page" way.
raw.githubusercontent.com
returns the raw content of files stored in github, so they can be downloaded simply to your computer. For example, if the page represents a ruby install script, then you will get a ruby install script that your ruby installation will understand.
If you instead download the file using the github.com link, you will actually be downloading a web page with buttons and comments and which displays your wanted script in the middle -- it's what you want to give to your web browser to get a nice page to look at, but for the computer, it is not a script that can be executed or code that can be compiled, but a web page to be displayed. That web page has a button called Raw that sends you to the corresponding content on raw.githubusercontent.com
.
To see the content of raw.githubusercontent.com/${repo}/${branch}/${path}
in the usual github interface:
raw.githubusercontent.com
with plain github.com
In this case, the branch name is "master" (which is a very common branch name), so you replace /master/
with /blob/master/
, and so
https://raw.githubusercontent.com/Homebrew/install/master/install
becomes
https://github.com/Homebrew/install/blob/master/install
This is the reverse of finding a file on Github and clicking the Raw link.
In Windows:
control /name microsoft.system
into the run dialog box that appears from the previous step.PATH
User environment variable.PATH
variable and add the following: %APPDATA%\npm
to the start of the PATH
environment variable (as shown in the image below).To accomodate all three points:
The file dialog is a setting in the browser.
For the button/save part assign the following function, boiled down from other answers, to your buttons onclick:
function DownloadCanvasAsImage(){
let downloadLink = document.createElement('a');
downloadLink.setAttribute('download', 'CanvasAsImage.png');
let canvas = document.getElementById('myCanvas');
let dataURL = canvas.toDataURL('image/png');
let url = dataURL.replace(/^data:image\/png/,'data:application/octet-stream');
downloadLink.setAttribute('href', url);
downloadLink.click();
}
Another, somewhat cleaner, approach is using Canvas.toBlob():
function DownloadCanvasAsImage(){
let downloadLink = document.createElement('a');
downloadLink.setAttribute('download', 'CanvasAsImage.png');
let canvas = document.getElementById('myCanvas');
canvas.toBlob(function(blob) {
let url = URL.createObjectURL(blob);
downloadLink.setAttribute('href', url);
downloadLink.click();
});
}
Neither solution is 100% cross browser compatible, so check the client
In a nutshell, no.
However, there are "nice" things you can do.
INSERT dbo.SPCall (What, When) VALUES (OBJECT_NAME(@@PROCID), GETDATE()
"There are "fun" things you can do:
RAISERROR ('Warning: pwn3d: call admin', 16, 1)
, see who callsWAITFOR DELAY '00:01:00'
, see who callsYou get the idea. The tried-and-tested "see who calls" method of IT support.
If the reports are Reporting Services, then you can mine the RS database for the report runs if you can match code to report DataSet.
You couldn't rely on DMVs anyway because they are reset om SQL Server restart. Query cache/locks are transient and don't persist for any length of time.
# Define the types of logger and level of logging
log4j.rootLogger = DEBUG,console, FILE
# Define the File appender
log4j.appender.FILE=org.apache.log4j.FileAppender
# Define Console Appender
log4j.appender.console=org.apache.log4j.ConsoleAppender
# Define the layout for console appender. If you do not
# define it, you will get an error
log4j.appender.console.layout=org.apache.log4j.PatternLayout
# Set the name of the file
log4j.appender.FILE.File=log.out
# Set the immediate flush to true (default)
log4j.appender.FILE.ImmediateFlush=true
# Set the threshold to debug mode
log4j.appender.FILE.Threshold=debug
# Set the append to false, overwrite
log4j.appender.FILE.Append=false
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
You can also use the filter function from the dplyr package which returns rows with matching conditions.
> library(dplyr)
> nrow(filter(aaa, sex == 1 & group1 == 2))
[1] 3
> nrow(filter(aaa, sex == 1 & group2 == "A"))
[1] 2
It depends on the database to which you're trying to connect, the method by which you created the connection, and the version of Excel that you're using. (Also, most probably, the version of the relevant ODBC driver on your computer.)
The following examples are using SQL Server 2008 and Excel 2007, both on my local machine.
When I used the Data Connection Wizard (on the Data tab of the ribbon, in the Get External Data section, under From Other Sources), I saw the same thing that you did: the Parameters button was disabled, and adding a parameter to the query, something like select field from table where field2 = ?
, caused Excel to complain that the value for the parameter had not been specified, and the changes were not saved.
When I used Microsoft Query (same place as the Data Connection Wizard), I was able to create parameters, specify a display name for them, and enter values each time the query was run. Bringing up the Connection Properties for that connection, the Parameters... button is enabled, and the parameters can be modified and used as I think you want.
I was also able to do this with an Access database. It seems reasonable that Microsoft Query could be used to create parameterized queries hitting other types of databases, but I can't easily test that right now.
A '$' in a variable means nothing special to the interpreter, much like an underscore.
From what I've seen, many people using jQuery (which is what your example code looks like to me) tend to prefix variables that contain a jQuery object with a $ so that they are easily identified and not mixed up with, say, integers.
The dollar sign function $()
in jQuery is a library function that is frequently used, so a short name is desirable.
Use the method "toArray()"
ArrayList<String> mStringList= new ArrayList<String>();
mStringList.add("ann");
mStringList.add("john");
Object[] mStringArray = mStringList.toArray();
for(int i = 0; i < mStringArray.length ; i++){
Log.d("string is",(String)mStringArray[i]);
}
or you can do it like this: (mentioned in other answers)
ArrayList<String> mStringList= new ArrayList<String>();
mStringList.add("ann");
mStringList.add("john");
String[] mStringArray = new String[mStringList.size()];
mStringArray = mStringList.toArray(mStringArray);
for(int i = 0; i < mStringArray.length ; i++){
Log.d("string is",(String)mStringArray[i]);
}
http://developer.android.com/reference/java/util/ArrayList.html#toArray()
char* result = strcpy((char*)malloc(str.length()+1), str.c_str());
There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.
When you define your list as:
List myList = new ArrayList();
you can only call methods and reference members that are defined in the List interface. If you define it as:
ArrayList myList = new ArrayList();
you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.
Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).
That's called polymorphism. You can read up on it.