You can use coprocessor what is available since HBase 0.92. See Coprocessor and AggregateProtocol and example
Understanding in depth
Hadoop
Hadoop
is an open source project of the Apache
foundation. It is a framework written in Java
, originally developed by Doug Cutting in 2005. It was created to support distribution for Nutch
, the text search engine. Hadoop
uses Google's Map Reduce
and Google File System Technologies as its foundation.
Features of Hadoop
Hadoop
is for high throughput rather than low latency. It is a batch operation handling massive quantities of data; therefore the response time is not immediate.RDBMS
.Versions of Hadoop
There are two versions of Hadoop
available :
Hadoop 1.0
It has two main parts :
1. Data Storage Framework
It is a general-purpose file system called Hadoop Distributed File System (HDFS
).
HDFS
is schema-less
It simply stores data files and these data files can be in just about any format.
The idea is to store files as close to their original form as possible.
This in turn provides the business units and the organization the much needed flexibility and agility without being overly worried by what it can implement.
2. Data Processing Framework
This is a simple functional programming model initially popularized by Google as MapReduce
.
It essentially uses two functions: MAP
and REDUCE
to process data.
The "Mappers" take in a set of key-value pairs and generate intermediate data (which is another list of key-value pairs).
The "Reducers" then act on this input to produce the output data.
The two functions seemingly work in isolation with one another, thus enabling the processing to be highly distributed in highly parallel, fault-tolerance and scalable way.
Limitations of Hadoop 1.0
The first limitation was the requirement of MapReduce
programming expertise.
It supported only batch processing which although is suitable for tasks such as log analysis, large scale data mining projects but pretty much unsuitable for other kinds of projects.
One major limitation was that Hadoop 1.0
was tightly computationally coupled with MapReduce
, which meant that the established data management vendors where left with two opinions:
Either rewrite their functionality in MapReduce
so that it could be
executed in Hadoop
or
Extract data from HDFS
or process it outside of Hadoop
.
None of the options were viable as it led to process inefficiencies caused by data being moved in and out of the Hadoop
cluster.
Hadoop 2.0
In Hadoop 2.0
, HDFS
continues to be data storage framework.
However, a new and seperate resource management framework called Yet Another Resource Negotiater (YARN) has been added.
Any application capable of dividing itself into parallel tasks is supported by YARN.
YARN coordinates the allocation of subtasks of the submitted application, thereby further enhancing the flexibility, scalability and efficiency of applications.
It works by having an Application Master in place of Job Tracker, running applications on resources governed by new Node Manager.
ApplicationMaster is able to run any application and not just MapReduce
.
This means it does not only support batch processing but also real-time processing. MapReduce
is no longer the only data processing option.
Advantages of Hadoop
It stores data in its native from. There is no structure imposed while keying in data or storing data. HDFS
is schema less. It is only later when the data needs to be processed that the structure is imposed on the raw data.
It is scalable. Hadoop
can store and distribute very large datasets across hundreds of inexpensive servers that operate in parallel.
It is resilient to failure. Hadoop
is fault tolerance. It practices replication of data diligently which means whenever data is sent to any node, the same data also gets replicated to other nodes in the cluster, thereby ensuring that in event of node failure,there will always be another copy of data available for use.
It is flexible. One of the key advantages of Hadoop
is that it can work with any kind of data: structured, unstructured or semi-structured. Also, the processing is extremely fast in Hadoop
owing to the "move code to data" paradigm.
Hadoop Ecosystem
Following are the components of Hadoop
ecosystem:
HDFS: Hadoop
Distributed File System. It simply stores data files as close to the original form as possible.
HBase: It is Hadoop's database and compares well with an RDBMS
. It supports structured data storage for large tables.
Hive: It enables analysis of large datasets using a language very similar to standard ANSI SQL
, which implies that anyone familier with SQL
should be able to access data on a Hadoop
cluster.
Pig: It is an easy to understand data flow language. It helps with analysis of large datasets which is quite the order with Hadoop
. Pig
scripts are automatically converted to MapReduce
jobs by the Pig
interpreter.
ZooKeeper: It is a coordination service for distributed applications.
Oozie: It is a workflow schedular
system to manage Apache Hadoop
jobs.
Mahout: It is a scalable machine learning and data mining library.
Chukwa: It is data collection system for managing large distributed system.
Sqoop: It is used to transfer bulk data between Hadoop
and structured data stores such as relational databases.
Ambari: It is a web based tool for provisioning, managing and monitoring Hadoop
clusters.
Hive
Hive
is a data warehouse infrastructure tool to process structured data in Hadoop
. It resides on top of Hadoop
to summarize Big Data and makes querying and analyzing easy.
Hive is not
A relational database
A design for Online Transaction Processing (OLTP
).
A language for real-time queries and row-level updates.
Features of Hive
It stores schema in database and processed data into HDFS
.
It is designed for OLAP
.
It provides SQL
type language for querying called HiveQL
or HQL
.
It is familier, fast, scalable and extensible.
Hive Architecture
The following components are contained in Hive Architecture:
User Interface: Hive
is a data warehouse
infrastructure that can create interaction between user and HDFS
. The User Interfaces that Hive
supports are Hive Web UI, Hive Command line and Hive HD Insight(In Windows Server).
MetaStore: Hive
chooses respective database
servers
to store the schema or Metadata
of tables, databases, columns in a table, their data types and HDFS
mapping.
HiveQL Process Engine: HiveQL
is similar to SQL
for querying on schema info on the Metastore
. It is one of the replacements of traditional approach for MapReduce
program. Instead of writing MapReduce
in Java
, we can write a query for MapReduce
and process it.
Exceution Engine: The conjunction part of HiveQL
process engine and MapReduce
is the Hive
Execution Engine. Execution engine processes the query and generates results as same as MapReduce results
. It uses the flavor of MapReduce
.
HDFS or HBase: Hadoop
Distributed File System or HBase
are the data storage techniques to store data into file system.
keep the delimiter in single quotes it will work.
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n';
This will work
If you want to clean up Solr index -
you can fire http url -
http://host:port/solr/[core name]/update?stream.body=<delete><query>*:*</query></delete>&commit=true
(replace [core name]
with the name of the core you want to delete from). Or use this if posting data xml data:
<delete><query>*:*</query></delete>
Be sure you use commit=true
to commit the changes
Don't have much idea with clearing hbase data though.
For Vuejs 2.5 & vue-router 3.0 nothing above worked for me, however after playing around a little bit the following seems to work:
export default new Router({
mode: 'history',
hash: false,
routes: [
...
,
{ path: '*', redirect: '/' }, // catch all use case
],
})
note that you will also need to add the catch-all path.
The permament pool contains everything that is not your application data, but rather things required for the VM: typically it contains interned strings, the byte code of defined classes, but also other "not yours" pieces of data.
See this. Your code would be something like the following:
from django.db.models import Max
# Generates a "SELECT MAX..." query
Argument.objects.aggregate(Max('rating')) # {'rating__max': 5}
You can also use this on existing querysets:
from django.db.models import Max
args = Argument.objects.filter(name='foo') # or whatever arbitrary queryset
args.aggregate(Max('rating')) # {'rating__max': 5}
If you need the model instance that contains this max value, then the code you posted is probably the best way to do it:
arg = args.order_by('-rating')[0]
Note that this will error if the queryset is empty, i.e. if no arguments match the query (because the [0]
part will raise an IndexError
). If you want to avoid that behavior and instead simply return None
in that case, use .first()
:
arg = args.order_by('-rating').first() # may return None
I think this should work.
UPDATE QuestionTrackings
SET QuestionID = (SELECT QuestionID
FROM AnswerTrackings
WHERE AnswerTrackings.AnswerID = QuestionTrackings.AnswerID)
WHERE QuestionID IS NULL
AND AnswerID IS NOT NULL;
Also you can use Android Debug Bridge (adb) to copy your file from Android device to folder on your PC:
adb pull /storage/emulated/0/AudioRecorder/1436854479696.mp4 <folder_on_your_PC_e.g. c:/temp>
And you can copy from device whole AudioRecorder
folder:
adb pull /storage/emulated/0/AudioRecorder <folder_on_your_PC_e.g. c:/temp>
You can try this
- (NSString *)stripRemoveSpaceFrom:(NSString *)str {
while ([str rangeOfString:@" "].location != NSNotFound) {
str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
}
return str;
}
Hope this will help you out.
Simplest:
Form form = new Form();
form.add("id", "1");
form.add("name", "supercobra");
ClientResponse response = webResource
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(ClientResponse.class, form);
First you should understand how localStorage works. you are doing wrong way to set/get values in local storage. Please read this for more information : How to Use Local Storage with JavaScript
This should give you the roles, users and permissions granted on a directory:
SELECT *
FROM all_tab_privs
WHERE table_name = 'your_directory'; --> needs to be upper case
And yes, it IS in the all_TAB_privs view ;-) A better name for that view would be something like "ALL_OBJECT_PRIVS", since it also includes PL/SQL objects and their execute permissions as well.
Setting adjustViewBounds to true and using a LinearLayout view group worked very well for me. No need to subclass or ask for device metrics:
//NOTE: "this" is a subclass of LinearLayout
ImageView splashImageView = new ImageView(context);
splashImageView.setImageResource(R.drawable.splash);
splashImageView.setAdjustViewBounds(true);
addView(splashImageView);
It would be the highest available priority setting, and would usually only be used on box that was dedicated to running that specific program. It's actually high enough that it could cause starvation of the keyboard and mouse threads to the extent that they become unresponsive.
So basicly, if you have to ask, don't use it :)
The answer is not simple:
It depends on the target machines (mobile vs desktop), it depends on the nature of your data, the browser, the OS, the hardware it runs on... you will need to benchmark if you really want to know.
It is mostly a memory vs computation problem ... as with most performance issues the difference can become significant with repeated elements (n) like lists, especially when nested (n x n, or worse) and also what kind of computations you run inside these elements:
ng-show: If those optional elements are often present (dense), like say 90% of the time, it may be faster to have them ready and only show/hide them, especially if their content is cheap (just plain text, nothing to compute or load). This consumes memory as it fills the DOM with hidden elements, but just show/hide something which already exists is likely to be a cheap operation for the browser.
ng-if: If on the contrary elements are likely not to be shown (sparse) just build them and destroy them in real time, especially if their content is expensive to get (computations/sorted/filtered, images, generated images). This is ideal for rare or 'on-demand' elements, it saves memory in terms of not filling the DOM but can cost a lot of computation (creating/destroying elements) and bandwidth (getting remote content). It also depends on how much you compute in the view (filtering/sorting) vs what you already have in the model (pre-sorted/pre-filtered data).
You can use display: inline-block
.
As an alternative approach to trying to parse the string and catching NumberFormatException
, you could use a regex; e.g.
if (Pattern.compile("-?[0-9]+").matches(str)) {
// its an integer
}
This is likely to be faster, especially if you precompile and reuse the regex.
However, the problem with this approach is that Integer.parseInt(str)
will also fail if str
represents a number that is outside range of legal int
values. While it is possible to craft a regex that only matches integers in the range Integer.MIN_INT
to Integer.MAX_INT
, it is not a pretty sight. (And I am not going to try it ...)
On the other hand ... it may be acceptable to treat "not an integer" and "integer too large" separately for validation purposes.
array_values does the job :
$myArray = array_values($myArray);
Also some other php function do not preserve the keys, i.e. reset the index.
You're offsetting the shadow, so to get it to uniformly surround the box, don't offset it:
-moz-box-shadow: 0 0 3px #ccc;
-webkit-box-shadow: 0 0 3px #ccc;
box-shadow: 0 0 3px #ccc;
Try this:
If (($x !~ /\D/) && ($x ne "")) { ... }
The following worked for me (Windows 7):
oradim -shutdown -sid enter_sid_here
oradim -startup -sid enter_sid_here
(with enter_sid_here
replaced by the SID)
I use a few methods depending. In the same stylesheet i use: @media (max-width: 450px), or for separate make sure you have the link in the header correctly. I had a look at your fixmeup and you have a confusing array of links to css. It acts as you say also on HTC desire S.
Essentially the same as Gringo Suave's answer, but with a generator:
from datetime import datetime, timedelta
def datetime_range(start=None, end=None):
span = end - start
for i in xrange(span.days + 1):
yield start + timedelta(days=i)
Then you can use it as follows:
In: list(datetime_range(start=datetime(2014, 1, 1), end=datetime(2014, 1, 5)))
Out:
[datetime.datetime(2014, 1, 1, 0, 0),
datetime.datetime(2014, 1, 2, 0, 0),
datetime.datetime(2014, 1, 3, 0, 0),
datetime.datetime(2014, 1, 4, 0, 0),
datetime.datetime(2014, 1, 5, 0, 0)]
Or like this:
In []: for date in datetime_range(start=datetime(2014, 1, 1), end=datetime(2014, 1, 5)):
...: print date
...:
2014-01-01 00:00:00
2014-01-02 00:00:00
2014-01-03 00:00:00
2014-01-04 00:00:00
2014-01-05 00:00:00
-Dspring.profiles.active=staging -Dspring.config.location=C:\Config
is not correct.
should be:
--spring.profiles.active=staging --spring.config.location=C:\Config
you can use the isUserInRole method of the HttpServletRequest object.
something like:
public String createForm(HttpSession session, HttpServletRequest request, ModelMap modelMap) {
if (request.isUserInRole("ROLE_ADMIN")) {
// code here
}
}
You can use MemberwiseClone
obj myobj2 = (obj)myobj.MemberwiseClone();
The copy is a shallow copy which means the reference properties in the clone are pointing to the same values as the original object but that shouldn't be an issue in your case as the properties in obj
are of value types.
If you own the source code, you can also implement ICloneable
For my use-case I was able to simply pipe to grep.
pg_dump -U user_name --data-only --column-inserts -t nyummy.cimory | grep "tokyo" > tokyo.sql
The only way to remove the ADT plugin from Eclipse is to go to Help > About Eclipse/About ADT > Installation Details
.
Select a plug-in you want to uninstall, then click Uninstall...
button at the bottom.
If you cannot remove ADT from this location, then your best option is probably to start fresh with a clean Eclipse install.
I think I'd do it as simply as:
public static int safeLongToInt(long l) {
if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
throw new IllegalArgumentException
(l + " cannot be cast to int without changing its value.");
}
return (int) l;
}
I think that expresses the intent more clearly than the repeated casting... but it's somewhat subjective.
Note of potential interest - in C# it would just be:
return checked ((int) l);
By typing 'jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10'
in Anaconda
PowerShell
or prompt, the Jupyter notebook will open with the new configuration. Try now to run your query.
navigator.app.exitApp();
add this line where you want you exit the application.
From MSDN -
CollectionViewSource.GetDefaultView(myGrid.ItemsSource).Refresh();
var name = from DataRow dr in tblClassCode.Rows where (long)dr["ID"] == Convert.ToInt32(i) select (int)dr["Name"]).FirstOrDefault().ToString()
I got the solution for onunload
in all browsers except Opera by changing the Ajax asynchronous request into synchronous request.
xmlhttp.open("POST","LogoutAction",false);
It works well for all browsers except Opera.
JavaScript doesn't have associate arrays. You need to use Objects instead:
var obj = {};
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);?
To get value you can use now different ways:
console.log(obj.name);?
console.log(obj[name]);?
console.log(obj["name"]);?
I like assylias' answer, however I would refactor it as follows:
Sub test()
Dim origNum As String
Dim creditOrDebit As String
origNum = "30062600006"
creditOrDebit = "D"
If creditOrDebit = "D" Then
If origNum = "006260006" Then
MsgBox "OK"
ElseIf origNum = "30062600006" Then
MsgBox "OK"
End If
End If
End Sub
This might save you some CPU cycles since if creditOrDebit
is <> "D"
there is no point in checking the value of origNum
.
I used the following procedure to test my theory that my procedure is faster:
Public Declare Function timeGetTime Lib "winmm.dll" () As Long
Sub DoTests2()
Dim startTime1 As Long
Dim endTime1 As Long
Dim startTime2 As Long
Dim endTime2 As Long
Dim i As Long
Dim msg As String
Const numberOfLoops As Long = 10000
Const origNum As String = "006260006"
Const creditOrDebit As String = "D"
startTime1 = timeGetTime
For i = 1 To numberOfLoops
If creditOrDebit = "D" Then
If origNum = "006260006" Then
' do something here
Debug.Print "OK"
ElseIf origNum = "30062600006" Then
' do something here
Debug.Print "OK"
End If
End If
Next i
endTime1 = timeGetTime
startTime2 = timeGetTime
For i = 1 To numberOfLoops
If (origNum = "006260006" Or origNum = "30062600006") And _
creditOrDebit = "D" Then
' do something here
Debug.Print "OK"
End If
Next i
endTime2 = timeGetTime
msg = "number of iterations: " & numberOfLoops & vbNewLine
msg = msg & "JP proc: " & Format$((endTime1 - startTime1), "#,###") & _
" ms" & vbNewLine
msg = msg & "assylias proc: " & Format$((endTime2 - startTime2), "#,###") & _
" ms"
MsgBox msg
End Sub
I must have a slow computer because 1,000,000 iterations took nowhere near ~200 ms as with assylias' test. I had to limit the iterations to 10,000 -- hey, I have other things to do :)
After running the above procedure 10 times, my procedure is faster only 20% of the time. However, when it is slower it is only superficially slower. As assylias pointed out, however, when creditOrDebit
is <>"D"
, my procedure is at least twice as fast. I was able to reasonably test it at 100 million iterations.
And that is why I refactored it - to short-circuit the logic so that origNum
doesn't need to be evaluated when creditOrDebit <> "D"
.
At this point, the rest depends on the OP's spreadsheet. If creditOrDebit
is likely to equal D, then use assylias' procedure, because it will usually run faster. But if creditOrDebit
has a wide range of possible values, and D
is not any more likely to be the target value, my procedure will leverage that to prevent needlessly evaluating the other variable.
Check every each value by a for loop once you checked the size of the array.
function equalArray(a, b) {
if (a.length === b.length) {
for (var i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
} else {
return false;
}
}
Some permissions issue for default sample.
I wanted to see how it works, I am creating the first extension, so I downloaded a simpler one.
Downloaded 'Typed URL History' sample from
https://developer.chrome.com/extensions/examples/api/history/showHistory.zip
which can be found at
https://developer.chrome.com/extensions/samples
this worked great, hope it helps
You can use dummynet ofcourse, There is extension of dummynet called KauNet. which can provide even more precise control of network conditions. It can drop/delay/re-order specific packets (that way you can perform more in-depth analysis of dropping key packets like TCP handshake to see how your web pages digest it). It also works in time domain. Usually most the emulators are tuned to work in data domain. In time domain you can specify from what time to what time you can alter the network conditions.
Because of historical reasons going back to the very first version of C, functions are assumed to have an implicit definition of int function(int arg1, int arg2, int arg3, etc)
.
Edit: no, I was wrong about int
for the arguments. Instead it passes whatever type the argument is. So it could be an int
or a double
or a char*
. Without a prototype the compiler will pass whatever size the argument is and the function being called had better use the correct argument type to receive it.
For more details look up K&R C
.
Asynchronous downloaded images with caching
Asynchronous downloaded images with caching
Here is one more repos which can be used to download images in background
According to wikipedia article on status codes. Nginx has a custom error code when http traffic is sent to https port(error code 497)
And according to nginx docs on error_page, you can define a URI that will be shown for a specific error.
Thus we can create a uri that clients will be sent to when error code 497 is raised.
#lets assume your IP address is 89.89.89.89 and also
#that you want nginx to listen on port 7000 and your app is running on port 3000
server {
listen 7000 ssl;
ssl_certificate /path/to/ssl_certificate.cer;
ssl_certificate_key /path/to/ssl_certificate_key.key;
ssl_client_certificate /path/to/ssl_client_certificate.cer;
error_page 497 301 =307 https://89.89.89.89:7000$request_uri;
location / {
proxy_pass http://89.89.89.89:3000/;
proxy_pass_header Server;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Protocol $scheme;
}
}
However if a client makes a request via any other method except a GET, that request will be turned into a GET. Thus to preserve the request method that the client came in via; we use error processing redirects as shown in nginx docs on error_page
And thats why we use the 301 =307
redirect.
Using the nginx.conf file shown here, we are able to have http and https listen in on the same port
Per above, a dataset or typed dataset might be a good temorary structure which you could use to do your filtering. A SqlDataReader is meant to read the data very quickly. While you are in the while() loop you are still connected to the DB and it is waiting for you to do whatever you are doing in order to read/process the next result before it moves on. In this case you might get better performance if you pull in all of the data, close the connection to the DB and process the results "offline".
People seem to hate datasets, so the above could be done wiht a collection of strongly typed objects as well.
I was looking into this because R was having issues installing into the default location and was instead just putting the packages into the temp folder. It turned out to be the latest update for Mcaffee Endpoint Security which apparently has issues with R. You can disable the threat protection while you install the packages and it will work properly.
As of 2021 insted of null i had to add {} in order to make it work!
axios.post(
url,
{},
{
params: {
key,
checksum
}
}
)
.then(response => {
return success(response);
})
.catch(error => {
return fail(error);
});
This happens because $cOTLdata
is not null but the index 'char_data'
does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.
To check whether the index exists or not you can use isset():
isset($cOTLdata['char_data'])
Which means the line should look something like this:
$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;
Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).
public class UserInfo {
String LoginId;
String Password;
String FirstName;
String LastName;
String Email;
String Mobile;
String Address;
String DOB;
public String getLoginId() {
return LoginId;
}
public void setLoginId(String loginId) {
LoginId = loginId;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getMobile() {
return Mobile;
}
public void setMobile(String mobile) {
Mobile = mobile;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
public String getDOB() {
return DOB;
}
public void setDOB(String DOB) {
this.DOB = DOB;
}
}
The syntax of the query is as follows:
Alter table <table name> rename column <column name> to <new column name>;
Example:
Alter table employee rename column eName to empName;
To rename a column name without space to a column name with space:
Alter table employee rename column empName to "Emp Name";
To rename a column with space to a column name without space:
Alter table employee rename column "emp name" to empName;
if you have permission then
Alias /favicon.ico /var/www/aktel/workspace1/PyBot/PyBot/static/favicon.ico
add alias to your virtual host. (in apache config file ) similarly for robots.txt
Alias /robots.txt /var/www/---your path ---/PyBot/robots.txt
The easiest way to install it is using Homebrew:
brew install jmeter
Or if you need plugins also:
brew install jmeter --with-plugins
And to open it, use the following command (since it doesn't appear in your Applications):
open /usr/local/bin/jmeter
As many folks here have mentioned, a mutex is used to protect a critical piece of code (AKA critical section.) You will acquire the mutex (lock), enter critical section, and release mutex (unlock) all in the same thread.
While using a semaphore, you can make a thread wait on a semaphore (say thread A), until another thread (say thread B)completes whatever task, and then sets the Semaphore for thread A to stop the wait, and continue its task.
Try this,to retrieve all files inside folder and sub-folder
public static void main(String[]args)
{
File curDir = new File(".");
getAllFiles(curDir);
}
private static void getAllFiles(File curDir) {
File[] filesList = curDir.listFiles();
for(File f : filesList){
if(f.isDirectory())
getAllFiles(f);
if(f.isFile()){
System.out.println(f.getName());
}
}
}
To retrieve files/folder only
public static void main(String[]args)
{
File curDir = new File(".");
getAllFiles(curDir);
}
private static void getAllFiles(File curDir) {
File[] filesList = curDir.listFiles();
for(File f : filesList){
if(f.isDirectory())
System.out.println(f.getName());
if(f.isFile()){
System.out.println(f.getName());
}
}
}
CROSS JOIN = (INNER) JOIN = comma (",")
TL;DR The only difference between SQL CROSS JOIN, (INNER) JOIN and comma (",") (besides comma having lower precedence for evaluation order) is that (INNER) JOIN has an ON while CROSS JOIN and comma don't.
Re intermediate products
All three produce an intermediate conceptual SQL-style relational "Cartesian" product, aka cross join, of all possible combinations of a row from each table. It is ON and/or WHERE that reduce the number of rows. SQL Fiddle
The SQL Standard defines <comma> via product (7.5 1.b.ii), <cross join> aka CROSS JOIN via <comma> (7.7 1.a) and (INNER) JOIN ON <search condition> via <comma> plus WHERE (7.7 1.b).
As Wikipedia puts it:
Cross join
CROSS JOIN returns the Cartesian product of rows from tables in the join. In other words, it will produce rows which combine each row from the first table with each row from the second table.
Inner join
[...] The result of the join can be defined as the outcome of first taking the Cartesian product (or Cross join) of all records in the tables (combining every record in table A with every record in table B) and then returning all records which satisfy the join predicate.
The "implicit join notation" simply lists the tables for joining, in the FROM clause of the SELECT statement, using commas to separate them. Thus it specifies a cross join
Re OUTER JOIN see my answer What is the difference between “INNER JOIN” and “OUTER JOIN”?.
Re OUTER JOINs and using ON vs WHERE in them see my answer Conditions in LEFT JOIN (OUTER JOIN) vs INNER JOIN.
Why compare columns between tables?
When there are no duplicate rows:
Every table holds the rows that make a true statement from a certain fill-in-the-[named-]blanks statement template. (It makes a true proposition from--satisfies--a certain (characteristic) predicate.)
A base table holds the rows that make a true statement from some DBA-given statement template:
/* rows where
customer C.CustomerID has age C.Age and ...
*/
FROM Customers C
A join's intermediate product holds the rows that make a true statement from the AND of its operands' templates:
/* rows where
customer C.CustomerID has age C.Age and ...
AND movie M.Movie is rented by customer M.CustomerID and ...
*/
FROM Customers C CROSS JOIN Movies M
ON & WHERE conditions are ANDed in to give a further template. The value is again the rows that satisfy that template:
/* rows where
customer C.CustomerID has age C.Age and ...
AND movie M.Movie is rented by customer M.CustomerID and ...
AND C.CustomerID = M.CustomerID
AND C.Age >= M.[Minimum Age]
AND C.Age = 18
*/
FROM Customers C INNER JOIN Movies M
ON C.CustomerID = M.CustomerID
AND C.Age >= M.[Minimum Age]
WHERE C.Age = 18
In particular, comparing columns for (SQL) equality between tables means that the rows kept from the product from the joined tables' parts of the template have the same (non-NULL) value for those columns. It's just coincidental that a lot of rows are typically removed by equality comparisons between tables--what is necessary and sufficient is to characterize the rows you want.
Just write SQL for the template for the rows you want!
Re the meaning of queries (and tables vs conditions) see:
How to get matching data from another SQL table for two different columns: Inner Join and/or Union?
Is there any rule of thumb to construct SQL query from a human-readable description?
Overloading "cross join"
Unfortunately the term "cross join" gets used for:
These various meanings get confounded. (Eg as in other answers and comments here.)
Using CROSS JOIN vs (INNER) JOIN vs comma
The common convention is:
Typically also conditions not on pairs of tables are kept for a WHERE. But they may have to be put in a(n INNER) JOIN ON to get appropriate rows for the argument to a RIGHT, LEFT or FULL (OUTER) JOIN.
Re "Don't use comma" Mixing comma with explicit JOIN can mislead because comma has lower precedence. But given the role of the intermediate product in the meaning of CROSS JOIN, (INNER) JOIN and comma, arguments for the convention above of not using it at all are shaky. A CROSS JOIN or comma is just like an (INNER) JOIN that's ON a TRUE condition. An intermediate product, ON and WHERE all introduce an AND in the corresponding predicate. However else INNER JOIN ON can be thought of--say, generating an output row only when finding a pair of input rows that satisfies the ON condition--it nevertheless returns the cross join rows that satisfy the condition. The only reason ON had to supplement comma in SQL was to write OUTER JOINs. Of course, an expression should make its meaning clear; but what is clear depends on what things are taken to mean.
Re Venn diagrams A Venn diagram with two intersecting circles can illustrate the difference between output rows for INNER, LEFT, RIGHT & FULL JOINs for the same input. And when the ON is unconditionally TRUE, the INNER JOIN result is the same as CROSS JOIN. Also it can illustrate the input and output rows for INTERSECT, UNION & EXCEPT. And when both inputs have the same columns, the INTERSECT result is the same as for standard SQL NATURAL JOIN, and the EXCEPT result is the same as for certain idioms involving LEFT & RIGHT JOIN. But it does not illustrate how (INNER) JOIN works in general. That just seems plausible at first glance. It can identify parts of input and/or output for special cases of ON, PKs (primary keys), FKs (foreign keys) and/or SELECT. All you have to do to see this is to identify what exactly are the elements of the sets represented by the circles. (Which muddled presentations never make clear.) Remember that in general for joins output rows have different headings from input rows. And SQL tables are bags not sets of rows with NULLs.
xcopy "C:\SomeFolderName" "D:\SomeFolderName" /h /i /c /k /e /r /y
Use the above command. It will definitely work.
In this command data will be copied from c:\ to D:\, even folders and system files as well. Here's what the flags do:
/h
copies hidden and system files also/i
if destination does not exist and copying more than one file, assume that destination must be a directory/c
continue copying even if error occurs/k
copies attributes/e
copies directories and subdirectories, including empty ones/r
overwrites read-only files/y
suppress prompting to confirm whether you want to overwrite a fileYou could do either:
dirname(__DIR__);
Or:
__DIR__ . '/..';
...but in a web server environment you will probably find that you are already working from current file's working directory, so you can probably just use:
'../'
...to reference the directory above. You can replace __DIR__
with dirname(__FILE__)
before PHP 5.3.0.
You should also be aware what __DIR__
and __FILE__
refers to:
The full path and filename of the file. If used inside an include, the name of the included file is returned.
So it may not always point to where you want it to.
You have some options to handle this deprecation the right (and future proof) way, depending on which kind of drawable you are loading:
A) drawables with theme attributes
ContextCompat.getDrawable(getActivity(), R.drawable.name);
You'll obtain a styled Drawable as your Activity theme instructs. This is probably what you need.
B) drawables without theme attributes
ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);
You'll get your unstyled drawable the old way. Please note: ResourcesCompat.getDrawable()
is not deprecated!
EXTRA) drawables with theme attributes from another theme
ResourcesCompat.getDrawable(getResources(), R.drawable.name, anotherTheme);
The differences are becoming fewer and less important. Traditionally, scripting languages extend existing programs... I think that's the main definition of "scripting" is that it refers to writing a set of instructions for an existing entity to perform. However, where scripting languages started with proprietary and colloquial syntax, most of the prevalent ones these days owe some relationship to C.
I think the "interpreted vs compiled" distinction is really a symptom of extending an existing program (with a built in interpreter), rather than an intrinsic difference. What programmers and laymen are more concerned about is, "what is the programmer doing?" The fact that one program is interpreted and another is compiled means very little in determining the difference in activity by the creator. You don't judge a playwright on whether his plays are more commonly read aloud or performed on stage, do you?
Update (2010/10/01): Yesss, Sun Java Finally Uploaded To The Ubuntu 10.10 Maverick Official Partner Repository.
Update (2010/09/27): Readers might want to check Sun Java6 Packages [updated]. I still expect official packages to be available in the partner repos at releast time though.
For an unknown reason, the sun-java6-jdk are not yet available in the partner repositories.
So either downloaded the required packages from http://archive.canonical.com/pool/partner/s/sun-java6/ and install them with dpkg -i
.
Or temporarily replace the maverick partner repository
http://archive.canonical.com/ubuntu maverick partner
by the lucid one (replace maverick
by lucid
in the above line, let me know if you need more help to do this). Then, install sun-java6. And revert the change.
A few practical facts that might be useful to decide which event to handle (run the script below and focus on the input box):
$('input').on('keyup keydown keypress',e=>console.log(e.type, e.keyCode, e.which, e.key))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input/>
_x000D_
Pressing:
non inserting/typing keys (e.g. Shift, Ctrl) will not trigger a keypress
. Press Ctrl and release it:
keydown 17 17 Control
keyup 17 17 Control
keys from keyboards that apply characters transformations to other characters may lead to Dead and duplicate "keys" (e.g. ~, ´) on keydown
. Press ´ and release it in order to display a double ´´
:
keydown 192 192 Dead
keydown 192 192 ´´
keypress 180 180 ´
keypress 180 180 ´
keyup 192 192 Dead
Additionally, non typing inputs (e.g. ranged <input type="range">
) will still trigger all keyup, keydown and keypress events according to the pressed keys.
I had this error when trying to save an entity through JPA.
It was because I had a column with @JoinColumn
annotation that didn't have @ManyToOne
annotation.
Adding @ManyToOne
fixed the issue.
If you need for espresso test the solutions is like this :
onView(withId(id)).check(matches(isChecked()));
Bye,
With xidel:
curl <...> | xidel - -se '$json'
xidel
can probably retrieve the JSON for you as well.
"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.
Check that you don't send ANY content before calling session_start
. Better yet, just make session_start
the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).
Provide the data frame and a string of comma separated names to remove:
remove_features <- function(df, features) {
rem_vec <- unlist(strsplit(features, ', '))
res <- df[,!(names(df) %in% rem_vec)]
return(res)
}
Usage:
remove_features(iris, "Sepal.Length, Petal.Width")
I eventually stumbled upon an example of the usage I was looking for - to assign an error to the Model in general, rather than one of it's properties, as usual you call:
ModelState.AddModelError(string key, string errorMessage);
but use an empty string for the key:
ModelState.AddModelError(string.Empty, "There is something wrong with Foo.");
The error message will present itself in the <%: Html.ValidationSummary() %>
as you'd expect.
I was looking solution for my Ionic Cordova app push notification.
Thanks to Syed Rafay's answer.
in app.component.ts
const options: PushOptions = {
android: {
topics: ['all']
},
in Server file
"to" => "/topics/all",
use Jquery or something here is example
of it http://riderdesign.com/articles/Check-username-availability-with-JQuery-and-ASP.NET.aspx i hope i will help you more
If you are going to output the lines anyway, you could run the output through the sort command. Not elegant, but it does not require much work:
cscript.exe //nologo YOUR-SCRIPT | Sort
Note //nologo omits the logo lines (Microsoft (R) Windows Script Host Version... blah blah blah) from appearing in the middle of your sorted output. (I guess MS does not know what stderr is for.)
See http://ss64.com/nt/sort.html for details on sort.
/+n is the most useful option if your sort key does not start in the first column.
Compares are always case-insensitive, which is lame.
I found the example class posted by @emmby above to be a great starting point. But it has a couple of flaws, as mentioned by other posters. The major one is that it persists the UUID to an XML file unnecessarily and thereafter always retrieves it from this file. This lays the class open to an easy hack: anyone with a rooted phone can edit the XML file to give themselves a new UUID.
I've updated the code so that it only persists to XML if absolutely necessary (i.e. when using a randomly generated UUID) and re-factored the logic as per @Brill Pappin's answer:
import android.content.Context;
import android.content.SharedPreferences;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import java.io.UnsupportedEncodingException;
import java.util.UUID;
public class DeviceUuidFactory {
protected static final String PREFS_FILE = "device_id.xml";
protected static final String PREFS_DEVICE_ID = "device_id";
protected static UUID uuid;
public DeviceUuidFactory(Context context) {
if( uuid ==null ) {
synchronized (DeviceUuidFactory.class) {
if( uuid == null) {
final SharedPreferences prefs = context.getSharedPreferences( PREFS_FILE, 0);
final String id = prefs.getString(PREFS_DEVICE_ID, null );
if (id != null) {
// Use the ids previously computed and stored in the prefs file
uuid = UUID.fromString(id);
} else {
final String androidId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
// Use the Android ID unless it's broken, in which case fallback on deviceId,
// unless it's not available, then fallback on a random number which we store
// to a prefs file
try {
if ( "9774d56d682e549c".equals(androidId) || (androidId == null) ) {
final String deviceId = ((TelephonyManager) context.getSystemService( Context.TELEPHONY_SERVICE )).getDeviceId();
if (deviceId != null)
{
uuid = UUID.nameUUIDFromBytes(deviceId.getBytes("utf8"));
}
else
{
uuid = UUID.randomUUID();
// Write the value out to the prefs file so it persists
prefs.edit().putString(PREFS_DEVICE_ID, uuid.toString() ).commit();
}
}
else
{
uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
}
}
}
/**
* Returns a unique UUID for the current android device. As with all UUIDs, this unique ID is "very highly likely"
* to be unique across all Android devices. Much more so than ANDROID_ID is.
*
* The UUID is generated by using ANDROID_ID as the base key if appropriate, falling back on
* TelephonyManager.getDeviceID() if ANDROID_ID is known to be incorrect, and finally falling back
* on a random UUID that's persisted to SharedPreferences if getDeviceID() does not return a
* usable value.
*
* In some rare circumstances, this ID may change. In particular, if the device is factory reset a new device ID
* may be generated. In addition, if a user upgrades their phone from certain buggy implementations of Android 2.2
* to a newer, non-buggy version of Android, the device ID may change. Or, if a user uninstalls your app on
* a device that has neither a proper Android ID nor a Device ID, this ID may change on reinstallation.
*
* Note that if the code falls back on using TelephonyManager.getDeviceId(), the resulting ID will NOT
* change after a factory reset. Something to be aware of.
*
* Works around a bug in Android 2.2 for many devices when using ANDROID_ID directly.
*
* @see http://code.google.com/p/android/issues/detail?id=10603
*
* @return a UUID that may be used to uniquely identify your device for most purposes.
*/
public UUID getDeviceUuid() {
return uuid;
}
try the !important
argument to make sure the CSS is not conflicting with any other styles you have specified. Also using a reset.css is good before you add your own styles.
select#wgmstr {
max-width: 50px;
min-width: 50px;
width: 50px !important;
}
or
<select name="wgtmsr" id="wgtmsr" style="width: 50px !important; min-width: 50px; max-width: 50px;">
on a Mac you might see the image:
if you right click on the docker icon then you see:
alternatively:
docker ps
and
docker run hello-world
For me in PgAdmin 4 on Mac OS High Sierra, Clicking the PostrgreSQL10 database under Servers in the left column, then the Properties tab, showed 5433 as the port under Connection. (I don't know why, because I chose 5432 during install). Anyway, I clicked the Edit icon under the Properties tab, change that to 5432, saved, and that solved the problem. Go figure.
To list all unstaged tracked changed files:
git diff --name-only
To list all staged tracked changed files:
git diff --name-only --staged
To list all staged and unstaged tracked changed files:
{ git diff --name-only ; git diff --name-only --staged ; } | sort | uniq
To list all untracked files (the ones listed by git status
, so not including any ignored files):
git ls-files --other --exclude-standard
If you're using this in a shell script, and you want to programmatically check if these commands returned anything, you'll be interested in git diff
's --exit-code
option.
This is a very common error while working on JSTL.
To solve this error simply :-
You will find the error has gone now!
Hope this helps.
java.lang.StringBuilder. Use int constructor to create an initial size.
You can do this:
if ($(".parent a[Id]").length > 0) {
/* then do something here */
}
Keep in mind that "blind" is a range of conditions - there are some who are legally blind that could read a really large monitor or with magnification help, and then there are those who have no vision at all. I remember a classmate in college who had a special device to magnify books, and special software she could use to magnify a part of the screen. She was working hard to finish college, because her eyesight was getting worse and was going to go away completely.
Programming also has a spectrum of needs - some people are good at cranking out lots and lots of code, and some people are better at looking at the big picture and architecture. I would imagine that given the difficulty imposed by the screen interface, blindness may enhance your ability to get the big picture...
This is code to compile and run java in sublime text 3
"shell_cmd": "javac -d . $file && java ${file_base_name}.${file_base_name}", "shell": true
Using underscore:
var dataArray = _.values(dataObject);
Please try the below Code
You can split the controller (PageCtrl) and service (dataService)
'use strict';_x000D_
(function () {_x000D_
angular.module('myApp')_x000D_
.controller('pageContl', ['$scope', 'dataService', PageContl])_x000D_
.service('dataService', ['$q', '$http', DataService]);_x000D_
function DataService($q, $http){_x000D_
this.$q = $q;_x000D_
this.$http = $http;_x000D_
//... blob blob _x000D_
}_x000D_
DataService.prototype = {_x000D_
getSearchData: function () {_x000D_
var deferred = this.$q.defer(); //initiating promise_x000D_
this.$http({_x000D_
method: 'POST',//GET_x000D_
url: 'test.json',_x000D_
headers: { 'Content-Type': 'application/json' }_x000D_
}).then(function(result) {_x000D_
deferred.resolve(result.data);_x000D_
},function (error) {_x000D_
deferred.reject(error);_x000D_
});_x000D_
return deferred.promise;_x000D_
},_x000D_
getABCDATA: function () {_x000D_
_x000D_
}_x000D_
};_x000D_
function PageContl($scope, dataService) {_x000D_
this.$scope = $scope;_x000D_
this.dataService = dataService; //injecting service Dependency in ctrl_x000D_
this.pageData = {}; //or [];_x000D_
}_x000D_
PageContl.prototype = {_x000D_
searchData: function () {_x000D_
var self = this; //we can't access 'this' of parent fn from callback or inner function, that's why assigning in temp variable_x000D_
this.dataService.getSearchData().then(function (data) {_x000D_
self.searchData = data;_x000D_
});_x000D_
}_x000D_
}_x000D_
}());
_x000D_
just fetch specific node data and its working perfect for me
mFirebaseInstance.getReference("yourNodeName").getRef().addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Log.e(TAG, "======="+postSnapshot.child("email").getValue());
Log.e(TAG, "======="+postSnapshot.child("name").getValue());
}
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "Failed to read app title value.", error.toException());
}
});
read.table
wants to return a data.frame
, which must have an element in each column. Therefore R expects each row to have the same number of elements and it doesn't fill in empty spaces by default. Try read.table("/PathTo/file.csv" , fill = TRUE )
to fill in the blanks.
e.g.
read.table( text= "Element1 Element2
Element5 Element6 Element7" , fill = TRUE , header = FALSE )
# V1 V2 V3
#1 Element1 Element2
#2 Element5 Element6 Element7
A note on whether or not to set header = FALSE
... read.table
tries to automatically determine if you have a header row thus:
header
is set toTRUE
if and only if the first row contains one fewer field than the number of columns
def valid = pointAddress.findAll { a ->
validPointTypes.any { a.contains(it) }
}
Should do it
You need to add sudo . I did the following to get it installed :
sudo apt-get install libsm6 libxrender1 libfontconfig1
and then did that (optional! maybe you won't need it)
sudo python3 -m pip install opencv-contrib-python
FINALLY got it done !
Still better solution could be to follow a design pattern such that the back-button press event gets propagated from active fragment down to host Activity. So, it's like.. if one of the active fragments consume the back-press, the Activity wouldn't get to act upon it, and vice-versa.
One way to do it is to have all your Fragments extend a base fragment that has an abstract 'boolean onBackPressed()' method.
@Override
public boolean onBackPressed() {
if(some_condition)
// Do something
return true; //Back press consumed.
} else {
// Back-press not consumed. Let Activity handle it
return false;
}
}
Keep track of active fragment inside your Activity and inside it's onBackPressed callback write something like this
@Override
public void onBackPressed() {
if(!activeFragment.onBackPressed())
super.onBackPressed();
}
}
This post has this pattern described in detail
This not work on IOS, setState -> render -> not change the text, but can change other. The textinput can't change itself value when textOnChange.
by the way, This work well on Android.
Date is a simpler class and is mainly there for backward compatibility reasons. If you need to set particular dates or do date arithmetic, use a Calendar. Calendars also handle localization. The previous date manipulation functions of Date have since been deprecated.
Personally I tend to use either time in milliseconds as a long (or Long, as appropriate) or Calendar when there is a choice.
Both Date and Calendar are mutable, which tends to present issues when using either in an API.
You may use rbind
but in this case you need to have the same number of columns in both tables, so try the following:
b$b<-as.double(NA) #keeping numeric format is essential for further calculations
new<-rbind(a,b)
If the InputStream
you're using supports mark/reset support, you could also attempt to read the first byte of the stream and then reset it to its original position:
input.mark(1);
final int bytesRead = input.read(new byte[1]);
input.reset();
if (bytesRead != -1) {
//stream not empty
} else {
//stream empty
}
If you don't control what kind of InputStream
you're using, you can use the markSupported()
method to check whether mark/reset will work on the stream, and fall back to the available()
method or the java.io.PushbackInputStream
method otherwise.
With kotlin this is the way I did:
class LoginActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
window.decorView.systemUiVisibility =
View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
View.SYSTEM_UI_FLAG_FULLSCREEN
}
}
Immersive Mode
The immersive mode is intended for apps in which the user will be heavily interacting with the screen. Examples are games, viewing images in a gallery, or reading paginated content, like a book or slides in a presentation. For this, just add this lines:
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
Sticky immersive
In the regular immersive mode, any time a user swipes from an edge, the system takes care of revealing the system bars—your app won't even be aware that the gesture occurred. So if the user might actually need to swipe from the edge of the screen as part of the primary app experience—such as when playing a game that requires lots of swiping or using a drawing app—you should instead enable the "sticky" immersive mode.
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
For more information: Enable fullscreen mode
In case your using the keyboard, sometimes happens that StatusBar shows when keyboard shows up. In that case I usually add this to my style xml
styles.xml
<style name="FullScreen" parent="AppTheme">
<item name="android:windowFullscreen">true</item>
</style>
And also this line to my manifest
<activity
android:name=".ui.login.LoginActivity"
android:label="@string/title_activity_login"
android:theme="@style/FullScreen">
Here is the snippets from my code.. If it solves your problems..
Set jsonpCallBack : 'photos' and dataType:'jsonp'
$('document').ready(function() {
var pm_url = 'http://localhost:8080/diztal/rest/login/test_cor?sessionKey=4324234';
$.ajax({
crossDomain: true,
url: pm_url,
type: 'GET',
dataType: 'jsonp',
jsonpCallback: 'photos'
});
});
function photos (data) {
alert(data);
$("#twitter_followers").html(data.responseCode);
};
@Path("/test_cor")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String testCOR(@QueryParam("sessionKey") String sessionKey, @Context HttpServletRequest httpRequest) {
ResponseJSON<LoginResponse> resp = new ResponseJSON<LoginResponse>();
resp.setResponseCode(sessionKey);
resp.setResponseText("Wrong Passcode");
resp.setResponseTypeClass("Login");
Gson gson = new Gson();
return "photos("+gson.toJson(resp)+")"; // CHECK_THIS_LINE
}
file_put_contents('file.txt', 'bar');
echo file_get_contents('file.txt'); // bar
file_put_contents('file.txt', 'foo');
echo file_get_contents('file.txt'); // foo
Alternatively, if you're stuck with fopen()
you can use the w
or w+
modes:
'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
Does this work?
Workbooks.Open Filename:=filepath, ReadOnly:=True
Or, as pointed out in a comment, to keep a reference to the opened workbook:
Dim book As Workbook
Set book = Workbooks.Open(Filename:=filepath, ReadOnly:=True)
For all struggling around with the #selector in Swift 3 or Swift 4, here a full code example:
// WE NEED A CLASS THAT SHOULD RECEIVE NOTIFICATIONS
class MyReceivingClass {
// ---------------------------------------------
// INIT -> GOOD PLACE FOR REGISTERING
// ---------------------------------------------
init() {
// WE REGISTER FOR SYSTEM NOTIFICATION (APP WILL RESIGN ACTIVE)
// Register without parameter
NotificationCenter.default.addObserver(self, selector: #selector(MyReceivingClass.handleNotification), name: .UIApplicationWillResignActive, object: nil)
// Register WITH parameter
NotificationCenter.default.addObserver(self, selector: #selector(MyReceivingClass.handle(withNotification:)), name: .UIApplicationWillResignActive, object: nil)
}
// ---------------------------------------------
// DE-INIT -> LAST OPTION FOR RE-REGISTERING
// ---------------------------------------------
deinit {
NotificationCenter.default.removeObserver(self)
}
// either "MyReceivingClass" must be a subclass of NSObject OR selector-methods MUST BE signed with '@objc'
// ---------------------------------------------
// HANDLE NOTIFICATION WITHOUT PARAMETER
// ---------------------------------------------
@objc func handleNotification() {
print("RECEIVED ANY NOTIFICATION")
}
// ---------------------------------------------
// HANDLE NOTIFICATION WITH PARAMETER
// ---------------------------------------------
@objc func handle(withNotification notification : NSNotification) {
print("RECEIVED SPECIFIC NOTIFICATION: \(notification)")
}
}
In this example we try to get POSTs from AppDelegate (so in AppDelegate implement this):
// ---------------------------------------------
// WHEN APP IS GOING TO BE INACTIVE
// ---------------------------------------------
func applicationWillResignActive(_ application: UIApplication) {
print("POSTING")
// Define identifiyer
let notificationName = Notification.Name.UIApplicationWillResignActive
// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)
}
One potential downside with setting the field value to "" (empty string) in the constructor is if the field is an optional field and is left unedited. Unless you do some massaging before posting your form, the field will be persisted to your data storage as an empty string instead of NULL.
This alternative will avoid empty strings:
constructor(props) {
super(props);
this.state = {
name: null
}
}
...
<input name="name" type="text" value={this.state.name || ''}/>
Next is a piece of code which uses csv module but extracts file.csv contents to a list of dicts using the first line which is a header of csv table
import csv
def csv2dicts(filename):
with open(filename, 'rb') as f:
reader = csv.reader(f)
lines = list(reader)
if len(lines) < 2: return None
names = lines[0]
if len(names) < 1: return None
dicts = []
for values in lines[1:]:
if len(values) != len(names): return None
d = {}
for i,_ in enumerate(names):
d[names[i]] = values[i]
dicts.append(d)
return dicts
return None
if __name__ == '__main__':
your_list = csv2dicts('file.csv')
print your_list
A multiprogramming is the process when a computer system is performing different tasks all at once in a single computer system.
A tiny update for @Terry Young answer, i.e. add IE 10+ support
if (window.navigator.msSaveOrOpenBlob) {
// IE 10+
var blob = new Blob([decodeURIComponent(encodeURI(csvString))], {
type: 'text/csv;charset=' + document.characterSet
});
window.navigator.msSaveBlob(blob, filename);
} else {
// actual real browsers
//Data URI
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csvData);
$(this).attr({
'download': filename,
'href': csvData,
'target': '_blank'
});
}
Sometimes I use a prefixes for my keys. For example:
var pre = 'foo',
key = pre + 1234
obj = {};
obj[key] = val;
Now you don't have any problem accessing them.
Here is my solution to smooth scroll to div / anchor using jQuery in case you have a fixed header so that it doesn't scroll underneath it. Also it works if you link it from other page.
Just replace ".site-header" to div that contains your header.
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
var headerheight = $(".site-header").outerHeight();
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: (target.offset().top - headerheight)
}, 1000);
return false;
}
}
});
//Executed on page load with URL containing an anchor tag.
if($(location.href.split("#")[1])) {
var headerheight = $(".site-header").outerHeight();
var target = $('#'+location.href.split("#")[1]);
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - headerheight
}, 1);
return false;
}
}
});
You want the gcc
-specific noinline
attribute.
This function attribute prevents a function from being considered for inlining. If the function does not have side-effects, there are optimizations other than inlining that causes function calls to be optimized away, although the function call is live. To keep such calls from being optimized away, put
asm ("");
Use it like this:
void __attribute__ ((noinline)) foo()
{
...
}
It ensures that the expression returns true. Otherwise, it throws a java.lang.AssertionError
.
http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.10
I like and learned a lot from Lasse V. Karlsen. I modified it into the following example, which highlights pretty well the difference between shallow dictionary copies and deep copies:
import copy
my_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}
my_copy = copy.copy(my_dict)
my_deepcopy = copy.deepcopy(my_dict)
Now if you change
my_dict['a'][2] = 7
and do
print("my_copy a[2]: ",my_copy['a'][2],",whereas my_deepcopy a[2]: ", my_deepcopy['a'][2])
you get
>> my_copy a[2]: 7 ,whereas my_deepcopy a[2]: 3
No one mentioned this, but in conjunction to the other responses, you can also get the apk file from your bin directory to your phone or tablet by putting it on a web site and just downloading it.
Your device will complain about installing it after you download it. Your device will advise you or a risk of installing programs from unknown sources and give you the option to bypass the advice.
Your question is very specific. You don't have to pull it from your emulator, just grab the apk file from the bin folder in your project and place it on your real device.
Most people are giving you valuable information for the next step (signing and publishing your apk), you are not required to do that step to get it on your real device.
Downloading it to your real device is a simple method.
Back in the old days of Python, to call a function with arbitrary arguments, you would use apply
:
apply(f,args,kwargs)
apply
still exists in Python2.7 though not in Python3, and is generally not used anymore. Nowadays,
f(*args,**kwargs)
is preferred. The multiprocessing.Pool
modules tries to provide a similar interface.
Pool.apply
is like Python apply
, except that the function call is performed in a separate process. Pool.apply
blocks until the function is completed.
Pool.apply_async
is also like Python's built-in apply
, except that the call returns immediately instead of waiting for the result. An AsyncResult
object is returned. You call its get()
method to retrieve the result of the function call. The get()
method blocks until the function is completed. Thus, pool.apply(func, args, kwargs)
is equivalent to pool.apply_async(func, args, kwargs).get()
.
In contrast to Pool.apply
, the Pool.apply_async
method also has a callback which, if supplied, is called when the function is complete. This can be used instead of calling get()
.
For example:
import multiprocessing as mp
import time
def foo_pool(x):
time.sleep(2)
return x*x
result_list = []
def log_result(result):
# This is called whenever foo_pool(i) returns a result.
# result_list is modified only by the main process, not the pool workers.
result_list.append(result)
def apply_async_with_callback():
pool = mp.Pool()
for i in range(10):
pool.apply_async(foo_pool, args = (i, ), callback = log_result)
pool.close()
pool.join()
print(result_list)
if __name__ == '__main__':
apply_async_with_callback()
may yield a result such as
[1, 0, 4, 9, 25, 16, 49, 36, 81, 64]
Notice, unlike pool.map
, the order of the results may not correspond to the order in which the pool.apply_async
calls were made.
So, if you need to run a function in a separate process, but want the current process to block until that function returns, use Pool.apply
. Like Pool.apply
, Pool.map
blocks until the complete result is returned.
If you want the Pool of worker processes to perform many function calls asynchronously, use Pool.apply_async
. The order of the results is not guaranteed to be the same as the order of the calls to Pool.apply_async
.
Notice also that you could call a number of different functions with Pool.apply_async
(not all calls need to use the same function).
In contrast, Pool.map
applies the same function to many arguments.
However, unlike Pool.apply_async
, the results are returned in an order corresponding to the order of the arguments.
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
This is by no means a robust example; you'll need to handle IOException
s and whatnot. But it should get you started.
If you need something with more capability, check out HttpClient.
If you really need a "Backup" then you also need database schema, like table definitions, view definitions, store procedures and so on. A backup of a database isn't just the data.
The value of the mysqldump format for backup is specifically that it is very EASY to use it to restore mysql databases. A backup that isn't easily restored is far less useful. If you are looking for a method to reliably backup mysql data to so you can restore to a mysql server then I think you should stick with the mysqldump tool.
Mysql is free and runs on many different platforms. Setting up a new mysql server that I can restore to is simple. I am not at all worried about not being able to setup mysql so I can do a restore.
I would be far more worried about a custom backup/restore based on a fragile format like csv/tsv failing. Are you sure that all your quotes, commas, or tabs that are in your data would get escaped correctly and then parsed correctly by your restore tool?
If you are looking for a method to extract the data then see several in the other answers.
I needed to do the same thing, so have written some JavaScript to enable this, using the onSelect
and beforeShowDay
events. It maintains its own array of selected dates, so unfortunately doesn't integrate with a textbox showing the current date, etc. I'm just using it as an inline control, and I can then query the array for the currently selected dates.
I used this code as a basis.
<script type="text/javascript">
// Maintain array of dates
var dates = new Array();
function addDate(date) {
if (jQuery.inArray(date, dates) < 0)
dates.push(date);
}
function removeDate(index) {
dates.splice(index, 1);
}
// Adds a date if we don't have it yet, else remove it
function addOrRemoveDate(date) {
var index = jQuery.inArray(date, dates);
if (index >= 0)
removeDate(index);
else
addDate(date);
}
// Takes a 1-digit number and inserts a zero before it
function padNumber(number) {
var ret = new String(number);
if (ret.length == 1)
ret = "0" + ret;
return ret;
}
jQuery(function () {
jQuery("#datepicker").datepicker({
onSelect: function (dateText, inst) {
addOrRemoveDate(dateText);
},
beforeShowDay: function (date) {
var year = date.getFullYear();
// months and days are inserted into the array in the form, e.g "01/01/2009", but here the format is "1/1/2009"
var month = padNumber(date.getMonth() + 1);
var day = padNumber(date.getDate());
// This depends on the datepicker's date format
var dateString = month + "/" + day + "/" + year;
var gotDate = jQuery.inArray(dateString, dates);
if (gotDate >= 0) {
// Enable date so it can be deselected. Set style to be highlighted
return [true, "ui-state-highlight"];
}
// Dates not in the array are left enabled, but with no extra style
return [true, ""];
}
});
});
</script>
Try this one:
if(FALSE !== ($key = array_search($_GET['name'],$_SESSION['name'])))
{
unset($_SESSION['name'][$key]);
}
Docker has a default entrypoint which is /bin/sh -c
but does not have a default command.
When you run docker like this:
docker run -i -t ubuntu bash
the entrypoint is the default /bin/sh -c
, the image is ubuntu
and the command is bash
.
The command is run via the entrypoint. i.e., the actual thing that gets executed is /bin/sh -c bash
. This allowed Docker to implement RUN
quickly by relying on the shell's parser.
Later on, people asked to be able to customize this, so ENTRYPOINT
and --entrypoint
were introduced.
Everything after ubuntu
in the example above is the command and is passed to the entrypoint. When using the CMD
instruction, it is exactly as if you were doing docker run -i -t ubuntu <cmd>
. <cmd>
will be the parameter of the entrypoint.
You will also get the same result if you instead type this command docker run -i -t ubuntu
. You will still start a bash shell in the container because of the ubuntu Dockerfile specified a default CMD: CMD ["bash"]
As everything is passed to the entrypoint, you can have a very nice behavior from your images. @Jiri example is good, it shows how to use an image as a "binary". When using ["/bin/cat"]
as entrypoint and then doing docker run img /etc/passwd
, you get it, /etc/passwd
is the command and is passed to the entrypoint so the end result execution is simply /bin/cat /etc/passwd
.
Another example would be to have any cli as entrypoint. For instance, if you have a redis image, instead of running docker run redisimg redis -H something -u toto get key
, you can simply have ENTRYPOINT ["redis", "-H", "something", "-u", "toto"]
and then run like this for the same result: docker run redisimg get key
.
You need to escape the ampersand:
<div class="test">&times</div>
×
means a multiplication sign. (Technically it should be ×
but lenient browsers let you omit the ;
.)
It worked for me:
File file = new File(getApplicationContext().getFilesDir(),"whatever.txt");
if(file.exists()){
//Do something
}
else{
//Nothing
}
Use this:
String str = " 12,12"
str = str.replaceAll("(\\d+)\\,(\\d+)", "$1.$2");
System.out.println("str:"+str); //-> str:12.12
hope help you.
try
<button onclick="window.location.href='b.php'">Click me</button>
find /PATH/TO/YOUR/FILES -name NAME.EXT -exec cp -rfp {} /DST_DIR \;
If you want to run the tsc command from the integrated terminal with the TypeScript module installed locally, you can add the following to your .vscode\settings.json file.
{
"terminal.integrated.env.windows": { "PATH": "${workspaceFolder}\\node_modules\\.bin;${env:PATH}" }
}
This will prepend the locally installed node module's binary/executable directory (where tsc.cmd is located) to the $env.PATH variable.
Connection refused means that the port you are trying to connect to is not actually open.
So either you are connecting to the wrong IP address, or to the wrong port, or the server is listening on the wrong port, or is not actually running.
A common mistake is not specifying the port number when binding or connecting in network byte order...
Sorry for comment in an old post but if you want to use an else if statement this will help you
{% if title == source %}
Do This
{% elif title == value %}
Do This
{% else %}
Do This
{% endif %}
For more info see Django Documentation
To be complete here is the code in Scala:
val list1 = List(1, 2, 3, 4, 5)
for (elem <- list1) println(list1.filter(_ != elem) reduceLeft(_*_))
This will print out the following:
120
60
40
30
24
The program will filter out the current elem (_ != elem); and multiply the new list with reduceLeft method. I think this will be O(n) if you use scala view or Iterator for lazy eval.
There is a very good answer to the same question.
Adding following lines to "~/.gitconfig":
[alias]
lg1 = log --graph --abbrev-commit --decorate --date=relative --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(bold yellow)%d%C(reset)' --all
lg2 = log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold cyan)%aD%C(reset) %C(bold green)(%ar)%C(reset)%C(bold yellow)%d%C(reset)%n'' %C(white)%s%C(reset) %C(dim white)- %an%C(reset)' --all
lg = !"git lg1"
If you think about it, comparing numbers to logical statements doesn't make much sense. However, since 0 is often associated with "Off" or "False" and 1 with "On" or "True", R has decided to allow 1 == TRUE
and 0 == FALSE
to both be true. Any other numeric-to-boolean comparison should yield false, unless it's something like 3 - 2 == TRUE
.
You must create your own SSLSocketFactory based on Bouncy Castle. After to use it, pass to the common HttpsConnextion for using this customized SocketFactory.
1. First : Create a TLSConnectionFactory
Here one tips:
1.1 Extend SSLConnectionFactory
1.2 Override this method :
@Override
public Socket createSocket(Socket socket, final String host, int port, boolean arg3)
This method will call the next internal method,
1.3 Implement an internal method _createSSLSocket(host, tlsClientProtocol);
Here you must create a Socket using TlsClientProtocol . The trick is override ...startHandshake() method calling TlsClientProtocol
private SSLSocket _createSSLSocket(final String host , final TlsClientProtocol tlsClientProtocol) {
return new SSLSocket() {
.... Override and implement SSLSocket methods, particulary:
startHandshake() {
}
}
Important : The full sample how to use TLS Client Protocol is well explained here: Using BouncyCastle for a simple HTTPS query
2. Second : Use this Customized SSLConnextionFactory on common HTTPSConnection.
This is important ! In other samples you can see into the web , u see hard-coded HTTP Commands....so with a customized SSLConnectionFactory u don't need nothing more...
URL myurl = new URL( "http:// ...URL tha only Works in TLS 1.2);
HttpsURLConnection con = (HttpsURLConnection )myurl.openConnection();
con.setSSLSocketFactory(new TSLSocketConnectionFactory());
The only way to get the users e-mail address is to request extended permissions on the email field. The user must allow you to see this and you cannot get the e-mail addresses of the user's friends.
http://developers.facebook.com/docs/authentication/permissions
You can do this if you are using Facebook connect by passing scope=email in the get string of your call to the Auth Dialog.
I'd recommend using an SDK instead of file_get_contents as it makes it far easier to perform the Oauth authentication.
The python function returning just the package version in a machine-readable format:
from importlib.metadata import version
version('numpy')
Prior to python 3.8:
pip install importlib-metadata
from importlib_metadata import version
version('numpy')
The bash equivalent (here also invoked from python) would be much more complex (but more robust - see caution below):
import subprocess
def get_installed_ver(pkg_name):
bash_str="pip freeze | grep -w %s= | awk -F '==' {'print $2'} | tr -d '\n'" %(pkg_name)
return(subprocess.check_output(bash_str, shell=True).decode())
Sample usage:
# pkg_name="xgboost"
# pkg_name="Flask"
# pkg_name="Flask-Caching"
pkg_name="scikit-learn"
print(get_installed_ver(pkg_name))
>>> 0.22
Note that in both cases pkg_name
parameter should contain package name in the format as returned by pip freeze
and not as used during import
, e.g. scikit-learn
not sklearn
or Flask-Caching
, not flask_caching
.
Note that while invoking pip freeze
in bash version may seem inefficient, only this method proves to be sufficiently robust to package naming peculiarities and inconsistencies (e.g. underscores vs dashes, small vs large caps, and abbreviations such as sklearn
vs scikit-learn
).
Caution: in complex environments both variants can return surprise version numbers, inconsistent with what you can actually get during import
.
One such problem arises when there are other versions of the package hidden in a user site-packages
subfolder. As an illustration of the perils of using version()
here's a situation I encountered:
$ pip freeze | grep lightgbm
lightgbm==2.3.1
and
$ python -c "import lightgbm; print(lightgbm.__version__)"
2.3.1
vs.
$ python -c "from importlib_metadata import version; print(version(\"lightgbm\"))"
2.2.3
until you delete the subfolder with the old version (here 2.2.3) from the user folder (only one would normally be preserved by `pip` - the one installed as last with the `--user` switch):
$ ls /home/jovyan/.local/lib/python3.7/site-packages/lightgbm*
/home/jovyan/.local/lib/python3.7/site-packages/lightgbm-2.2.3.dist-info
/home/jovyan/.local/lib/python3.7/site-packages/lightgbm-2.3.1.dist-info
Another problem is having some conda-installed packages in the same environment. If they share dependencies with your pip-installed packages, and versions of these dependencies differ, you may get downgrades of your pip-installed dependencies.
To illustrate, the latest version of numpy
available in PyPI on 04-01-2020 was 1.18.0, while at the same time Anaconda's conda-forge
channel had only 1.17.3 version on numpy
as their latest. So when you installed a basemap
package with conda (as second), your previously pip-installed numpy
would get downgraded by conda to 1.17.3, and version 1.18.0 would become unavailable to the import
function. In this case version()
would be right, and pip freeze
/conda list
wrong:
$ python -c "from importlib_metadata import version; print(version(\"numpy\"))"
1.17.3
$ python -c "import numpy; print(numpy.__version__)"
1.17.3
$ pip freeze | grep numpy
numpy==1.18.0
$ conda list | grep numpy
numpy 1.18.0 pypi_0 pypi
UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
WHERE number like 'KIT%'
or simply this if you are sure that you have no values like this CKIT002
UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
session.query().with_entities(SomeModel.col1)
is the same as
session.query(SomeModel.col1)
for alias, we can use .label()
session.query(SomeModel.col1.label('some alias name'))
I solved it this way:
$ brew uninstall --force node
$ brew uninstall --force npm
after it
$ brew install node
which suggested me to overwrite simlinks
Error: The `brew link` step did not complete successfully
The formula built, but is not symlinked into /usr/local
Could not symlink share/doc/node/gdbinit
Target /usr/local/share/doc/node/gdbinit
already exists. You may want to remove it:
rm '/usr/local/share/doc/node/gdbinit'
To force the link and overwrite all conflicting files:
brew link --overwrite node
after executing
$ brew link --overwrite node
everything worked again.
"Public API access" the key generated there is the key you got to paste into your public static final String DEVELOPER_KEY as part of this writing 26.12.2013 It is not the clientID but you got take the steps mentioned above to obtain one and generate the public api access key.
You can also use a proxy tool like Charles to capture the outgoing request headers, data, etc. by passing the proxy details through CURLOPT_PROXY
to your curl_setopt_array
method.
For example:
$proxy = '127.0.0.1:8888';
$opt = array (
CURLOPT_URL => "http://www.example.com",
CURLOPT_PROXY => $proxy,
CURLOPT_POST => true,
CURLOPT_VERBOSE => true,
);
$ch = curl_init();
curl_setopt_array($ch, $opt);
curl_exec($ch);
curl_close($ch);
Adding to Cheeken's answer, This is how you sort a list of tuples by the 2nd item in descending order.
sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)],key=lambda x: x[1], reverse=True)
These answers didn't work for me. I had to use the following:
import subprocess
p = subprocess.Popen(["pwd"], stdout=subprocess.PIPE)
out = p.stdout.read()
print out
Or as a function (using shell=True was required for me on Python 2.6.7 and check_output was not added until 2.7, making it unusable here):
def system_call(command):
p = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True)
return p.stdout.read()
see this article!
identify UNC par or local drive path by searching index of ":"
if its is UNC PATH you cam map UNC path
code to execute drive name is mapped drive name < UNC Mapped Drive or Local Drive>.
using System.IO;
private long GetTotalFreeSpace(string driveName)
{
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.IsReady && drive.Name == driveName)
{
return drive.TotalFreeSpace;
}
}
return -1;
}
unmap after you requirement done.
public static void deleteLine() throws IOException {
RandomAccessFile file = new RandomAccessFile("me.txt", "rw");
String delete;
String task="";
byte []tasking;
while ((delete = file.readLine()) != null) {
if (delete.startsWith("BAD")) {
continue;
}
task+=delete+"\n";
}
System.out.println(task);
BufferedWriter writer = new BufferedWriter(new FileWriter("me.txt"));
writer.write(task);
file.close();
writer.close();
}
Here's something similar, in Ruby:
wait = Selenium::WebDriver::Wait.new(:timeout => 10)
wait.until { @driver.execute_script('return document.readyState').eql?('complete') }
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/activity_register_header"
android:minHeight="50dp"
android:orientation="vertical"
android:visibility="gone" />
Try this piece of code..For me this code worked..
This work for me:
<section class="h-100">
<header class="container h-100">
<div class="d-flex align-items-center justify-content-center h-100">
<div class="d-flex flex-column">
<h1 class="text align-self-center p-2">item 1</h1>
<h4 class="text align-self-center p-2">item 2</h4>
<button class="btn btn-danger align-self-center p-2" type="button" name="button">item 3</button>
</div>
</div>
</header>
</section>
Using WHERE DATE(datetime) = '2009-10-20'
has performance issues. As stated here:
DATE()
for all rows, including those that don't match.Use BETWEEN
or >
, <
, =
operators which allow to use an index:
SELECT * FROM data
WHERE datetime BETWEEN '2009-10-20 00:00:00' AND '2009-10-20 23:59:59'
Update: the impact on using LIKE
instead of operators in an indexed column is high. These are some test results on a table with 1,176,000 rows:
datetime LIKE '2009-10-20%'
=> 2931msdatetime >= '2009-10-20 00:00:00' AND datetime <= '2009-10-20 23:59:59'
=> 168msWhen doing a second call over the same query the difference is even higher: 2984ms vs 7ms (yes, just 7 milliseconds!). I found this while rewriting some old code on a project using Hibernate.
There are three unique situations:
Margin="a,b,c,d"
.Margin="a,b"
.Margin="a"
.If there are 4 numbers, then its left
, top
, right
, bottom
(a clockwise circle starting from the middle left margin). First number is always the "West" like "WPF":
<object Margin="left,top,right,bottom"/>
Example: if we use Margin="10,20,30,40"
it generates:
If there are 2 numbers, then the first is left & right margin thickness, the second is top & bottom margin thickness. First number is always the "West" like "WPF":
<object Margin="a,b"/> // Equivalent to Margin="a,b,a,b".
Example: if we use Margin="10,30"
, the left & right margin are both 10, and the top & bottom are both 30.
If there is 1 number, then the number is repeated (its essentially a border thickness).
<object Margin="a"/> // Equivalent to Margin="a,a,a,a".
Example: if we use Margin="20"
it generates:
Have been working on a large-scale WPF application for the past 5 years with over 100 screens. Part of a team of 5 WPF/C#/Java devs. We eventually settled on either using 1 number (for border thickness) or 4 numbers. We never use 2. It is consistent, and seems to be a good way to reduce cognitive load when developing.
The rule:
All width numbers start on the left (the "West" like "WPF") and go clockwise (if two numbers, only go clockwise twice, then mirror the rest).
You are wasting your time:
P1
name anyway.Just put all your functions in the .py
file:
# my_module.py
def f1():
pass
def f2():
pass
def f3():
pass
And use them like this:
import my_module
my_module.f1()
my_module.f2()
my_module.f3()
or:
from my_module import f1
from my_module import f2
from my_module import f3
f1()
f2()
f3()
This should be enough for starters.
I added a ticket to add an option of some sort here:
https://github.com/pydata/pandas/issues/1450
In the meantime, result.fillna('')
should do what you want
EDIT: in the development version (to be 0.8.0 final) if you specify an empty list of na_values
, empty strings will stay empty strings in the result
Following @Aravind's answer with more details
@RequestMapping("/myPath.htm")
public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception{
myServiceMethodSettingCookie(request, response); //Do service call passing the response
return new ModelAndView("CustomerAddView");
}
// service method
void myServiceMethodSettingCookie(HttpServletRequest request, HttpServletResponse response){
final String cookieName = "my_cool_cookie";
final String cookieValue = "my cool value here !"; // you could assign it some encoded value
final Boolean useSecureCookie = false;
final int expiryTime = 60 * 60 * 24; // 24h in seconds
final String cookiePath = "/";
Cookie cookie = new Cookie(cookieName, cookieValue);
cookie.setSecure(useSecureCookie); // determines whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL
cookie.setMaxAge(expiryTime); // A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.
cookie.setPath(cookiePath); // The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories
response.addCookie(cookie);
}
Related docs:
http://docs.oracle.com/javaee/7/api/javax/servlet/http/Cookie.html
http://docs.spring.io/spring-security/site/docs/3.0.x/reference/springsecurity.html
This is what matplotlib.pyplot.scatter
is for.
As a quick example:
import matplotlib.pyplot as plt
import numpy as np
# Generate data...
t = np.linspace(0, 2 * np.pi, 20)
x = np.sin(t)
y = np.cos(t)
plt.scatter(t,x,c=y)
plt.show()
Using the autofocus
attribute works well with text input and checkboxes.
<input type="text" name="foo" value="boo" autofocus="autofocus"> FooBoo
<input type="checkbox" name="foo" value="boo" autofocus="autofocus"> FooBoo
It may be very simple, but couldn't you just round it up then minus 1? For example:
number=1.5
round(number)-1
> 1
In your case you can use __FILE__
variable !
It should help.
It is one of predefined.
Read more about predefined constants in PHP http://php.net/manual/en/language.constants.predefined.php
You could write
x = condition ? true : x;
So that x is unmodified when the condition is false.
This then is equivalent to
if (condition) x = true
EDIT:
!defaults.slideshowWidth
? defaults.slideshowWidth = obj.find('img').width()+'px'
: null
There are a couple of alternatives - I'm not saying these are better/worse - merely alternatives
Passing in null as the third parameter works because the existing value is null. If you refactor and change the condition, then there is a danger that this is no longer true. Passing in the exising value as the 2nd choice in the ternary guards against this:
!defaults.slideshowWidth =
? defaults.slideshowWidth = obj.find('img').width()+'px'
: defaults.slideshowwidth
Safer, but perhaps not as nice to look at, and more typing. In practice, I'd probably write
defaults.slideshowWidth = defaults.slideshowWidth
|| obj.find('img').width()+'px'
1.Run Spring Boot app with java -jar command
To run your Spring Boot app from a command line in a Terminal window you can use java -jar command. This is provided your Spring Boot app was packaged as an executable jar file.
java -jar target/app-0.0.1-SNAPSHOT.jar
2.Run Spring Boot app using Maven
You can also use Maven plugin to run your Spring Boot app. Use the below command to run your Spring Boot app with Maven plugin:
mvn spring-boot:run
3.Run Spring Boot App with Gradle
And if you use Gradle you can run the Spring Boot app with the following command:
gradle bootRun
open the file
/etc/apache2/httpd.conf
and change
#LoadModule php5_module libexec/apache2/libphp5.so
into
LoadModule php5_module libexec/apache2/libphp5.so
So just uncoment the PHP module load in httpd.conf
When you want to write in javascript alert from a php variable, you have to add an other "\" before "\n". Instead the alert pop-up is not working.
ex:
PHP :
$text = "Example Text : \n"
$text2 = "Example Text : \\n"
JS:
window.alert('<?php echo $text; ?>'); // not working
window.alert('<?php echo $text2; ?>'); // is working
go to kafka/libs folder we can see multiple jars search for something similar kafka_2.11-0.10.1.1.jar.asc in this case the kafka version is 0.10.1.1
export CLASSPATH=/home/appnetix/LOG4J_HOME/log4j-1.2.16.jar
or, if you already have some classpath set
export CLASSPATH=$CLASSPATH:/home/appnetix/LOG4J_HOME/log4j-1.2.16.jar
and, if also you want to include current directory
export CLASSPATH=$CLASSPATH:/home/appnetix/LOG4J_HOME/log4j-1.2.16.jar:.
There are tools that let you monitor the VM's memory usage. The VM can expose memory statistics using JMX. You can also print GC statistics to see how the memory is performing over time.
Invoking System.gc() can harm the GC's performance because objects will be prematurely moved from the new to old generations, and weak references will be cleared prematurely. This can result in decreased memory efficiency, longer GC times, and decreased cache hits (for caches that use weak refs). I agree with your consultant: System.gc() is bad. I'd go as far as to disable it using the command line switch.
You can try java.time api;
Instant date = Instant.ofEpochMilli(1549362600000l);
LocalDateTime utc = LocalDateTime.ofInstant(date, ZoneOffset.UTC);
You can try using the simple NSArray in syntax for iterating over the array in swift which makes for shorter code. The following is working for me:
class ModelAttachment {
var id: String?
var url: String?
var thumb: String?
}
var modelAttachementObj = ModelAttachment()
modelAttachementObj.id = "1"
modelAttachementObj.url = "http://www.google.com"
modelAttachementObj.thumb = "thumb"
var imgs: Array<ModelAttachment> = [modelAttachementObj]
for img in imgs {
let url = img.url
NSLog(url!)
}
Another option is to inherit from the appropriate abstract base class from the `collections module as documented here.
In case the container is its own iterator, you can inherit from
collections.Iterator
. You only need to implement the next
method then.
An example is:
>>> from collections import Iterator
>>> class MyContainer(Iterator):
... def __init__(self, *data):
... self.data = list(data)
... def next(self):
... if not self.data:
... raise StopIteration
... return self.data.pop()
...
...
...
>>> c = MyContainer(1, "two", 3, 4.0)
>>> for i in c:
... print i
...
...
4.0
3
two
1
While you are looking at the collections
module, consider inheriting from Sequence
, Mapping
or another abstract base class if that is more appropriate. Here is an example for a Sequence
subclass:
>>> from collections import Sequence
>>> class MyContainer(Sequence):
... def __init__(self, *data):
... self.data = list(data)
... def __getitem__(self, index):
... return self.data[index]
... def __len__(self):
... return len(self.data)
...
...
...
>>> c = MyContainer(1, "two", 3, 4.0)
>>> for i in c:
... print i
...
...
1
two
3
4.0
NB: Thanks to Glenn Maynard for drawing my attention to the need to clarify the difference between iterators on the one hand and containers that are iterables rather than iterators on the other.
Update 2018
Bootstrap 4
Now that BS4 is flexbox, the fixed-fluid is simple. Just set the width of the fixed column, and use the .col
class on the fluid column.
.sidebar {
width: 180px;
min-height: 100vh;
}
<div class="row">
<div class="sidebar p-2">Fixed width</div>
<div class="col bg-dark text-white pt-2">
Content
</div>
</div>
http://www.codeply.com/go/7LzXiPxo6a
Bootstrap 3..
One approach to a fixed-fluid layout is using media queries that align with Bootstrap's breakpoints so that you only use the fixed width columns are larger screens and then let the layout stack responsively on smaller screens...
@media (min-width:768px) {
#sidebar {
min-width: 300px;
max-width: 300px;
}
#main {
width:calc(100% - 300px);
}
}
Working Bootstrap 3 Fixed-Fluid Demo
Related Q&A:
Fixed width column with a container-fluid in bootstrap
How to left column fixed and right scrollable in Bootstrap 4, responsive?
I don't think you can do this with CSS. Instead, at regular 'word lengths' along the string, insert an HTML soft-hyphen:
ACTGATCG­AGCTGAAG­CGCAGTGC­GATGCTTC­GATGATGC­TGACGATG
This will display a hyphen at the end of the line, where it wraps, which may or may not be what you want.
Note Safari seems to wrap the long string in a <textarea>
anyway, unlike Firefox.
I think it is a better idea to start working with a raw data and then translate it to DOM (document object model)
I would suggest you to work with array of objects and then output it to the DOM in order to accomplish your task.
You can see working example of following code at http://www.softxml.com/stackoverflow/shoppingCart.htm
You can try following approach:
//create array that will hold all ordered products
var shoppingCart = [];
//this function manipulates DOM and displays content of our shopping cart
function displayShoppingCart(){
var orderedProductsTblBody=document.getElementById("orderedProductsTblBody");
//ensure we delete all previously added rows from ordered products table
while(orderedProductsTblBody.rows.length>0) {
orderedProductsTblBody.deleteRow(0);
}
//variable to hold total price of shopping cart
var cart_total_price=0;
//iterate over array of objects
for(var product in shoppingCart){
//add new row
var row=orderedProductsTblBody.insertRow();
//create three cells for product properties
var cellName = row.insertCell(0);
var cellDescription = row.insertCell(1);
var cellPrice = row.insertCell(2);
cellPrice.align="right";
//fill cells with values from current product object of our array
cellName.innerHTML = shoppingCart[product].Name;
cellDescription.innerHTML = shoppingCart[product].Description;
cellPrice.innerHTML = shoppingCart[product].Price;
cart_total_price+=shoppingCart[product].Price;
}
//fill total cost of our shopping cart
document.getElementById("cart_total").innerHTML=cart_total_price;
}
function AddtoCart(name,description,price){
//Below we create JavaScript Object that will hold three properties you have mentioned: Name,Description and Price
var singleProduct = {};
//Fill the product object with data
singleProduct.Name=name;
singleProduct.Description=description;
singleProduct.Price=price;
//Add newly created product to our shopping cart
shoppingCart.push(singleProduct);
//call display function to show on screen
displayShoppingCart();
}
//Add some products to our shopping cart via code or you can create a button with onclick event
//AddtoCart("Table","Big red table",50);
//AddtoCart("Door","Big yellow door",150);
//AddtoCart("Car","Ferrari S23",150000);
<table cellpadding="4" cellspacing="4" border="1">
<tr>
<td valign="top">
<table cellpadding="4" cellspacing="4" border="0">
<thead>
<tr>
<td colspan="2">
Products for sale
</td>
</tr>
</thead>
<tbody>
<tr>
<td>
Table
</td>
<td>
<input type="button" value="Add to cart" onclick="AddtoCart('Table','Big red table',50)"/>
</td>
</tr>
<tr>
<td>
Door
</td>
<td>
<input type="button" value="Add to cart" onclick="AddtoCart('Door','Yellow Door',150)"/>
</td>
</tr>
<tr>
<td>
Car
</td>
<td>
<input type="button" value="Add to cart" onclick="AddtoCart('Ferrari','Ferrari S234',150000)"/>
</td>
</tr>
</tbody>
</table>
</td>
<td valign="top">
<table cellpadding="4" cellspacing="4" border="1" id="orderedProductsTbl">
<thead>
<tr>
<td>
Name
</td>
<td>
Description
</td>
<td>
Price
</td>
</tr>
</thead>
<tbody id="orderedProductsTblBody">
</tbody>
<tfoot>
<tr>
<td colspan="3" align="right" id="cart_total">
</td>
</tr>
</tfoot>
</table>
</td>
</tr>
</table>
Please have a look at following free client-side shopping cart:
SoftEcart(js) is a Responsive, Handlebars & JSON based, E-Commerce shopping cart written in JavaScript with built-in PayPal integration.
Documentation
http://www.softxml.com/softecartjs-demo/documentation/SoftecartJS_free.html
Hope you will find it useful.
Given an object which I suspect to be some kind of IList<>
, how can I determine of what it's an IList<>
?
Here's a reliable solution. My apologies for length - C#'s introspection API makes this suprisingly difficult.
/// <summary>
/// Test if a type implements IList of T, and if so, determine T.
/// </summary>
public static bool TryListOfWhat(Type type, out Type innerType)
{
Contract.Requires(type != null);
var interfaceTest = new Func<Type, Type>(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>) ? i.GetGenericArguments().Single() : null);
innerType = interfaceTest(type);
if (innerType != null)
{
return true;
}
foreach (var i in type.GetInterfaces())
{
innerType = interfaceTest(i);
if (innerType != null)
{
return true;
}
}
return false;
}
Example usage:
object value = new ObservableCollection<int>();
Type innerType;
TryListOfWhat(value.GetType(), out innerType).Dump();
innerType.Dump();
Returns
True
typeof(Int32)
Close from iframe inside a dialog:
window.parent.$('.ui-dialog-content:visible').dialog('close');
Use fnmatch: https://docs.python.org/2/library/fnmatch.html
import fnmatch
import os
for file in os.listdir('.'):
if fnmatch.fnmatch(file, '*.txt'):
print file
The top answer of the question Anders Lindahl refers to an xsd file.
Personally I found this xsd file also very useful (I don't remember how I found that one). It looks a bit less intimidating, and as far as I used it, all the elements and attributes seem to be recognized by Jenkins (v1.451)
One thing though: when adding multiple <failure ...
elements, only one was retained in Jenkins. When creating the xml file, I now concatenate all the failures in one.
Update 2016-11 The link is broken now. A better alternative is this page from cubic.org: JUnit XML reporting file format, where a nice effort has been taken to provide a sensible documented example. Example and xsd are copied below, but their page looks waay nicer.
<?xml version="1.0" encoding="UTF-8"?>
<!-- a description of the JUnit XML format and how Jenkins parses it. See also junit.xsd -->
<!-- if only a single testsuite element is present, the testsuites
element can be omitted. All attributes are optional. -->
<testsuites disabled="" <!-- total number of disabled tests from all testsuites. -->
errors="" <!-- total number of tests with error result from all testsuites. -->
failures="" <!-- total number of failed tests from all testsuites. -->
name=""
tests="" <!-- total number of successful tests from all testsuites. -->
time="" <!-- time in seconds to execute all test suites. -->
>
<!-- testsuite can appear multiple times, if contained in a testsuites element.
It can also be the root element. -->
<testsuite name="" <!-- Full (class) name of the test for non-aggregated testsuite documents.
Class name without the package for aggregated testsuites documents. Required -->
tests="" <!-- The total number of tests in the suite, required. -->
disabled="" <!-- the total number of disabled tests in the suite. optional -->
errors="" <!-- The total number of tests in the suite that errored. An errored test is one that had an unanticipated problem,
for example an unchecked throwable; or a problem with the implementation of the test. optional -->
failures="" <!-- The total number of tests in the suite that failed. A failure is a test which the code has explicitly failed
by using the mechanisms for that purpose. e.g., via an assertEquals. optional -->
hostname="" <!-- Host on which the tests were executed. 'localhost' should be used if the hostname cannot be determined. optional -->
id="" <!-- Starts at 0 for the first testsuite and is incremented by 1 for each following testsuite -->
package="" <!-- Derived from testsuite/@name in the non-aggregated documents. optional -->
skipped="" <!-- The total number of skipped tests. optional -->
time="" <!-- Time taken (in seconds) to execute the tests in the suite. optional -->
timestamp="" <!-- when the test was executed in ISO 8601 format (2014-01-21T16:17:18). Timezone may not be specified. optional -->
>
<!-- Properties (e.g., environment settings) set during test
execution. The properties element can appear 0 or once. -->
<properties>
<!-- property can appear multiple times. The name and value attributres are required. -->
<property name="" value=""/>
</properties>
<!-- testcase can appear multiple times, see /testsuites/testsuite@tests -->
<testcase name="" <!-- Name of the test method, required. -->
assertions="" <!-- number of assertions in the test case. optional -->
classname="" <!-- Full class name for the class the test method is in. required -->
status=""
time="" <!-- Time taken (in seconds) to execute the test. optional -->
>
<!-- If the test was not executed or failed, you can specify one
the skipped, error or failure elements. -->
<!-- skipped can appear 0 or once. optional -->
<skipped/>
<!-- Indicates that the test errored. An errored test is one
that had an unanticipated problem. For example an unchecked
throwable or a problem with the implementation of the
test. Contains as a text node relevant data for the error,
for example a stack trace. optional -->
<error message="" <!-- The error message. e.g., if a java exception is thrown, the return value of getMessage() -->
type="" <!-- The type of error that occured. e.g., if a java execption is thrown the full class name of the exception. -->
></error>
<!-- Indicates that the test failed. A failure is a test which
the code has explicitly failed by using the mechanisms for
that purpose. For example via an assertEquals. Contains as
a text node relevant data for the failure, e.g., a stack
trace. optional -->
<failure message="" <!-- The message specified in the assert. -->
type="" <!-- The type of the assert. -->
></failure>
<!-- Data that was written to standard out while the test was executed. optional -->
<system-out></system-out>
<!-- Data that was written to standard error while the test was executed. optional -->
<system-err></system-err>
</testcase>
<!-- Data that was written to standard out while the test suite was executed. optional -->
<system-out></system-out>
<!-- Data that was written to standard error while the test suite was executed. optional -->
<system-err></system-err>
</testsuite>
</testsuites>
<?xml version="1.0" encoding="UTF-8" ?>
<!-- from https://svn.jenkins-ci.org/trunk/hudson/dtkit/dtkit-format/dtkit-junit-model/src/main/resources/com/thalesgroup/dtkit/junit/model/xsd/junit-4.xsd -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="failure">
<xs:complexType mixed="true">
<xs:attribute name="type" type="xs:string" use="optional"/>
<xs:attribute name="message" type="xs:string" use="optional"/>
</xs:complexType>
</xs:element>
<xs:element name="error">
<xs:complexType mixed="true">
<xs:attribute name="type" type="xs:string" use="optional"/>
<xs:attribute name="message" type="xs:string" use="optional"/>
</xs:complexType>
</xs:element>
<xs:element name="properties">
<xs:complexType>
<xs:sequence>
<xs:element ref="property" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="property">
<xs:complexType>
<xs:attribute name="name" type="xs:string" use="required"/>
<xs:attribute name="value" type="xs:string" use="required"/>
</xs:complexType>
</xs:element>
<xs:element name="skipped" type="xs:string"/>
<xs:element name="system-err" type="xs:string"/>
<xs:element name="system-out" type="xs:string"/>
<xs:element name="testcase">
<xs:complexType>
<xs:sequence>
<xs:element ref="skipped" minOccurs="0" maxOccurs="1"/>
<xs:element ref="error" minOccurs="0" maxOccurs="unbounded"/>
<xs:element ref="failure" minOccurs="0" maxOccurs="unbounded"/>
<xs:element ref="system-out" minOccurs="0" maxOccurs="unbounded"/>
<xs:element ref="system-err" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required"/>
<xs:attribute name="assertions" type="xs:string" use="optional"/>
<xs:attribute name="time" type="xs:string" use="optional"/>
<xs:attribute name="classname" type="xs:string" use="optional"/>
<xs:attribute name="status" type="xs:string" use="optional"/>
</xs:complexType>
</xs:element>
<xs:element name="testsuite">
<xs:complexType>
<xs:sequence>
<xs:element ref="properties" minOccurs="0" maxOccurs="1"/>
<xs:element ref="testcase" minOccurs="0" maxOccurs="unbounded"/>
<xs:element ref="system-out" minOccurs="0" maxOccurs="1"/>
<xs:element ref="system-err" minOccurs="0" maxOccurs="1"/>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="required"/>
<xs:attribute name="tests" type="xs:string" use="required"/>
<xs:attribute name="failures" type="xs:string" use="optional"/>
<xs:attribute name="errors" type="xs:string" use="optional"/>
<xs:attribute name="time" type="xs:string" use="optional"/>
<xs:attribute name="disabled" type="xs:string" use="optional"/>
<xs:attribute name="skipped" type="xs:string" use="optional"/>
<xs:attribute name="timestamp" type="xs:string" use="optional"/>
<xs:attribute name="hostname" type="xs:string" use="optional"/>
<xs:attribute name="id" type="xs:string" use="optional"/>
<xs:attribute name="package" type="xs:string" use="optional"/>
</xs:complexType>
</xs:element>
<xs:element name="testsuites">
<xs:complexType>
<xs:sequence>
<xs:element ref="testsuite" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
<xs:attribute name="name" type="xs:string" use="optional"/>
<xs:attribute name="time" type="xs:string" use="optional"/>
<xs:attribute name="tests" type="xs:string" use="optional"/>
<xs:attribute name="failures" type="xs:string" use="optional"/>
<xs:attribute name="disabled" type="xs:string" use="optional"/>
<xs:attribute name="errors" type="xs:string" use="optional"/>
</xs:complexType>
</xs:element>
</xs:schema>
So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]
Check field type in table just save time stamp value in datatype like bigint
etc.
Not datetime
type
If you pass a DateTime
from a .Net code to a javascript code,
C#:
DateTime net_datetime = DateTime.Now;
javascript treats it as a string, like "/Date(1245398693390)/"
:
You can convert it as fllowing:
// convert the string to date correctly
var d = eval(net_datetime.slice(1, -1))
or:
// convert the string to date correctly
var d = eval("/Date(1245398693390)/".slice(1, -1))
$product_id = $this->input->get('id', TRUE);
echo $product_id;
Ugh everyone's answers on here are incomplete, and lets stop using jquery in SO answers already please. Check jquery's documentation if you want info on jquery.
Here's a generalized pure-javascript function for testing whether or not an element has scrollbars in a complete way:
// dimension - Either 'y' or 'x'
// computedStyles - (Optional) Pass in the domNodes computed styles if you already have it (since I hear its somewhat expensive)
function hasScrollBars(domNode, dimension, computedStyles) {
dimension = dimension.toUpperCase()
if(dimension === 'Y') {
var length = 'Height'
} else {
var length = 'Width'
}
var scrollLength = 'scroll'+length
var clientLength = 'client'+length
var overflowDimension = 'overflow'+dimension
var hasVScroll = domNode[scrollLength] > domNode[clientLength]
// Check the overflow and overflowY properties for "auto" and "visible" values
var cStyle = computedStyles || getComputedStyle(domNode)
return hasVScroll && (cStyle[overflowDimension] == "visible"
|| cStyle[overflowDimension] == "auto"
)
|| cStyle[overflowDimension] == "scroll"
}
If you are working with a Mac... the keytool is part of the Java SDK and can be found in the following location /System/Library/Java/JavaVirtualMachines/[VERSION].jdk/Contents/Home/bin/keytool
you should be using the .Value of the datetime parameter. All Nullable structs have a value property which returns the concrete type of the object. but you must check to see if it is null beforehand otherwise you will get a runtime error.
i.e:
datetime.Value
but check to see if it has a value first!
if (datetime.HasValue)
{
// work with datetime.Value
}
There is an easier way using Xcode (without using command line tools and looking up addresses one at a time)
Take any .xcarchive file. If you have one from before you can use that. If you don't have one, create one by running the Product > Archive from Xcode.
Right click on the .xcarchive file and select 'Show Package Contents'
Copy the dsym file (of the version of the app that crashed) to the dSYMs folder
Copy the .app file (of the version of the app that crashed) to the Products > Applications folder
Edit the Info.plist and edit the CFBundleShortVersionString and CFBundleVersion under the ApplicationProperties dictionary. This will help you identify the archive later
Double click the .xcarchive to import it to Xcode. It should open Organizer.
Go back to the crash log (in Devices window in Xcode)
Drag your .crash file there (if not already present)
The entire crash log should now be symbolicated. If not, then right click and select 'Re-symbolicate crash log'
plt.axis('scaled')
works well for me.
If you did git push origin -u localBranchName:remoteBranchName
and on sequentially git push
commands, you get errors that then origin doesn't exist, then follow these steps:
git remote -v
Check if there is any remote that I don't care.
Delete them with git remote remove 'name'
git config --edit
Look for possible signs of a old/non-existent remote.
Look for pushdefault
:
[remote]
pushdefault = oldremote
Update oldremote
value and save.
git push
should work now.
this works for me, sudo apt-get install libx11-dev
Swift 4
let data = myStringVariable.data(using: String.Encoding.utf8.rawValue)
In the Cygwin package manager, click on curl from within the "net" category. Yes, it's that simple.
Unfortunately, none of the answers to this question takes into account some valid HTTP_ACCEPT_LANGUAGE
such as:
q=0.8,en-US;q=0.5,en;q=0.3
: having the q
priority value at first place.ZH-CN
: old browsers that capitalise (wrongly) the whole langcode.*
: that basically say "serve whatever language you have".After a comprehensive test with thousands of different Accept-Languages in my server, I ended up having this language detection method:
define('SUPPORTED_LANGUAGES', ['en', 'es']);
function detect_language() {
foreach (preg_split('/[;,]/', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $sub) {
if (substr($sub, 0, 2) == 'q=') continue;
if (strpos($sub, '-') !== false) $sub = explode('-', $sub)[0];
if (in_array(strtolower($sub), SUPPORTED_LANGUAGES)) return $sub;
}
return 'en';
}
Another way of changing the size of the bullets would be:
::before
pseudo-element.Example:
ul {_x000D_
list-style-type: none;_x000D_
}_x000D_
_x000D_
li::before {_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
width: 5px;_x000D_
height: 5px;_x000D_
background-color: #000000;_x000D_
margin-right: 8px;_x000D_
content: ' '_x000D_
}
_x000D_
<ul>_x000D_
<li>first element</li>_x000D_
<li>second element</li>_x000D_
</ul>
_x000D_
No markup changes needed
I just use the "New Class" dialog in Eclipse and set the base class as Activity. I'm not aware of any other way to do this. What other method would you expect to be available?
Why do you want to initialize the length? Theoretically there is no need for this. It can even result in confusing behavior, because all tests that use the length
to find out whether an array is empty or not will report that the array is not empty.
Some tests show that setting the initial length of large arrays can be more efficient if the array is filled afterwards, but the performance gain (if any) seem to differ from browser to browser.
jsLint does not like new Array()
because the constructer is ambiguous.
new Array(4);
creates an empty array of length 4. But
new Array('4');
creates an array containing the value '4'
.
Regarding your comment: In JS you don't need to initialize the length of the array. It grows dynamically. You can just store the length in some variable, e.g.
var data = [];
var length = 5; // user defined length
for(var i = 0; i < length; i++) {
data.push(createSomeObject());
}
Both projects aim to make it easier to deploy & manage applications inside containers in your datacenter or cloud.
In order to deploy applications on top of Mesos, one can use Marathon or Kubernetes for Mesos.
Marathon is a cluster-wide init and control system for running Linux services in cgroups and Docker containers. Marathon has a number of different canary deploy features and is a very mature project.
Marathon runs on top of Mesos, which is a highly scalable, battle tested and flexible resource manager. Marathon is proven to scale and runs in many production environments.
The Mesos and Mesosphere technology stack provides a cloud-like environment for running existing Linux workloads, but it also provides a native environment for building new distributed systems.
Mesos is a distributed systems kernel, with a full API for programming directly against the datacenter. It abstracts underlying hardware (e.g. bare metal or VMs) away and just exposes the resources. It contains primitives for writing distributed applications (e.g. Spark was originally a Mesos App, Chronos, etc.) such as Message Passing, Task Execution, etc. Thus, entirely new applications are made possible. Apache Spark is one example for a new (in Mesos jargon called) framework that was built originally for Mesos. This enabled really fast development - the developers of Spark didn't have to worry about networking to distribute tasks amongst nodes as this is a core primitive in Mesos.
To my knowledge, Kubernetes is not used inside Google in production deployments today. For production, Google uses Omega/Borg, which is much more similar to the Mesos/Marathon model. However the great thing about using Mesos as the foundation is that both Kubernetes and Marathon can run on top of it.
More resources about Marathon:
If the program was written in C# you can get the source code in almost its original form using .NET Reflector. You won't be able to see comments and local variable names, but it is very readable.
If it was written C++ it's not so easy... even if you could decompile the code into valid C++ it is unlikely that it will resemble the original source because of inlined functions and optimizations which are hard to reverse.
Please note that by reverse engineering and modifying the source code you might breaking the terms of use of the programs unless you wrote them yourself or have permission from the author.
.label, .text {display: inline}
Although if you use that, you might as well change the div's to span's.
Here is some text I found at experts-exchange:
Bug 14575666
In 12.1, the default value for the SQLNET.ALLOWED_LOGON_VERSION parameter has been updated to 11. This means that database clients using pre-11g JDBC thin drivers cannot authenticate to 12.1 database servers unless theSQLNET.ALLOWED_LOGON_VERSION parameter is set to the old default of 8.
This will cause a 10.2.0.5 Oracle RAC database creation using DBCA to fail with the ORA-28040: No matching authentication protocol error in 12.1 Oracle ASM and Oracle Grid Infrastructure environments.
Workaround: Set SQLNET.ALLOWED_LOGON_VERSION=8 in the oracle/network/admin/sqlnet.ora file.
andyras is completely correct. One minor addition, try this (for example)
plot 'ls.dat' using 4:xtic(1)
This will keep your datafile in the correct order, but also preserve your version tic labels on the x-axis.
The Method Works Properly For me:
var lanopt = $(".language-option");
lanopt.on("show.bs.collapse",".collapse", function(){
lanopt.find(".collapse.in").collapse("hide");
});
It may help you.
var t0 = date.now();
doSomething();
var t1 = date.now();
console.log("Call to doSomething took approximate" + (t1 - t0)/1000 + " seconds.")
Another reason this can sometimes come up is due to a misconfiguration in your docker-compose (if you're using it) whereby the mysql container is not on the same network that your app servers are on.
If the network flag is forgotten or incorrect docker won't add the mysql to the DNS for the app server and therefore throw an error like this.
You should use data.response
in your JS instead of json.response
.
df2 <- df[!names(df) %in% c("c1", "c2")]
The main reason you use the default queue over the main queue is to run tasks in the background.
For instance, if I am downloading a file from the internet and I want to update the user on the progress of the download, I will run the download in the priority default queue and update the UI in the main queue asynchronously.
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Thread
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
});
});
Script the create table
in management studio, run that script in bar to create the table. (Right click table in object explorer, script table as, create to...)
INSERT bar.[schema].table SELECT * FROM foo.[schema].table
there are lots of compression methods that work recursively command line and its good to know who the end audience is.
i.e. if it is to be sent to someone running windows then zip would probably be best:
zip -r file.zip folder_to_zip
unzip filenname.zip
for other linux users or your self tar is great
tar -cvzf filename.tar.gz folder
tar -cvjf filename.tar.bz2 folder # even more compression
#change the -c to -x to above to extract
One must be careful with tar and how things are tarred up/extracted, for example if I run
cd ~
tar -cvzf passwd.tar.gz /etc/passwd
tar: Removing leading `/' from member names
/etc/passwd
pwd
/home/myusername
tar -xvzf passwd.tar.gz
this will create /home/myusername/etc/passwd
unsure if all versions of tar do this:
Removing leading `/' from member names
Answer is very simple use the .NET Framework tools sn.exe
. So open the Visual Studio 2008 Command Prompt and then point to the dll’s folder you want to get the public key,
Use the following command,
sn –T myDLL.dll
This will give you the public key token. Remember one thing this only works if the assembly has to be strongly signed.
Example
C:\WINNT\Microsoft.NET\Framework\v3.5>sn -T EdmGen.exe Microsoft (R) .NET Framework Strong Name Utility Version 3.5.21022.8 Copyright (c) Microsoft Corporation. All rights reserved. Public key token is b77a5c561934e089
i saw following in a book:
this.setState(state => state.someProperty.falg = false);
but i'm not sure if it's right..
People have already mentioned ternary expressions. Sometimes with a simple conditional assignment as your example, it is possible to use a mathematical expression to perform the conditional assignment. This may not make your code very readable, but it does get it on one fairly short line. Your example could be written like this:
x = 2*(i>100) | 1*(i<100)
The comparisons would be True or False, and when multiplying with numbers would then be either 1 or 0. One could use a + instead of an | in the middle.
Answer provided by Nicholas Krasnov
SELECT *
FROM BOOKING_SESSION
WHERE TO_CHAR(T_SESSION_DATETIME, 'DD-MM-YYYY') ='20-03-2012';
And the Postgres equivalent (second line is mandatory only if you want "id" to be a key):
ALTER TABLE tableName ADD id SERIAL;
ALTER TABLE tableName ADD PRIMARY KEY (id);
Say:
sed "s|\$ROOT|${HOME}|" abc.sh
Note:
/
since the replacement contains /
$
in the pattern since you don't want to expand it.EDIT: In order to replace all occurrences of $ROOT
, say
sed "s|\$ROOT|${HOME}|g" abc.sh
Letting a parent have pointer-events: none
will disable the child a-tag
like this (requires that the div covers the a and hasn't 0 width/height):
<div class="disabled">
<a href="/"></a>
</div>
where:
.disabled {
pointer-events: none;
}
I also had the same issue while playing around Zend Framework 2 and composer. I'm using PHP 5.4 (installed via macports) and my solution was to install openssl for PHP 5.4 via macports as well.
sudo port install php54-openssl
your question is basically O/RM's vs hand writing SQL
Take a look at some of the other O/RM solutions out there, L2S isn't the only one (NHibernate, ActiveRecord)
http://en.wikipedia.org/wiki/List_of_object-relational_mapping_software
to address the specific questions: