You would want to use __slots__
if you are going to instantiate a lot (hundreds, thousands) of objects of the same class. __slots__
only exists as a memory optimization tool.
It's highly discouraged to use __slots__
for constraining attribute creation.
Pickling objects with __slots__
won't work with the default (oldest) pickle protocol; it's necessary to specify a later version.
Some other introspection features of python may also be adversely affected.
If you use DisplayFor
, then you have to either define the format via the DisplayFormat
attribute or use a custom display template. (A full list of preset DisplayFormatString
's can be found here.)
[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime? AuditDate { get; set; }
Or create the view Views\Shared\DisplayTemplates\DateTime.cshtml
:
@model DateTime?
@if (Model.HasValue)
{
@Model.Value.ToString("MM/dd/yyyy")
}
That will apply to all DateTime
s, though, even ones where you're encoding the time as well. If you want it to apply only to date-only properties, then use Views\Shared\DisplayTemplates\Date.cshtml
and the DataType
attribute on your property:
[DataType(DataType.Date)]
public DateTime? AuditDate { get; set; }
The final option is to not use DisplayFor
and instead render the property directly:
@if (Model.AuditDate.HasValue)
{
@Model.AuditDate.Value.ToString("MM/dd/yyyy")
}
If you're asking this because you want to speed up your web site, check out Yahoo's page on Best Practices for Speeding Up Your Web Site. It has a lot of best practices for speeding up your web site.
You can try the following:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog fDialog = new OpenFileDialog();
fDialog.Title = "Select file to be upload";
fDialog.Filter = "All Files|*.*";
// fDialog.Filter = "PDF Files|*.pdf";
if (fDialog.ShowDialog() == DialogResult.OK)
{
textBox1.Text = fDialog.FileName.ToString();
}
}
String methodName= "...";
String[] args = {};
Method[] methods = clazz.getMethods();
for (Method m : methods) {
if (methodName.equals(m.getName())) {
// for static methods we can use null as instance of class
m.invoke(null, new Object[] {args});
break;
}
}
The extra [ ] on the outside of your second syntax are unnecessary, and possibly confusing. You may use them, but if you must you need to have whitespace between them.
Alternatively:
while [ $stats -gt 300 ] || [ $stats -eq 0 ]
in my case all works fine. See in logcat. Maybe logcat show something that can help you to resolve your problem
Anyway you can try do it programmatically:
public class ActivityName extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// remove title
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
}
}
You can use anonymous types for this, i.e.:
var pageObject = (from op in db.ObjectPermissions
join pg in db.Pages on op.ObjectPermissionName equals page.PageName
where pg.PageID == page.PageID
select new { pg, op }).SingleOrDefault();
This will make pageObject into an IEnumerable of an anonymous type so AFAIK you won't be able to pass it around to other methods, however if you're simply obtaining data to play with in the method you're currently in it's perfectly fine. You can also name properties in your anonymous type, i.e.:-
var pageObject = (from op in db.ObjectPermissions
join pg in db.Pages on op.ObjectPermissionName equals page.PageName
where pg.PageID == page.PageID
select new
{
PermissionName = pg,
ObjectPermission = op
}).SingleOrDefault();
This will enable you to say:-
if (pageObject.PermissionName.FooBar == "golden goose") Application.Exit();
For example :-)
With PHP 5.6 on Amazon Linux (should be the same on RedHat or CentOS):
yum install php56-opcache
and then restart apache.
Webkit browsers (not sure about FireBug) allow you to copy the HTML of an element easily, so that's one part of the process out of the way.
Running this (in the javascript console) prior to copying the HTML for an element will move all the computed styles for the parent element given, as well as all child elements, into the inline style attribute which will then be available as part of the HTML.
var el = document.querySelector("#someid");
var els = el.getElementsByTagName("*");
for(var i = -1, l = els.length; ++i < l;){
els[i].setAttribute("style", window.getComputedStyle(els[i]).cssText);
}
It's a total hack and you'll have alot of "junk" css attributes to wade through, but should at least get your started.
Perhaps this can be useful for someone:
In my case, I was getting an array of objects, each containing a date set by Mongoose.
I used:
ng-repeat="comment in post.comments | orderBy : sortComment : true"
And defined the function:
$scope.sortComment = function(comment) {
var date = new Date(comment.created);
return date;
};
This worked for me.
Vikas answer works perfectly for me, here I also add support for the delay (show / hide).
var popover = $('#example');
var options = {
animation : true,
html: true,
trigger: 'manual',
placement: 'right',
delay: {show: 500, hide: 100}
};
popover
.popover(options)
.on("mouseenter", function () {
var t = this;
var popover = $(this);
setTimeout(function () {
if (popover.is(":hover")) {
popover.popover("show");
popover.siblings(".popover").on("mouseleave", function () {
$(t).popover('hide');
});
}
}, options.delay.show);
})
.on("mouseleave", function () {
var t = this;
var popover = $(this);
setTimeout(function () {
if (popover.siblings(".popover").length && !popover.siblings(".popover").is(":hover")) {
$(t).popover("hide")
}
}, options.delay.hide);
});
Also please pay attention I changed:
if (!$(".popover:hover").length) {
with:
if (popover.siblings(".popover").length && !popover.siblings(".popover").is(":hover")) {
so that it references exactly at that opened popover, and not any other (since now, through the delay, more than 1 could be open at the same time)
I just made my own version of this. My function can be used to extract whatever you want from it, if you don't need all of it, then you can easily remove some code.
<html>
<body>
<script type="text/javascript">
// Useful function to separate path name and extension from full path string
function pathToFile(str)
{
var nOffset = Math.max(0, Math.max(str.lastIndexOf('\\'), str.lastIndexOf('/')));
var eOffset = str.lastIndexOf('.');
if(eOffset < 0 && eOffset < nOffset)
{
eOffset = str.length;
}
return {isDirectory: eOffset === str.length, // Optionally: && nOffset+1 === str.length if trailing slash means dir, and otherwise always file
path: str.substring(0, nOffset),
name: str.substring(nOffset > 0 ? nOffset + 1 : nOffset, eOffset),
extension: str.substring(eOffset > 0 ? eOffset + 1 : eOffset, str.length)};
}
// Testing the function
var testcases = [
"C:\\blabla\\blaeobuaeu\\testcase1.jpeg",
"/tmp/blabla/testcase2.png",
"testcase3.htm",
"C:\\Testcase4", "/dir.with.dots/fileWithoutDots",
"/dir.with.dots/another.dir/"
];
for(var i=0;i<testcases.length;i++)
{
var file = pathToFile(testcases[i]);
document.write("- " + (file.isDirectory ? "Directory" : "File") + " with name '" + file.name + "' has extension: '" + file.extension + "' is in directory: '" + file.path + "'<br />");
}
</script>
</body>
</html>
Will output the following:
With && nOffset+1 === str.length
added to isDirectory
:
Given the testcases you can see this function works quite robustly compared to the other proposed methods here.
Note for newbies about the \\: \ is an escape character, for example \n means a newline and \t a tab. To make it possible to write \n, you must actually type \\n.
Why don't you set both Background & BorderBrush
by same brush
<Style TargetType="{x:Type Button}" >
<Setter Property="Background" Value="{StaticResource marginBackGround}"></Setter>
<Setter Property="BorderBrush" Value="{StaticResource marginBackGround}"></Setter>
</Style>
<LinearGradientBrush x:Key="marginBackGround" EndPoint=".5,1" StartPoint="0.5,0">
<GradientStop Color="#EE82EE" Offset="0"/>
<GradientStop Color="#7B30B6" Offset="0.5"/>
<GradientStop Color="#510088" Offset="0.5"/>
<GradientStop Color="#76209B" Offset="0.9"/>
<GradientStop Color="#C750B9" Offset="1"/>
</LinearGradientBrush>
Please use this command:
readlink -f $(which java)
It works for me with Ubuntu gnome.
On my computer the result is:
/usr/lib/jvm/java-7-oracle/jre/bin/java
Regards.
Yet the question is answered accurately above, but just want to share my knowledge . Postback is basically a property that we can use while doing some tasks that need us to manage the state of the page, that is either we have fired some event for e.g. a button click or if we have refreshed our page. When our page loads for the very first time , that is if we have refreshed our page, at that time postback-property is false, and after that it becomes true.
if(!ispostback)
{
// do some task here
}
else
{
//do another task here
}
http://happycodng.blogspot.in/2013/09/concept-of-postback-in.html
You're close; you should use dot notation in your use of the $
update operator to do that:
Person.update({'items.id': 2}, {'$set': {
'items.$.name': 'updated item2',
'items.$.value': 'two updated'
}}, function(err) { ...
Just for anyone who still has an issue, I also had an issue where I typed ngif
rather than ngIf
(notice the capital 'I').
Filter out the null instances before groupingBy.
Here is an exampleMyObjectlist.stream()
.filter(p -> p.getSomeInstance() != null)
.collect(Collectors.groupingBy(MyObject::getSomeInstance));
try this. m = row, n = col
vector<vector<int>> matrix(m, vector<int>(n));
for(i = 0;i < m; i++)
{
for(j = 0; j < n; j++)
{
cin >> matrix[i][j];
}
cout << endl;
}
cout << "::matrix::" << endl;
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
You can do in this way:
Integer i = 1;
new BigInteger("" + i);
Did some testing with the following script, on both PS 2 and PS 4 and had the same result. I hope this helps people.
$PSVersionTable.PSVersion
function PSscript {
$PSscript = Get-Item $MyInvocation.ScriptName
Return $PSscript
}
""
$PSscript = PSscript
$PSscript.FullName
$PSscript.Name
$PSscript.BaseName
$PSscript.Extension
$PSscript.DirectoryName
""
$PSscript = Get-Item $MyInvocation.InvocationName
$PSscript.FullName
$PSscript.Name
$PSscript.BaseName
$PSscript.Extension
$PSscript.DirectoryName
Results -
Major Minor Build Revision
----- ----- ----- --------
4 0 -1 -1
C:\PSscripts\Untitled1.ps1
Untitled1.ps1
Untitled1
.ps1
C:\PSscripts
C:\PSscripts\Untitled1.ps1
Untitled1.ps1
Untitled1
.ps1
C:\PSscripts
Using regexp: \S will match non whitespace character:anything but not a space, tab or new line. If your string has a single character which is not a space, tab or new line, then it's not empty. Therefore you just need to search for one character: \S
JavaScript:
function checkvalue() {
var mystring = document.getElementById('myString').value;
if(!mystring.match(/\S/)) {
alert ('Empty value is not allowed');
return false;
} else {
alert("correct input");
return true;
}
}
HTML:
<form onsubmit="return checkvalue(this)">
<input name="myString" type="text" value='' id="myString">
<input type="submit" value="check value" />
</form>
This is what I used to copy some resource files: the copy-files is an empty target to ignore errors
add_custom_target(copy-files ALL
COMMAND ${CMAKE_COMMAND} -E copy_directory
${CMAKE_BINARY_DIR}/SOURCEDIRECTORY
${CMAKE_BINARY_DIR}/DESTINATIONDIRECTORY
)
Add the following to you environment variable PATH
.
C:\Python27\Scripts
This path will contain the pip
executable file. Make sure it exist. If it doesn't then you'll need to install it using the get-pip.py
script.
Additonally, you can read the following link to get a better understanding.
I am blind and have been a programmer for the last 12 years or so. Currently am a senior architect and work with Sapient Corporation (a cambridge-based consulting company creating both Web-based and thick client based enterprise solutions). I use several screen readers but mostly stick with Jaws for windows and NVDA.
I have mostly worked on the Microsoft platform and visual studio as my environment. I also use tools like the MS Sql enterprise studio and others for DB access, network monitoring etc. I tried to spend some time with emacspeak but since my work was mostly based on the MS platform, never really spent a lot of time there. I have also spent a couple of years working on C++ on linux - mostly used notepad or visual studio on windows for all the coding and then samba to share files with the linux environment. Also used borland C for some experimental stuff. Have recently been playing around with python, which as other people have noted above is particularly unfriendly for a blind user because it is written using indentation as the nesting mechanism. Having said that, NVDA, the most popular open source screen reader is written completely using python and some of the commiters on that project are themself blind. A particularly interesting question I get frequently asked as an architect is how do I deal with diagrams - UML and visio and rational rose etc. Visio is probably the most accessible diagraming tool out there. I was able to write jaws scripts to read rational rose diagrams for me. I've used a tool called T-dub (technical diagram understanding for the blind) developed by some german university for accessing UML 2.0 diagrams. Have used a java-based ugly tool called magic draw for doing model-driven development and was a commiter on the androMDA project and helped develop the .Net code generator from a UML model.
In general, I find that I thrive most in a team environment where I can work on my strengths. For example, while a diagram is extremely useful to communicate/document a design, the actual design process involves a lot of thinking and brainstorming and when the design has been thought out, one of your team mates can help you quickly put together a neatly drawn picture out of it. People incorrectly mis-construe the above to be lack of independence or ability while I see this as pure inter-dependence -- as in I am sure that the team mate alone could never have come up with that design on his/her own and in-turn, if I depend on him to document the design, so be it. Most hurdles I face are tool-based inaccessibility. For example all oracle products have been progressively declining in accessibility over the years (shame on them) and a team environment basically allows me an extra layer of defense against these over and above my screen readers and custom scripts.
For horizontal scroll, keep these two properties in mind:
overflow-x:scroll;
white-space: nowrap;
See working link : click me
HTML
<p>overflow:scroll</p>
<div class="scroll">You can use the overflow property when you want to have better control of the layout. The default value is visible.You can use the overflow property when you want to have better control of the layout. The default value is visible.</div>
CSS
div.scroll
{
background-color:#00FFFF;
height:40px;
overflow-x:scroll;
white-space: nowrap;
}
Updated version of HCD's solution which avoids conflict:
var y = $j(window).scrollTop();
$j("html, body").animate({ scrollTop: y + $j(window).height() }, 600);
This happened to me and it took me an hour to find it. In my case I had typed too fast and did:
[seld method];
instead of:
[self method];
Seriously! I don't know why it didn't catch this in a more recognizable way. But it was of course looking for a class called "seld".
After trying several things, this worked for me:
With addresses other than 0.0.0.0
I had no success.
Just do (int)myLongValue
. It'll do exactly what you want (discarding MSBs and taking LSBs) in unchecked
context (which is the compiler default). It'll throw OverflowException
in checked
context if the value doesn't fit in an int
:
int myIntValue = unchecked((int)myLongValue);
This theme required awhile to find results and reasons:
using MaiaDB 5.4. via SuSE-LINUX tumblweed
some files in the appointed directory havn't been necessary in any direct relation with mariadb. I.e: I placed some hints, a text-file, some bakup-copys somewhere in the same appointed directory for mysql mariadb and this caused endless error-messages and blocking the server from starting. Mariadb appears to be very sensible and hostile with the presence of other files not beeing database files(comments,backups,experimantal files etc) .
using libreoffice as client then there already this generated much problems with the creation and working on a database and caused some crashes.The crashes eventually produced bad tables.
May be because of that or may be because of the presence of not yet deleted but unusable tables !! the mysql mariadb server crashed and didn't want to do it' job not even start.
Error message always same : "Table 'some.table' doesn't exist in engine"
But when it started then tables appeared as normal, but it was unpossible to work on them.
So what to do without a more precise Error Message ?? The unusable tables showed up with: "CHECK TABLE" or on the command line of the system with "mysqlcheck " So I deleted by filemanager or on the system-level as root or as allowed user all the questionable files and then problem was solved.
Proposal: the Error Message could be a bit more precisely for example: "corrupted tables" (which can be found by CHECK TABLE, but only if the server is running) or by mysqlcheck even whe server is not running - but here are other disturbing files like hints/bakups a.s.o not visible.
ANYWAY it helped a lot to have backup-copies of the original database-files on a backup volume. This helped to check out and test it again and again until solution was found.
Good luck all - Herbert
A very simple check you can do with Cell formulas:
Sheet 1 (new - old)
=(if(AND(Ref_New<>"";Ref_Old="");Ref_New;"")
Sheet 2 (old - new)
=(if(AND(Ref_Old<>"";Ref_New="");Ref_Old;"")
This formulas should work for an ENGLISH Excel. For other languages they need to be translated. (For German i can assist)
You need to open all three Excel Documents, then copy the first formula into A1 of your sheet 1 and the second into A1 of sheet 2. Now click in A1 of the first cell and mark "Ref_New", now you can select your reference, go to the new file and click in the A1, go back to sheet1 and do the same for "Ref_Old" with the old file. Replace also the other "Ref_New".
Doe the same for Sheet two.
Now copy the formaula form A1 over the complete range where zour data is in the old and the new file.
But two cases are not covered here:
To cover this two cases also, you should create your own function, means learn VBA. A very useful Excel page is cpearson.com
This also works - it will remove all the folders called "a" and their contents:
rm -rf `find -type d -name a`
This was answered by a few others but I found a solution that worked really well for me.
System.out.println(CvType.typeToString(yourMat.type()));
A variable referencing an array is basically a pointer to its first element, so yes, you can legitimately return a pointer to an array, because thery're essentially the same thing. Check this out yourself:
#include <assert.h>
int main() {
int a[] = {1, 2, 3, 4, 5};
int* pArr = a;
int* pFirstElem = &(a[0]);
assert(a == pArr);
assert(a == pFirstElem);
return 0;
}
This also means that passing an array to a function should be done via pointer (and not via int in[5]
), and possibly along with the length of the array:
int* test(int* in, int len) {
int* out = in;
return out;
}
That said, you're right that using pointers (without fully understanding them) is pretty dangerous. For example, referencing an array that was allocated on the stack and went out of scope yields undefined behavior:
#include <iostream>
using namespace std;
int main() {
int* pArr = 0;
{
int a[] = {1, 2, 3, 4, 5};
pArr = a; // or test(a) if you wish
}
// a[] went out of scope here, but pArr holds a pointer to it
// all bets are off, this can output "1", output 1st chapter
// of "Romeo and Juliet", crash the program or destroy the
// universe
cout << pArr[0] << endl; // WRONG!
return 0;
}
So if you don't feel competent enough, just use std::vector
.
[answer to the updated question]
The correct way to write your test
function is either this:
void test(int* a, int* b, int* c, int len) {
for (int i = 0; i < len; ++i) c[i] = a[i] + b[i];
}
...
int main() {
int a[5] = {...}, b[5] = {...}, c[5] = {};
test(a, b, c, 5);
// c now holds the result
}
Or this (using std::vector
):
#include <vector>
vector<int> test(const vector<int>& a, const vector<int>& b) {
vector<int> result(a.size());
for (int i = 0; i < a.size(); ++i) {
result[i] = a[i] + b[i];
}
return result; // copy will be elided
}
I am using such code in config.php:
$lang = 'ru'; // this language will be used if there is no any lang information from useragent (for example, from command line, wget, etc...
if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'],0,2);
$tmp_value = $_COOKIE['language'];
if (!empty($tmp_value)) $lang = $tmp_value;
switch ($lang)
{
case 'ru':
$config['language'] = 'russian';
setlocale(LC_ALL,'ru_RU.UTF-8');
break;
case 'uk':
$config['language'] = 'ukrainian';
setlocale(LC_ALL,'uk_UA.UTF-8');
break;
case 'foo':
$config['language'] = 'foo';
setlocale(LC_ALL,'foo_FOO.UTF-8');
break;
default:
$config['language'] = 'english';
setlocale(LC_ALL,'en_US.UTF-8');
break;
}
.... and then i'm using usualy internal mechanizm of CI
o, almost forget! in views i using buttons, which seting cookie 'language' with language, prefered by user.
So, first this code try to detect "preffered language" setted in user`s useragent (browser). Then code try to read cookie 'language'. And finaly - switch sets language for CI-application
Make sure you are in the correct VirtualEnvironment. I updated PyCharm and for some reason had to point my project at my VE again. Opening the terminal, I was not in my VE when attempting zappa update (and got this error). Restarting PyCharm, all back to normal.
The answer of delfuego is the simplest way to solve the certificate problem. But, in my case, one of our third party url (using https), updated their certificate every 2 months automatically. It means that I have to import the cert to our Java trust store manually every 2 months as well. Sometimes it caused production problems.
So, I made a method to solve it with SecureRestClientTrustManager to be able to consume https url without importing the cert file. Here is the method:
public static String doPostSecureWithHeader(String url, String body, Map headers) throws Exception { log.info("start doPostSecureWithHeader " + url + " with param " + body); long startTime; long endTime; startTime = System.currentTimeMillis(); Client client; client = Client.create(); WebResource webResource; webResource = null; String output = null; try{ SSLContext sslContext = null; SecureRestClientTrustManager secureRestClientTrustManager = new SecureRestClientTrustManager(); sslContext = SSLContext.getInstance("SSL"); sslContext .init(null, new javax.net.ssl.TrustManager[] { secureRestClientTrustManager }, null); DefaultClientConfig defaultClientConfig = new DefaultClientConfig(); defaultClientConfig .getProperties() .put(com.sun.jersey.client.urlconnection.HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new com.sun.jersey.client.urlconnection.HTTPSProperties( getHostnameVerifier(), sslContext)); client = Client.create(defaultClientConfig); webResource = client.resource(url); if(headers!=null && headers.size()>0){ for (Map.Entry entry : headers.entrySet()){ webResource.setProperty(entry.getKey(), entry.getValue()); } } WebResource.Builder builder = webResource.accept("application/json"); if(headers!=null && headers.size()>0){ for (Map.Entry entry : headers.entrySet()){ builder.header(entry.getKey(), entry.getValue()); } } ClientResponse response = builder .post(ClientResponse.class, body); output = response.getEntity(String.class); } catch(Exception e){ log.error(e.getMessage(),e); if(e.toString().contains("One or more of query value parameters are null")){ output="-1"; } if(e.toString().contains("401 Unauthorized")){ throw e; } } finally { if (client!= null) { client.destroy(); } } endTime = System.currentTimeMillis(); log.info("time hit "+ url +" selama "+ (endTime - startTime) + " milliseconds dengan output = "+output); return output; }
Your best bet is to change that column to a timestamp. MySQL will automatically use the first timestamp in a row as a 'last modified' value and update it for you. This is configurable if you just want to save creation time.
See doc http://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
I know it's already an old question, but i had the same error today. For me setting the connection variable on model did the work.
/**
* Table properties
*/
protected $connection = 'mysql-utf8';
protected $table = 'notification';
protected $primaryKey = 'id';
I don't know if the issue was with the database (probably), but the texts fields with special chars (like ~, ´ e etc) were all messed up.
---- Editing
That $connection var is used to select wich db connection your model will use. Sometimes it happens that in database.php (under /config folder) you have multiples connections and the default one is not using UTF-8 charset.
In any case, be sure to properly use charset and collation into your connection.
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'your_database'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', 'database_password'),
'unix_socket' => env('DB_SOCKET', ''),
'prefix' => '',
'strict' => false,
'engine' => null
],
'mysql-utf8' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'your_database'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', 'database_password'),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
'engine' => null
],
I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = "Data Source=D:\test.xls " & _
";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
For i = 0 To rs.Fields.Count - 1
Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
strNaam = rs.Fields(0).Value
Next
rs.MoveNext
Loop
rs.Close
There are other ways, depending on what you want to do, such as GetString (GetString Method Description).
postgres (since version 9.0) allows anonymous blocks in any of the supported server-side scripting languages
DO '
DECLARE somevariable int = -1;
BEGIN
INSERT INTO foo VALUES ( somevariable );
END
' ;
http://www.postgresql.org/docs/current/static/sql-do.html
As everything is inside a string, external string variables being substituted in will need to be escaped and quoted twice. Using dollar quoting instead will not give full protection against SQL injection.
The windows object has a windows field in which it is cloned and stores the date of the open window, close should be called on this field:
window.open("", '_self').window.close();
You could use wmic command:
wmic logicaldisk where drivetype=2 get <DeviceID, VolumeName, Description, ...>
Drivetype 2 indicates that its a removable disk.
go to Run Configuration and in argument tab you can write your argument
@JaredPar: Yes you can use Shelvesets for reviews but keep in mind that shelvesets can be overwritten by yourself/others and therefore are not long term stable. Therefore for regulatory relevant reviews you should never use a Shelveset as base but rather a checkin (Changeset). For an informal review it is ok but not for a formal (E.g. FTA relevant) review!
No, but you can install an isolated Python build (such as ActivePython) under your $HOME
directory.
This approach is the fastest, and doesn't require you to compile Python yourself.
(as a bonus, you also get to use ActiveState's binary package manager)
I encountered this problem as well and the other answers here were helpful, but I am using a Route::resource
which takes care of GET
, POST
, and other requests.
In my case I left my route as is:
Route::resource('file', 'FilesController');
And simply modified my form to submit to the store
function in my FilesController
{{ Form::open(array('route' => 'file.store')) }}
This fixed the issue, and I thought it was worth pointing out as a separate answer since various other answers suggest adding a new POST
route. This is an option but it's not necessary.
Try this:
$('#contra').focusout(function (){
$('#btnPassword').focus();
});
Clear:both gives you that space between them.
For example your code:
<div style="float:left">Hello</div>
<div style="float:right">Howdy dere pardner</div>
Will currently display as :
Hello ................... Howdy dere pardner
If you add the following to above snippet,
<div style="clear:both"></div>
In between them it will display as:
Hello ................
Howdy dere pardner
giving you that space between hello and Howdy dere pardner.
Js fiiddle http://jsfiddle.net/Qk5vR/1/
A for loop is useful when you have an indication or determination, in advance, of how many times you want a loop to run. As an example, if you need to perform a process for each day of the week, you know you want 7 loops.
A foreach loop is when you want to repeat a process for all pieces of a collection or array, but it is not important specifically how many times the loop runs. As an example, you are formatting a list of favorite books for users. Every user may have a different number of books, or none, and we don't really care how many it is, we just want the loop to act on all of them.
...
String str = "bla!/bla/bla/"
String parts[] = str.split("/");
//To get fist "bla!"
String dir1 = parts[0];
Interesting. The only thing I knew that had to do with programming and had POCO in it is the POCO C++ framework.
Adding this to your code android:focusableInTouchMode="true"
will make sure that your keypad doesn't appear on startup for your edittext box. You want to add this line to your linear layout that contains the EditTextBox. You should be able to play with this to solve both your problems. I have tested this. Simple solution.
ie: In your app_list_view.xml file
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:focusableInTouchMode="true">
<EditText
android:id="@+id/filter_edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search"
android:inputType="text"
android:maxLines="1"/>
<ListView
android:id="@id/android:list"
android:layout_height="fill_parent"
android:layout_weight="1.0"
android:layout_width="fill_parent"
android:focusable="true"
android:descendantFocusability="beforeDescendants"/>
</LinearLayout>
------------------ EDIT: To Make keyboard appear on startup -----------------------
This is to make they Keyboard appear on the username edittextbox on startup. All I've done is added an empty Scrollview to the bottom of the .xml file, this puts the first edittext into focus and pops up the keyboard. I admit this is a hack, but I am assuming you just want this to work. I've tested it, and it works fine.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="20dip"
android:paddingRight="20dip">
<EditText
android:id="@+id/userName"
android:singleLine="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:imeOptions="actionDone"
android:inputType="text"
android:maxLines="1"
/>
<EditText
android:id="@+id/password"
android:password="true"
android:singleLine="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Password" />
<ScrollView
android:id="@+id/ScrollView01"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
</ScrollView>
</LinearLayout>
If you are looking for a more eloquent solution, I've found this question which might help you out, it is not as simple as the solution above but probably a better solution. I haven't tested it but it apparently works. I think it is similar to the solution you've tried which didn't work for you though.
Hope this is what you are looking for.
Cheers!
Another way is to use a lambda expression. Depending on interpreter version and whether you wish to create a sorted dictionary or sorted key-value tuples (as the OP does), this may even be faster than the accepted answer.
d = {'aa': 3, 'bb': 4, 'cc': 2, 'dd': 1}
s = sorted(d.items(), key=lambda x: x[1], reverse=True)
for k, v in s:
print(k, v)
Scenario
I was getting SSLHandshake exceptions on devices running versions of Android earlier than Android 5.0. In my use case I also wanted to create a TrustManager to trust my client certificate.
I implemented NoSSLv3SocketFactory and NoSSLv3Factory to remove SSLv3 from my client's list of supported protocols but I could get neither of these solutions to work.
Some things I learned:
What worked for me
Allow Android's security Provider
to update when starting your app.
The default Provider before 5.0+ does not disable SSLv3. Provided you have access to Google Play services it is relatively straightforward to patch Android's security Provider from your app.
private void updateAndroidSecurityProvider(Activity callingActivity) {
try {
ProviderInstaller.installIfNeeded(this);
} catch (GooglePlayServicesRepairableException e) {
// Thrown when Google Play Services is not installed, up-to-date, or enabled
// Show dialog to allow users to install, update, or otherwise enable Google Play services.
GooglePlayServicesUtil.getErrorDialog(e.getConnectionStatusCode(), callingActivity, 0);
} catch (GooglePlayServicesNotAvailableException e) {
Log.e("SecurityException", "Google Play Services not available.");
}
}
If you now create your OkHttpClient or HttpURLConnection TLSv1.1 and TLSv1.2 should be available as protocols and SSLv3 should be removed. If the client/connection (or more specifically it's SSLContext) was initialised before calling ProviderInstaller.installIfNeeded(...)
then it will need to be recreated.
Don't forget to add the following dependency (latest version found here):
compile 'com.google.android.gms:play-services-auth:16.0.1'
Sources:
Aside
I didn't need to explicitly set which cipher algorithms my client should use but I found a SO post recommending those considered most secure at the time of writing: Which Cipher Suites to enable for SSL Socket?
The git cherry-pick <commit>
command allows you to take a single commit (from whatever branch) and, essentially, rebase it in your working branch.
Chapter 5 of the Pro Git book explains it better than I can, complete with diagrams and such. (The chapter on Rebasing is also good reading.)
Lastly, there are some good comments on the cherry-picking vs merging vs rebasing in another SO question.
Complementary answer to Robert's answer http://jsfiddle.net/ak9Sb/ in jQuery
When getting/setting checkbox state, one may encounter these phenomenons:
.trigger("click");
Does check an unchecked checkbox, but do not add the checked attribute. If you use triggers, do not try to get the state with "checked" attribute.
.attr("checked", "");
Does not uncheck the checkbox...
easy if its pdf or img use
return (in_Array($file['content-type'], ['image/jpg', 'application/pdf']));
Yes, that is one way to get the first line of output from a command.
If the command outputs anything to standard error that you would like to capture in the same manner, you need to redirect the standard error of the command to the standard output stream:
utility 2>&1 | head -n 1
There are many other ways to capture the first line too, including sed 1q
(quit after first line), sed -n 1p
(only print first line, but read everything), awk 'FNR == 1'
(only print first line, but again, read everything) etc.
Check the length of sys.argv
:
if len(sys.argv) > 1:
blah = sys.argv[1]
else:
blah = 'blah'
Some people prefer the exception-based approach you've suggested (eg, try: blah = sys.argv[1]; except IndexError: blah = 'blah'
), but I don't like it as much because it doesn't “scale” nearly as nicely (eg, when you want to accept two or three arguments) and it can potentially hide errors (eg, if you used blah = foo(sys.argv[1])
, but foo(...)
raised an IndexError
, that IndexError
would be ignored).
Because the number can be up to 15 digits, you'll need to cast to an 64 bit (8-byte) integer. Try this:
SELECT * FROM table
WHERE myint = mytext::int8
The ::
cast operator is historical but convenient. Postgres also conforms to the SQL standard syntax
myint = cast ( mytext as int8)
If you have literal text you want to compare with an int
, cast the int
to text:
SELECT * FROM table
WHERE myint::varchar(255) = mytext
Probably the simplest way is using subplot2grid
, described in Customizing Location of Subplot Using GridSpec.
ax = plt.subplot2grid((2, 2), (0, 0))
is equal to
import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(2, 2)
ax = plt.subplot(gs[0, 0])
so bmu's example becomes:
import numpy as np
import matplotlib.pyplot as plt
# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# plot it
fig = plt.figure(figsize=(8, 6))
ax0 = plt.subplot2grid((1, 3), (0, 0), colspan=2)
ax0.plot(x, y)
ax1 = plt.subplot2grid((1, 3), (0, 2))
ax1.plot(y, x)
plt.tight_layout()
plt.savefig('grid_figure.pdf')
For hiding a widget you can use function pack_forget() and to again show it you can use pack() function and implement them both in separate functions.
from Tkinter import *
root = Tk()
label=Label(root,text="I was Hidden")
def labelactive():
label.pack()
def labeldeactive():
label.pack_forget()
Button(root,text="Show",command=labelactive).pack()
Button(root,text="Hide",command=labeldeactive).pack()
root.mainloop()
You can try this:
do {
var op = prompt("please input operatot \n you most select one of * - / * ")
} while (typeof op == "object" || op == "");
// execute block of code when click on cancle or ok whthout input
Display line numbers:
:set nu
Stop showing the line numbers:
:set nonu
Its short for :set nonumber
ps. These commands are to be run in normal mode.
In my case, the source and/or old object file(s) were locked (read-only) by a semi-crashed IDE or from a backup cloud service that stopped working properly. Restarting all programs and services that were associated with the folder structure solved the problem.
I'll just assume that gitk
is not desired for this. In that case, try git show --name-only <sha>
.
CODE SNIPPET:
extension UIView {
// OUTPUT 1
func dropShadow(scale: Bool = true) {
layer.masksToBounds = false
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 0.5
layer.shadowOffset = CGSize(width: -1, height: 1)
layer.shadowRadius = 1
layer.shadowPath = UIBezierPath(rect: bounds).cgPath
layer.shouldRasterize = true
layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}
// OUTPUT 2
func dropShadow(color: UIColor, opacity: Float = 0.5, offSet: CGSize, radius: CGFloat = 1, scale: Bool = true) {
layer.masksToBounds = false
layer.shadowColor = color.cgColor
layer.shadowOpacity = opacity
layer.shadowOffset = offSet
layer.shadowRadius = radius
layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
layer.shouldRasterize = true
layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}
}
NOTE: If you don't pass any parameter to that function, then the scale argument will be true by default. You can define a default value for any parameter in a function by assigning a value to the parameter after that parameter’s type. If a default value is defined, you can omit that parameter when calling the function.
OUTPUT 1:
shadowView.dropShadow()
OUTPUT 2:
shadowView.dropShadow(color: .red, opacity: 1, offSet: CGSize(width: -1, height: 1), radius: 3, scale: true)
layer.shouldRasterize = true
will make the shadow static and cause a shadow for the initial state of theUIView
. So I would recommend not to uselayer.shouldRasterize = true
in dynamic layouts like view inside aUITableViewCell
.
I am not sure what the last line means. Does it mean, I read the file, create multiple Movie objects. Then make a vector of pointers where each element (pointer) points to one of those Movie objects?
I would guess this is what is intended. The intent is probably that you read the data for one movie, allocate an object with new
, fill the object in with the data, and then push the address of the data onto the vector
(probably not the best design, but most likely what's intended anyway).
For a simple file search you could use grep's -l
and -r
options:
grep -rl "mystring"
All the search is done by grep. Of course, if you need to select files on some other parameter, find is the correct solution:
find . -iname "*.php" -execdir grep -l "mystring" {} +
The execdir
option builds each grep command per each directory, and concatenates filenames into only one command (+
).
I found another strange reason and i thought maybe another developer confused as me. I did run install.bat that created to install my service in developer Command Prompt of VS2010 but my service generated in VS2012. it was going to this error and drives me to crazy but i try VS2012 Developer Command Prompt tools and everything gone to be OK. I don't no why but my problem was solved. so you can test it and if anyone know reason of that please share with us. Thanks.
One workaround is just to use select without any other clauses.
SQL server determines case sensitivity by COLLATION
.
COLLATION
can be set at various levels.
One can check the COLLATION
at each level as mentioned in Raj More's answer.
Check Server Collation
SELECT SERVERPROPERTY('COLLATION')
Check Database Collation
SELECT DATABASEPROPERTYEX('AdventureWorks', 'Collation') SQLCollation;
Check Column Collation
select table_name, column_name, collation_name
from INFORMATION_SCHEMA.COLUMNS
where table_name = @table_name
Check Expression Collation
For expression level COLLATION
you need to look at the expression. :)
It would be generally at the end of the expression as in below example.
SELECT name FROM customer ORDER BY name COLLATE Latin1_General_CS_AI;
Collation Description
For getting description of each COLLATION
value try this.
SELECT * FROM fn_helpcollations()
And you should see something like this.
You can always put a WHERE
clause to filter and see description only for your COLLATION
.
You can find a list of collations here.
Run Spring Boot app using Maven
You can also use Maven plugin to run your Spring Boot app. Use the below example to run your Spring Boot app with Maven plugin:
mvn spring-boot:run
Run Spring Boot App with Gradle
And if you use Gradle you can run the Spring Boot app with the following command:
gradle bootRun
If you are still intrested in why this didn't work for you at first:
The reason you don't see changes you've made to the cell's style is because you do these changes before the form was shown, and so they are disregarded.
Changing cell styles in the events suggested here will do the job, but they are called multiple times causing your style changes to happen more times than you wish, and so aren't very efficient.
To solve this, either change the style after the point in your code in which the form is shown, or subscribe to the Shown event, and place your changes there (this is event is called significantly less than the other events suggested).
Surely you want to know about window.requestIdleCallback(), which queues a function to be called during a browser's idle periods.
You can see an elegant usage of this API in the Quicklink repo.
const requestIdleCallback = window.requestIdleCallback ||
function (cb) {
const start = Date.now();
return setTimeout(function () {
cb({
didTimeout: false,
timeRemaining: function () {
return Math.max(0, 50 - (Date.now() - start));
},
});
}, 1);
};
The meaning of the code above is: if the browser supports requestIdleCallback
(check the compatibility), uses it. If is not supported, uses a setTimeout(()=> {}, 1)
as fallback, which should queue the function to be called at the end of the event loop.
Then you can use it like this:
requestIdleCallback(() => {...}, {
timeout: 2000
});
The second parameter is optional, you might want to set a timeout
if you want to make sure the function is executed.
String u = request.getParameter("username");
String p = request.getParameter("password");
try {
st = con.createStatement();
String sql;
sql = "SELECT * FROM TableName where USERNAME = '" + u + "' and PASSWORD = '"
+ p + "'";
ResultSet rs = st.executeQuery(sql);
if (rs.next()) {
RequestDispatcher requestDispatcher = request
.getRequestDispatcher("/home.jsp");
requestDispatcher.forward(request, response);
} else {
RequestDispatcher requestDispatcher = request
.getRequestDispatcher("/invalidLogin.jsp");
requestDispatcher.forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
finally{
try {
rs.close();
ps.close();
con.close();
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public static bool Contains(this string input, string findMe, StringComparison comparisonType)
{
return String.IsNullOrWhiteSpace(input) ? false : input.IndexOf(findMe, comparisonType) > -1;
}
You should try something like this
List xx= (List) list.get(0)
String id = (String) xx.get(0)
or if you have a House value object the result of the query is of the same type, then
House myhouse = (House) list.get(0);
I know that this question has been asked for a long time but as of today one simple answer is:
<img src="image.png" style="width: 55vw; min-width: 330px;" />
The use of vw in here tells that the width is relative to 55% of the width of the viewport.
All the major browsers nowadays support this.
Check this link.
Yet another way to do this but not a very good one:
return (Boolean.valueOf(a).hashCode() + Boolean.valueOf(b).hashCode() + Boolean.valueOf(c).hashCode()) < 3705);
The Boolean
hashcode values are fixed at 1231 for true and 1237 for false so could equally have used <= 3699
Most of the answers here suggest that one should append the parameter(s) to the URL, something like the following snippet or a similar variation:
location.href = location.href + "¶meter=" + value;
This will work quite well for the majority of the cases.
However
That's not the correct way to append a parameter to a URL in my opinion.
Because the suggested approach does not test if the parameter is already set in the URL, if not careful one may end up with a very long URL with the same parameter repeated multiple times. ie:
https://stackoverflow.com/?¶m=1¶m=1¶m=1¶m=1¶m=1¶m=1¶m=1¶m=1¶m=1
at this point is where problems begin. The suggested approach could and will create a very long URL after multiple page refreshes, thus making the URL invalid. Follow this link for more information about long URL What is the maximum length of a URL in different browsers?
This is my suggested approach:
function URL_add_parameter(url, param, value){
var hash = {};
var parser = document.createElement('a');
parser.href = url;
var parameters = parser.search.split(/\?|&/);
for(var i=0; i < parameters.length; i++) {
if(!parameters[i])
continue;
var ary = parameters[i].split('=');
hash[ary[0]] = ary[1];
}
hash[param] = value;
var list = [];
Object.keys(hash).forEach(function (key) {
list.push(key + '=' + hash[key]);
});
parser.search = '?' + list.join('&');
return parser.href;
}
With this function one just will have to do the following:
location.href = URL_add_parameter(location.href, 'param', 'value');
As noted in the accepted answer - you can use the special { props.children } property. However - you can just pass a component as a prop as the title requests. I think this is cleaner sometimes as you might want to pass several components and have them render in different places. Here's the react docs with an example of how to do it:
https://reactjs.org/docs/composition-vs-inheritance.html
Make sure you are actually passing a component and not an object (this tripped me up initially).
The code is simply this:
const Parent = () => {
return (
<Child componentToPassDown={<SomeComp />} />
)
}
const Child = ({ componentToPassDown }) => {
return (
<>
{componentToPassDown}
</>
)
}
var string = string.split(",");
I experienced an issue where background images with spaces in the filename where causing the style to not be applied. To correct this I had to ensure the string path was encapsulated in single quotes.
Note the escaped \' in my example below.
<div :style="{
height: '100px',
backgroundColor: '#323232',
backgroundImage: 'url(\'' + event.image + '\')',
backgroundPosition: 'center center',
backgroundSize: 'cover'
}">
</div>
You may try it like this:
DECLARE @i int = 0
WHILE @i < 300
BEGIN
SET @i = @i + 1
/* your code*/
END
Here it is:
select player_name, player_salary, (player_salary * 1.1) as player_newsalary
from player
order by player_name, player_salary, player_newsalary desc
You don't need to "group by" if there is only one instance of a player in the table.
I had the same issue because I had 2 .git
folders in the working directory.
Your problem may be caused by the same thing, so I recommend checking to see if you have multiple .git
folders, and, if so, deleting one of them.
That allowed me to upload the project successfully.
Had the same problem, I just coerced the id into a string.
My schema:
const product = new mongooseClient.Schema({
retailerID: { type: mongoose.SchemaTypes.ObjectId, required: true, index: true }
});
And then, when inserting:
retailerID: `${retailer._id}`
You can just use:
> names(LIST)
[1] "A" "B"
Obviously the names of the first element is just
> names(LIST)[1]
[1] "A"
My way is @Html.CheckBoxFor(model => model.As, new { @value= "true" })
(meaning is checked)
In Case of Arrays you can do it like this:
In .ts
file (Parent component) where you are updating your rawLapsData
do it like this:
rawLapsData = somevalue; // change detection will not happen
Solution:
rawLapsData = {...somevalue}; //change detection will happen
and ngOnChanges
will called in child component
The correct solution is to add the timezone info e.g., to get the current time as an aware datetime object in Python 3:
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
On older Python versions, you could define the utc
tzinfo object yourself (example from datetime docs):
from datetime import tzinfo, timedelta, datetime
ZERO = timedelta(0)
class UTC(tzinfo):
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
utc = UTC()
then:
now = datetime.now(utc)
In the case where you have multiple extensions this one-liner using pathlib
and str.replace
works a treat:
>>> from pathlib import Path
>>> p = Path("/path/to/myfile.tar.gz")
>>> extensions = "".join(p.suffixes)
# any python version
>>> str(p).replace(extensions, "")
'/path/to/myfile'
# python>=3.9
>>> str(p).removesuffix(extensions)
'/path/to/myfile'
>>> p = Path("/path/to/myfile.tar.gz")
>>> extensions = "".join(p.suffixes)
>>> new_ext = ".jpg"
>>> str(p).replace(extensions, new_ext)
'/path/to/myfile.jpg'
If you also want a pathlib
object output then you can obviously wrap the line in Path()
>>> Path(str(p).replace("".join(p.suffixes), ""))
PosixPath('/path/to/myfile')
from pathlib import Path
from typing import Union
PathLike = Union[str, Path]
def replace_ext(path: PathLike, new_ext: str = "") -> Path:
extensions = "".join(Path(path).suffixes)
return Path(str(p).replace(extensions, new_ext))
p = Path("/path/to/myfile.tar.gz")
new_ext = ".jpg"
assert replace_ext(p, new_ext) == Path('/path/to/myfile.jpg')
assert replace_ext(str(p), new_ext) == Path('/path/to/myfile.jpg')
assert replace_ext(p) == Path('/path/to/myfile')
Check out James Padolsey's animateToSelector
Intro: This jQuery plugin will allow you to animate any element to styles specified in your stylesheet. All you have to do is pass a selector and the plugin will look for that selector in your StyleSheet and will then apply it as an animation.
I would have expected your syntax to work too. The problem arises because when you create new columns with the column-list syntax (df[[new1, new2]] = ...
), pandas requires that the right hand side be a DataFrame (note that it doesn't actually matter if the columns of the DataFrame have the same names as the columns you are creating).
Your syntax works fine for assigning scalar values to existing columns, and pandas is also happy to assign scalar values to a new column using the single-column syntax (df[new1] = ...
). So the solution is either to convert this into several single-column assignments, or create a suitable DataFrame for the right-hand side.
Here are several approaches that will work:
import pandas as pd
import numpy as np
df = pd.DataFrame({
'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]
})
Then one of the following:
df['column_new_1'], df['column_new_2'], df['column_new_3'] = [np.nan, 'dogs', 3]
DataFrame
conveniently expands a single row to match the index, so you can do this:df[['column_new_1', 'column_new_2', 'column_new_3']] = pd.DataFrame([[np.nan, 'dogs', 3]], index=df.index)
df = pd.concat(
[
df,
pd.DataFrame(
[[np.nan, 'dogs', 3]],
index=df.index,
columns=['column_new_1', 'column_new_2', 'column_new_3']
)
], axis=1
)
join
instead of concat
(may be less efficient):df = df.join(pd.DataFrame(
[[np.nan, 'dogs', 3]],
index=df.index,
columns=['column_new_1', 'column_new_2', 'column_new_3']
))
df = df.join(pd.DataFrame(
{
'column_new_1': np.nan,
'column_new_2': 'dogs',
'column_new_3': 3
}, index=df.index
))
.assign()
with multiple column arguments.I like this variant on @zero's answer a lot, but like the previous one, the new columns will always be sorted alphabetically, at least with early versions of Python:
df = df.assign(column_new_1=np.nan, column_new_2='dogs', column_new_3=3)
new_cols = ['column_new_1', 'column_new_2', 'column_new_3']
new_vals = [np.nan, 'dogs', 3]
df = df.reindex(columns=df.columns.tolist() + new_cols) # add empty cols
df[new_cols] = new_vals # multi-column assignment works for existing cols
df['column_new_1'] = np.nan
df['column_new_2'] = 'dogs'
df['column_new_3'] = 3
Note: many of these options have already been covered in other answers: Add multiple columns to DataFrame and set them equal to an existing column, Is it possible to add several columns at once to a pandas DataFrame?, Add multiple empty columns to pandas DataFrame
ehh, its not a bug as one person mentioned. that is the expected behavior as the number of days in a month is often different. The easiest way to get the previous month using strtotime would probably be to use -1 month from the first of this month.
$date_string = date('Y-m', strtotime('-1 month', strtotime(date('Y-m-01'))));
There's also php2xmi. You have to do a bit of manual work, but it generates all the classes, so all you have to do is to drag them into a classdiagram in Umbrello.
Otherwise, generating a diagram with the use of reflection and graphviz, is fairly simple. I have a snippet over here, that you can use as a starting point.
The results of the execution time directly contradict the results of the Query Cost, but I'm having difficulty determining what "Query Cost" actually means.
Query cost
is what optimizer thinks of how long your query will take (relative to total batch time).
The optimizer tries to choose the optimal query plan by looking at your query and statistics of your data, trying several execution plans and selecting the least costly of them.
Here you may read in more detail about how does it try to do this.
As you can see, this may differ significantly of what you actually get.
The only real query perfomance metric is, of course, how long does the query actually take.
@Mikael Svenson's answer is correct. I just wanted to add a small addition to it:
The Messagebox icon can also be included has an additional property like below:
DialogResult dialogResult = MessageBox.Show("Sure", "Please Confirm Your Action", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
I suggest this one:
if [ "$a" = "$b" ]
Notice the white space between the openning/closing brackets and the variables and also the white spaces wrapping the '=' sign.
Also, be careful of your script header. It's not the same thing whether you use
#!/bin/bash
or
#!/bin/sh
This depends on implementation, but usually on x86 and other popular architectures like ARM int
s take 4 bytes. You can always check at compile time using sizeof(int)
or whatever other type you want to check.
If you want to make sure you use a type of a specific size, use the types in <stdint.h>
null and undefined are both false for value equality (null==undefined): they both collapse to boolean false. They are not the same object (null!==undefined).
undefined is a property of the global object ("window" in browsers), but is a primitive type and not an object itself. It's the default value for uninitialized variables and functions ending without a return statement.
null is an instance of Object. null is used for DOM methods that return collection objects to indicate an empty result, which provides a false value without indicating an error.
See this article on alistapart.com. (Ed: The article has been updated since originally linked)
self
is being used to maintain a reference to the original this
even as the context is changing. It's a technique often used in event handlers (especially in closures).
Edit: Note that using self
is now discouraged as window.self
exists and has the potential to cause errors if you are not careful.
What you call the variable doesn't particularly matter. var that = this;
is fine, but there's nothing magic about the name.
Functions declared inside a context (e.g. callbacks, closures) will have access to the variables/function declared in the same scope or above.
For example, a simple event callback:
function MyConstructor(options) {_x000D_
let that = this;_x000D_
_x000D_
this.someprop = options.someprop || 'defaultprop';_x000D_
_x000D_
document.addEventListener('click', (event) => {_x000D_
alert(that.someprop);_x000D_
});_x000D_
}_x000D_
_x000D_
new MyConstructor({_x000D_
someprop: "Hello World"_x000D_
});
_x000D_
This depends on implementation, but the general rule is that the domain is checked against all SANs and the common name. If the domain is found there, then the certificate is ok for connection.
RFC 5280, section 4.1.2.6 says "The subject name MAY be carried in the subject field and/or the subjectAltName extension". This means that the domain name must be checked against both SubjectAltName extension and Subject property (namely it's common name parameter) of the certificate. These two places complement each other, and not duplicate it. And SubjectAltName is a proper place to put additional names, such as www.domain.com or www2.domain.com
Update: as per RFC 6125, published in 2011, the validator must check SAN first, and if SAN exists, then CN should not be checked. Note that RFC 6125 is relatively recent and there still exist certificates and CAs that issue certificates, which include the "main" domain name in CN and alternative domain names in SAN. I.e. by excluding CN from validation if SAN is present, you can deny some otherwise valid certificate.
How is the column defined? If its a varchar field, then its not a number (or stored as one). Oracle may be able to do the conversion for you (eg, select * from someTable where charField = 0), but it will only return rows where the conversion holds true and is possible. This is also far from ideal situation performance wise.
So, if you want to do number comparisons and treat this column as a number, perhaps it should be defined as a number?
That said, here's what you might do:
create or replace function myToNumber(i_val in varchar2) return number is
v_num number;
begin
begin
select to_number(i_val) into v_num from dual;
exception
when invalid_number then
return null;
end;
return v_num;
end;
You might also include the other parameters that the regular to_number has. Use as so:
select * from someTable where myToNumber(someCharField) > 0;
It won't return any rows that Oracle sees as an invalid number.
Cheers.
list = new List<ProcedureTime>(); sortedList = list.OrderByDescending(ProcedureTime=> ProcedureTime.EndTime).ToList();
Which works for me to show the time sorted in descending order.
A cookie key(used to identify a session) and a cookie are the same thing being used in different ways. So the limit would be the same. According to Microsoft its 4096 bytes.
cookies are usually limited to 4096 bytes and you can't store more than 20 cookies per site. By using a single cookie with subkeys, you use fewer of those 20 cookies that your site is allotted. In addition, a single cookie takes up about 50 characters for overhead (expiration information, and so on), plus the length of the value that you store in it, all of which counts toward the 4096-byte limit. If you store five subkeys instead of five separate cookies, you save the overhead of the separate cookies and can save around 200 bytes.
There is all you need:
expected bytes, not str
The leading b
makes your string binary.
What version of Python do you use? 2.x or 3.x?
Edit: See http://docs.python.org/release/3.0.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit for the gory details of strings in Python 3.x
Here is a version of James Farey's best rational approximation algorithm with adjustable level of fuzziness ported to javascript from the aspect ratio calculation code originally written in python.
The method takes a float (width/height
) and an upper limit for the fraction numerator/denominator.
In the example below I am setting an upper limit of 50
because I need 1035x582
(1.77835051546) to be treated as 16:9
(1.77777777778) rather than 345:194
which you get with the plain gcd
algorithm listed in other answers.
<html>
<body>
<script type="text/javascript">
function aspect_ratio(val, lim) {
var lower = [0, 1];
var upper = [1, 0];
while (true) {
var mediant = [lower[0] + upper[0], lower[1] + upper[1]];
if (val * mediant[1] > mediant[0]) {
if (lim < mediant[1]) {
return upper;
}
lower = mediant;
} else if (val * mediant[1] == mediant[0]) {
if (lim >= mediant[1]) {
return mediant;
}
if (lower[1] < upper[1]) {
return lower;
}
return upper;
} else {
if (lim < mediant[1]) {
return lower;
}
upper = mediant;
}
}
}
document.write (aspect_ratio(800 / 600, 50) +"<br/>");
document.write (aspect_ratio(1035 / 582, 50) + "<br/>");
document.write (aspect_ratio(2560 / 1440, 50) + "<br/>");
</script>
</body></html>
The result:
4,3 // (1.33333333333) (800 x 600)
16,9 // (1.77777777778) (2560.0 x 1440)
16,9 // (1.77835051546) (1035.0 x 582)
node-http-proxy is a great solution as was suggested by @hross above. If you're not deadset on using node, we use NGINX to do the same thing. It works really well with node. We use it for example to process SSL requests before forwarding them to node. It can also handle cacheing and forwarding routes. Yay!
Dependency walker works on normal win32 binaries. All .NET dll's and exe's have a small stub header part which makes them look like normal binaries, but all it basically says is "load the CLR" - so that's all that dependency walker will tell you.
To see which things your .NET app actually relies on, you can use the tremendously excellent .NET reflector from Red Gate. (EDIT: Note that .NET Reflector is now a paid product. ILSpy is free and open source and very similar.)
Load your DLL into it, right click, and chose 'Analyze' - you'll then see a "Depends On" item which will show you all the other dll's (and methods inside those dll's) that it needs.
It can sometimes get trickier though, in that your app depends on X dll, and X dll is present, but for whatever reason can't be loaded or located at runtime.
To troubleshoot those kinds of issues, Microsoft have an Assembly Binding Log Viewer which can show you what's going on at runtime
In Chrome 8.0.552 on a Mac, you can find this under menu View/Developer/JavaScript Console ... or you can use Alt+CMD+J.
Grep DOES NOT use "wildcards" for search – that's shell globbing, like *.jpg. Grep uses "regular expressions" for pattern matching. While in the shell '*' means "anything", in grep it means "match the previous item zero or more times".
More information and examples here: http://www.regular-expressions.info/reference.html
To answer of your question - you can find files matching some pattern with grep:
find /somedir -type f -print | grep 'LMN2011' # that will show files whose names contain LMN2011
Then you can search their content (case insensitive):
find /somedir -type f -print | grep -i 'LMN2011' | xargs grep -i 'LMN20113456'
If the paths can contain spaces, you should use the "zero end" feature:
find /somedir -type f -print0 | grep -iz 'LMN2011' | xargs -0 grep -i 'LMN20113456'
Try Microsoft's NEWT, it worked perfect for me. It supplies customized latency, packet drop techniques and more :)
http://blog.mrpol.nl/2010/01/14/network-emulator-toolkit/
Update 1:
Here is a good video tutorial for NEWT - Network Emulator For Windows Toolkit Tutorial (Credits to Jimmery)
For loading the layout in layout-land folder means you have two separate layouts then you have to make setContentView
in onConfigurationChanged
method.
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
setContentView(R.layout.yourxmlinlayout-land);
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
setContentView(R.layout.yourxmlinlayoutfolder);
}
}
If you have only one layout then no necessary to make setContentView in This method. simply
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return
statement. When the code goes down that path, the function ends with no value returned, and so returns None
.
Updated: It sounds like your code looks like this:
def b(self, p, data):
current = p
if current.data == data:
return True
elif current.data == 1:
return False
else:
self.b(current.next, data)
That else clause is your None
path. You need to return the value that the recursive call returns:
else:
return self.b(current.next, data)
BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.
This CSS effectively hides the spin-button for webkit browsers (have tested it in Chrome 7.0.517.44 and Safari Version 5.0.2 (6533.18.5)):
input::-webkit-outer-spin-button,_x000D_
input::-webkit-inner-spin-button {_x000D_
/* display: none; <- Crashes Chrome on hover */_x000D_
-webkit-appearance: none;_x000D_
margin: 0; /* <-- Apparently some margin are still there even though it's hidden */_x000D_
}_x000D_
_x000D_
input[type=number] {_x000D_
-moz-appearance:textfield; /* Firefox */_x000D_
}
_x000D_
<input type="number" step="0.01" />
_x000D_
You can always use the inspector (webkit, possibly Firebug for Firefox) to look for matched CSS properties for the elements you are interested in, look for Pseudo elements. This image shows results for an input element type="number":
Google's libs-for-android has a nice libraries for managing image and file cache.
Databases are heavily optimized for common usage scenarios (and LIKE is one of those).
You won't find a faster way of doing your search if you want to stay on the DB-level.
You might consider storing the time as a DateTime, and in UTC. I typically use DateTime instead of Timestamp because of the fact that MySql converts dates to UTC and back to local time when storing and retrieving the data. I'd rather keep any of that kind of logic in one place (Business layer). I'm sure there are other situations where using Timestamp is preferable though.
The Swift equivalent to what you're describing is string interpolation. If you're thinking about things like JavaScript doing "x" + array
, the equivalent in Swift is "x\(array)"
.
As a general note, there is an important difference between string interpolation vs the Printable
protocol. Only certain classes conform to Printable
. Every class can be string interpolated somehow. That's helpful when writing generic functions. You don't have to limit yourself to Printable
classes.
$_
last argument of last command$#
number of arguments passed to current script$*
/ $@
list of arguments passed to script as string / delimited listoff the top of my head. Google for bash special variables.
Where do you get the list of ids from in the first place? Since they are IDs in your database, did they come from some previous query?
When I have seen this in the past it has been because:-
I think there may be better ways to rework this code that just getting this SQL statement to work. If you provide more details you might get some ideas.
For What its worth, this is what I did and maybe it can help others even though the article is old.
PHP:
session_start();
$_SESSION['ipaddress'] = $_SERVER['REMOTE_ADDR'];
if(isset($_SESSION['userID'])){
if(!strpos($_SESSION['activeID'], '-')){
$_SESSION['activeID'] = $_SESSION['userID'].'-'.$_SESSION['activeID'];
}
}elseif(!isset($_SESSION['activeID'])){
$_SESSION['activeID'] = time();
}
JS
window.setInterval(function(){
var userid = '<?php echo $_SESSION['activeID']; ?>';
var ipaddress = '<?php echo $_SESSION['ipaddress']; ?>';
var action = 'data';
$.ajax({
url:'activeUser.php',
method:'POST',
data:{action:action,userid:userid,ipaddress:ipaddress},
success:function(response){
//alert(response);
}
});
}, 5000);
Ajax call to activeUser.php
if(isset($_POST['action'])){
if(isset($_POST['userid'])){
$stamp = time();
$activeid = $_POST['userid'];
$ip = $_POST['ipaddress'];
$query = "SELECT stamp FROM activeusers WHERE activeid = '".$activeid."' LIMIT 1";
$results = RUNSIMPLEDB($query);
if($results->num_rows > 0){
$query = "UPDATE activeusers SET stamp = '$stamp' WHERE activeid = '".$activeid."' AND ip = '$ip' LIMIT 1";
RUNSIMPLEDB($query);
}else{
$query = "INSERT INTO activeusers (activeid,stamp,ip)
VALUES ('".$activeid."','$stamp','$ip')";
RUNSIMPLEDB($query);
}
}
}
Database:
CREATE TABLE `activeusers` (
`id` int(11) NOT NULL,
`activeid` varchar(20) NOT NULL,
`stamp` int(11) NOT NULL,
`ip` text
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Basically every 5 seconds the js will post to a php file that will track the user and the users ip address. Active users are simply a database record that have an update to the database time stamp within 5 seconds. Old users stop updating to the database. The ip address is used just to ensure that a user is unique so 2 people on the site at the same time don't register as 1 user.
Probably not the most efficient solution but it does the job.
Just another way not mentioned yet:
If you installed it locally to a project then open up the node_modules folder and check your webpack module.
$cd /node_modules/webpack/package.json
Open the package.json file and look under version
An asynchronously loaded script is likely going to run AFTER the document has been fully parsed and closed. Thus, you can't use document.write()
from such a script (well technically you can, but it won't do what you want).
You will need to replace any document.write()
statements in that script with explicit DOM manipulations by creating the DOM elements and then inserting them into a particular parent with .appendChild()
or .insertBefore()
or setting .innerHTML
or some mechanism for direct DOM manipulation like that.
For example, instead of this type of code in an inline script:
<div id="container">
<script>
document.write('<span style="color:red;">Hello</span>');
</script>
</div>
You would use this to replace the inline script above in a dynamically loaded script:
var container = document.getElementById("container");
var content = document.createElement("span");
content.style.color = "red";
content.innerHTML = "Hello";
container.appendChild(content);
Or, if there was no other content in the container that you needed to just append to, you could simply do this:
var container = document.getElementById("container");
container.innerHTML = '<span style="color:red;">Hello</span>';
Use the timeIntervalSinceDate
method
NSTimeInterval secondsElapsed = [secondDate timeIntervalSinceDate:firstDate];
NSTimeInterval
is just a double
, define in NSDate
like this:
typedef double NSTimeInterval;
I would imagine you could accomplish placing the mouse cursor to a given area of the screen if you didn't use the real (system) mouse cursor.
For instance, you could create an image to act in place of your cursor, handle an event which upon detecting mouseenter into your scene, set the style on the system cursor to 'none' (sceneElement.style.cursor = 'none'
), then would bring up a hidden image element acting as a cursor to be anywhere you like with in the scene based on a predefined axis/bounding box translation.
This way no matter how you moved the real cursor your translation method would keep your image cursor wherever you needed it.
edit: an example in jsFiddle using an image representation and forced mouse movement
This should get you started: Using VBA in your own Excel workbook, have it prompt the user for the filename of their data file, then just copy that fixed range into your target workbook (that could be either the same workbook as your macro enabled one, or a third workbook). Here's a quick vba example of how that works:
' Get customer workbook...
Dim customerBook As Workbook
Dim filter As String
Dim caption As String
Dim customerFilename As String
Dim customerWorkbook As Workbook
Dim targetWorkbook As Workbook
' make weak assumption that active workbook is the target
Set targetWorkbook = Application.ActiveWorkbook
' get the customer workbook
filter = "Text files (*.xlsx),*.xlsx"
caption = "Please Select an input file "
customerFilename = Application.GetOpenFilename(filter, , caption)
Set customerWorkbook = Application.Workbooks.Open(customerFilename)
' assume range is A1 - C10 in sheet1
' copy data from customer to target workbook
Dim targetSheet As Worksheet
Set targetSheet = targetWorkbook.Worksheets(1)
Dim sourceSheet As Worksheet
Set sourceSheet = customerWorkbook.Worksheets(1)
targetSheet.Range("A1", "C10").Value = sourceSheet.Range("A1", "C10").Value
' Close customer workbook
customerWorkbook.Close
Depending on the number of headers and your development habits, you may want to investigate gccmakedep. This program examines your current directory and adds to the end of the makefile the header dependencies for each .c/cpp file. This is overkill when you have 2 headers and one program file. However, if you have 5+ little test programs and you are editing one of 10 headers, you can then trust make to rebuild exactly those programs which were changed by your modifications.
It prevents the browser from doing MIME-type sniffing. Most browsers are now respecting this header, including Chrome/Chromium, Edge, IE >= 8.0, Firefox >= 50 and Opera >= 13. See :
Sending the new X-Content-Type-Options response header with the value nosniff will prevent Internet Explorer from MIME-sniffing a response away from the declared content-type.
EDIT:
Oh and, that's an HTTP header, not a HTML meta tag option.
See also : http://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx
why do I have to pass seconds = uptime to timedelta
Because timedelta objects can be passed seconds, milliseconds, days, etc... so you need to specify what are you passing in (this is why you use the explicit key). Typecasting to int
is superfluous as they could also accept floats.
and why does the string casting works so nicely that I get HH:MM:SS ?
It's not the typecasting that formats, is the internal __str__
method of the object. In fact you will achieve the same result if you write:
print datetime.timedelta(seconds=int(uptime))
You cannot change a table while the INSERT trigger is firing. The INSERT might do some locking which could result in a deadlock. Also, updating the table from a trigger would then cause the same trigger to fire again in an infinite recursive loop. Both of these reasons are why MySQL prevents you from doing this.
However, depending on what you're trying to achieve, you can access the new values by using NEW.fieldname or even the old values--if doing an UPDATE--with OLD.
If you had a row named full_brand_name
and you wanted to use the first two letters as a short name in the field small_name
you could use:
CREATE TRIGGER `capital` BEFORE INSERT ON `brandnames`
FOR EACH ROW BEGIN
SET NEW.short_name = CONCAT(UCASE(LEFT(NEW.full_name,1)) , LCASE(SUBSTRING(NEW.full_name,2)))
END
Try this EDITED:
(SELECT COUNT(motorbike.owner_id),owner.name,transport.type FROM transport,owner,motorbike WHERE transport.type='motobike' AND owner.owner_id=motorbike.owner_id AND transport.type_id=motorbike.motorbike_id GROUP BY motorbike.owner_id)
UNION ALL
(SELECT COUNT(car.owner_id),owner.name,transport.type FROM transport,owner,car WHERE transport.type='car' AND owner.owner_id=car.owner_id AND transport.type_id=car.car_id GROUP BY car.owner_id)
That message isn't actually an error - it's just a warning that the file in question isn't of the right architecture (e.g. 32-bit vs 64-bit, wrong CPU architecture). The linker will keep looking for a library of the right type.
Of course, if you're also getting an error along the lines of can't find lPI-Http
then you have a problem :-)
It's hard to suggest what the exact remedy will be without knowing the details of your build system and makefiles, but here are a couple of shots in the dark:
CFLAGS
rather than
CTAGS
- are you sure this is
correct? (What you have may be correct - this will depend on your build system!)LDFLAGS
If that doesn't help - can you post the full error output, plus the actual command (e.g. gcc foo.c -m32 -Dxxx
etc) that was being executed?
try with sticky jquery plugin
https://github.com/garand/sticky
<script src="jquery.js"></script>_x000D_
<script src="jquery.sticky.js"></script>_x000D_
<script>_x000D_
$(document).ready(function(){_x000D_
$("#sticker").sticky({topSpacing:0});_x000D_
});_x000D_
</script>
_x000D_
By chance, is this occurring on a directory using OverlayFS (or some other special file system type)?
I just had this issue where my cross-compiled version of bash would use an internal implementation of getcwd
which has issues with OverlayFS. I found information about this here:
It seems that this can be traced to an internal implementation of getcwd() in bash. When cross-compiled, it can't check for getcwd() use of malloc, so it is cautious and sets GETCWD_BROKEN and uses an internal implementation of getcwd(). This internal implementation doesn't seem to work well with OverlayFS.
http://permalink.gmane.org/gmane.linux.embedded.yocto.general/25204
You can configure and rebuild bash with bash_cv_getcwd_malloc=yes
(if you're actually building bash and your C library does malloc a getcwd call).
Simply put, you can do the following:-
if (android.os.Build.VERSION.SDK_INT >= 21) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
In this instance, your div
elements have been changed from block
level elements to inline
elements. A typical characteristic of inline
elements is that they respect the whitespace in the markup. This explains why a gap of space is generated between the elements. (example)
There are a few solutions that can be used to solve this.
Example 1 - Comment the whitespace out: (example)
<div>text</div><!--
--><div>text</div><!--
--><div>text</div><!--
--><div>text</div><!--
--><div>text</div>
Example 2 - Remove the line breaks: (example)
<div>text</div><div>text</div><div>text</div><div>text</div><div>text</div>
Example 3 - Close part of the tag on the next line (example)
<div>text</div
><div>text</div
><div>text</div
><div>text</div
><div>text</div>
Example 4 - Close the entire tag on the next line: (example)
<div>text
</div><div>text
</div><div>text
</div><div>text
</div><div>text
</div>
font-size
Since the whitespace between the inline
elements is determined by the font-size
, you could simply reset the font-size
to 0
, and thus remove the space between the elements.
Just set font-size: 0
on the parent elements, and then declare a new font-size
for the children elements. This works, as demonstrated here (example)
#parent {
font-size: 0;
}
#child {
font-size: 16px;
}
This method works pretty well, as it doesn't require a change in the markup; however, it doesn't work if the child element's font-size
is declared using em
units. I would therefore recommend removing the whitespace from the markup, or alternatively floating the elements and thus avoiding the space generated by inline
elements.
display: flex
In some cases, you can also set the display
of the parent element to flex
. (example)
This effectively removes the spaces between the elements in supported browsers. Don't forget to add appropriate vendor prefixes for additional support.
.parent {
display: flex;
}
.parent > div {
display: inline-block;
padding: 1em;
border: 2px solid #f00;
}
.parent {_x000D_
display: flex;_x000D_
}_x000D_
.parent > div {_x000D_
display: inline-block;_x000D_
padding: 1em;_x000D_
border: 2px solid #f00;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div>text</div>_x000D_
<div>text</div>_x000D_
<div>text</div>_x000D_
<div>text</div>_x000D_
<div>text</div>_x000D_
</div>
_x000D_
It is incredibly unreliable to use negative margins to remove the space between inline
elements. Please don't use negative margins if there are other, more optimal, solutions.
On a related note: the java compiler uses int to represent boolean since JVM has a limited support for the boolean type.See Section 3.3.4 The boolean type.
In JVM, the integer zero represents false, and any non-zero integer represents true (Source : Inside Java Virtual Machine by Bill Venners)
Some times you need to add other <proxy></proxy>
tags, and specify the https in the protocol tags: <protocol>https</protocol>
Eg: n sub-category level for categories .Below table primary-key id is referred by foreign-key sub_category_id
Download the source package, open Terminal.app, navigate to the directory where you currently have the file, and then execute:
R CMD INSTALL RJSONIO_0.2-3.tar.gz
Do note that this will only succeed when either: a) the package does not need compilation or b) the needed system tools for compilation are present. See: https://cran.r-project.org/bin/macosx/tools/
The preceding answers that I tried do not allow for automatic expansion (autocompletion) of subdirectories of the aliased directory.
However, if you push the directory that you want to alias onto the dirs
stack...
$ pushd ~/my/aliased/dir
...you can then type dirs -v
to see its numeric position in the stack:
0 ~/my/aliased/dir
1 ~/Downloads
2 /media/usbdrive
and refer to it using that number for most if not all commands that expect a directory parameter:
$ mv foo.txt ~0
You can even use Tab to show the immediate subdirectories of the "aliased" directory:
$ cd ~0/<Tab>
child_dir1 child_dir2
I just wanted to add an additional option: In your input add the form tag and specify the name of a form that doesn't exist on your page:
<input form="fakeForm" type="text" readonly value="random value" />
ES2015 onwards:
From ES6/ES2015, we have default parameters in the language specification. So we can just do something simple like,
function A(a, b = 4, c = 5) {
}
or combined with ES2015 destructuring,
function B({c} = {c: 2}, [d, e] = [3, 4]) {
}
For detailed explanation,
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/default_parameters
Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.
Pre ES2015:
If you're going to handle values which are NOT Numbers, Strings, Boolean, NaN
, or null
you can simply use
(So, for Objects, Arrays and Functions that you plan never to send null
, you can use)
param || DEFAULT_VALUE
for example,
function X(a) {
a = a || function() {};
}
Though this looks simple and kinda works, this is restrictive and can be an anti-pattern because ||
operates on all falsy values (""
, null
, NaN
, false
, 0
) too - which makes this method impossible to assign a param the falsy value passed as the argument.
So, in order to handle only undefined
values explicitly, the preferred approach would be,
function C(a, b) {
a = typeof a === 'undefined' ? DEFAULT_VALUE_A : a;
b = typeof b === 'undefined' ? DEFAULT_VALUE_B : b;
}
to_char
actually lets you pull out the Year and month in one fell swoop!
select to_char(date('2014-05-10'),'Mon-YY') as year_month; --'May-14'
select to_char(date('2014-05-10'),'YYYY-MM') as year_month; --'2014-05'
or in the case of the user's example above:
select to_char(date,'YY-Mon') as year_month
sum("Sales") as "Sales"
from some_table
group by 1;
Also note that redirect:
and forward:
prefixes are handled by UrlBasedViewResolver
, so you need to have at least one subclass of UrlBasedViewResolver
among your view resolvers, such as InternalResourceViewResolver
.
First off: a List
is a Collection
. It is a specialized Collection
, however.
A Collection
is just that: a collection of items. You can add stuff, remove stuff, iterate over stuff and query how much stuff is in there.
A List
adds the information about a defined sequence of stuff to it: You can get the element at position n, you can add an element at position n, you can remove the element at position n.
In a Collection
you can't do that: "the 5th element in this collection" isn't defined, because there is no defined order.
There are other specialized Collections as well, for example a Set
which adds the feature that it will never contain the same element twice.
Do you have ROWS of data (horizontal) as you stated or COLUMNS (vertical)?
If it's the latter you can use "Text to columns" functionality to convert a whole column "in situ" - to do that:
Select column > Data > Text to columns > Next > Next > Choose "Date" under "column data format" and "YMD" from dropdown > Finish
....otherwise you can convert with a formula by using
=TEXT(A1,"0000-00-00")+0
and format in required date format
You need to include inttypes.h
if you want all those nifty new format specifiers for the intN_t
types and their brethren, and that is the correct (ie, portable) way to do it, provided your compiler complies with C99. You shouldn't use the standard ones like %d
or %u
in case the sizes are different to what you think.
It includes stdint.h
and extends it with quite a few other things, such as the macros that can be used for the printf/scanf
family of calls. This is covered in section 7.8 of the ISO C99 standard.
For example, the following program:
#include <stdio.h>
#include <inttypes.h>
int main (void) {
uint32_t a=1234;
uint16_t b=5678;
printf("%" PRIu32 "\n",a);
printf("%" PRIu16 "\n",b);
return 0;
}
outputs:
1234
5678
You can also put the exclamation mark inside the brackets:
if [[ ! $PATH =~ $temp ]]
but you should anchor your pattern to reduce false positives:
temp=/mnt/silo/bin
pattern="(^|:)${temp}(:|$)"
if [[ ! "${PATH}" =~ ${pattern} ]]
which looks for a match at the beginning or end with a colon before or after it (or both). I recommend using lowercase or mixed case variable names as a habit to reduce the chance of name collisions with shell variables.
int[] arr = { 1, 2, 3, 4, 5 };
List<Integer> list = Arrays.stream(arr) // IntStream
.boxed() // Stream<Integer>
.collect(Collectors.toList());
see this
If you have an interface in your controller
public myController(IXInterface Xinstance){}
You must register them to Dependency Injection container.
container.Bind<IXInterface>().To<XClass>().InRequestScope();
We can easily do that in css3. We have to simply use @import statement. The following video easily describes the way how to do that. so go ahead and watch it out.
I've tried all the solutions from the answers but couldn't get mysql
command to work from the terminal, always getting the message
bash: command not found
The solution is to change the .bash_profile, and add the mysql path to .bash_profile
To do so follow these steps: 1. Open a new Terminal window or make sure you are in the home directory 2. Open .bash_profile using
nano .bash_profile
3. Add the following command to add the mysql path
PATH="/usr/local/mysql/bin:${PATH}"
export PATH
4. Press Ctrl+X, then press y and press enter.
Try this example.
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<GridView
android:numColumns="auto_fit"
android:gravity="center"
android:columnWidth="100dp"
android:stretchMode="columnWidth"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/grid"
android:background="#fff7ff"
/>
</LinearLayout>
grid_single.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp" >
<ImageView
android:id="@+id/grid_image"
android:layout_width="60dp"
android:layout_height="60dp"
>
</ImageView>
<TextView
android:id="@+id/grid_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:textSize="9sp"
android:textColor="#3a0fff">
</TextView>
</LinearLayout>
CustomGrid.java:
package com.example.lalit.gridtest;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomGrid extends BaseAdapter {
private Context mContext;
private final String[] web;
private final int[] Imageid;
public CustomGrid(Context c, String[] web, int[] Imageid) {
mContext = c;
this.Imageid = Imageid;
this.web = web;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return web.length;
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View grid;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
grid = new View(mContext);
grid = inflater.inflate(R.layout.grid_single, null);
TextView textView = (TextView) grid.findViewById(R.id.grid_text);
ImageView imageView = (ImageView) grid.findViewById(R.id.grid_image);
textView.setText(web[position]);
imageView.setImageResource(Imageid[position]);
} else {
grid = (View) convertView;
}
return grid;
}
}
MainActivity.java:
package com.example.lalit.gridtest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
GridView grid;
String[] web = {
"Mom",
"Mahendra",
"Narayan",
"Bhai",
"Deepak",
"Sanjay",
"Navdeep",
"Lovesh",
};
int[] imageId = {
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final CustomGrid adapter = new CustomGrid(MainActivity.this, web, imageId);
grid = (GridView) findViewById(R.id.grid);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id){
if (web[position].toString().equals("Mom")) {
try {
String uri ="te:"+ "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if (web[position].toString().equals("Mahendra")) {
try {
String uri = "tel:" + "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Narayan")){
try {
String uri = "tel:" + "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Bhai")){
try {
String uri = "tel:" + "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Deepak")){
try {
String uri = "tel:" + "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Sanjay")){
try {
String uri = "tel:" + "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Navdeep")){
try {
String uri = "tel:" + "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
if(web[position].toString().equals("Lovesh")){
try {
String uri = "tel:" + "**********";
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
startActivity(callIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Your call has failed...",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
});
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lalit.gridtest" >
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
When a VS2013 C++ project is opened in VS2015, and there are warnings about "The build tools for v120... cannot be found", I simply need to edit the .vcxproj file and change <PlatformToolset>v120</PlatformToolset>
to <PlatformToolset>v140</PlatformToolset>
, and close and re-open the solution.
Define extension: String+Extension.ts
interface String {
toBoolean(): boolean
}
String.prototype.toBoolean = function (): boolean {
switch (this) {
case 'true':
case '1':
case 'on':
case 'yes':
return true
default:
return false
}
}
And import in any file where you want to use it '@/path/to/String+Extension'
After one whole day research of the round corner view with shadow, I'm glad to post my custom uiview class here, hope to end this question:
#import <UIKit/UIKit.h>
@interface RoundCornerShadowView : UIView
@end
#import "RoundCornerShadowView.h"
@implementation RoundCornerShadowView
// *** must override this method, not the other method ***
// otherwise, the background corner doesn't disappear....
// @2015/05/29
-(void) layoutSubviews {
[super layoutSubviews];//is must to ensure rightly layout children view
//1. first, create Inner layer with content
CALayer *innerView = [CALayer layer];
innerView.frame = CGRectMake(0,0,self.bounds.size.width,self.bounds.size.height);
//instead of: innerView.frame = self.frame;
innerView.borderWidth = 1.0f;
innerView.cornerRadius = 6.0f;
innerView.masksToBounds = YES;
innerView.borderColor = [[UIColor lightGrayColor] CGColor];
innerView.backgroundColor = [[UIColor whiteColor] CGColor];
//put the layer to the BOTTOM of layers is also a MUST step...
//otherwise this layer will overlay the sub uiviews in current uiview...
[self.layer insertSublayer:innerView atIndex:0];
//2. then, create shadow with self layer
self.layer.masksToBounds = NO;
self.layer.shadowColor = [[UIColor darkGrayColor] CGColor];
self.layer.shadowOpacity = 0.4f;
//shadow length
self.layer.shadowRadius = 2.0f;
//no offset
self.layer.shadowOffset = CGSizeMake(0, 0);
//right down shadow
//[self.layer setShadowOffset: CGSizeMake(1.0f, 1.0f)];
//3. last but important, MUST clear current view background color, or the color will show in the corner!
self.backgroundColor = [UIColor clearColor];
}
@end
so, NO need to add subview in view or below in target view, just add one layer in current view, and do 3 step to complete it!
take a close look at to the comments in the code, it's helpful to understanding the component!
You can input the following command on Linux:
find ./ -name "*." | xargs svn add
Equals comparison:
((f1 IS NULL AND f2 IS NULL) OR (f1 IS NOT NULL AND f2 IS NOT NULL AND f1 = f2))
Not Equal To comparison: Just negate the Equals comparison above.
NOT ((f1 IS NULL AND f2 IS NULL) OR (f1 IS NOT NULL AND f2 IS NOT NULL AND f1 = f2))
Is it verbose? Yes, it is. However it's efficient since it doesn't call any function. The idea is to use short circuit in predicates to make sure the equal operator (=) is used only with non-null values, otherwise null would propagate up in the expression tree.
Here's an example using hooks (requires React >= 16.8.0)
// import React, { useState } from 'react';_x000D_
const { useState } = React;_x000D_
_x000D_
function App() {_x000D_
const [checked, setChecked] = useState(false);_x000D_
const toggleChecked = () => setChecked(value => !value);_x000D_
return (_x000D_
<input_x000D_
type="checkbox"_x000D_
checked={checked}_x000D_
onChange={toggleChecked}_x000D_
/>_x000D_
);_x000D_
}_x000D_
_x000D_
const rootElement = document.getElementById("root");_x000D_
ReactDOM.render(<App />, rootElement);
_x000D_
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>_x000D_
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>_x000D_
_x000D_
<div id="root"><div>
_x000D_
Use this
if let navVCsCount = navigationController?.viewControllers.count {
navigationController?.viewControllers.removeSubrange(Range(2..<navVCsCount - 1))
}
It will take care of ViewControllers of navigationController. viewControllers and also a navigationItems stacked in navigationBar.
Note: Be sure to call it at least after viewDidAppear
beginupd.getTime()
will give you time in milliseconds since January 1, 1970, 00:00:00 GMT till the time you have specified in Date
object
This was incredibly handy to me. I would like to suggest another workaround to perfectly highlight the rounded corners if you are using your own CustomAdapter
.
First of all, go inside your drawable folder and create 4 different shapes:
shape_top
<gradient
android:startColor="#ffffff"
android:endColor="#ffffff"
android:angle="270"/>
<corners
android:topLeftRadius="10dp"
android:topRightRadius="10dp"/>
shape_normal
<gradient
android:startColor="#ffffff"
android:endColor="#ffffff"
android:angle="270"/>
<corners
android:topLeftRadius="10dp"
android:topRightRadius="10dp"/>
shape_bottom
<gradient
android:startColor="#ffffff"
android:endColor="#ffffff"
android:angle="270"/>
<corners
android:bottomRightRadius="10dp"
android:bottomRightRadius="10dp"/>
shape_rounded
<gradient
android:startColor="#ffffff"
android:endColor="#ffffff"
android:angle="270"/>
<corners
android:topLeftRadius="10dp"
android:topRightRadius="10dp"
android:bottomRightRadius="10dp"
android:bottomRightRadius="10dp"/>
Now, create a different row layout for each shape, i.e. for shape_top
:
You can also do this programatically changing the background.
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="20dp"
android:layout_marginRight="10dp"
android:fontFamily="sans-serif-light"
android:text="TextView"
android:textSize="22dp" />
<TextView
android:id="@+id/txtValue1"
android:layout_width="match_parent"
android:layout_height="48dp"
android:textSize="22dp"
android:layout_gravity="right|center"
android:gravity="center|right"
android:layout_marginLeft="20dp"
android:layout_marginRight="35dp"
android:text="Fix"
android:scaleType="fitEnd" />
And define a selector for each shaped-list, i.e. for shape_top
:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Selected Item -->
<item android:state_selected="true"
android:drawable="@drawable/shape_top" />
<item android:state_activated="true"
android:drawable="@drawable/shape_top" />
<!-- Default Item -->
<item android:state_selected="false"
android:drawable="@android:color/transparent" />
</selector>
Finally, define the layout options inside your CustomAdapter
:
if(position==0)
{
convertView = mInflater.inflate(R.layout.list_layout_top, null);
}
else
{
convertView = mInflater.inflate(R.layout.list_layout_normal, null);
}
if(position==getCount()-1)
{
convertView = mInflater.inflate(R.layout.list_layout_bottom, null);
}
if(getCount()==1)
{
convertView = mInflater.inflate(R.layout.list_layout_unique, null);
}
And that's done!
findById
is a convenience method on the model that's provided by Mongoose to find a document by its _id. The documentation for it can be found here.
Example:
// Search by ObjectId
var id = "56e6dd2eb4494ed008d595bd";
UserModel.findById(id, function (err, user) { ... } );
Functionally, it's the same as calling:
UserModel.findOne({_id: id}, function (err, user) { ... });
Note that Mongoose will cast the provided id
value to the type of _id
as defined in the schema (defaulting to ObjectId).
I think you are looking for:
window.location = 'http://someUrl.com';
It's not jQuery; it's pure JavaScript.
#include <unistd.h>
#include <stdio.h>
#include <iconv.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int opt = -1, min_len = 0, max_len = 0;
char ofile[256], fchar[2], tchar[2];
ofile[0] = 0;
fchar[0] = 0;
tchar[0] = 0;
while((opt = getopt(argc, argv, "o:f:t:l:L:")) != -1)
{
switch(opt)
{
case 'o':
strncpy(ofile, optarg, 255);
break;
case 'f':
strncpy(fchar, optarg, 1);
break;
case 't':
strncpy(tchar, optarg, 1);
break;
case 'l':
min_len = atoi(optarg);
break;
case 'L':
max_len = atoi(optarg);
break;
default:
printf("usage: %s -oftlL\n\t-o output file\n\t-f from char\n\t-t to char\n\t-l min seq len\n\t-L max seq len", argv[0]);
}
}
if(max_len < 1)
{
printf("error, length must be more than 0\n");
return 1;
}
if(min_len > max_len)
{
printf("error, max length must be greater or equal min_length\n");
return 1;
}
if((int)fchar[0] > (int)tchar[0])
{
printf("error, invalid range specified\n");
return 1;
}
FILE *out = fopen(ofile, "w");
if(!out)
{
printf("failed to open input file with error: %s\n", strerror(errno));
return 1;
}
int cur_len = min_len;
while(cur_len <= max_len)
{
char buf[cur_len];
for(int i = 0; i < cur_len; i++)
buf[i] = fchar[0];
fwrite(buf, cur_len, 1, out);
fwrite("\n", 1, 1, out);
while(buf[0] != (tchar[0]+1))
{
while(buf[cur_len-1] < tchar[0])
{
(int)buf[cur_len-1]++;
fwrite(buf, cur_len, 1, out);
fwrite("\n", 1, 1, out);
}
if(cur_len < 2)
break;
if(buf[0] == tchar[0])
{
bool stop = true;
for(int i = 1; i < cur_len; i++)
{
if(buf[i] != tchar[0])
{
stop = false;
break;
}
}
if(stop)
break;
}
int u = cur_len-2;
for(; u>=0 && buf[u] >= tchar[0]; u--)
;
(int)buf[u]++;
for(int i = u+1; i < cur_len; i++)
buf[i] = fchar[0];
fwrite(buf, cur_len, 1, out);
fwrite("\n", 1, 1, out);
}
cur_len++;
}
fclose(out);
return 0;
}
here my implementation in c++, it write all combinations to specified files, but behaviour can be changed, i made in to generate various dictionaries, it accept min and max length and character range, currently only ansi supported, it enough for my needs
You could probably use an inheritance structure although the more I played with this the dirtier I felt.
class AnimalEnum:
@classmethod
def verify(cls, other):
return issubclass(other.__class__, cls)
class Dog(AnimalEnum):
pass
def do_something(thing_that_should_be_an_enum):
if not AnimalEnum.verify(thing_that_should_be_an_enum):
raise OhGodWhy
DELIMiTER $$
create procedure GetUserRolesEnabled(in UserId int)
Begin
select * from users
where id=UserId ;
END $$
DELIMITER ;
Assuming that your objects are all of a similar type you could add a method as a category of their base class that calls the function you're using for your criteria. Then create an NSPredicate object that refers to that method.
In some category define your method that uses your function
@implementation BaseClass (SomeCategory)
- (BOOL)myMethod {
return someComparisonFunction(self, whatever);
}
@end
Then wherever you'll be filtering:
- (NSArray *)myFilteredObjects {
NSPredicate *pred = [NSPredicate predicateWithFormat:@"myMethod = TRUE"];
return [myArray filteredArrayUsingPredicate:pred];
}
Of course, if your function only compares against properties reachable from within your class it may just be easier to convert the function's conditions to a predicate string.
The easiest thing to do is 0- the value
for instance if int i = 5;
0-i would give you -5
and if i was -6;
0- i would give you 6
"A call stack is composed of stack frames..." — Wikipedia
A stack frame is a thing that you put on the stack. They are data structures that contain information about subroutines to call.
something
{
something1
something2
}
something3
In Python
Something
something1
something2
something3
You can use jQuery's .eq()
method to get the element with a certain index.
$('ul li').eq(index).css({'background-color':'#343434'});
For Spring-boot 1.3.3 the method exchange() for List is working as in the related answer
Noting down my situation here may be useful to somebody,
I have to send a custom intent with multiple intent extras to a broadcast receiver in Android P,
The details are,
Receiver name: com.hardian.testservice.TestBroadcastReceiver
Intent action = "com.hardian.testservice.ADD_DATA"
intent extras are,
Run the following in command line.
adb shell "am broadcast -a com.hardian.testservice.ADD_DATA --es text 'test msg' --es source 1 -n com.hardian.testservice/.TestBroadcastReceiver"
Hope this helps.
Try:
alter table <your table> modify <column name> null;
var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];
$.each(arrofobject, function(index, val) {
console.log(val.category);
});
Check if you are using any sort of jquery/javascript validation on the page and try disabling it and see what happens. You can use your browser's developer tools to see if any javascript file with validate or validation is being loaded. You can also look for hidden form elements (ie. style set to display:none; or something like that) and make sure there isn't a hidden validation error on those that's not being rendered.
Your problem is you have the b
in the open
flag.
The flag rt
(read, text) is the default, so, using the context manager, simply do this:
with open('sample.csv') as ifile:
read = csv.reader(ifile)
for row in read:
print (row)
The context manager means you don't need generic error handling (without which you may get stuck with the file open, especially in an interpreter), because it will automatically close the file on an error, or on exiting the context.
The above is the same as:
with open('sample.csv', 'r') as ifile:
...
or
with open('sample.csv', 'rt') as ifile:
...
You get an extension ID when you upload your extension to Google Web Store. Ie. Adblock has URL https://chrome.google.com/webstore/detail/cfhdojbkjhnklbpkdaibdccddilifddb
and the last part of this URL is its extension ID cfhdojbkjhnklbpkdaibdccddilifddb
.
If you wish to read installed extension IDs from your extension, check out the managment module. chrome.management.getAll
allows to fetch information about all installed extensions.
android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
Because Submit
button is inside login_modal
so you need to use loginDialog
view to access button:
Submit = (Button)loginDialog.findViewById(R.id.Submit);
Josh's comments are spot on. If you are not super familiar with critical values I'd suggest playing with qt, reading the manual (?qt
) in conjunction with looking at a look up table (LINK). When I first moved from SPSS to R I created a function that made critical t value look up pretty easy (I'd never use this now as it takes too much time and with the p values that are generally provided in the output it's a moot point). Here's the code for that:
critical.t <- function(){
cat("\n","\bEnter Alpha Level","\n")
alpha<-scan(n=1,what = double(0),quiet=T)
cat("\n","\b1 Tailed or 2 Tailed:\nEnter either 1 or 2","\n")
tt <- scan(n=1,what = double(0),quiet=T)
cat("\n","\bEnter Number of Observations","\n")
n <- scan(n=1,what = double(0),quiet=T)
cat("\n\nCritical Value =",qt(1-(alpha/tt), n-2), "\n")
}
critical.t()
Try this code:--
UIImageView *imv = [[UIImageView alloc]initWithFrame:CGRectMake(3,2, 20, 25)];
imv.image=[UIImage imageNamed:@"arrow2.png"];
[cell addSubview:imv];
[imv release];
To had to distinct by two fields (derivative_id & vehicle_type) and to sort by cheapest car. Had to nest aggs.
GET /cars/_search
{
"size": 0,
"aggs": {
"distinct_by_derivative_id": {
"terms": {
"field": "derivative_id"
},
"aggs": {
"vehicle_type": {
"terms": {
"field": "vehicle_type"
},
"aggs": {
"cheapest_vehicle": {
"top_hits": {
"sort": [
{ "rental": { "order": "asc" } }
],
"_source": { "includes": [ "manufacturer_name",
"rental",
"vehicle_type"
]
},
"size": 1
}
}
}
}
}
}
}
}
Result:
{
"took" : 3,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 8,
"relation" : "eq"
},
"max_score" : null,
"hits" : [ ]
},
"aggregations" : {
"distinct_by_derivative_id" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "04",
"doc_count" : 3,
"vehicle_type" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "CAR",
"doc_count" : 2,
"cheapest_vehicle" : {
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "cars",
"_type" : "_doc",
"_id" : "8",
"_score" : null,
"_source" : {
"vehicle_type" : "CAR",
"manufacturer_name" : "Renault",
"rental" : 89.99
},
"sort" : [
89.99
]
}
]
}
}
},
{
"key" : "LCV",
"doc_count" : 1,
"cheapest_vehicle" : {
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "cars",
"_type" : "_doc",
"_id" : "7",
"_score" : null,
"_source" : {
"vehicle_type" : "LCV",
"manufacturer_name" : "Ford",
"rental" : 99.99
},
"sort" : [
99.99
]
}
]
}
}
}
]
}
},
{
"key" : "01",
"doc_count" : 2,
"vehicle_type" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "CAR",
"doc_count" : 1,
"cheapest_vehicle" : {
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "cars",
"_type" : "_doc",
"_id" : "1",
"_score" : null,
"_source" : {
"vehicle_type" : "CAR",
"manufacturer_name" : "Ford",
"rental" : 599.99
},
"sort" : [
599.99
]
}
]
}
}
},
{
"key" : "LCV",
"doc_count" : 1,
"cheapest_vehicle" : {
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "cars",
"_type" : "_doc",
"_id" : "2",
"_score" : null,
"_source" : {
"vehicle_type" : "LCV",
"manufacturer_name" : "Ford",
"rental" : 599.99
},
"sort" : [
599.99
]
}
]
}
}
}
]
}
},
{
"key" : "02",
"doc_count" : 2,
"vehicle_type" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "CAR",
"doc_count" : 2,
"cheapest_vehicle" : {
"hits" : {
"total" : {
"value" : 2,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "cars",
"_type" : "_doc",
"_id" : "4",
"_score" : null,
"_source" : {
"vehicle_type" : "CAR",
"manufacturer_name" : "Audi",
"rental" : 499.99
},
"sort" : [
499.99
]
}
]
}
}
}
]
}
},
{
"key" : "03",
"doc_count" : 1,
"vehicle_type" : {
"doc_count_error_upper_bound" : 0,
"sum_other_doc_count" : 0,
"buckets" : [
{
"key" : "CAR",
"doc_count" : 1,
"cheapest_vehicle" : {
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : null,
"hits" : [
{
"_index" : "cars",
"_type" : "_doc",
"_id" : "5",
"_score" : null,
"_source" : {
"vehicle_type" : "CAR",
"manufacturer_name" : "Audi",
"rental" : 399.99
},
"sort" : [
399.99
]
}
]
}
}
}
]
}
}
]
}
}
}
A functional solution would go like this:
$fruit = array('apple', 'banana', 'pear', 'grape');
$sep = ',';
array_reduce(
$fruits,
function($fruitsStr, $fruit) use ($sep) {
return (('' == $fruitsStr) ? $fruit : $fruitsStr . $sep . $fruit);
},
''
);
Why not just doing it this way?
DateTime dt1 = new DateTime(2009, 6, 1);
DateTime dt2 = DateTime.Now;
double totalminutes = (dt2 - dt1).TotalMinutes;
Hope this helps.
This answer applies to using gVim on Windows 10. I cannot guarantee the same results for other operating systems.
Add:
set nobackup
set noswapfile
set noundofile
To your _vimrc file.
Note: This is the direct answer to the question (for Windows 10) and probably not the safest thing to do (read the other answers), but this is the fastest solution in my case.
The following query should give the exact stuff you are looking out for.
select datediff(second, '2010-01-22 15:29:55.090' , '2010-01-22 15:30:09.153')
Here is the link from MSDN for what all you can do with datediff function . https://msdn.microsoft.com/en-us/library/ms189794.aspx
If you just want a very quick way to debug the result:
$ch = curl_init();
curl_exec($ch);
$curl_error = curl_error($ch);
echo "<script>console.log($curl_error);</script>"
You are looking for the .remove()
function.
Recursive solution to print all items in a list:
def printItems(l):
for i in l:
if isinstance(i,list):
printItems(i)
else:
print i
l = [['vegas','London'],['US','UK']]
printItems(l)