Personally I extract the POST array and then have if(!$login || !$password) then echo fill out the form :)
But its still giving an error message in Query Builder. I am using SqlServerCe 2008.
SELECT Products_Master.ProductName, Order_Products.Quantity, Order_Details.TotalTax, Order_Products.Cost, Order_Details.Discount,
Order_Details.TotalPrice
FROM Order_Products INNER JOIN
Order_Details ON Order_Details.OrderID = Order_Products.OrderID INNER JOIN
Products_Master ON Products_Master.ProductCode = Order_Products.ProductCode
HAVING (Order_Details.OrderID = (SELECT MAX(OrderID) AS Expr1 FROM Order_Details AS mx1))
I replaced WHERE with HAVING as said by @powerlord. But still showing an error.
Error parsing the query. [Token line number = 1, Token line offset = 371, Token in error = SELECT]
As simple as:
$A="1"
function changeA2 () { $global:A="0"}
changeA2
$A
No. Its not possible to add link through css. But you can use jquery
$('.case').each(function() {
var link = $(this).html();
$(this).contents().wrap('<a href="example.com/script.php?id="></a>');
});
Here the demo: http://jsfiddle.net/r5uWX/1/
I got this problem after i added a line in my build.gradle
file.
compile 'com.balysv:material-ripple:1.0.2'
Solution: I changed this line to
implementation 'com.balysv:material-ripple:1.0.2'
and then pressed sync again
.
Tada! all was working again.
why you looking for this problem into your code? Even, if it's copypasted.
If you can see, what exactly happening after save file in synced folder - you will see something like *****
at the end of file. It's not related to your code at all.
Solution.
If you are using nginx
in vagrant box - add to server config:
sendfile off;
If you are using apache
in vagrant box - add to server config:
EnableSendfile Off;
Source of problem: VirtualBox Bug
You can't do variable manipulation in django templates. You have two options, either write your own template tag or do this in view,
The GitHub repository setup page is just a suggested list of commands (and GitHub now suggests using the HTTPS protocol). Unless you have administrative access to GitHub's site, I don't know of any way to change their suggested commands.
If you'd rather use the SSH protocol, simply add a remote branch like so (i.e. use this command in place of GitHub's suggested command). To modify an existing branch, see the next section.
$ git remote add origin [email protected]:nikhilbhardwaj/abc.git
As you already know, to switch a pre-existing repository to use SSH instead of HTTPS, you can change the remote url within your .git/config
file.
[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
-url = https://github.com/nikhilbhardwaj/abc.git
+url = [email protected]:nikhilbhardwaj/abc.git
A shortcut is to use the set-url
command:
$ git remote set-url origin [email protected]:nikhilbhardwaj/abc.git
#define PADDING 5
@interface MyLabel : UILabel
@end
@implementation MyLabel
- (void)drawTextInRect:(CGRect)rect {
return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, UIEdgeInsetsMake(0, PADDING, 0, PADDING))];
}
- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
return CGRectInset([self.attributedText boundingRectWithSize:CGSizeMake(999, 999)
options:NSStringDrawingUsesLineFragmentOrigin
context:nil], -PADDING, 0);
}
@end
For non-printable keys such as arrow keys and shortcut keys such as Ctrl-z, Ctrl-x, Ctrl-c that may trigger some action in the browser (for instance, inside editable documents or elements), you may not get a keypress event in all browsers. For this reason you have to use keydown
instead, if you're interested in suppressing the browser's default action. If not, keyup
will do just as well.
Attaching a keydown
event to document
works in all the major browsers:
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.ctrlKey && evt.keyCode == 90) {
alert("Ctrl-Z");
}
};
For a complete reference, I strongly recommend Jan Wolter's article on JavaScript key handling.
I normally would use a generator function. Each time you use a yield statement, it will add an item to the sequence.
The following will create an iterator that yields five, and then every item in some_list.
def __iter__(self):
yield 5
yield from some_list
Pre-3.3, yield from
didn't exist, so you would have to do:
def __iter__(self):
yield 5
for x in some_list:
yield x
Go and get the latest version of miniconda for Raspberry Pi - made for armv7l processor and bundled with Python 3 (eg.: uname -m
)
wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-armv7l.sh
md5sum Miniconda3-latest-Linux-armv7l.sh
bash Miniconda3-latest-Linux-armv7l.sh
After installation, source your updated .bashrc file with source ~/.bashrc
. Then enter the command python --version
, which should give you:
Python 3.4.3 :: Continuum Analytics, Inc.
ES6
find()
find()
is located on Array.prototype
so it can be used on every array.find()
takes a callback where a boolean
condition is tested. The function returns the value (not the index!)const array = [4, 33, 8, 56, 23];
const found = array.find(element => {
return element > 50;
});
console.log(found); // 56
_x000D_
In JBoss EAP 6.4, right click on the server and open launch configuration under VM argument you will find
{-Dprogram.name=JBossTools: jboss-eap" -server -Xms1024m -Xmx1024m -XX:MaxPermSize=256m}
update it to
{-Dprogram.name=JBossTools: JBoss 6.4" -server -Xms512m -Xmx512m}
this will solve your problem.
N+1 SELECT problem is really hard to spot, especially in projects with large domain, to the moment when it starts degrading the performance. Even if the problem is fixed i.e. by adding eager loading, a further development may break the solution and/or introduce N+1 SELECT problem again in other places.
I've created open source library jplusone to address those problems in JPA based Spring Boot Java applications. The library provides two major features:
2020-10-22 18:41:43.236 DEBUG 14913 --- [ main] c.a.j.core.report.ReportGenerator : ROOT com.adgadev.jplusone.test.domain.bookshop.BookshopControllerTest.shouldGetBookDetailsLazily(BookshopControllerTest.java:65) com.adgadev.jplusone.test.domain.bookshop.BookshopController.getSampleBookUsingLazyLoading(BookshopController.java:31) com.adgadev.jplusone.test.domain.bookshop.BookshopService.getSampleBookDetailsUsingLazyLoading [PROXY] SESSION BOUNDARY OPERATION [IMPLICIT] com.adgadev.jplusone.test.domain.bookshop.BookshopService.getSampleBookDetailsUsingLazyLoading(BookshopService.java:35) com.adgadev.jplusone.test.domain.bookshop.Author.getName [PROXY] com.adgadev.jplusone.test.domain.bookshop.Author [FETCHING ENTITY] STATEMENT [READ] select [...] from author author0_ left outer join genre genre1_ on author0_.genre_id=genre1_.id where author0_.id=1 OPERATION [IMPLICIT] com.adgadev.jplusone.test.domain.bookshop.BookshopService.getSampleBookDetailsUsingLazyLoading(BookshopService.java:36) com.adgadev.jplusone.test.domain.bookshop.Author.countWrittenBooks(Author.java:53) com.adgadev.jplusone.test.domain.bookshop.Author.books [FETCHING COLLECTION] STATEMENT [READ] select [...] from book books0_ where books0_.author_id=1
@SpringBootTest
class LazyLoadingTest {
@Autowired
private JPlusOneAssertionContext assertionContext;
@Autowired
private SampleService sampleService;
@Test
public void shouldBusinessCheckOperationAgainstJPlusOneAssertionRule() {
JPlusOneAssertionRule rule = JPlusOneAssertionRule
.within().lastSession()
.shouldBe().noImplicitOperations().exceptAnyOf(exclusions -> exclusions
.loadingEntity(Author.class).times(atMost(2))
.loadingCollection(Author.class, "books")
);
// trigger business operation which you wish to be asserted against the rule,
// i.e. calling a service or sending request to your API controller
sampleService.executeBusinessOperation();
rule.check(assertionContext);
}
}
Java 8
return Collections.list(httpServletRequest.getParameterNames())
.stream()
.collect(Collectors.toMap(parameterName -> parameterName, httpServletRequest::getParameterValues));
|| is a logical or and | is a bit-wise or.
This is an old post, but get it with this:
function getLocalIp()
{ return gethostbyname(trim(`hostname`)); }
For example:
die( getLocalIp() );
Found it on another site, do not remove the trim command because otherwise you will get the computers name.
BACKTICKS (The special quotes): It works because PHP will attempt to run whatever it's between those "special quotes" (backticks) as a shell command and returns the resulting output.
gethostbyname(trim(`hostname`));
Is very similar (but much more efficient) than doing:
$exec = exec("hostname"); //the "hostname" is a valid command in both windows and linux
$hostname = trim($exec); //remove any spaces before and after
$ip = gethostbyname($hostname); //resolves the hostname using local hosts resolver or DNS
In Xcode 4 and possibly before, in the run script build phase there is an option "Show enviroment variables in build phase". If selected this will show then on a olive green background in the build log.
You (or Joomla) is likely including this file multiple times. Enclose your function in a conditional block:
if (!function_exists('parseDate')) {
// ... proceed to declare your function
}
Use repr
and eval
:
>>> s = set([1,2,3])
>>> strs = repr(s)
>>> strs
'set([1, 2, 3])'
>>> eval(strs)
set([1, 2, 3])
Note that eval
is not safe if the source of string is unknown, prefer ast.literal_eval
for safer conversion:
>>> from ast import literal_eval
>>> s = set([10, 20, 30])
>>> lis = str(list(s))
>>> set(literal_eval(lis))
set([10, 20, 30])
help on repr
:
repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.
the easy way i found to do this is to put a field with a value and ask the user to remove the text in this field. since bots only fill them up. if the field is not empty it means that the user is not human and it wont be posted. its the same purpose of a captcha code.
Here is a simple AppCompatActivity extension function, which closes opened Dialog Fragment:
fun AppCompatActivity.whenDialogOpenDismiss(
tag: String
) {
supportFragmentManager.findFragmentByTag(tag)?.let {
if(it is DialogFragment) it.dismiss() }
}
Of course you can call it from any activity directly. If you need to call it from a Fragment just make the same extension function about Fragment class
Native DOM elements that are inputs also have a form
attribute that points to the form they belong to:
var form = element.form;
alert($(form).attr('name'));
According to w3schools, the .form
property of input fields is supported by IE 4.0+, Firefox 1.0+, Opera 9.0+, which is even more browsers that jQuery guarantees, so you should stick to this.
If this were a different type of element (not an <input>
), you could find the closest parent with closest
:
var $form = $(element).closest('form');
alert($form.attr('name'));
Also, see this MDN link on the form
property of HTMLInputElement
:
The question isn't clear - is this for an alert on page load? You shouldn't see any alert dialogues when using Selenium, as it replaces alert()
with its own version which just captures the message given for verification.
Selenium doesn't support alert()
on page load, as it needs to patch the function in the window under test with its own version.
If you can't get rid of onload alerts from the application under test, you should look into using GUI automation to click the popups which are generated, e.g. AutoIT if you're on Windows.
In C, fgets(), and you need to know the maximum size to prevent truncation.
I used the Sebastien Horin function getIp and request()->ip() (at global request), because to localhost the getIp function return null:
$this->getIp() ?? request()->ip();
The getIp function:
public function getIp(){
foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key){
if (array_key_exists($key, $_SERVER) === true){
foreach (explode(',', $_SERVER[$key]) as $ip){
$ip = trim($ip); // just to be safe
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
return $ip;
}
}
}
}
}
In short \r has ASCII value 13 (CR) and \n has ASCII value 10 (LF). Mac uses CR as line delimiter (at least, it did before, I am not sure for modern macs), *nix uses LF and Windows uses both (CRLF).
You can call sortable
on a <tbody>
instead of on the individual rows.
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
</tbody>
</table>?
<script>
$('tbody').sortable();
</script>
$(function() {_x000D_
$( "tbody" ).sortable();_x000D_
});
_x000D_
_x000D_
table {_x000D_
border-spacing: collapse;_x000D_
border-spacing: 0;_x000D_
}_x000D_
td {_x000D_
width: 50px;_x000D_
height: 25px;_x000D_
border: 1px solid black;_x000D_
}
_x000D_
_x000D_
_x000D_
<link href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet">_x000D_
<script src="//code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>_x000D_
_x000D_
<table>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3</td>_x000D_
<td>4</td>_x000D_
</tr>_x000D_
<tr> _x000D_
<td>5</td>_x000D_
<td>6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>7</td>_x000D_
<td>8</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>9</td> _x000D_
<td>10</td>_x000D_
</tr> _x000D_
</tbody> _x000D_
</table>
_x000D_
In res folder select the XML file in which you want to view your images,
<ImageView
android:id="@+id/image1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/imagep1" />
Ctrl-Alt-Down: copies current line or selected lines to below
Ctrl-Alt-Up:: copies current line or selected lines to above
Ctrl-Shift-L: brings up a List of shortcut keys
See Windows/Preference->General->Keys.
Just a little addition if one wants to parse a space separated text file line by line.
read_file = function (path)
local file = io.open(path, "rb")
if not file then return nil end
local lines = {}
for line in io.lines(path) do
local words = {}
for word in line:gmatch("%w+") do
table.insert(words, word)
end
table.insert(lines, words)
end
file:close()
return lines;
end
NEQ is usually used for numbers and == is typically used for string comparison.
I cannot find any documentation that mentions a specific and equivalent inequality operand for string comparison (in place of NEQ). The solution using IF NOT == seems the most sound approach. I can't immediately think of a circumstance in which the evaluation of operations in a batch file would cause an issue or unexpected behavior when applying the IF NOT == comparison method to strings.
I wish I could offer insight into how the two functions behave differently on a lower level - would disassembling separate batch files (that use NEQ and IF NOT ==) offer any clues in terms of which (unofficially documented) native API calls conhost.exe is utilizing?
Got help from this discussion. In my case the
git reset HEAD subby
git commit
worked for me :)
The problem is not that you can't forward-declare a template class. Yes, you do need to know all of the template parameters and their defaults to be able to forward-declare it correctly:
namespace std {
template<class T, class Allocator = std::allocator<T>>
class list;
}
But to make even such a forward declaration in namespace std
is explicitly prohibited by the standard: the only thing you're allowed to put in std
is a template specialisation, commonly std::less
on a user-defined type. Someone else can cite the relevant text if necessary.
Just #include <list>
and don't worry about it.
Oh, incidentally, any name containing double-underscores is reserved for use by the implementation, so you should use something like TEST_H
instead of __TEST__
. It's not going to generate a warning or an error, but if your program has a clash with an implementation-defined identifier, then it's not guaranteed to compile or run correctly: it's ill-formed. Also prohibited are names beginning with an underscore followed by a capital letter, among others. In general, don't start things with underscores unless you know what magic you're dealing with.
formatDate
is the function you can call it and pass the date you want to format to dd/mm/yyyy
var unformatedDate = new Date("2017-08-10 18:30:00");_x000D_
_x000D_
$("#hello").append(formatDate(unformatedDate));_x000D_
function formatDate(nowDate) {_x000D_
return nowDate.getDate() +"/"+ (nowDate.getMonth() + 1) + '/'+ nowDate.getFullYear();_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="hello">_x000D_
_x000D_
_x000D_
</div>
_x000D_
You have to add a MySQL jdbc driver to the classpath.
Either put a MySQL binary jar to tomcat lib folder or add it to we application WEB-INF/lib folder.
You can find binary jar (Change version accordingly): https://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.27
Go to C:\Users\username\Anaconda3
and search for Uninstall-Anaconda3.exe
which will remove all the components of Anaconda.
This is what I used to use a csv file into an array. Couldn't get the above answers to work, but this worked for me.
$(document).ready(function() {
"use strict";
$.ajax({
type: "GET",
url: "../files/icd10List.csv",
dataType: "text",
success: function(data) {processData(data);}
});
});
function processData(icd10Codes) {
"use strict";
var input = $.csv.toArrays(icd10Codes);
$("#test").append(input);
}
Used the jQuery-CSV Plug-in linked above.
Use clear: both;
I spent over a week trying to figure this out!
Yep, why not?
fs.Write(myByteArray, 0, myByteArray.Length);
I tried using the dtypes=[datetime, ...] option, but
import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4']
dtypes = [datetime, datetime, str, float]
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)
I encountered the following error:
TypeError: data type not understood
The only change I had to make is to replace datetime with datetime.datetime
import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4']
dtypes = [datetime.datetime, datetime.datetime, str, float]
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)
Another solution is to use stat_count()
when dealing with discrete variables (and stat_bin()
with continuous ones).
ggplot(data = df, aes(x = x)) +
geom_bar(stat = "count") +
stat_count(geom = "text", colour = "white", size = 3.5,
aes(label = ..count..),position=position_stack(vjust=0.5))
You can get the difference between two DateTime using this
DateTime startDate = DateTime.now();
DateTime endDate = DateTime.now();
Days daysBetween = Days.daysBetween(startDate, endDate);
System.out.println(daysBetween.toStandardSeconds());
For those who are still getting blank response with $request->getContent()
, you can use:
$request->all()
e.g:
public function foo(Request $request){
$bodyContent = $request->all();
}
I also had this problem, it was due to renaming a view by creating a new outlet to it. Your might have the old connection outlet in the storyboard.
What you need to do is to remove the old outlet from the storyboard.
I think this will help you... Creating Threads and Passing Data at Start Time!
Imports System.Threading
' The ThreadWithState class contains the information needed for
' a task, and the method that executes the task.
Public Class ThreadWithState
' State information used in the task.
Private boilerplate As String
Private value As Integer
' The constructor obtains the state information.
Public Sub New(text As String, number As Integer)
boilerplate = text
value = number
End Sub
' The thread procedure performs the task, such as formatting
' and printing a document.
Public Sub ThreadProc()
Console.WriteLine(boilerplate, value)
End Sub
End Class
' Entry point for the example.
'
Public Class Example
Public Shared Sub Main()
' Supply the state information required by the task.
Dim tws As New ThreadWithState( _
"This report displays the number {0}.", 42)
' Create a thread to execute the task, and then
' start the thread.
Dim t As New Thread(New ThreadStart(AddressOf tws.ThreadProc))
t.Start()
Console.WriteLine("Main thread does some work, then waits.")
t.Join()
Console.WriteLine( _
"Independent task has completed main thread ends.")
End Sub
End Class
' The example displays the following output:
' Main thread does some work, then waits.
' This report displays the number 42.
' Independent task has completed; main thread ends.
awk -F: '{print $2}' <<< $var
Lots of answers here, but here comes a working example with code that you can copy and paste and test immediately:
For me the error 12514 was solved after specifying the correct SERVICE_NAME.
You find that on the server in the file tnsnames.ora
which comes with 3 predefined service names (one of them is "XE").
HKEY_LOCAL_MACHINE\SOFTWARE\Oracle\ODP.NET\4.112.4.0\DllPath
. On 64 bit machines write additionally to HKLM\SOFTWARE\Wow6432Node\Oracle\...
HKEY_LOCAL_MACHINE\SOFTWARE\Oracle\ODP.NET\4.121.2.0\DllPath
Oracle.ManagedDataAccess.dll
which is only 4 MB and is a pure managed DLL which works in 32 bit and 64 bit processes as well and depends on no other DLL and does not require any registry entries.using Oracle.DataAccess.Client; or using Oracle.ManagedDataAccess.Client; .... string oradb = "Data Source=(DESCRIPTION=" + "(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.1.158)(PORT=1521)))" + "(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));" + "User Id=SYSTEM;Password=xxx;"; using (OracleConnection conn = new OracleConnection(oradb)) { conn.Open(); using (OracleCommand cmd = new OracleCommand()) { cmd.Connection = conn; cmd.CommandText = "select TABLESPACE_NAME from DBA_DATA_FILES"; using (OracleDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { listBox.Items.Add(dr["TABLESPACE_NAME"]); } } } }
If the SERVICE_NAME=XE
is wrong you get error 12514. The SERVICE_NAME
is optional. You can also leave it away.
Of course it is right what you say at the beginning, and C logical operator &&
and ||
are what you usually use to "connect" conditions (expressions that can be evaluated as true or false); the comma operator is not a logical operator and its use in that example makes no sense, as explained by other users. You can use it e.g. to "concatenate" statements in the for itself: you can initialize and update j altogether with i; or use the comma operator in other ways
#include <stdio.h>
int main(void) // as std wants
{
int i, j;
// init both i and j; condition, we suppose && is the "original"
// intention; update i and j
for(i=0, j=2; j>=0 && i<=5; i++, j--)
{
printf("%d ", i+j);
}
return 0;
}
Resolved with Notepad++ :
1) Menu->Edit->EOL Conversion -> Unix/OSX Format
2) Then Save
Fixed
For what it's worth, here are two pointless ways of doing it:
scala> case class Foo(bar: Int)
defined class Foo
scala> import scalaz._, Scalaz._
import scalaz._
import Scalaz._
scala> val c = Vector(Foo(9), Foo(11))
c: scala.collection.immutable.Vector[Foo] = Vector(Foo(9), Foo(11))
scala> c.map(((_: Foo).bar) &&& identity).toMap
res30: scala.collection.immutable.Map[Int,Foo] = Map(9 -> Foo(9), 11 -> Foo(11))
scala> c.map(((_: Foo).bar) >>= (Pair.apply[Int, Foo] _).curried).toMap
res31: scala.collection.immutable.Map[Int,Foo] = Map(9 -> Foo(9), 11 -> Foo(11))
DevArt's OraDirect provider now supports entity framework. See http://devart.com/news/2008/directs475.html
I have been working on a Java servlet application that needs to construct very dynamic SQL statements for adhoc reporting purposes. The basic function of the app is to feed a bunch of named HTTP request parameters into a pre-coded query, and generate a nicely formatted table of output. I used Spring MVC and the dependency injection framework to store all of my SQL queries in XML files and load them into the reporting application, along with the table formatting information. Eventually, the reporting requirements became more complicated than the capabilities of the existing parameter mapping frameworks and I had to write my own. It was an interesting exercise in development and produced a framework for parameter mapping much more robust than anything else I could find.
The new parameter mappings looked as such:
select app.name as "App",
${optional(" app.owner as "Owner", "):showOwner}
sv.name as "Server", sum(act.trans_ct) as "Trans"
from activity_records act, servers sv, applications app
where act.server_id = sv.id
and act.app_id = app.id
and sv.id = ${integer(0,50):serverId}
and app.id in ${integerList(50):appId}
group by app.name, ${optional(" app.owner, "):showOwner} sv.name
order by app.name, sv.name
The beauty of the resulting framework was that it could process HTTP request parameters directly into the query with proper type checking and limit checking. No extra mappings required for input validation. In the example query above, the parameter named serverId would be checked to make sure it could cast to an integer and was in the range of 0-50. The parameter appId would be processed as an array of integers, with a length limit of 50. If the field showOwner is present and set to "true", the bits of SQL in the quotes will be added to the generated query for the optional field mappings. field Several more parameter type mappings are available including optional segments of SQL with further parameter mappings. It allows for as complex of a query mapping as the developer can come up with. It even has controls in the report configuration to determine whether a given query will have the final mappings via a PreparedStatement or simply ran as a pre-built query.
For the sample Http request values:
showOwner: true
serverId: 20
appId: 1,2,3,5,7,11,13
It would produce the following SQL:
select app.name as "App",
app.owner as "Owner",
sv.name as "Server", sum(act.trans_ct) as "Trans"
from activity_records act, servers sv, applications app
where act.server_id = sv.id
and act.app_id = app.id
and sv.id = 20
and app.id in (1,2,3,5,7,11,13)
group by app.name, app.owner, sv.name
order by app.name, sv.name
I really think that Spring or Hibernate or one of those frameworks should offer a more robust mapping mechanism that verifies types, allows for complex data types like arrays and other such features. I wrote my engine for only my purposes, it isn't quite read for general release. It only works with Oracle queries at the moment and all of the code belongs to a big corporation. Someday I may take my ideas and build a new open source framework, but I'm hoping one of the existing big players will take up the challenge.
Extending the Community answer that will not work when the list is empty, here is working code for mode:
def mode(arr):
if arr==[]:
return None
else:
return max(set(arr), key=arr.count)
Declaration, generally, refers to the introduction of a new name in the program. For example, you can declare a new function by describing it's "signature":
void xyz();
or declare an incomplete type:
class klass;
struct ztruct;
and last but not least, to declare an object:
int x;
It is described, in the C++ standard, at §3.1/1 as:
A declaration (Clause 7) may introduce one or more names into a translation unit or redeclare names introduced by previous declarations.
A definition is a definition of a previously declared name (or it can be both definition and declaration). For example:
int x;
void xyz() {...}
class klass {...};
struct ztruct {...};
enum { x, y, z };
Specifically the C++ standard defines it, at §3.1/1, as:
A declaration is a definition unless it declares a function without specifying the function’s body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification25 (7.5) and neither an initializer nor a function- body, it declares a static data member in a class definition (9.2, 9.4), it is a class name declaration (9.1), it is an opaque-enum-declaration (7.2), it is a template-parameter (14.1), it is a parameter-declaration (8.3.5) in a function declarator that is not the declarator of a function-definition, or it is a typedef declaration (7.1.3), an alias-declaration (7.1.3), a using-declaration (7.3.3), a static_assert-declaration (Clause 7), an attribute- declaration (Clause 7), an empty-declaration (Clause 7), or a using-directive (7.3.4).
Initialization refers to the "assignment" of a value, at construction time. For a generic object of type T
, it's often in the form:
T x = i;
but in C++ it can be:
T x(i);
or even:
T x {i};
with C++11.
So does it mean definition equals declaration plus initialization?
It depends. On what you are talking about. If you are talking about an object, for example:
int x;
This is a definition without initialization. The following, instead, is a definition with initialization:
int x = 0;
In certain context, it doesn't make sense to talk about "initialization", "definition" and "declaration". If you are talking about a function, for example, initialization does not mean much.
So, the answer is no: definition does not automatically mean declaration plus initialization.
This is what I use, which does not need you to hardcore your resource names and will look for the drawable resources first in your apps resources and then in the stock android resources if nothing was found - allowing you to use default icons and such.
private class ImageGetter implements Html.ImageGetter {
public Drawable getDrawable(String source) {
int id;
id = getResources().getIdentifier(source, "drawable", getPackageName());
if (id == 0) {
// the drawable resource wasn't found in our package, maybe it is a stock android drawable?
id = getResources().getIdentifier(source, "drawable", "android");
}
if (id == 0) {
// prevent a crash if the resource still can't be found
return null;
}
else {
Drawable d = getResources().getDrawable(id);
d.setBounds(0,0,d.getIntrinsicWidth(),d.getIntrinsicHeight());
return d;
}
}
}
Which can be used as such (example):
String myHtml = "This will display an image to the right <img src='ic_menu_more' />";
myTextview.setText(Html.fromHtml(myHtml, new ImageGetter(), null);
Why not show create table myTable
?
Someone told me this but I didn't see anyone mention here, anything bad?
It's neat if you just want to take a glance at the indexes along with column infomations.
if the string is mutable, then you can transform it in place using this form:
[string replaceOccurrencesOfString:@" "
withString:@""
options:0
range:NSMakeRange(0, string.length)];
this is also useful if you would like the result to be a mutable instance of an input string:
NSMutableString * string = [concreteString mutableCopy];
[string replaceOccurrencesOfString:@" "
withString:@""
options:0
range:NSMakeRange(0, string.length)];
Here's a proof by induction, considering N
terms, but it's the same for N - 1
:
For N = 0
the formula is obviously true.
Suppose 1 + 2 + 3 + ... + N = N(N + 1) / 2
is true for some natural N
.
We'll prove 1 + 2 + 3 + ... + N + (N + 1) = (N + 1)(N + 2) / 2
is also true by using our previous assumption:
1 + 2 + 3 + ... + N + (N + 1) = (N(N + 1) / 2) + (N + 1)
= (N + 1)((N / 2) + 1)
= (N + 1)(N + 2) / 2
.
So the formula holds for all N
.
If you've already displayed the element on the page previously, you can simply take the height directly from the DOM element (reachable in jQuery with .get(0)), since it is set even when the element is hidden:
$('.hidden-element').get(0).height;
same for the width:
$('.hidden-element').get(0).width;
(thanks to Skeets O'Reilly for correction)
Use int64_t
, that portable C99 code.
int64_t var = 0x0000444400004444LL;
For printing:
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
printf("blabla %" PRIi64 " blabla\n", var);
A percentage in the value of the font-size
property is relative to the parent element’s font size. CSS 2.1 says this obscurely and confusingly (referring to “inherited font size”), but CSS3 Text says it very clearly.
The parent of the body
element is the root element, i.e. the html
element. Unless set in a style sheet, the font size of the root element is implementation-dependent. It typically depends on user settings.
Setting font-size: 100%
is pointless in many cases, as an element inherits its parent’s font size (leading to the same result), if no style sheet sets its own font size. However, it can be useful to override settings in other style sheets (including browser default style sheets).
For example, an input
element typically has a setting in browser style sheet, making its default font size smaller than that of copy text. If you wish to make the font size the same, you can set
input { font-size: 100% }
For the body
element, the logically redundant setting font-size: 100%
is used fairly often, as it is believed to help against some browser bugs (in browsers that probably have lost their significance now).
DeepCompare method to compare two json objects..
deepCompare = (arg1, arg2) => {_x000D_
if (Object.prototype.toString.call(arg1) === Object.prototype.toString.call(arg2)){_x000D_
if (Object.prototype.toString.call(arg1) === '[object Object]' || Object.prototype.toString.call(arg1) === '[object Array]' ){_x000D_
if (Object.keys(arg1).length !== Object.keys(arg2).length ){_x000D_
return false;_x000D_
}_x000D_
return (Object.keys(arg1).every(function(key){_x000D_
return deepCompare(arg1[key],arg2[key]);_x000D_
}));_x000D_
}_x000D_
return (arg1===arg2);_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
console.log(deepCompare({a:1},{a:'1'})) // false_x000D_
console.log(deepCompare({a:1},{a:1})) // true
_x000D_
The problem is that jQuery doesn't trigger the native click
event for <a>
elements so that navigation doesn't happen (the normal behavior of an <a>
), so you need to do that manually. For almost all other scenarios, the native DOM event is triggered (at least attempted to - it's in a try/catch).
To trigger it manually, try:
var a = $("<a>")
.attr("href", "http://i.stack.imgur.com/L8rHf.png")
.attr("download", "img.png")
.appendTo("body");
a[0].click();
a.remove();
DEMO: http://jsfiddle.net/HTggQ/
Relevant line in current jQuery source: https://github.com/jquery/jquery/blob/1.11.1/src/event.js#L332
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
The best way for spell checking in python is by: SymSpell, Bk-Tree or Peter Novig's method.
The fastest one is SymSpell.
This is Method1: Reference link pyspellchecker
This library is based on Peter Norvig's implementation.
pip install pyspellchecker
from spellchecker import SpellChecker
spell = SpellChecker()
# find those words that may be misspelled
misspelled = spell.unknown(['something', 'is', 'hapenning', 'here'])
for word in misspelled:
# Get the one `most likely` answer
print(spell.correction(word))
# Get a list of `likely` options
print(spell.candidates(word))
Method2: SymSpell Python
pip install -U symspellpy
Simply just append your fields and their values to the elements:
$user->roles()->sync([
1 => ['F1' => 'F1 Updated']
]);
Putting an encoded json inside the cookie is my favorite method, to get properly formated data out of a cookie. Try that:
$expiry = time() + 12345;
$data = (object) array( "value1" => "just for fun", "value2" => "i'll save whatever I want here" );
$cookieData = (object) array( "data" => $data, "expiry" => $expiry );
setcookie( "cookiename", json_encode( $cookieData ), $expiry );
then when you get your cookie next time:
$cookie = json_decode( $_COOKIE[ "cookiename" ] );
you can simply extract the expiry time, which was inserted as data inside the cookie itself..
$expiry = $cookie->expiry;
and additionally the data which will come out as a usable object :)
$data = $cookie->data;
$value1 = $cookie->data->value1;
etc. I find that to be a much neater way to use cookies, because you can nest as many small objects within other objects as you wish!
As posted already
All you need to do is to give ownership of the folders to Apache :
but I added -R for chown command:
sudo chown -R www-data:www-data /path/to/your/project/vendor
sudo chown -R www-data:www-data /path/to/your/project/storage
You can use replace_entities from w3lib.html library
In [202]: from w3lib.html import replace_entities
In [203]: replace_entities("£682m")
Out[203]: u'\xa3682m'
In [204]: print replace_entities("£682m")
£682m
I'm just sharing this answer because I had similar problem.
In the end, error was caused because I inadvertently changed the fileTree
. In my case, I fixed by changing:
// implementation or compile
implementation fileTree(include: ['*.jar'])
to
// implementation or compile
implementation fileTree(include: ['*.jar'], dir: 'libs')
Were your tests performed on your personal computer, or on a web server? It is a blank page, or is it a complex online system with images, databases, etc.? Are your scripts performing a simple hover event action, or are they a core component to how your website renders and interacts with the user? There are several things to consider here, and the relevance of these recommendations almost always become rules when you venture into high-caliber web development.
The purpose of the "put stylesheets at the top and scripts at the bottom" rule is that, in general, it's the best way to achieve optimal progressive rendering, which is critical to the user experience.
All else aside: assuming your test is valid, and you really are producing results contrary to the popular rules, it'd come as no surprise, really. Every website (and everything it takes to make the whole thing appear on a user's screen) is different and the Internet is constantly evolving.
There are several decisions to make:
The first about resource path:
Model the image as a resource on its own:
Nested in user (/user/:id/image): the relationship between the user and the image is made implicitly
In the root path (/image):
The client is held responsible for establishing the relationship between the image and the user, or;
If a security context is being provided with the POST request used to create an image, the server can implicitly establish a relationship between the authenticated user and the image.
Embed the image as part of the user
The second decision is about how to represent the image resource:
This would be my decision track:
Then comes the question: Is there any performance impact about choosing base64 vs multipart?. We could think that exchanging data in multipart format should be more efficient. But this article shows how little do both representations differ in terms of size.
My choice Base64:
A more parsimonious way, rather than iterating through via a for loop you could also just print the original object containing all files inside your S3 bucket:
session = Session(aws_access_key_id=aws_access_key_id,aws_secret_access_key=aws_secret_access_key)
s3 = session.resource('s3')
bucket = s3.Bucket('bucket_name')
files_in_s3 = bucket.objects.all()
#you can print this iterable with print(list(files_in_s3))
so it's easy)))
Watch this...
var stuff = {};
$('input[type=checkbox]').each(function(i, e) {
stuff[i] = e.checked;
});
And you will have:
Object {0: true, 1: false, 2: false, 3: false}
Or:
$('input[type=checkbox]').each(function(i, e) {
stuff['row'+i] = e.checked;
});
You will have:
Object {row0: true, row1: false, row2: false, row3: false}
Or:
$('input[type=checkbox]').each(function(i, e) {
stuff[e.className+i] = e.checked;
});
You will have:
Object {checkbox0: true, checkbox1: false, checkbox2: false, checkbox3: false}
I have taken Vlad's idea and changed it a little bit. Instead of
grep -rl oldstr path | xargs sed -i 's/oldstr/newstr/g' /dev/null
Which yields
sed: couldn't edit /dev/null: not a regular file
I'm doing in 3 different connections to the remote server
touch deleteme
grep -rl oldstr path | xargs sed -i 's/oldstr/newstr/g' ./deleteme
rm deleteme
Although this is less elegant and requires 2 more connections to the server (maybe there's a way to do it all in one line) it does the job efficiently as well
Older versions of git require you first define an ignore pattern and immediately (on the next line) define the exclusion. [tested on version 1.9.3 (Apple Git-50)]
/config.php
!/*/config.php
Later versions only require the following [tested on version 2.2.1]
/config.php
NW.js allows you to create desktop applications using Javascript without all the security restrictions usually placed on the browser. So you can run executables with a function, or create/edit/read/write/delete files. You can access the hardware, such as current CPU usage or total ram in use, etc.
You can create a windows, linux, or mac desktop application with it that doesn't require any installation.
And for all SQL Server versions
SELECT CAST(0.973684210526315789 * 100 AS DECIMAL(18, 2))
Imagine a large binary blob where all 0x00 bytes shall be replaced by "\1\x30" and all 0x01 bytes by "\1\x31" because the transport protocol allows no \0-bytes.
In cases where:
the provided solutions cannot be applied (because they replace only single characters) or have a performance problem, because they would call string::replace several times which generates copies of the size of the blob over and over. (I do not know the boost solution, maybe it is OK from that perspective)
This one walks along all occurrences in the source string and builds the new string piece by piece once:
void replaceAll(std::string& source, const std::string& from, const std::string& to)
{
std::string newString;
newString.reserve(source.length()); // avoids a few memory allocations
std::string::size_type lastPos = 0;
std::string::size_type findPos;
while(std::string::npos != (findPos = source.find(from, lastPos)))
{
newString.append(source, lastPos, findPos - lastPos);
newString += to;
lastPos = findPos + from.length();
}
// Care for the rest after last occurrence
newString += source.substr(lastPos);
source.swap(newString);
}
Took some tooling around but this is what I ended up with.
Generated and installed a certificate on IIS7. Exported as PFX from IIS
Convert to pkcs12
openssl pkcs12 -in certificate.pfx -out certificate.cer -nodes
NOTE: While converting PFX to PEM format, openssl will put all the Certificates and Private Key into a single file. You will need to open the file in Text editor and copy each Certificate & Private key(including the BEGIN/END statements) to its own individual text file and save them as certificate.cer, CAcert.cer, privateKey.key respectively.
-----BEGIN PRIVATE KEY-----
Saved as certificate.key
-----END PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
Saved as certificate.crt
-----END CERTIFICATE-----
Added to apache vhost w/ Webmin.
How about:
String.prototype.strcmp = function(s) {
if (this < s) return -1;
if (this > s) return 1;
return 0;
}
Then, to compare s1 with 2:
s1.strcmp(s2)
Kind of Inception going on here.
for (PlaylistadMap playlistadMap : playlistadMaps) {
PlayList innerPlayList = playlistadMap.getPlayList();
for (Iterator<PlaylistadMap> iterator = innerPlayList.getPlaylistadMaps().iterator(); iterator.hasNext();) {
PlaylistadMap innerPlaylistadMap = iterator.next();
if (innerPlaylistadMap.equals(PlaylistadMap)) {
iterator.remove();
session.delete(innerPlaylistadMap);
}
}
}
taken from : Android UI : Fixing skipped frames
Anyone who begins developing android application sees this message on logcat “Choreographer(abc): Skipped xx frames! The application may be doing too much work on its main thread.” So what does it actually means, why should you be concerned and how to solve it.
What this means is that your code is taking long to process and frames are being skipped because of it, It maybe because of some heavy processing that you are doing at the heart of your application or DB access or any other thing which causes the thread to stop for a while.
Here is a more detailed explanation:
Choreographer lets apps to connect themselves to the vsync, and properly time things to improve performance.
Android view animations internally uses Choreographer for the same purpose: to properly time the animations and possibly improve performance.
Since Choreographer is told about every vsync events, I can tell if one of the Runnables passed along by the Choreographer.post* apis doesnt finish in one frame’s time, causing frames to be skipped.
In my understanding Choreographer can only detect the frame skipping. It has no way of telling why this happens.
The message “The application may be doing too much work on its main thread.” could be misleading.
Why you should be concerned
When this message pops up on android emulator and the number of frames skipped are fairly small (<100) then you can take a safe bet of the emulator being slow – which happens almost all the times. But if the number of frames skipped and large and in the order of 300+ then there can be some serious trouble with your code. Android devices come in a vast array of hardware unlike ios and windows devices. The RAM and CPU varies and if you want a reasonable performance and user experience on all the devices then you need to fix this thing. When frames are skipped the UI is slow and laggy, which is not a desirable user experience.
How to fix it
Fixing this requires identifying nodes where there is or possibly can happen long duration of processing. The best way is to do all the processing no matter how small or big in a thread separate from main UI thread. So be it accessing data form SQLite Database or doing some hardcore maths or simply sorting an array – Do it in a different thread
Now there is a catch here, You will create a new Thread for doing these operations and when you run your application, it will crash saying “Only the original thread that created a view hierarchy can touch its views“. You need to know this fact that UI in android can be changed by the main thread or the UI thread only. Any other thread which attempts to do so, fails and crashes with this error. What you need to do is create a new Runnable inside runOnUiThread and inside this runnable you should do all the operations involving the UI. Find an example here.
So we have Thread and Runnable for processing data out of main Thread, what else? There is AsyncTask in android which enables doing long time processes on the UI thread. This is the most useful when you applications are data driven or web api driven or use complex UI’s like those build using Canvas. The power of AsyncTask is that is allows doing things in background and once you are done doing the processing, you can simply do the required actions on UI without causing any lagging effect. This is possible because the AsyncTask derives itself from Activity’s UI thread – all the operations you do on UI via AsyncTask are done is a different thread from the main UI thread, No hindrance to user interaction.
So this is what you need to know for making smooth android applications and as far I know every beginner gets this message on his console.
An option for delegates in C++ that is not otherwise mentioned here is to do it C style using a function ptr and a context argument. This is probably the same pattern that many asking this question are trying to avoid. But, the pattern is portable, efficient, and is usable in embedded and kernel code.
class SomeClass
{
in someMember;
int SomeFunc( int);
static void EventFunc( void* this__, int a, int b, int c)
{
SomeClass* this_ = static_cast< SomeClass*>( this__);
this_->SomeFunc( a );
this_->someMember = b + c;
}
};
void ScheduleEvent( void (*delegateFunc)( void*, int, int, int), void* delegateContext);
...
SomeClass* someObject = new SomeObject();
...
ScheduleEvent( SomeClass::EventFunc, someObject);
...
I haven't tried specifically getting the VM settings, but there is a wealth of information in the JMX utilities specifically the MXBean utilities. This would be where I would start. Hopefully you find something there to help you.
The sun website has a bunch on the technology:
http://java.sun.com/javase/6/docs/technotes/guides/management/mxbeans.html
You could try this registry hack:
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters]
"DeadGWDetectDefault"=dword:00000001
"KeepAliveTime"=dword:00120000
If it works, just keep increasing the KeepAliveTime
. It is currently set for 2 minutes.
You can use awk just to print the first 'field' if there won't be any spaces (or if there will be, change the separator'.
I put the fields you had above into a file and did this
awk '{ print $1 }' < test.txt
1234567890
1234567891
I don't know if that's any better.
tl;dr:
concat
and append
currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True
to silence it. In the future the default will change to not sort, so it's best to specify either sort=True
or False
now, or better yet ensure that your non-concatenation indices match.
The warning is new in pandas 0.23.0:
In a future version of pandas pandas.concat()
and DataFrame.append()
will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned,
link.
More information from linked very old github issue, comment by smcinerney :
When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.
This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.
After some time the parameter sort
was implemented in pandas.concat
and DataFrame.append
:
sort : boolean, default None
Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.
Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.
This has no effect when join='inner', which already preserves the order of the non-concatenation axis.
So if both DataFrames have the same columns in the same order, there is no warning and no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
a b
0 1 0
1 2 8
0 4 7
1 5 3
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])
print (pd.concat([df1, df2]))
b a
0 0 1
1 8 2
0 7 4
1 3 5
But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort
is explicitly set (sort=None
is the default value):
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=True))
a b
0 1 0
1 2 8
0 4 7
1 5 3
print (pd.concat([df1, df2], sort=False))
b a
0 0 1
1 8 2
0 7 4
1 3 5
If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a
and b
from df1
with a
and b
from df2
in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.
Lastly, if you pass sort=True
, columns are sorted alphanumerically. If sort=False
and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:
df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]},
columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]},
columns=['c','b','a','d'])
print (pd.concat([df1, df2]))
FutureWarning: Sorting because non-concatenation axis is not aligned.
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=True))
a b c d e
0 1 0 NaN NaN 5.0
1 2 8 NaN NaN 0.0
0 4 7 2.0 7.0 NaN
1 5 3 8.0 0.0 NaN
print (pd.concat([df1, df2], sort=False))
b a e c d
0 0 1 5.0 NaN NaN
1 8 2 0.0 NaN NaN
0 7 4 NaN 2.0 7.0
1 3 5 NaN 8.0 0.0
In your code:
placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
.append(placement_by_video_summary_new, sort=True)
.sort_index()
This converts from System.Drawing.Bitmap to BitmapImage:
MemoryStream ms = new MemoryStream();
YOURBITMAP.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
BitmapImage image = new BitmapImage();
image.BeginInit();
ms.Seek(0, SeekOrigin.Begin);
image.StreamSource = ms;
image.EndInit();
Hold shift and right click on SQL Server Mangement studion icon. You can Run as other windows account user.
for me
config set stop-writes-on-bgsave-error no
and I reload my mac, it works
You can open SQL Compact 4.0 Databases from Visual Studio 2012 directly, by going to
and following the instructions there.
If you're okay with them being upgraded to 4.0, you can open older versions of SQL Compact Databases also - handy if you just want to have a look at some tables, etc for stuff like Windows Phone local database development.
(note I'm not sure if this requires a specific SKU of VS2012, if it helps I'm running Premium)
In the shell write
gnuplot -persist -e "plot filename1.dat,filename2.dat"
and consecutively the files you want. -persist is used to make the gnuplot screen stay as long as the user doesn't exit it manually.
You could write a method to print a 2d array like this:
//Displays a 2d array in the console, one line per row.
static void printMatrix(int[][] grid) {
for(int r=0; r<grid.length; r++) {
for(int c=0; c<grid[r].length; c++)
System.out.print(grid[r][c] + " ");
System.out.println();
}
}
Do git help gitignore
You will get the help page with following line:
A line starting with # serves as a comment.
Not sure why another useful option is not yet mentioned:
UPDATE my_table m
JOIN (
SELECT 1 as id, 10 as _col1, 20 as _col2
UNION ALL
SELECT 2, 5, 10
UNION ALL
SELECT 3, 15, 30
) vals ON m.id = vals.id
SET col1 = _col1, col2 = _col2;
Java 8 introduced the Iterable#forEach()
/ Map#forEach()
method, which is more efficient for many Collection
/ Map
implementations compared to the "classical" for-each loop. However, also in this case an index is not provided. The trick here is to use AtomicInteger
outside the lambda expression. Note: variables used within the lambda expression must be effectively final, that is why we cannot use an ordinary int
.
final AtomicInteger indexHolder = new AtomicInteger();
map.forEach((k, v) -> {
final int index = indexHolder.getAndIncrement();
// use the index
});
limit = 75
info = data[:limit] + '..' * (len(data) > limit)
setState
takes new state and optional callback function which is called after the state has been updated.
this.setState(
{newState: 'whatever'},
() => {/*do something after the state has been updated*/}
)
In terms of networking and security, the Backend is by far the most (should be) secure node.
The middle-end portion, usually being a web server, will be somewhat in the wild and cut off in many respects from a company's network. The middle-end node is usually placed in the DMZ and segmented from the network with firewall settings. Most of the server-side code parsing of web pages is handled on the middle-end web server.
Getting to the backend means going through the middle-end, which has a carefully crafted set of rules allowing/disallowing access to the vital nummies which are stored on the database (backend) server.
Like others have mentioned, a functor is an object that acts like a function, i.e. it overloads the function call operator.
Functors are commonly used in STL algorithms. They are useful because they can hold state before and between function calls, like a closure in functional languages. For example, you could define a MultiplyBy
functor that multiplies its argument by a specified amount:
class MultiplyBy {
private:
int factor;
public:
MultiplyBy(int x) : factor(x) {
}
int operator () (int other) const {
return factor * other;
}
};
Then you could pass a MultiplyBy
object to an algorithm like std::transform:
int array[5] = {1, 2, 3, 4, 5};
std::transform(array, array + 5, array, MultiplyBy(3));
// Now, array is {3, 6, 9, 12, 15}
Another advantage of a functor over a pointer to a function is that the call can be inlined in more cases. If you passed a function pointer to transform
, unless that call got inlined and the compiler knows that you always pass the same function to it, it can't inline the call through the pointer.
What you need are character classes. In that, you've only to worry about the ]
, \
and -
characters (and ^
if you're placing it straight after the beginning of the character class "[
" ).
Syntax: [
characters]
where characters is a list with characters.
Example:
var cleanString = dirtyString.replace(/[|&;$%@"<>()+,]/g, "");
next()
does not work in your case because you first call readlines()
which basically sets the file iterator to point to the end of file.
Since you are reading in all the lines anyway you can refer to the next line using an index:
filne = "in"
with open(filne, 'r+') as f:
lines = f.readlines()
for i in range(0, len(lines)):
line = lines[i]
print line
if line[:5] == "anim ":
ne = lines[i + 1] # you may want to check that i < len(lines)
print ' ne ',ne,'\n'
break
you can specify which column to sort by, with following steps:
steps: * top * shift + F * select a column from the list e.g. n means sort by memory, * press enter * ok
You probably have allProviders
typed as object[]
as well. And property country
does not exist on object
. If you don't care about typing, you can declare both allProviders
and countryProviders
as Array<any>
:
let countryProviders: Array<any>;
let allProviders: Array<any>;
If you do want static type checking. You can create an interface for the structure and use it:
interface Provider {
region: string,
country: string,
locale: string,
company: string
}
let countryProviders: Array<Provider>;
let allProviders: Array<Provider>;
Have the element display as a block:
display: block;
KB:2019779,"You may receive incorrect values when using SCOPE_IDENTITY() and @@IDENTITY", The OUTPUT clause is the safest mechanism:
string sql = @"
DECLARE @InsertedRows AS TABLE (Id int);
INSERT INTO [MyTable] ([Stuff]) OUTPUT Inserted.Id INTO @InsertedRows
VALUES (@Stuff);
SELECT Id FROM @InsertedRows";
var id = connection.Query<int>(sql, new { Stuff = mystuff}).Single();
Simplest and best:
i = 0
while not there_is_reason_to_break(i):
# some code here
i += 1
It may be tempting to choose the closest analogy to the C code possible in Python:
from itertools import count
for i in count():
if thereIsAReasonToBreak(i):
break
But beware, modifying i
will not affect the flow of the loop as it would in C. Therefore, using a while
loop is actually a more appropriate choice for porting that C code to Python.
Since git 1.8 (October 2012) you are able to do this from the command line:
git remote set-url origin --push --add user1@repo1
git remote set-url origin --push --add user2@repo2
git remote -v
Then git push
will push to user1@repo1, then push to user2@repo2.
Reset form inside the modal. Sample Code:
$('#myModal').on('hide.bs.modal', '#myModal', function (e) {
$('#myModal form')[0].reset();
});
May be this problem cause by Gmail account protection. Just click below link and disable security settings.It will work. https://www.google.com/settings/security/lesssecureapps
len(list_name)
function takes list as a parameter and it calls list's __len__()
function.
If you are not allowed to use C++'s string class (which is terrible teaching C++ imho), a raw, safe array version would look something like this.
#include <cstring>
#include <iostream>
int main()
{
char array1[] ="The dog jumps ";
char array2[] = "over the log";
char * newArray = new char[std::strlen(array1)+std::strlen(array2)+1];
std::strcpy(newArray,array1);
std::strcat(newArray,array2);
std::cout << newArray << std::endl;
delete [] newArray;
return 0;
}
This assures you have enough space in the array you're doing the concatenation to, without assuming some predefined MAX_SIZE
. The only requirement is that your strings are null-terminated, which is usually the case unless you're doing some weird fixed-size string hacking.
Edit, a safe version with the "enough buffer space" assumption:
#include <cstring>
#include <iostream>
int main()
{
const unsigned BUFFER_SIZE = 50;
char array1[BUFFER_SIZE];
std::strncpy(array1, "The dog jumps ", BUFFER_SIZE-1); //-1 for null-termination
char array2[] = "over the log";
std::strncat(array1,array2,BUFFER_SIZE-strlen(array1)-1); //-1 for null-termination
std::cout << array1 << std::endl;
return 0;
}
All of the above seem to work when spliced in, but gobyexample's signals page has a really clean and complete example of signal capturing. Worth adding to this list.
Be careful of race conditions: if the file disappears between the "exists" check and the time you open it, your program will fail unexpectedly.
It's better to go and open the file, check for failure and if all is good then do something with the file. It's even more important with security-critical code.
Details about security and race conditions: http://www.ibm.com/developerworks/library/l-sprace.html
The Updated code is :
private class SMSReceiver extends BroadcastReceiver {
private Bundle bundle;
private SmsMessage currentSMS;
private String message;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
bundle = intent.getExtras();
if (bundle != null) {
Object[] pdu_Objects = (Object[]) bundle.get("pdus");
if (pdu_Objects != null) {
for (Object aObject : pdu_Objects) {
currentSMS = getIncomingMessage(aObject, bundle);
String senderNo = currentSMS.getDisplayOriginatingAddress();
message = currentSMS.getDisplayMessageBody();
Toast.makeText(OtpActivity.this, "senderNum: " + senderNo + " :\n message: " + message, Toast.LENGTH_LONG).show();
}
this.abortBroadcast();
// End of loop
}
}
} // bundle null
}
}
private SmsMessage getIncomingMessage(Object aObject, Bundle bundle) {
SmsMessage currentSMS;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String format = bundle.getString("format");
currentSMS = SmsMessage.createFromPdu((byte[]) aObject, format);
} else {
currentSMS = SmsMessage.createFromPdu((byte[]) aObject);
}
return currentSMS;
}
older code was :
Object [] pdus = (Object[]) myBundle.get("pdus");
messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String format = myBundle.getString("format");
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
}
else {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
strMessage += "SMS From: " + messages[i].getOriginatingAddress();
strMessage += " : ";
strMessage += messages[i].getMessageBody();
strMessage += "\n";
}
The simple SYntax of code is :
private class SMSReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Telephony.Sms.Intents.SMS_RECEIVED_ACTION)) {
SmsMessage[] smsMessages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
for (SmsMessage message : smsMessages) {
// Do whatever you want to do with SMS.
}
}
}
}
You should really just iterate back the array in the traditional way
Every time you remove an element from the list, the elements after will be push forward. As long as you don't change elements other than the iterating one, the following code should work.
public class Test(){
private ArrayList<A> abc = new ArrayList<A>();
public void doStuff(){
for(int i = (abc.size() - 1); i >= 0; i--)
abc.get(i).doSomething();
}
public void removeA(A a){
abc.remove(a);
}
}
This was what worked for me (using jquery datepicker):
$('body').on('focus', '.datepicker', function() {
$(this).removeClass('hasDatepicker').datepicker();
});
These two schools are not really excluding.
Here is the scenario where you simply have to use
Task.Run(() => AsyncOperation()).Wait();
or something like
AsyncContext.Run(AsyncOperation);
I have a MVC action that is under database transaction attribute. The idea was (probably) to roll back everything done in the action if something goes wrong. This does not allow context switching, otherwise transaction rollback or commit is going to fail itself.
The library I need is async as it is expected to run async.
The only option. Run it as a normal sync call.
I am just saying to each its own.
I believe the solutions,
,engine='python'
, error_bad_lines = False
will be good if it is dummy columns and you want to delete it. In my case, the second row really had more columns and I wanted those columns to be integrated and to have the number of columns = MAX(columns).
Please refer to the solution below that I could not read anywhere:
try:
df_data = pd.read_csv(PATH, header = bl_header, sep = str_sep)
except pd.errors.ParserError as err:
str_find = 'saw '
int_position = int(str(err).find(str_find)) + len(str_find)
str_nbCol = str(err)[int_position:]
l_col = range(int(str_nbCol))
df_data = pd.read_csv(PATH, header = bl_header, sep = str_sep, names = l_col)
Case 1 : Yes, this works fine.
Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.
Share and enjoy.
Tested and Working procedure:
Goto the file path
..\apache-tomcat-7.0.x\webapps\ROOT\index.jsp
remove the whole content or declare the below lines of code at the top of the index.jsp
<% response.sendRedirect("http://yourRedirectionURL"); %>
Please note that in jsp file you need to start the above line with <% and end with %>
Since .Net 4.6 and above please use DateTimeOffset.Now.ToUnixTimeSeconds()
list.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Return data as XML
SELECT CONVERT(XML, [Data]) AS [Value]
FROM [dbo].[FormData]
WHERE [UID] LIKE '{my-uid}'
Make sure you set a reasonable limit in the SSMS options window, depending on the result you're expecting.
This will work if the text you're returning doesn't contain unencoded characters like &
instead of &
that will cause the XML conversion to fail.
Returning data using PowerShell
For this you will need the PowerShell SQL Server module installed on the machine on which you'll be running the command.
If you're all set up, configure and run the following script:
Invoke-Sqlcmd -Query "SELECT [Data] FROM [dbo].[FormData] WHERE [UID] LIKE '{my-uid}'" -ServerInstance "database-server-name" -Database "database-name" -Username "user" -Password "password" -MaxCharLength 10000000 | Out-File -filePath "C:\db_data.txt"
Make sure you set the -MaxCharLength
parameter to a value that suits your needs.
I also had this problem. I changed port and did other things, but they didn't help me. In my case, I connected Tomcat to IDE after installing Netbeans (before). I just uninstalled Netbeans and Tomcat after that I reinstall Netbeans along with Tomcat (NOT separately). And the problem was solved.
I'd rather use static widths and if you'd like your page to resize depending on screen size, you can have a look at media queries.
Or, you can set a min-width on elements like header, navigation, content etc.
The built in FTP command doesn't have a facility for security. Use cUrl instead. It's scriptable, far more robust and has FTP security.
According to the jQuery docs, calling toggle()
without parameters will toggle visibility.
$('#play-pause').click(function(){
$('#video-over').toggle();
});
there is a easy way: 1. using website's web.config 2. in "staticContent" section remove specific fileExtension and add mimeMap 3. add "clientCache"
<configuration>
<system.webServer>
<urlCompression doStaticCompression="true" doDynamicCompression="true" />
<staticContent>
<remove fileExtension=".ipa" />
<remove fileExtension=".apk" />
<mimeMap fileExtension=".ipa" mimeType="application/iphone" />
<mimeMap fileExtension=".apk" mimeType="application/vnd.android.package-archive" />
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="777.00:00:00" />
</staticContent>
</system.webServer>
</configuration>
It's been commented multiple times that this is not the correct answer to this question, and I agree. Back when this answer was written, IE 9 was still new (about 8 months old) and many developers including myself needed a solution for <= IE 9. IE 9 is when IE started supporting background-origin
. However, it's been over six and a half years, so here's the updated solution which I highly recommend over using an actual border. In case < IE 9 support is needed. My original answer can be found below the demo snippet. It uses an opaque border to simulate padding for background images.
#hello {
padding-right: 10px;
background-color:green;
background: url("https://placehold.it/15/5C5/FFF") no-repeat scroll right center #e8e8e8;
background-origin: content-box;
}
_x000D_
<p id="hello">I want the background icon to have padding to it too!I want the background icon twant the background icon to have padding to it too!I want the background icon to have padding to it too!I want the background icon to have padding to it too!</p>
_x000D_
you can fake it with a 10px border of the same color as the background:
http://jsbin.com/eparad/edit#javascript,html,live
#hello {
border: 10px solid #e8e8e8;
background-color: green;
background: url("http://www.costascuisine.com/images/buttons/collapseIcon.gif")
no-repeat scroll right center #e8e8e8;
}
Piggy backing on @MikkaS answer for Mongo Client v3.x, I just needed the async / await format, which looks slightly modified as this:
const myFunc = async () => {
// Prepping here...
// Connect
let client = await MongoClient.connect('mongodb://localhost');
let db = await client.db();
// Run the query
let cursor = await db.collection('customers').find({});
// Do whatever you want on the result.
}
As some of the comments above mentioned, the transpose of 1D arrays are 1D arrays, so one way to transpose a 1D array would be to convert the array to a matrix like so:
np.transpose(a.reshape(len(a), 1))
:-) Sunday | 0 -> Sun
|
Monday | 1 -> Mon
Tuesday | 2 -> Tue
Wednesday | 3 -> Wed
Thursday | 4 -> Thu
Friday | 5 -> Fri
Saturday | 6 -> Sat
|
:-) Sunday | 7 -> Sun
As you can see above, and as said before, the numbers 0
and 7
are both assigned to Sunday. There are also the English abbreviated days of the week listed, which can also be used in the crontab.
Examples of Number or Abbreviation Use
15 09 * * 5,6,0 command
15 09 * * 5,6,7 command
15 09 * * 5-7 command
15 09 * * Fri,Sat,Sun command
The four examples do all the same and execute a command every Friday, Saturday, and Sunday at 9.15 o'clock.
In Detail
Having two numbers 0
and 7
for Sunday can be useful for writing weekday ranges starting with 0
or ending with 7
. So you can write ranges starting with Sunday or ending with it, like 0-2
or 5-7
for example (ranges must start with the lower number and must end with the higher). The abbreviations cannot be used to define a weekday range.
map(&:name) takes an enumerable object (tags in your case) and runs the name method for each element/tag, outputting each returned value from the method.
It is a shorthand for
array.map { |element| element.name }
which returns the array of element(tag) names
Also, I want to mention one more thing.
When you start an application from adb shell am
, it automatically adds FLAG_ACTIVITY_NEW_TASK flag which makes behavior change. See the code.
For example, if you launch Play Store activity from adb shell am
, pressing 'Back' button(hardware back button) wouldn't take you your app, instead it would take you previous Play Store activity if there was some(If there was not Play store task, then it would take you your app). FLAG_ACTIVITY_NEW_TASK documentation says :
if a task is already running for the activity you are now starting, then a new activity will not be started; instead, the current task will simply be brought to the front of the screen with the state it was last in
This caused me to spend a few hours to find out what went wrong.
So, keep in mind that adb shell am
add FLAG_ACTIVITY_NEW_TASK flag.
You can simply do the following steps,
You can change the options for pandas max_columns feature as follows
import pandas as pd
pd.options.display.max_columns = 10
(this allows 10 columns to display, you can change this as you need)
Like that you can change the number of rows as you need to display as follows (if you need to change maximum rows as well)
pd.options.display.max_rows = 999
(this allows to print 999 rows at a time)
Please kindly refer the doc to change different options/settings for pandas
I'd like to do this way :)
const sthError = () => Promise.reject('sth error');
const test = opts => {
return (async () => {
// do sth
await sthError();
return 'ok';
})().catch(err => {
console.error(err); // error will be catched there
});
};
test().then(ret => {
console.log(ret);
});
It's similar to handling error with co
const test = opts => {
return co(function*() {
// do sth
yield sthError();
return 'ok';
}).catch(err => {
console.error(err);
});
};
As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:
WHILE EXISTS (SELECT 1
FROM YourTable
WHERE <yourCondition>)
DELETE TOP(10000) FROM YourTable
WHERE <yourCondition>
Create an array of Views and apply it to: container.addView(viewarr[position]);
public class Layoutes extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
Layoutes(Context context){
this.context=context;
}
int layoutes[]={R.layout.one,R.layout.two,R.layout.three};
@Override
public int getCount() {
return layoutes.length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return (view==(LinearLayout)object);
}
@Override
public Object instantiateItem(ViewGroup container, int position){
layoutInflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View one=layoutInflater.inflate(R.layout.one,container,false);
View two=layoutInflater.inflate(R.layout.two,container,false);
View three=layoutInflater.inflate(R.layout.three,container,false);
View viewarr[]={one,two,three};
container.addView(viewarr[position]);
return viewarr[position];
}
@Override
public void destroyItem(ViewGroup container, int position, Object object){
container.removeView((LinearLayout) object);
}
}
There is also:
try:
del mydict[key]
except KeyError:
pass
This only does 1 lookup instead of 2. However, except
clauses are expensive, so if you end up hitting the except clause frequently, this will probably be less efficient than what you already have.
You can just use the -R (recursive) flag.
chmod -R 777 /Users/Test/Desktop/PATH
You're looking for:
animation-fill-mode: forwards;
More info on MDN and browser support list on canIuse.
The -nc
, --no-clobber
option isn't the best solution as newer files will not be downloaded. One should use -N
instead which will download and overwrite the file only if the server has a newer version, so the correct answer is:
wget -N http://www.example.com/images/misc/pic.png
Then running Wget with -N, with or without
-r
or-p
, the decision as to whether or not to download a newer copy of a file depends on the local and remote timestamp and size of the file.-nc
may not be specified at the same time as-N
.
-N
,--timestamping
: Turn on time-stamping.
You provide credentials in a URLRequest
instance, like this in Swift 3:
let username = "user"
let password = "pass"
let loginString = String(format: "%@:%@", username, password)
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString()
// create the request
let url = URL(string: "http://www.example.com/")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
// fire off the request
// make sure your class conforms to NSURLConnectionDelegate
let urlConnection = NSURLConnection(request: request, delegate: self)
Or in an NSMutableURLRequest
in Swift 2:
// set up the base64-encoded credentials
let username = "user"
let password = "pass"
let loginString = NSString(format: "%@:%@", username, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions([])
// create the request
let url = NSURL(string: "http://www.example.com/")
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
// fire off the request
// make sure your class conforms to NSURLConnectionDelegate
let urlConnection = NSURLConnection(request: request, delegate: self)
I suppose you can open Java files in Visual Studio and just use the command line tools directly. I don't think you'd get syntax highlighting or autocompletion though.
Eclipse is really not all that different from Visual Studio, and there are a lot of tools that are designed to make Android development more comfortable that work from within Eclipse.
If you are using Authentication, I recommend adding the following in web.config file.
In my case, users are redirected to the login page upon timing out:
<authentication mode="Forms">
<forms defaultUrl="Login.aspx" timeout="120"/>
</authentication>
If using JDBC driver you may use function escape sequence like this:
select {fn MOD(5, 2)}
#Result 1
select mod(5, 2)
#SQL Error [195] [S00010]: 'mod' is not a recognized built-in function name.
Its possible to do silent install on Android 6 and above. Using the function supplied in the answer by Boris Treukhov, ignore everything else in the post, root is not required either.
Install your app as device admin, you can have full kiosk mode with silent install of updates in the background.
Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.
For more information about the network errors
Angular
var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');
formData.forEach((value,key) => {
console.log(key+" "+value)
});
Not: When I am working on Angular 5 (with TypeScript 2.4.2), I tried as above and it works except a static checking error but also for(var pair of formData.entries())
is not working.
var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');
formData.forEach((value,key) => {
console.log(key+" "+value)
});
_x000D_
What's so confusing about it... getters are functions that are called when you get a property, setters, when you set it. example, if you do
obj.prop = "abc";
You're setting the property prop, if you're using getters/setters, then the setter function will be called, with "abc" as an argument. The setter function definition inside the object would ideally look something like this:
set prop(var) {
// do stuff with var...
}
I'm not sure how well that is implemented across browsers. It seems Firefox also has an alternative syntax, with double-underscored special ("magic") methods. As usual Internet Explorer does not support any of this.
DO NOT USE SASS OR ANGULAR's EMBEDDED CSS SYSTEM!!
I cannot stress this enough. The people at Angular did not understand basic cascading style sheet systems as when you use both these technologies - as with this angular.json setting - the compiler stuffs all your CSS into Javascript modules then spits them out into the head of your HTML pages as embedded CSS that breaks and confuses cascade orders and disables native CSS import cascades.
For that reason, I recommend you REMOVE ALL STYLE REFERENCES FROM "ANGULAR.JSON", then add them back into your "index.html" manually as links like this:
<link href="styles/styles.css" rel="stylesheet" />
You now have a fully functioning, cascading CSS system that's fully cached in your browser over many refreshes without ECMAScripted circus tricks, saving huge amounts of bandwidth, increasing CSS overall management in static files, and full control over your cascade order minus the clunky embedded CSS injected into the head of all your web pages which Angular tries to do.
SASS isn't even necessary when you understand how to manage cascades in basic CSS files. Large sites with complex CSS can be very simple to manage for those that bother to learn cascade orders using a handful of linked CSS files.
Okay, so if later on down the line the issue is that you have a query that's greater than the allowable size (which may happen if it keeps growing) you're going to have to break it into chunks and execute the string values. So, let's say you have a stored procedure like the following:
CREATE PROCEDURE ExecuteMyHugeQuery
@SQL VARCHAR(MAX) -- 2GB size limit as stated by Martin Smith
AS
BEGIN
-- Now, if the length is greater than some arbitrary value
-- Let's say 2000 for this example
-- Let's chunk it
-- Let's also assume we won't allow anything larger than 8000 total
DECLARE @len INT
SELECT @len = LEN(@SQL)
IF (@len > 8000)
BEGIN
RAISERROR ('The query cannot be larger than 8000 characters total.',
16,
1);
END
-- Let's declare our possible chunks
DECLARE @Chunk1 VARCHAR(2000),
@Chunk2 VARCHAR(2000),
@Chunk3 VARCHAR(2000),
@Chunk4 VARCHAR(2000)
SELECT @Chunk1 = '',
@Chunk2 = '',
@Chunk3 = '',
@Chunk4 = ''
IF (@len > 2000)
BEGIN
-- Let's set the right chunks
-- We already know we need two chunks so let's set the first
SELECT @Chunk1 = SUBSTRING(@SQL, 1, 2000)
-- Let's see if we need three chunks
IF (@len > 4000)
BEGIN
SELECT @Chunk2 = SUBSTRING(@SQL, 2001, 2000)
-- Let's see if we need four chunks
IF (@len > 6000)
BEGIN
SELECT @Chunk3 = SUBSTRING(@SQL, 4001, 2000)
SELECT @Chunk4 = SUBSTRING(@SQL, 6001, (@len - 6001))
END
ELSE
BEGIN
SELECT @Chunk3 = SUBSTRING(@SQL, 4001, (@len - 4001))
END
END
ELSE
BEGIN
SELECT @Chunk2 = SUBSTRING(@SQL, 2001, (@len - 2001))
END
END
-- Alright, now that we've broken it down, let's execute it
EXEC (@Chunk1 + @Chunk2 + @Chunk3 + @Chunk4)
END
If you want to modify the original array instead of returning a new array, use .push()
...
array1.push.apply(array1, array2);
array1.push.apply(array1, array3);
I used .apply
to push the individual members of arrays 2
and 3
at once.
or...
array1.push.apply(array1, array2.concat(array3));
To deal with large arrays, you can do this in batches.
for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
array1.push.apply(array1, to_add.slice(n, n+300));
}
If you do this a lot, create a method or function to handle it.
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
and use it like this:
array1.pushArrayMembers(array2, array3);
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
value: function() {_x000D_
for (var i = 0; i < arguments.length; i++) {_x000D_
var to_add = arguments[i];_x000D_
for (var n = 0; n < to_add.length; n+=300) {_x000D_
push_apply(this, slice_call(to_add, n, n+300));_x000D_
}_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
I do not really know about it, but it seems to me, by experience, that jpcgt is actually right. Following example: If I use following code
t = [] # implicit instantiation
t = t.append(1)
in the interpreter, then calling t gives me just "t" without any list, and if I append something else, e.g.
t = t.append(2)
I get the error "'NoneType' object has no attribute 'append'". If, however, I create the list by
t = list() # explicit instantiation
then it works fine.
In addition to S.Lott's answer and as becomingGuru mentioned in comments, its possible to add the queryset filters by overriding the ModelForm.__init__
function. (This could easily apply to regular forms) it can help with reuse and keeps the view function tidy.
class ClientForm(forms.ModelForm):
def __init__(self,company,*args,**kwargs):
super (ClientForm,self ).__init__(*args,**kwargs) # populates the post
self.fields['rate'].queryset = Rate.objects.filter(company=company)
self.fields['client'].queryset = Client.objects.filter(company=company)
class Meta:
model = Client
def addclient(request, company_id):
the_company = get_object_or_404(Company, id=company_id)
if request.POST:
form = ClientForm(the_company,request.POST) #<-- Note the extra arg
if form.is_valid():
form.save()
return HttpResponseRedirect(the_company.get_clients_url())
else:
form = ClientForm(the_company)
return render_to_response('addclient.html',
{'form': form, 'the_company':the_company})
This can be useful for reuse say if you have common filters needed on many models (normally I declare an abstract Form class). E.g.
class UberClientForm(ClientForm):
class Meta:
model = UberClient
def view(request):
...
form = UberClientForm(company)
...
#or even extend the existing custom init
class PITAClient(ClientForm):
def __init__(company, *args, **args):
super (PITAClient,self ).__init__(company,*args,**kwargs)
self.fields['support_staff'].queryset = User.objects.exclude(user='michael')
Other than that I'm just restating Django blog material of which there are many good ones out there.
Here's a simple trap that prints the last argument of whatever failed to STDERR, reports the line it failed on, and exits the script with the line number as the exit code. Note these are not always great ideas, but this demonstrates some creative application you could build on.
trap 'echo >&2 "$_ at $LINENO"; exit $LINENO;' ERR
I put that in a script with a loop to test it. I just check for a hit on some random numbers; you might use actual tests. If I need to bail, I call false (which triggers the trap) with the message I want to throw.
For elaborated functionality, have the trap call a processing function. You can always use a case statement on your arg ($_) if you need to do more cleanup, etc. Assign to a var for a little syntactic sugar -
trap 'echo >&2 "$_ at $LINENO"; exit $LINENO;' ERR
throw=false
raise=false
while :
do x=$(( $RANDOM % 10 ))
case "$x" in
0) $throw "DIVISION BY ZERO" ;;
3) $raise "MAGIC NUMBER" ;;
*) echo got $x ;;
esac
done
Sample output:
# bash tst
got 2
got 8
DIVISION BY ZERO at 6
# echo $?
6
Obviously, you could
runTest1 "Test1 fails" # message not used if it succeeds
Lots of room for design improvement.
The draw backs include the fact that false
isn't pretty (thus the sugar), and other things tripping the trap might look a little stupid. Still, I like this method.
inactive session the day before kill
begin_x000D_
for i in (select * from v$session where status='INACTIVE' and (sysdate-PREV_EXEC_START)>1)_x000D_
LOOP_x000D_
EXECUTE IMMEDIATE(q'{ALTER SYSTEM KILL SESSION '}'||i.sid||q'[,]' ||i.serial#||q'[']'||' IMMEDIATE');_x000D_
END LOOP;_x000D_
end;
_x000D_
The following example shows benchmarks for a few alternatives.
library(rbenchmark) # Note spelling: "rbenchmark", not "benchmark"
benchmark(seq(0,1e6,by=2),(0:5e5)*2,seq.int(0L,1e6L,by=2L))
## test replications elapsed relative user.self sys.self
## 2 (0:5e+05) * 2 100 0.587 3.536145 0.344 0.244
## 1 seq(0, 1e6, by = 2) 100 2.760 16.626506 1.832 0.900
## 3 seq.int(0, 1e6, by = 2) 100 0.166 1.000000 0.056 0.096
In this case, seq.int
is the fastest method and seq
the slowest. If performance of this step isn't that important (it still takes < 3 seconds to generate a sequence of 500,000 values), I might still use seq
as the most readable solution.
time after 30 min, this easiest solution in php
date('Y-m-d H:i:s', strtotime("+30 minutes"));
for DateTime class (PHP 5 >= 5.2.0, PHP 7)
$dateobj = new DateTime();
$dateobj ->modify("+30 minutes");
No, there is no way to access the element by index in JavaScript objects.
One solution to this if you have access to the source of this JSON, would be to change each element to a JSON object and stick the key inside of that object like this:
var obj = [
{"key":"set1", "data":[1, 2, 3]},
{"key":"set2", "data":[4, 5, 6, 7, 8]},
{"key":"set3", "data":[9, 10, 11, 12]}
];
You would then be able to access the elements numerically:
for(var i = 0; i < obj.length; i++) {
var k = obj[i]['key'];
var data = obj[i]['data'];
//do something with k or data...
}
2 more solutions I had luck with when neither tab close + reopening the page in another tab nor closing all tabs in Chrome (and the browser) then restarting it didn't work:
1) I fixed it on my machine by closing the tab, force-closing Chrome, & restarting the browser without restoring tabs (Note: on a computer running CentOS Linux).
2) My boss (also on CentOS) had the same issue (alerts are a big part of my company's Javascript debugging process for numerous reasons e.g. legacy), but my 1st method didn't work for him. However, I managed to fix it for him with the following process:
a) Make an empty text file called FixChrome.sh, and paste in the following bash script:
#! /bin/bash
cd ~/.config/google-chrome/Default //adjust for your Chrome install location
rm Preferences
rm 'Current Session'
rm 'Current Tabs'
rm 'Last Session'
rm 'Last Tabs'
b) close Chrome, then open Terminal and run the script (bash FixChrome.sh).
It worked for him. Downside is that you lose all tabs from your current & previous session, but it's worth it if this matters to you.
Gson gson = new Gson();
Wrapper[] arr = gson.fromJson(str, Wrapper[].class);
class Wrapper{
int number;
String title;
}
Seems to work fine. But there is an extra ,
Comma in your string.
[
{
"number" : "3",
"title" : "hello_world"
},
{
"number" : "2",
"title" : "hello_world"
}
]
The answer was given already by either Sivasubramaniam Arunachalam or ch3ka.
I am just adding a performances view of the answer.
dicttest={}
dicttest['ligne1']={'ligne1.1':'test','ligne1.2':'test8'}
%timeit dicttest['ligne1']['ligne1.1']
%timeit dicttest.get('ligne1').get('ligne1.1')
gives us :
112 ns ± 29.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
235 ns ± 9.82 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Basically, if you specify a files
parameter (a dictionary), then requests
will send a multipart/form-data
POST instead of a application/x-www-form-urlencoded
POST. You are not limited to using actual files in that dictionary, however:
>>> import requests
>>> response = requests.post('http://httpbin.org/post', files=dict(foo='bar'))
>>> response.status_code
200
and httpbin.org lets you know what headers you posted with; in response.json()
we have:
>>> from pprint import pprint
>>> pprint(response.json()['headers'])
{'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'close',
'Content-Length': '141',
'Content-Type': 'multipart/form-data; '
'boundary=c7cbfdd911b4e720f1dd8f479c50bc7f',
'Host': 'httpbin.org',
'User-Agent': 'python-requests/2.21.0'}
Better still, you can further control the filename, content type and additional headers for each part by using a tuple instead of a single string or bytes object. The tuple is expected to contain between 2 and 4 elements; the filename, the content, optionally a content type, and an optional dictionary of further headers.
I'd use the tuple form with None
as the filename, so that the filename="..."
parameter is dropped from the request for those parts:
>>> files = {'foo': 'bar'}
>>> print(requests.Request('POST', 'http://httpbin.org/post', files=files).prepare().body.decode('utf8'))
--bb3f05a247b43eede27a124ef8b968c5
Content-Disposition: form-data; name="foo"; filename="foo"
bar
--bb3f05a247b43eede27a124ef8b968c5--
>>> files = {'foo': (None, 'bar')}
>>> print(requests.Request('POST', 'http://httpbin.org/post', files=files).prepare().body.decode('utf8'))
--d5ca8c90a869c5ae31f70fa3ddb23c76
Content-Disposition: form-data; name="foo"
bar
--d5ca8c90a869c5ae31f70fa3ddb23c76--
files
can also be a list of two-value tuples, if you need ordering and/or multiple fields with the same name:
requests.post(
'http://requestb.in/xucj9exu',
files=(
('foo', (None, 'bar')),
('foo', (None, 'baz')),
('spam', (None, 'eggs')),
)
)
If you specify both files
and data
, then it depends on the value of data
what will be used to create the POST body. If data
is a string, only it willl be used; otherwise both data
and files
are used, with the elements in data
listed first.
There is also the excellent requests-toolbelt
project, which includes advanced Multipart support. It takes field definitions in the same format as the files
parameter, but unlike requests
, it defaults to not setting a filename parameter. In addition, it can stream the request from open file objects, where requests
will first construct the request body in memory:
from requests_toolbelt.multipart.encoder import MultipartEncoder
mp_encoder = MultipartEncoder(
fields={
'foo': 'bar',
# plain file object, no filename or mime type produces a
# Content-Disposition header with just the part name
'spam': ('spam.txt', open('spam.txt', 'rb'), 'text/plain'),
}
)
r = requests.post(
'http://httpbin.org/post',
data=mp_encoder, # The MultipartEncoder is posted as data, don't use files=...!
# The MultipartEncoder provides the content-type header with the boundary:
headers={'Content-Type': mp_encoder.content_type}
)
Fields follow the same conventions; use a tuple with between 2 and 4 elements to add a filename, part mime-type or extra headers. Unlike the files
parameter, no attempt is made to find a default filename
value if you don't use a tuple.
One advantage your current approach does have is that it will raise an error if multiple rows are returned by the predicate. To reproduce that you can use.
SELECT @currentTerm = currentterm,
@termID = termid,
@endDate = enddate
FROM table1
WHERE iscurrent = 1
IF( @@ROWCOUNT <> 1 )
BEGIN
RAISERROR ('Unexpected number of matching rows',
16,
1)
RETURN
END
This is the simplest way I know to get the first day of the previous month:
Step 1: Move data to Postgres
Step 2:
select date_trunc('month', getdate()) - '1 MONTH'::interval;
You should use :
- (NSComparisonResult)compare:(NSDate *)anotherDate
to compare dates. There is no operator overloading in objective C.
That would be the tempfile module.
It has functions to get the temporary directory, and also has some shortcuts to create temporary files and directories in it, either named or unnamed.
Example:
import tempfile
print tempfile.gettempdir() # prints the current temporary directory
f = tempfile.TemporaryFile()
f.write('something on temporaryfile')
f.seek(0) # return to beginning of file
print f.read() # reads data back from the file
f.close() # temporary file is automatically deleted here
For completeness, here's how it searches for the temporary directory, according to the documentation:
TMPDIR
environment variable.TEMP
environment variable.TMP
environment variable.Wimp$ScrapDir
environment variable.C:\TEMP
, C:\TMP
, \TEMP
, and \TMP
, in that order./tmp
, /var/tmp
, and /usr/tmp
, in that order.Apple have changed the name of the certificate that is issued. You can now use the same certificate for both development and production. While you can still request a development only certificate you can no longer request a production only certificate.
C# developer working on Windows here. What works for me is simply download the file eng.traineddata from the following URL:
https://github.com/tesseract-ocr/tessdata/blob/master/eng.traineddata
and copy it to the following directory in my Console Application project:
[Project Directory]\bin\Debug\tessdata
I did manually create the tessdata folder above.
Thanks for all the contributions above. I would just like to share some additional information from my experiences while ignoring files.
When the folders are already under revision control
After svn import and svn co the files, what we usually do for the first time.
All runtime cache, attachments folders will be under version control. so, before svn ps svn:ignore, we need to delete it from the repository.
With SVN version 1.5 above we can use svn del --keep-local your_folder
,
but for an earlier version, my solution is:
.svn
hidden folder)When we need more than one folder to be ignored
svn:ignore
svn pe
will need to edit the text file, and you can use this command if required to set your text editor using vi:
export SVN_EDITOR=vi
The file looks something simply like this:
runtime
cache
attachments
assets
A simple answer would be : No, it doesn't
Explanation : According to the definition of unique constraints (SQL-92)
A unique constraint is satisfied if and only if no two rows in a table have the same non-null values in the unique columns
This statement can have two interpretations as :
NULL
and NULL
is not allowedNULL
and NULL
is fine, but StackOverflow
and StackOverflow
is not allowedSince MySQL follows second interpretation, multiple NULL
values are allowed in UNIQUE
constraint column. Second, if you would try to understand the concept of NULL
in SQL, you will find that two NULL
values can be compared at all since NULL
in SQL refers to unavailable or unassigned value (you can't compare nothing with nothing). Now, if you are not allowing multiple NULL
values in UNIQUE
constraint column, you are contracting the meaning of NULL
in SQL. I would summarise my answer by saying :
MySQL supports UNIQUE constraint but not on the cost of ignoring NULL values
The major concern here is that the collections don't keep the type in the definition. The types are only available in runtime. I came up with a function to test complex collections (it has one constraint though).
Check if the object is an instance of a generic collection. In order to represent a collection,
false
instanceof
evaluationList
or Set
, the type of the list comes next e.g. {List, Integer} for List<Integer>
Map
, the key and value types come next e.g. {Map, String, Integer} for Map<String, Integer>
More complex use cases could be generated using the same rules. For example in order to represent List<Map<String, GenericRecord>>
, it can be called as
Map<String, Integer> map = new HashMap<>();
map.put("S1", 1);
map.put("S2", 2);
List<Map<String, Integer> obj = new ArrayList<>();
obj.add(map);
isInstanceOfGenericCollection(obj, List.class, List.class, Map.class, String.class, GenericRecord.class);
Note that this implementation doesn't support nested types in the Map. Hence, the type of key and value should be a class and not a collection. But it shouldn't be hard to add it.
public static boolean isInstanceOfGenericCollection(Object object, Class<?>... classes) {
if (classes.length == 0) return false;
if (classes.length == 1) return classes[0].isInstance(object);
if (classes[0].equals(List.class))
return object instanceof List && ((List<?>) object).stream().allMatch(item -> isInstanceOfGenericCollection(item, Arrays.copyOfRange(classes, 1, classes.length)));
if (classes[0].equals(Set.class))
return object instanceof Set && ((Set<?>) object).stream().allMatch(item -> isInstanceOfGenericCollection(item, Arrays.copyOfRange(classes, 1, classes.length)));
if (classes[0].equals(Map.class))
return object instanceof Map &&
((Map<?, ?>) object).keySet().stream().allMatch(classes[classes.length - 2]::isInstance) &&
((Map<?, ?>) object).values().stream().allMatch(classes[classes.length - 1]::isInstance);
return false;
}
php_value memory_limit 30M
php_value post_max_size 100M
php_value upload_max_filesize 30M
Use all 3 in .htaccess
after everything at last line. php_value post_max_size
must be more than than the remaining two.
Array.filter( document.getElementsByClassName('appBanner'), function(elem){ elem.style.visibility = 'hidden'; });
Forked @http://jsfiddle.net/QVJXD/
`su -c "Your command right here" -s /bin/sh username`
The above command is correct, but on Red Hat if selinux is enforcing it will not allow cron to execute scripts as another user. example;
execl: couldn't exec /bin/sh
execl: Permission denied
I had to install setroubleshoot and setools and run the following to allow it:
yum install setroubleshoot setools
sealert -a /var/log/audit/audit.log
grep crond /var/log/audit/audit.log | audit2allow -M mypol
semodule -i mypol.p
You could use a couple approaches. First would be to use the strong tag
Here is an <strong>example of that tag</strong>.
Another approach would be to use the font-weight property. You can achieve inline, or via a class or id. Let's say you're using a class.
.className {
font-weight: bold;
}
Alternatively, you can also use a hard value for font-weight and most fonts support a value between 300 and 700, incremented by 100. For example, the following would be bold:
.className {
font-weight: 700;
}
Grepping the URL before and after might give you some peace of mind:
svn info | grep URL
URL: svn://svnrepo.rz.mycompany.org/repos/trunk/DataPortal
Relative URL: (...doesn't matter...)
And checking on your version (to be >1.7) to ensure, svn relocate
is the right thing to use:
svn --version
Lastly, adding to the above, if your repository url change also involves a change of protocol you might need to state the before and after url (also see here)
svn relocate svn://svnrepo.rz.mycompany.org/repos/trunk/DataPortal
https://svngate.mycompany.org/svn/repos/trunk/DataPortal
All in one single line of course.Thereafter, get the good feeling, that all went smoothly:
svn info | grep URL:
If you feel like it, a bit more of self-assurance, the new svn repo URL is connected and working:
svn status --show-updates
svn diff
The documentation says:
However, JUnit Jupiter’s
org.junit.jupiter.Assertions
class does not provide anassertThat()
method like the one found in JUnit 4’sorg.junit.Assert
class which accepts a HamcrestMatcher
. Instead, developers are encouraged to use the built-in support for matchers provided by third-party assertion libraries.
Example for Hamcrest:
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.jupiter.api.Test;
class HamcrestAssertionDemo {
@Test
void assertWithHamcrestMatcher() {
SubClass subClass = new SubClass();
assertThat(subClass, instanceOf(BaseClass.class));
}
}
Example for AssertJ:
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
class AssertJDemo {
@Test
void assertWithAssertJ() {
SubClass subClass = new SubClass();
assertThat(subClass).isInstanceOf(BaseClass.class);
}
}
Note that this assumes you want to test behaviors similar to instanceof
(which accepts subclasses). If you want exact equal type, I don’t see a better way than asserting the two class to be equal like you mentioned in the question.
What Harley said, except the last point - it's not actually necessary to change the '/'s into '\'s before calling open. Windows is quite happy to accept paths with forward slashes.
infile = open('c:/folder/subfolder/file.txt')
The only time you're likely to need the string normpathed is if you're passing to to another program via the shell (using os.system
or the subprocess
module).
Update: micro-optimizations like this one are just not worth it, engines are so smart these days that I would advice in the 2020 to simply just go with
var arr = [];
.
Here is how I would do it:
var mynumber = 10;
var arr = new Array(mynumber);
for (var i = 0; i < mynumber; i++) {
arr[i] = (i + 1).toString();
}
My answer is pretty much the same of everyone, but note that I did something different:
So I created the array with new Array(mynumber);
HTML
<div id="wrapper">
<div id="nav"></div>
<div id="content"></div>
<div class="clearFloat"></div>
</div>
CSS
.clearFloat {
font-size: 0px;
line-height: 0px;
margin: 0px;
padding: 0px;
clear: both;
height: 0px;
}
With join - interpreter will wait until your process get completed or terminated
>>> from threading import Thread
>>> import time
>>> def sam():
... print 'started'
... time.sleep(10)
... print 'waiting for 10sec'
...
>>> t = Thread(target=sam)
>>> t.start()
started
>>> t.join() # with join interpreter will wait until your process get completed or terminated
done? # this line printed after thread execution stopped i.e after 10sec
waiting for 10sec
>>> done?
without join - interpreter wont wait until process get terminated,
>>> t = Thread(target=sam)
>>> t.start()
started
>>> print 'yes done' #without join interpreter wont wait until process get terminated
yes done
>>> waiting for 10sec
Why does C# have both 'ref' and 'out'?
The caller of a method which takes an out parameter is not required to assign to the variable passed as the out parameter prior to the call; however, the callee is required to assign to the out parameter before returning.
In contrast ref parameters are considered initially assigned by the caller. As such, the callee is not required to assign to the ref parameter before use. Ref parameters are passed both into and out of a method.
So, out
means out, while ref
is for in and out.
These correspond closely to the [out]
and [in,out]
parameters of COM interfaces, the advantages of out
parameters being that callers need not pass a pre-allocated object in cases where it is not needed by the method being called - this avoids both the cost of allocation, and any cost that might be associated with marshaling (more likely with COM, but not uncommon in .NET).
An easy way to do this is to user "select
" and realize you can get a list of all columns
for the dataframe
, df
, with df.columns
drop_list = ['a column', 'another column', ...]
df.select([column for column in df.columns if column not in drop_list])
Before I respond to this question, I must explain to you the SERIALIZATION, because if you understand what it means serialization in science computer you can easily understand this keyword.
Serialization
When an object is transferred through the network / saved on physical media(file,...), the object must be "serialized". Serialization converts byte status object series. These bytes are sent on the network/saved and the object is re-created from these bytes.
Example
public class Foo implements Serializable
{
private String attr1;
private String attr2;
...
}
Now IF YOU WANT TO do NOT TRANSFERT/SAVED field of this object SO, you can use keyword transient
private transient attr2;
In this code you just need to call this in your button click.
private void list_paired_Devices() {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
ArrayList<String> devices = new ArrayList<>();
for (BluetoothDevice bt : pairedDevices) {
devices.add(bt.getName() + "\n" + bt.getAddress());
}
ArrayAdapter arrayAdapter = new ArrayAdapter(bluetooth.this, android.R.layout.simple_list_item_1, devices);
emp.setAdapter(arrayAdapter);
}
I found same question or related question on stackoverflow
Is there any way to change input type=“date” format?
I found one simple solution, You can not give particulate Format but you can customize Like this.
HTML Code:
<body>
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt" onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />
</body>
CSS Code:
#dt{text-indent: -500px;height:25px; width:200px;}
Javascript Code :
function mydate()
{
//alert("");
document.getElementById("dt").hidden=false;
document.getElementById("ndt").hidden=true;
}
function mydate1()
{
d=new Date(document.getElementById("dt").value);
dt=d.getDate();
mn=d.getMonth();
mn++;
yy=d.getFullYear();
document.getElementById("ndt").value=dt+"/"+mn+"/"+yy
document.getElementById("ndt").hidden=false;
document.getElementById("dt").hidden=true;
}
Output:
It can be easily done using html2canvas, try out the following,
try adding the div inside a html modal and call the model id using a jquery function. In the function you can specify the size (height, width) of the image to be displayed. Using modal is an easy way to capture a html div into an image in a button onclick.
for example have a look at the code sample,
`
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<div class="modal-body">
<p>Some text in the modal.</p>
`
paste the div, which you want to be displayed, inside the model. Hope it will help.
I fixed all my asp.net problems simply by creating a new user called IUSER with a password and added it the Network Service and User Groups. Then create all your virtual sites and applications set authentication to IUSER with its password.. set high level file access to include IUSER and BAM it fixed at least 3-4 issues including this one..
Dave
I am able to achieve subfolders by following the top answer to this question.
However, as the project grows bigger, you will have many sub-folders:
sourceSets {
main {
res.srcDirs =
[
'src/main/res/layouts/somethingA',
'src/main/res/layouts/somethingB',
'src/main/res/layouts/somethingC',
'src/main/res/layouts/somethingD',
'src/main/res/layouts/somethingE',
'src/main/res/layouts/somethingF',
'src/main/res/layouts/somethingG',
'src/main/res/layouts/somethingH',
'src/main/res/layouts/...many more',
'src/main/res'
]
}
}
Not a big problem, but:
app/build.gradle
everytime you add a new folder.So I wrote a simple Groovy method to grab all nested folders:
def getLayoutList(path) {
File file = new File(path)
def throwAway = file.path.split("/")[0]
def newPath = file.path.substring(throwAway.length() + 1)
def array = file.list().collect {
"${newPath}/${it}"
}
array.push("src/main/res");
return array
}
Paste this method outside of the android {...}
block in your app/build.gradle
.
For a structure like this:
<project root>
+-- app <---------- TAKE NOTE
+-- build
+-- build.gradle
+-- gradle
+-- gradle.properties
+-- gradlew
+-- gradlew.bat
+-- local.properties
+-- settings.gradle
Use it like this:
android {
sourceSets {
main {
res.srcDirs = getLayoutList("app/src/main/res/layouts/")
}
}
}
If you have a structure like this:
<project root>
+-- my_special_app_name <---------- TAKE NOTE
+-- build
+-- build.gradle
+-- gradle
+-- gradle.properties
+-- gradlew
+-- gradlew.bat
+-- local.properties
+-- settings.gradle
You will use it like this:
android {
sourceSets {
main {
res.srcDirs = getLayoutList("my_special_app_name/src/main/res/layouts/")
}
}
}
getLayoutList()
takes a relative path
as an argument. The relative path
is relative to the root of the project. So when we input "app/src/main/res/layouts/"
, it will return all the subfolders' name as an array, which will be exactly the same as:
[
'src/main/res/layouts/somethingA',
'src/main/res/layouts/somethingB',
'src/main/res/layouts/somethingC',
'src/main/res/layouts/somethingD',
'src/main/res/layouts/somethingE',
'src/main/res/layouts/somethingF',
'src/main/res/layouts/somethingG',
'src/main/res/layouts/somethingH',
'src/main/res/layouts/...many more',
'src/main/res'
]
Here's the script with comments for understanding:
def getLayoutList(path) {
// let's say path = "app/src/main/res/layouts/
File file = new File(path)
def throwAway = file.path.split("/")[0]
// throwAway = 'app'
def newPath = file.path.substring(throwAway.length() + 1) // +1 is for '/'
// newPath = src/main/res/layouts/
def array = file.list().collect {
// println "filename: ${it}" // uncomment for debugging
"${newPath}/${it}"
}
array.push("src/main/res");
// println "result: ${array}" // uncomment for debugging
return array
}
Hope it helps!
Just add this in your dependencies
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
Finally
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:design:23.0.1'
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
}
And also add this code:
android {
useLibrary 'org.apache.http.legacy'
}
FYI
Specify requirement for Apache HTTP Legacy library If your app is targeting API level 28 (Android 9.0) or above, you must include the following declaration within the element of AndroidManifest.xml.
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
$(document).ready(function() {
$(".tab").click(function () {
if(!$(this).hasClass('active'))
{
$(".tab.active").removeClass("active");
$(this).addClass("active");
}
});
});
iPhone:
Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25
iPad:
Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25
For a complete list and more details about the iOS user agent check out these 2 resources:
Safari User Agent Strings (http://useragentstring.com/pages/Safari/)
Complete List of iOS User-Agent Strings (http://enterpriseios.com/wiki/UserAgent)
ps -eo pid,cmd,lstart | grep YOUR-PID-HERE
You could use the isNaN Function. It returns true if the data is not a number. That would be something like that:
function checkInp()
{
var x=document.forms["myForm"]["age"].value;
if (isNaN(x)) // this is the code I need to change
{
alert("Must input numbers");
return false;
}
}
Note: isNan considers 10.2 as a valid number.