As the authors of the tool, we of course use SmartInspect for logging and tracing .NET applications. We usually use the named pipe protocol for live logging and (encrypted) binary log files for end-user logs. We use the SmartInspect Console as the viewer and monitoring tool.
There are actually quite a few logging frameworks and tools for .NET out there. There's an overview and comparison of the different tools on DotNetLogging.com.
Another thing to notice is you are trying to convert a date in mm/dd/yyyy but if you have any plans of comparing this converted date to some other date then make sure to convert it in yyyy-mm-dd format only since to_char literally converts it into a string and with any other format we will get undesired result. For any more explanation follow this: Comparing Dates in Oracle SQL
Does first function isValidDate(s) proposed by RobG will work for input string '1/2/'? I think NOT, because the YEAR is not validated ;(
My proposition is to use improved version of this function:
//input in ISO format: yyyy-MM-dd
function DatePicker_IsValidDate(input) {
var bits = input.split('-');
var d = new Date(bits[0], bits[1] - 1, bits[2]);
return d.getFullYear() == bits[0] && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[2]);
}
i think Access is a best choice for your case. But you have to split database, see: http://accessblog.net/2005/07/how-to-split-database-into-be-and-fe.html
•How can we make sure that the write-user can make changes to the table data while other users use the data? Do the read-users put locks on tables? Does the write-user have to put locks on the table? Does Access do this for us or do we have to explicitly code this?
there are no read locks unless you put them explicitly. Just use "No Locks"
•Are there any common problems with "MS Access transactions" that we should be aware of?
should not be problems with 1-2 write users
•Can we work on forms, queries etc. while they are being used? How can we "program" without being in the way of the users?
if you split database - then no problem to work on FE design.
•Which settings in MS Access have an influence on how things are handled?
What do you mean?
•Our background is mostly in Oracle, where is Access different in handling multiple users? Is there such thing as "isolation levels" in Access?
no isolation levels in access. BTW, you can then later move data to oracle and keep access frontend, if you have lot of users and big database.
Do not forget to verify if your text editor encodes properly your code in UTF-8.
Otherwise, you may have invisible characters that are not interpreted as UTF-8.
Here's a jQuery plugin that I wrote to merge two object arrays by a key. Keep in mind that this modifies the destination array in-place.
(function($) {_x000D_
$.extendObjectArray = function(destArray, srcArray, key) {_x000D_
for (var index = 0; index < srcArray.length; index++) {_x000D_
var srcObject = srcArray[index];_x000D_
var existObject = destArray.filter(function(destObj) {_x000D_
return destObj[key] === srcObject[key];_x000D_
});_x000D_
if (existObject.length > 0) {_x000D_
var existingIndex = destArray.indexOf(existObject[0]);_x000D_
$.extend(true, destArray[existingIndex], srcObject);_x000D_
} else {_x000D_
destArray.push(srcObject);_x000D_
}_x000D_
}_x000D_
return destArray;_x000D_
};_x000D_
})(jQuery);_x000D_
_x000D_
var arr1 = [_x000D_
{ name: "lang", value: "English" },_x000D_
{ name: "age", value: "18" }_x000D_
];_x000D_
var arr2 = [_x000D_
{ name: "childs", value: '5' },_x000D_
{ name: "lang", value: "German" }_x000D_
];_x000D_
var arr3 = $.extendObjectArray(arr1, arr2, 'name');_x000D_
_x000D_
console.log(JSON.stringify(arr3, null, 2));
_x000D_
.as-console-wrapper { top: 0; max-height: 100% !important; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
(function($) {
$.extendObjectArray = (destArr, srcArr, key) => {
srcArr.forEach(srcObj => (existObj => {
if (existObj.length) {
$.extend(true, destArr[destArr.indexOf(existObj[0])], srcObj);
} else {
destArr.push(srcObj);
}
})(destArr.filter(v => v[key] === srcObj[key])));
return destArr;
};
})(jQuery);
Simply put list(yourQuerySet)
.
Another way is using HashSet
:
var hash = new HashSet<int>();
var duplicates = list.Where(i => !hash.Add(i));
If you want unique values in your duplicates list:
var myhash = new HashSet<int>();
var mylist = new List<int>(){1,1,2,2,3,3,3,4,4,4};
var duplicates = mylist.Where(item => !myhash.Add(item)).Distinct().ToList();
Here is the same solution as a generic extension method:
public static class Extensions
{
public static IEnumerable<TSource> GetDuplicates<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector, IEqualityComparer<TKey> comparer)
{
var hash = new HashSet<TKey>(comparer);
return source.Where(item => !hash.Add(selector(item))).ToList();
}
public static IEnumerable<TSource> GetDuplicates<TSource>(this IEnumerable<TSource> source, IEqualityComparer<TSource> comparer)
{
return source.GetDuplicates(x => x, comparer);
}
public static IEnumerable<TSource> GetDuplicates<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector)
{
return source.GetDuplicates(selector, null);
}
public static IEnumerable<TSource> GetDuplicates<TSource>(this IEnumerable<TSource> source)
{
return source.GetDuplicates(x => x, null);
}
}
Virtualenv is your friend
Even if you want to add a package to your primary install, it's still best to do it in a virtual environment first, to ensure compatibility with your other packages. However, if you get familiar with virtualenv, you'll probably find there's really no reason to install anything in your base install.
For all of you who believe the myth that temp variables are in memory only
First, the table variable is NOT necessarily memory resident. Under memory pressure, the pages belonging to a table variable can be pushed out to tempdb.
Read the article here: TempDB:: Table variable vs local temporary table
It may not be quite what you want, since it's not a standard command on anyone's systems, but since my program should work fine on POSIX systems (if compiled), I'll mention it anyway. If you have the ability to compile or add programs on the machine in question, it should work.
I've used it without issue for about a year now, but it could be that it won't handle some edge cases. Most specifically, I have no idea what it would do with newlines in strings; a case for \\n
might need to be added. This list of characters is not authoritative, but I believe it covers everything else.
I wrote this specifically as a 'helper' program so I could make a wrapper for things like scp
commands.
It can likely be implemented as a shell function as well
I therefore present escapify.c
. I use it like so:
scp user@host:"$(escapify "/this/path/needs to be escaped/file.c")" destination_file.c
PLEASE NOTE: I made this program for my own personal use. It also will (probably wrongly) assume that if it is given more than one argument that it should just print an unescaped space and continue on. This means that it can be used to pass multiple escaped arguments correctly, but could be seen as unwanted behavior by some.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
char c='\0';
int i=0;
int j=1;
/* do not care if no args passed; escaped nothing is still nothing. */
if(argc < 2)
{
return 0;
}
while(j<argc)
{
while(i<strlen(argv[j]))
{
c=argv[j][i];
/* this switch has no breaks on purpose. */
switch(c)
{
case ';':
case '\'':
case ' ':
case '!':
case '"':
case '#':
case '$':
case '&':
case '(':
case ')':
case '|':
case '*':
case ',':
case '<':
case '>':
case '[':
case ']':
case '\\':
case '^':
case '`':
case '{':
case '}':
putchar('\\');
default:
putchar(c);
}
i++;
}
j++;
if(j<argc) {
putchar(' ');
}
i=0;
}
/* newline at end */
putchar ('\n');
return 0;
}
Through the Computer management console, navigate through Event Viewer > Windows Logs > System. Every services that change state will be logged here.
You'll see info like: The XXXX service entered the running state or The XXXX service entered the stopped state, etc.
final static String EXTRA_MESSAGE = "edit.list.message";
Context context;
public void onClick (View view)
{
Intent intent = new Intent(this,display.class);
RelativeLayout relativeLayout = (RelativeLayout) view.getParent();
TextView textView = (TextView) relativeLayout.findViewById(R.id.textView1);
String message = textView.getText().toString();
intent.putExtra(EXTRA_MESSAGE,message);
startActivity(intent);
}
In a newer version of pandas (0.17 and up), you can use to_numeric function. It allows you to convert the whole dataframe or just individual columns. It also gives you an ability to select how to treat stuff that can't be converted to numeric values:
import pandas as pd
s = pd.Series(['1.0', '2', -3])
pd.to_numeric(s)
s = pd.Series(['apple', '1.0', '2', -3])
pd.to_numeric(s, errors='ignore')
pd.to_numeric(s, errors='coerce')
mysqldiskusage --server=root:MyPassword@localhost pics
+----------+----------------+
| db_name | total |
+----------+----------------+
| pics | 1,179,131,029 |
+----------+----------------+
If not installed, this can be installed by installing the mysql-utils
package which should be packaged by most major distributions.
I doubt you can rotate an element using DOM/CSS. Your best bet would be to render to a canvas and rotate that (not sure on the specifics).
Try this, it's working for me.
Sender:
byte[] message = ...
Socket socket = ...
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
dOut.writeInt(message.length); // write length of the message
dOut.write(message); // write the message
Receiver:
Socket socket = ...
DataInputStream dIn = new DataInputStream(socket.getInputStream());
int length = dIn.readInt(); // read length of incoming message
if(length>0) {
byte[] message = new byte[length];
dIn.readFully(message, 0, message.length); // read the message
}
Many thanks to @Ciro Santilli answer! I found that his choice for boundary is quite "unhappy" because all of thoose hyphens: in fact, as @Fake Name commented, when you are using your boundary inside request it comes with two more hyphens on front:
Example:
POST / HTTP/1.1
HOST: host.example.com
Cookie: some_cookies...
Connection: Keep-Alive
Content-Type: multipart/form-data; boundary=12345
--12345
Content-Disposition: form-data; name="sometext"
some text that you wrote in your html form ...
--12345
Content-Disposition: form-data; name="name_of_post_request" filename="filename.xyz"
content of filename.xyz that you upload in your form with input[type=file]
--12345
Content-Disposition: form-data; name="image" filename="picture_of_sunset.jpg"
content of picture_of_sunset.jpg ...
--12345--
I found on this w3.org page that is possible to incapsulate multipart/mixed header in a multipart/form-data, simply choosing another boundary string inside multipart/mixed and using that one to incapsulate data. At the end, you must "close" all boundary used in FILO order to close the POST request (like:
POST / HTTP/1.1
...
Content-Type: multipart/form-data; boundary=12345
--12345
Content-Disposition: form-data; name="sometext"
some text sent via post...
--12345
Content-Disposition: form-data; name="files"
Content-Type: multipart/mixed; boundary=abcde
--abcde
Content-Disposition: file; file="picture.jpg"
content of jpg...
--abcde
Content-Disposition: file; file="test.py"
content of test.py file ....
--abcde--
--12345--
Take a look at the link above.
Try adding the drive letter:
include_path='.;c:\xampplite\php\pear\PEAR'
also verify that PEAR.php is actually there, it might be in \php\ instead:
include_path='.;c:\xampplite\php'
I fixed it very simple:
.parent {
position: relative;
z-index: 1;
}
.child {
position: absolute;
z-index: -1;
}
What this does is stack the parent at z-index: 1, which gives the child room to 'end up' at z-index: 0 since other dom elements 'exist' on z-index: 0. If we don't give the parent an z-index of 1 the child will end up below the other dom elements and thus will not be visible.
This also works for pseudo elements like :after
You can remove an entry from your map by explicitly assigning it to 'undefined'. As in your case:
myArray["lastname"] = undefined;
The result depends on the timezone that corresponds to the input time strings.
The simplest case if both dates use the same utc offset:
#!/usr/bin/env python3
from datetime import datetime, timedelta
time_format = "%Y-%d-%m %H:%M:%S"
dt1 = datetime.strptime("2010-01-01 17:31:22", time_format)
dt2 = datetime.strptime("2010-01-03 17:31:22", time_format)
print((dt2 - dt1) // timedelta(minutes=1)) # minutes
If your Python version doesn't support td // timedelta
; replace it with int(td.total_seconds() // 60)
.
If the input time is in the local timezone that might have different utc offset at different times e.g., it has daylight saving time then you should make dt1
, dt2
into aware datetime objects before finding the difference, to take into account the possible changes in the utc offset.
The portable way to make an aware local datetime objects is to use pytz
timezones:
#!/usr/bin/env python
from datetime import timedelta
import tzlocal # $ pip install tzlocal
local_tz = tzlocal.get_localzone() # get pytz timezone
aware_dt1, aware_dt2 = map(local_tz.localize, [dt1, dt2])
td = aware_dt2 - aware_dt1 # elapsed time
If either dt1
or dt2
correspond to an ambiguous time then the default is_dst=False
is used to disambiguate. You could set is_dst=None
to raise an exception for ambiguous or non-existent local times instead.
If you can't install 3rd party modules then time.mktime()
could be used from @Ken Cochrane's answer that can find the correct utc offset on some platforms for some dates in some timezones -- if you don't need a consistent (but perhaps wrong) result then it is much better than doing dt2 - dt1
with naive datetime objects that always fails if the corresponding utc offsets are different.
@PathVariable
is to obtain some placeholder from the URI (Spring call it an URI Template)
— see Spring Reference Chapter 16.3.2.2 URI Template Patterns@RequestParam
is to obtain a parameter from the URI as well — see Spring Reference Chapter 16.3.3.3 Binding request parameters to method parameters with @RequestParamIf the URL http://localhost:8080/MyApp/user/1234/invoices?date=12-05-2013
gets the invoices for user 1234 on December 5th, 2013, the controller method would look like:
@RequestMapping(value="/user/{userId}/invoices", method = RequestMethod.GET)
public List<Invoice> listUsersInvoices(
@PathVariable("userId") int user,
@RequestParam(value = "date", required = false) Date dateOrNull) {
...
}
Also, request parameters can be optional, and as of Spring 4.3.3 path variables can be optional as well. Beware though, this might change the URL path hierarchy and introduce request mapping conflicts. For example, would /user/invoices
provide the invoices for user null
or details about a user with ID "invoices"?
GitLab's "merge request" feature is equivalent to GitHub's "pull request" feature. Both are means of pulling changes from another branch or fork into your branch and merging the changes with your existing code. They are useful tools for code review and change management.
An article from GitLab discusses the differences in naming the feature:
Merge or pull requests are created in a git management application and ask an assigned person to merge two branches. Tools such as GitHub and Bitbucket choose the name pull request since the first manual action would be to pull the feature branch. Tools such as GitLab and Gitorious choose the name merge request since that is the final action that is requested of the assignee. In this article we'll refer to them as merge requests.
A "merge request" should not be confused with the git merge
command. Neither should a "pull request" be confused with the git pull
command. Both git
commands are used behind the scenes in both pull requests and merge requests, but a merge/pull request refers to a much broader topic than just these two commands.
Assuming that you are using mvn and cloudera distribution of hadoop. I'm using cdh4.6 and adding these dependencies worked for me.I think you should check the versions of hadoop and mvn dependencies.
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-core</artifactId>
<version>2.0.0-mr1-cdh4.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>2.0.0-cdh4.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
<version>2.0.0-cdh4.6.0</version>
</dependency>
don't forget to add cloudera mvn repository.
<repository>
<id>cloudera</id>
<url>https://repository.cloudera.com/artifactory/cloudera-repos/</url>
</repository>
Here’s the modern answer.
DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
DateTimeFormatter displayFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.forLanguageTag("zh-SG"));
String dateString = "31/05/2011";
LocalDate date = LocalDate.parse(dateString, sourceFormatter);
System.out.println(date.format(displayFormatter));
Output from this snippet is:
31/05/11
See if you can live with the 2-digit year. Or use FormatStyle.MEDIUM
to obtain 2011?5?31?
. I recommend you use Java’s built-in date and time formats when you can. It’s easier and lends itself very well to internationalization.
If you need the exact format you gave, just use the source formatter as display formatter too:
System.out.println(date.format(sourceFormatter));
31/05/2011
I recommend you don’t use SimpleDateFormat
. It’s notoriously troublesome and long outdated. Instead I use java.time, the modern Java date and time API.
To obtain a specific format you need to format the parsed date back into a string. Netiher an old-fashioned Date
nor a modern LocalDate
can have a format in it.
Link: Oracle tutorial: Date Time explaining how to use java.time.
jQuery.trim() works well.
create table employee
(
empid int,
empname varchar(40),
designation varchar(30),
hiredate datetime,
Bsalary int,
depno constraint emp_m foreign key references department(depno)
)
We should have an primary key to create foreign key or relationship between two or more table .
What you are looking for is called Model persistence in sklearn words and it is documented in introduction and in model persistence sections.
So you have initialized your classifier and trained it for a long time with
clf = some.classifier()
clf.fit(X, y)
After this you have two options:
1) Using Pickle
import pickle
# now you can save it to a file
with open('filename.pkl', 'wb') as f:
pickle.dump(clf, f)
# and later you can load it
with open('filename.pkl', 'rb') as f:
clf = pickle.load(f)
2) Using Joblib
from sklearn.externals import joblib
# now you can save it to a file
joblib.dump(clf, 'filename.pkl')
# and later you can load it
clf = joblib.load('filename.pkl')
One more time it is helpful to read the above-mentioned links
Take below reference to convert a JSON into POJO and vice-versa
Let's suppose your JSON schema looks like:
{
"type":"object",
"properties": {
"dataOne": {
"type": "string"
},
"dataTwo": {
"type": "integer"
},
"dataThree": {
"type": "boolean"
}
}
}
Then to covert into POJO, your need to decleare some classes as explained in below style:
==================================
package ;
public class DataOne
{
private String type;
public void setType(String type){
this.type = type;
}
public String getType(){
return this.type;
}
}
==================================
package ;
public class DataTwo
{
private String type;
public void setType(String type){
this.type = type;
}
public String getType(){
return this.type;
}
}
==================================
package ;
public class DataThree
{
private String type;
public void setType(String type){
this.type = type;
}
public String getType(){
return this.type;
}
}
==================================
package ;
public class Properties
{
private DataOne dataOne;
private DataTwo dataTwo;
private DataThree dataThree;
public void setDataOne(DataOne dataOne){
this.dataOne = dataOne;
}
public DataOne getDataOne(){
return this.dataOne;
}
public void setDataTwo(DataTwo dataTwo){
this.dataTwo = dataTwo;
}
public DataTwo getDataTwo(){
return this.dataTwo;
}
public void setDataThree(DataThree dataThree){
this.dataThree = dataThree;
}
public DataThree getDataThree(){
return this.dataThree;
}
}
==================================
package ;
public class Root
{
private String type;
private Properties properties;
public void setType(String type){
this.type = type;
}
public String getType(){
return this.type;
}
public void setProperties(Properties properties){
this.properties = properties;
}
public Properties getProperties(){
return this.properties;
}
}
In Java, 2D arrays are really arrays of arrays with possibly different lengths (there are no guarantees that in 2D arrays that the 2nd dimension arrays all be the same length)
You can get the length of any 2nd dimension array as z[n].length
where 0 <= n < z.length
.
If you're treating your 2D array as a matrix, you can simply get z.length
and z[0].length
, but note that you might be making an assumption that for each array in the 2nd dimension that the length is the same (for some programs this might be a reasonable assumption).
One thing you might want to consider besides the other issues mentioned is that isEmpty()
was introduced in 1.6, so if you use it you won't be able to run the code on Java 1.5 or below.
See: http://www.postgresql.org/docs/9.1/static/arrays.html
If your non-native driver still does not allow you to pass arrays, then you can:
pass a string representation of an array (which your stored procedure can then parse into an array -- see string_to_array
)
CREATE FUNCTION my_method(TEXT) RETURNS VOID AS $$
DECLARE
ids INT[];
BEGIN
ids = string_to_array($1,',');
...
END $$ LANGUAGE plpgsql;
then
SELECT my_method(:1)
with :1 = '1,2,3,4'
rely on Postgres itself to cast from a string to an array
CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$
...
END $$ LANGUAGE plpgsql;
then
SELECT my_method('{1,2,3,4}')
choose not to use bind variables and issue an explicit command string with all parameters spelled out instead (make sure to validate or escape all parameters coming from outside to avoid SQL injection attacks.)
CREATE FUNCTION my_method(INT[]) RETURNS VOID AS $$
...
END $$ LANGUAGE plpgsql;
then
SELECT my_method(ARRAY [1,2,3,4])
The simplest way I found is to use BitmapDescriptorFactory.defaultMarker() the documentation even has an example of setting the color. From my own code:
MarkerOptions marker = new MarkerOptions()
.title(formatInfo(data))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.position(new LatLng(data.getLatitude(), data.getLongitude()))
I share my solution (assuming everything is already configured to connect to google bucket in flask)
from google.cloud import storage
@app.route('/upload/', methods=['POST'])
def upload():
if request.method == 'POST':
# FileStorage object wrapper
file = request.files["file"]
if file:
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = app.config['GOOGLE_APPLICATION_CREDENTIALS']
bucket_name = "bucket_name"
storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)
# Upload file to Google Bucket
blob = bucket.blob(file.filename)
blob.upload_from_string(file.read())
My post
You may use this class to test two accessing threads and one mutating the shared instance of ConcurrentHashMap
:
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ConcurrentMapIteration
{
private final Map<String, String> map = new ConcurrentHashMap<String, String>();
private final static int MAP_SIZE = 100000;
public static void main(String[] args)
{
new ConcurrentMapIteration().run();
}
public ConcurrentMapIteration()
{
for (int i = 0; i < MAP_SIZE; i++)
{
map.put("key" + i, UUID.randomUUID().toString());
}
}
private final ExecutorService executor = Executors.newCachedThreadPool();
private final class Accessor implements Runnable
{
private final Map<String, String> map;
public Accessor(Map<String, String> map)
{
this.map = map;
}
@Override
public void run()
{
for (Map.Entry<String, String> entry : this.map.entrySet())
{
System.out.println(
Thread.currentThread().getName() + " - [" + entry.getKey() + ", " + entry.getValue() + ']'
);
}
}
}
private final class Mutator implements Runnable
{
private final Map<String, String> map;
private final Random random = new Random();
public Mutator(Map<String, String> map)
{
this.map = map;
}
@Override
public void run()
{
for (int i = 0; i < 100; i++)
{
this.map.remove("key" + random.nextInt(MAP_SIZE));
this.map.put("key" + random.nextInt(MAP_SIZE), UUID.randomUUID().toString());
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
private void run()
{
Accessor a1 = new Accessor(this.map);
Accessor a2 = new Accessor(this.map);
Mutator m = new Mutator(this.map);
executor.execute(a1);
executor.execute(m);
executor.execute(a2);
}
}
No exception will be thrown.
Sharing the same iterator between accessor threads can lead to deadlock:
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ConcurrentMapIteration
{
private final Map<String, String> map = new ConcurrentHashMap<String, String>();
private final Iterator<Map.Entry<String, String>> iterator;
private final static int MAP_SIZE = 100000;
public static void main(String[] args)
{
new ConcurrentMapIteration().run();
}
public ConcurrentMapIteration()
{
for (int i = 0; i < MAP_SIZE; i++)
{
map.put("key" + i, UUID.randomUUID().toString());
}
this.iterator = this.map.entrySet().iterator();
}
private final ExecutorService executor = Executors.newCachedThreadPool();
private final class Accessor implements Runnable
{
private final Iterator<Map.Entry<String, String>> iterator;
public Accessor(Iterator<Map.Entry<String, String>> iterator)
{
this.iterator = iterator;
}
@Override
public void run()
{
while(iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
try
{
String st = Thread.currentThread().getName() + " - [" + entry.getKey() + ", " + entry.getValue() + ']';
} catch (Exception e)
{
e.printStackTrace();
}
}
}
}
private final class Mutator implements Runnable
{
private final Map<String, String> map;
private final Random random = new Random();
public Mutator(Map<String, String> map)
{
this.map = map;
}
@Override
public void run()
{
for (int i = 0; i < 100; i++)
{
this.map.remove("key" + random.nextInt(MAP_SIZE));
this.map.put("key" + random.nextInt(MAP_SIZE), UUID.randomUUID().toString());
}
}
}
private void run()
{
Accessor a1 = new Accessor(this.iterator);
Accessor a2 = new Accessor(this.iterator);
Mutator m = new Mutator(this.map);
executor.execute(a1);
executor.execute(m);
executor.execute(a2);
}
}
As soon as you start sharing the same Iterator<Map.Entry<String, String>>
among accessor and mutator threads java.lang.IllegalStateException
s will start popping up.
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ConcurrentMapIteration
{
private final Map<String, String> map = new ConcurrentHashMap<String, String>();
private final Iterator<Map.Entry<String, String>> iterator;
private final static int MAP_SIZE = 100000;
public static void main(String[] args)
{
new ConcurrentMapIteration().run();
}
public ConcurrentMapIteration()
{
for (int i = 0; i < MAP_SIZE; i++)
{
map.put("key" + i, UUID.randomUUID().toString());
}
this.iterator = this.map.entrySet().iterator();
}
private final ExecutorService executor = Executors.newCachedThreadPool();
private final class Accessor implements Runnable
{
private final Iterator<Map.Entry<String, String>> iterator;
public Accessor(Iterator<Map.Entry<String, String>> iterator)
{
this.iterator = iterator;
}
@Override
public void run()
{
while (iterator.hasNext())
{
Map.Entry<String, String> entry = iterator.next();
try
{
String st =
Thread.currentThread().getName() + " - [" + entry.getKey() + ", " + entry.getValue() + ']';
} catch (Exception e)
{
e.printStackTrace();
}
}
}
}
private final class Mutator implements Runnable
{
private final Random random = new Random();
private final Iterator<Map.Entry<String, String>> iterator;
private final Map<String, String> map;
public Mutator(Map<String, String> map, Iterator<Map.Entry<String, String>> iterator)
{
this.map = map;
this.iterator = iterator;
}
@Override
public void run()
{
while (iterator.hasNext())
{
try
{
iterator.remove();
this.map.put("key" + random.nextInt(MAP_SIZE), UUID.randomUUID().toString());
} catch (Exception ex)
{
ex.printStackTrace();
}
}
}
}
private void run()
{
Accessor a1 = new Accessor(this.iterator);
Accessor a2 = new Accessor(this.iterator);
Mutator m = new Mutator(map, this.iterator);
executor.execute(a1);
executor.execute(m);
executor.execute(a2);
}
}
Try to use datepicker/ timepicker instead of datetimepicker like:
replace:
$('#datetimepicker1').datetimepicker();
with:
$('#datetimepicker1').datepicker(); // or timepicker for time picker
You can enable the CURLOPT_VERBOSE
option:
curl_setopt($curlhandle, CURLOPT_VERBOSE, true);
When CURLOPT_VERBOSE
is set, output is written to STDERR or the file specified using CURLOPT_STDERR
. The output is very informative.
You can also use tcpdump or wireshark to watch the network traffic.
As an alternative to some of the answers suggested above, if you have powershell installed, you can invoke that directly as your terminal. That is edit the corresponding setting.json
value as follows:
"terminal.integrated.shell.windows": "C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe"
I find this works well as the environment is correctly configured.
/**
* If $header is an array of headers
* It will format and return the correct $header
* $header = [
* 'Accept' => 'application/json',
* 'Content-Type' => 'application/x-www-form-urlencoded'
* ];
*/
$i_header = $header;
if(is_array($i_header) === true){
$header = [];
foreach ($i_header as $param => $value) {
$header[] = "$param: $value";
}
}
If there is no existing method then I guess you can iterate from 0 to input.size()/2
, taking each consecutive element and appending it to a new ArrayList.
EDIT: Actually, I think you can take that List and use it to instantiate a new ArrayList using one of the ArrayList constructors.
Well, everybody giving their answer so I thought I write too.
I am having the same proxy issue as all others. To solve this I tried many solutions but it did not work.
Search .npmrc file name in C:\Users\your_username drive and than add this line:
I did only this and my is solved.
If you have to use href for backwards compability, you can also use
<a href="javascript:void(0)">link</a>
instead of # ,if you don't want to use the attribute
On MacOSX, you run top command as well but need to type "o" then "vsize" then ENTER.
Yes, your secret key appears to be missing. Without it, you will not be able to decrypt the files.
Do you have the key backed up somewhere?
Re-creating the keys, whether you use the same passphrase or not, will not work. Each key pair is unique.
Just append a #
followed by the ID of the <a>
tag (or other HTML tag, like a <section>
) that you're trying to get to. For example, if you are trying to link to the header in this HTML:
<p>This is some content.</p>
<h2><a id="target">Some Header</a></h2>
<p>This is some more content.</p>
You could use the link <a href="http://url.to.site/index.html#target">Link</a>
.
update based on Ordering by the order of values in a SQL IN() clause
Solution:
DECLARE @counter int
SET @counter = 0
;WITH q AS
(
select * from Products WHERE ID in (SELECT TOP (10) ID FROM Products WHERE ID IN( 3,2,1)
ORDER BY ID DESC)
)
update q set Display= @counter, @counter = @counter + 1
This updates based on descending 3,2,1
Hope helps someone.
Be aware that running
import os
os.system("tzutil /s \"Central Standard Time\"");
will alter Windows system time, NOT just the local python environment time (so is definitley NOT the same as:
>>> os.environ['TZ'] = 'Europe/London'
>>> time.tzset()
which will only set in the current environment time (in Unix only)
Google Custom Search (as advocated in the top rated answers) works well, but is very expensive, compared to its competitors (below) or compared to other Google API's. It has a small free tier (100 queries/day) and a very high price of $5 per 1000 query.
They offer the option to upgrade to Site Search, which has slightly better prices, but that is meant for searching one site (your own), so it is really something quite different - not an upgrade.
The main alternatives seem to be:
Bing Search API
https://datamarket.azure.com/dataset/5BA839F1-12CE-4CCE-BF57-A49D98D29A44
Which has a free tier of 5000q/month, and prices starting at 5 query per penny, and no hard limit.
UPDATE: At the end of 2016 this API was shutdown in favour of its Azure counterpart "Cognitive Services Bing Search API":
https://azure.microsoft.com/en-us/services/cognitive-services/search/
See here for a pricing chart, which starts at US$3/m for 1,000 transactions. Unless I'm missing something it is quite expensive.
Yahoo BOSS Search API
UPDATE: Was discontinued on March 31, 2016.
http://developer.yahoo.com/boss/search/
With prices starting at about 12 queries/penny for whole web searches.
And some I haven't heard of before:
http://www.gigablast.com/searchfeed.html
http://www.faroo.com/hp/api/api.html
http://www.entireweb.com/search_api/implementation/
[discontinued - as pointed out below]
There is a bit of discussion of some of these on this SO post.
[got closed for being off-topic and is now gone]
There are a lot of good answers here, but I only want to add one thing. It sometimes happens that you want to scroll your ScrollView to a specific view of the layout, instead of a full scroll to the top or the bottom.
A simple example: in a registration form, if the user tap the "Signup" button when a edit text of the form is not filled, you want to scroll to that specific edit text to tell the user that he must fill that field.
In that case, you can do something like that:
scrollView.post(new Runnable() {
public void run() {
scrollView.scrollTo(0, editText.getBottom());
}
});
or, if you want a smooth scroll instead of an instant scroll:
scrollView.post(new Runnable() {
public void run() {
scrollView.smoothScrollTo(0, editText.getBottom());
}
});
Obviously you can use any type of view instead of Edit Text. Note that getBottom() returns the coordinates of the view based on its parent layout, so all the views used inside the ScrollView should have only a parent (for example a Linear Layout).
If you have multiple parents inside the child of the ScrollView, the only solution i've found is to call requestChildFocus on the parent view:
editText.getParent().requestChildFocus(editText, editText);
but in this case you cannot have a smooth scroll.
I hope this answer can help someone with the same problem.
In Mongoose: from the document:
To remove a document from a subdocument array we may pass an object with a matching _id.
contact.phone.pull({ _id: itemId }) // remove
contact.phone.pull(itemId); // this also works
See Leonid Beschastny's answer for the correct answer.
A very simple & most powerful solution to vertically align center:
.outer-div {_x000D_
height: 200px;_x000D_
width: 200px;_x000D_
text-align: center;_x000D_
border: 1px solid #000;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
position: relative;_x000D_
top: 50%;_x000D_
transform: translateY(-50%);_x000D_
color: red;_x000D_
}
_x000D_
<div class="outer-div">_x000D_
<span class="inner">No data available</span>_x000D_
</div>
_x000D_
As ant31 already pointed out you can use the synchronize
module to this. By default, the module transfers files between the control machine and the current remote host (inventory_host
), however that can be changed using the task's delegate_to
parameter (it's important to note that this is a parameter of the task, not of the module).
You can place the task on either ServerA
or ServerB
, but you have to adjust the direction of the transfer accordingly (using the mode
parameter of synchronize
).
Placing the task on ServerB
- hosts: ServerB
tasks:
- name: Transfer file from ServerA to ServerB
synchronize:
src: /path/on/server_a
dest: /path/on/server_b
delegate_to: ServerA
This uses the default mode: push
, so the file gets transferred from the delegate (ServerA
) to the current remote (ServerB
).
This might sound like strange, since the task has been placed on ServerB
(via hosts: ServerB
). However, one has to keep in mind that the task is actually executed on the delegated host, which in this case is ServerA
. So pushing (from ServerA
to ServerB
) is indeed the correct direction. Also remember that we cannot simply choose not to delegate at all, since that would mean that the transfer happens between the control machine and ServerB
.
Placing the task on ServerA
- hosts: ServerA
tasks:
- name: Transfer file from ServerA to ServerB
synchronize:
src: /path/on/server_a
dest: /path/on/server_b
mode: pull
delegate_to: ServerB
This uses mode: pull
to invert the transfer direction. Again, keep in mind that the task is actually executed on ServerB
, so pulling is the right choice.
If your goal is to initialize the static variable in your header file (instead of a *.cpp file, which you may want if you are sticking to a "header only" idiom), then you can work around the initialization problem by using a template. Templated static variables can be initialized in a header, without causing multiple symbols to be defined.
See here for an example:
I have written a quick example to demonstrate how to create a layout programmatically.
public class CodeLayout extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Creating a new RelativeLayout
RelativeLayout relativeLayout = new RelativeLayout(this);
// Defining the RelativeLayout layout parameters.
// In this case I want to fill its parent
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);
// Creating a new TextView
TextView tv = new TextView(this);
tv.setText("Test");
// Defining the layout parameters of the TextView
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
// Setting the parameters on the TextView
tv.setLayoutParams(lp);
// Adding the TextView to the RelativeLayout as a child
relativeLayout.addView(tv);
// Setting the RelativeLayout as our content view
setContentView(relativeLayout, rlp);
}
}
In theory everything should be clear as it is commented. If you don't understand something just tell me.
The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.
That being said, I suggest looking at buildwith.com
You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.
To suppress the page number on the first page, add \thispagestyle{empty}
after the \maketitle
command.
The second page of the document will then be numbered "2". If you want this page to be numbered "1", you can add \pagenumbering{arabic}
after the \clearpage
command, and this will reset the page number.
Here's a complete minimal example:
\documentclass[notitlepage]{article}
\title{My Report}
\author{My Name}
\begin{document}
\maketitle
\thispagestyle{empty}
\begin{abstract}
\ldots
\end{abstract}
\clearpage
\pagenumbering{arabic}
\section{First Section}
\ldots
\end{document}
From the Markdown Cheatsheet:
You can add it to your repo and reference it with an image tag:
Inline-style:
![alt text](https://github.com/adam-p/markdown-here/raw/master/src/common/images/icon48.png "Logo Title Text 1")
Reference-style:
![alt text][logo]
[logo]: https://github.com/adam-p/markdown-here/raw/master/src/common/images/icon48.png "Logo Title Text 2"
Inline-style:
Reference-style:
Alternatively you can use the url directly:
![](http://www.reactiongifs.us/wp-content/uploads/2013/10/nuh_uh_conan_obrien.gif)
This is a fairly old question, but I though I should post this. It is a foreach loop for GNU C99.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define FOREACH_COMP(INDEX, ARRAY, ARRAY_TYPE, SIZE) \
__extension__ \
({ \
bool ret = 0; \
if (__builtin_types_compatible_p (const char*, ARRAY_TYPE)) \
ret = INDEX < strlen ((const char*)ARRAY); \
else \
ret = INDEX < SIZE; \
ret; \
})
#define FOREACH_ELEM(INDEX, ARRAY, TYPE) \
__extension__ \
({ \
TYPE *tmp_array_ = ARRAY; \
&tmp_array_[INDEX]; \
})
#define FOREACH(VAR, ARRAY) \
for (void *array_ = (void*)(ARRAY); array_; array_ = 0) \
for (size_t i_ = 0; i_ && array_ && FOREACH_COMP (i_, array_, \
__typeof__ (ARRAY), \
sizeof (ARRAY) / sizeof ((ARRAY)[0])); \
i_++) \
for (bool b_ = 1; b_; (b_) ? array_ = 0 : 0, b_ = 0) \
for (VAR = FOREACH_ELEM (i_, array_, __typeof__ ((ARRAY)[0])); b_; b_ = 0)
/* example's */
int
main (int argc, char **argv)
{
int array[10];
/* initialize the array */
int i = 0;
FOREACH (int *x, array)
{
*x = i;
++i;
}
char *str = "hello, world!";
FOREACH (char *c, str)
printf ("%c\n", *c);
return EXIT_SUCCESS;
}
This code has been tested to work with gcc, icc and clang on GNU/Linux.
Here is solution implemented with ES6
const toggleClass = (el, className) => el.classList.toggle(className);
usage example
toggleClass(document.querySelector('div.active'), 'active'); // The div container will not have the 'active' class anymore
With ES6 you can write this:
const countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
const $ul = $('<ul>', { class: "mylist" }).append(
countries.map(country =>
$("<li>").append($("<a>").text(country))
)
);
This is possible due to type erasure. You will find that
List<TestA> x = new ArrayList<TestA>();
List<TestB> y = new ArrayList<TestB>();
x.getClass().equals(y.getClass()); // true
Internally both lists are of type List<Object>
. For that reason you can't cast one to the other - there is nothing to cast.
Your CustomValidator
will only fire when the TextBox
isn't empty.
If you need to ensure that it's not empty then you'll need a RequiredFieldValidator
too.
EDIT:
If your CustomValidator
specifies the ControlToValidate
attribute (and your original example does) then your validation functions will only be called when the control isn't empty.
If you don't specify ControlToValidate
then your validation functions will be called every time.
This opens up a second possible solution to the problem. Rather than using a separate RequiredFieldValidator
, you could omit the ControlToValidate
attribute from the CustomValidator
and setup your validation functions to do something like this:
Client Side code (Javascript):
function TextBoxDCountyClient(sender, args) {
var v = document.getElementById('<%=TextBoxDTownCity.ClientID%>').value;
if (v == '') {
args.IsValid = false; // field is empty
}
else {
// do your other validation tests here...
}
}
Server side code (C#):
protected void TextBoxDTownCity_Validate(
object source, ServerValidateEventArgs args)
{
string v = TextBoxDTownCity.Text;
if (v == string.Empty)
{
args.IsValid = false; // field is empty
}
else
{
// do your other validation tests here...
}
}
My understanding is that "-u" or "--set-upstream" allows you to specify the upstream (remote) repository for the branch you're on, so that next time you run "git push", you don't even have to specify the remote repository.
Push and set upstream (remote) repository as origin:
$ git push -u origin
Next time you push, you don't have to specify the remote repository:
$ git push
I was working on Azure SQL server .For storing the data i used table values param like
DECLARE @INTERMEDIATE_TABLE3 TABLE {
x int;
}
I discovered the error in writing on the queries
SELECT
*
FROM [@INTERMEDIATE_TABLE3]
WHERE [@INTERMEDIATE_TABLE3].[ConsentDefinitionId] = 3
while quering the colomns ,its okay to wrap it with brabces like [@INTERMEDIATE_TABLE3].[ConsentDefinitionId] but when refering just the table valued param ,there shoul be no params.So it should be used as @INTERMEDIATE_TABLE3
So the code now must be changed to
SELECT
*
FROM @INTERMEDIATE_TABLE3
WHERE [@INTERMEDIATE_TABLE3].[ConsentDefinitionId] =3.
Okay this is an example for the new embed code for youtube videos.
<iframe title="YouTube video player" class="youtube-player" type="text/html" width="560" height="345" src="http://www.youtube.com/embed/8v_4O44sfjM" frameborder="0" allowFullScreen></iframe>
if you want to autoplay it, at the src="http://www.youtube.com/embed/8v_4O44sfjM"
add the ?autoplay=1
parameter
So the code will look like this:
<iframe title="YouTube video player" class="youtube-player" type="text/html" width="560" height="345" src="http://www.youtube.com/embed/8v_4O44sfjM?autoplay=1" frameborder="0" allowFullScreen></iframe>
i tried this on my blog and it works ! Hope this help (:
For PHP (I know the question is Java, but Google brought me here), you can use stream wrappers and file_exists
$bucket = "MyBucket";
$key = "MyKey";
$s3 = Aws\S3\S3Client->factory([...]);
$s3->registerStreamWrapper();
$keyExists = file_exists("s3://$bucket/$key");
A simpler solution is git rebase <SHA1 of B> topic
. This works irrespective of where your HEAD
is.
We can confirm this behaviour from git rebase doc
<upstream>
Upstream branch to compare against. May be any valid commit, not just an existing branch name. Defaults to the configured upstream for the current branch.
topic
too in the above command ?
git rebase <SHA1 of B> <SHA1 of topic>
This will also work but rebase then won't make Topic
point to new branch so created and HEAD
will be in detached state. So from here you have to manually delete old Topic
and create a new branch reference on new branch created by rebase.
my solution is this:
cd android
and then:
./gradlew assembleMyBuild --stacktrace
I find the STR function the cleanest means of accomplishing this.
SELECT STR(ceiling(123.415432875), 6, 2)
The org/hamcrest/SelfDescribing class is not on the run-time classpath.
There's a 'cheap and dirty' trick that I have used... shhhh don't tell anyone. If you output tab delimited text and make the file name *.xls then Excel opens it without objection, question or warning. So just crank the data out into a text file with tab delimitation and you can open it with Excel or Open Office.
Parsing JSON in Swift is an excellent job for code generation. I've created a tool at http://www.guideluxe.com/JsonToSwift to do just that.
You supply a sample JSON object with a class name and the tool will generate a corresponding Swift class, as well as any needed subsidiary Swift classes, to represent the structure implied by the sample JSON. Also included are class methods used to populate Swift objects, including one that utilizes the NSJSONSerialization.JSONObjectWithData method. The necessary mappings from the NSArray and NSDictionary objects are provided.
From the generated code, you only need to supply an NSData object containing JSON that matches the sample provided to the tool.
Other than Foundation, there are no dependencies.
My work was inspired by http://json2csharp.com/, which is very handy for .NET projects.
Here's how to create an NSData object from a JSON file.
let fileUrl: NSURL = NSBundle.mainBundle().URLForResource("JsonFile", withExtension: "json")!
let jsonData: NSData = NSData(contentsOfURL: fileUrl)!
This would get all files in path/to/files with an .swf extension into an array and then sort that array by the file's mtime
$files = glob('path/to/files/*.swf');
usort($files, function($a, $b) {
return filemtime($b) - filemtime($a);
});
The above uses an Lambda function and requires PHP 5.3. Prior to 5.3, you would do
usort($files, create_function('$a,$b', 'return filemtime($b)-filemtime($a);'));
If you don't want to use an anonymous function, you can just as well define the callback as a regular function and pass the function name to usort
instead.
With the resulting array, you would then iterate over the files like this:
foreach($files as $file){
printf('<tr><td><input type="checkbox" name="box[]"></td>
<td><a href="%1$s" target="_blank">%1$s</a></td>
<td>%2$s</td></tr>',
$file, // or basename($file) for just the filename w\out path
date('F d Y, H:i:s', filemtime($file)));
}
Note that because you already called filemtime
when sorting the files, there is no additional cost when calling it again in the foreach loop due to the stat cache.
The standalone
declaration is a way of telling the parser to ignore any markup declarations in the DTD. The DTD is thereafter used for validation only.
As an example, consider the humble <img>
tag. If you look at the XHTML 1.0 DTD, you see a markup declaration telling the parser that <img>
tags must be EMPTY and possess src
and alt
attributes. When a browser is going through an XHTML 1.0 document and finds an <img>
tag, it should notice that the DTD requires src
and alt
attributes and add them if they are not present. It will also self-close the <img>
tag since it is supposed to be EMPTY. This is what the XML specification means by "markup declarations can affect the content of the document." You can then use the standalone
declaration to tell the parser to ignore these rules.
Whether or not your parser actually does this is another question, but a standards-compliant validating parser (like a browser) should.
Note that if you do not specify a DTD, then the standalone declaration "has no meaning," so there's no reason to use it unless you also specify a DTD.
I have a search form with an icon that clears the text when clicked. However, the problem (on mobile & tablets) was that the keyboard would collapse/hide, as the click
event removed focus
was removed from the input
.
Goal: after clearing the search form (clicking/tapping on x-icon) keep the keyboard visible!
To accomplish this, apply stopPropagation()
on the event like so:
function clear ($event) {
$event.preventDefault();
$event.stopPropagation();
self.query = '';
$timeout(function () {
document.getElementById('sidebar-search').focus();
}, 1);
}
And the HTML form:
<form ng-controller="SearchController as search"
ng-submit="search.submit($event)">
<input type="search" id="sidebar-search"
ng-model="search.query">
<span class="glyphicon glyphicon-remove-circle"
ng-click="search.clear($event)">
</span>
</form>
IF you're still having trouble, you may try switching 'top' to 'bottom' in chromeFix above, and also a div rather than a span
<div id="chromeFix"></div>
style:
#chromeFix { display: block; position: absolute; width: 1px; height: 100%; bottom: 0px; left: 0px; }
The getElementsByClassName
method is now natively supported by the most recent versions of Firefox, Safari, Chrome, IE and Opera, you could make a function to check if a native implementation is available, otherwise use the Dustin Diaz method:
function getElementsByClassName(node,classname) {
if (node.getElementsByClassName) { // use native implementation if available
return node.getElementsByClassName(classname);
} else {
return (function getElementsByClass(searchClass,node) {
if ( node == null )
node = document;
var classElements = [],
els = node.getElementsByTagName("*"),
elsLen = els.length,
pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
})(classname, node);
}
}
Usage:
function toggle_visibility(className) {
var elements = getElementsByClassName(document, className),
n = elements.length;
for (var i = 0; i < n; i++) {
var e = elements[i];
if(e.style.display == 'block') {
e.style.display = 'none';
} else {
e.style.display = 'block';
}
}
}
You can use this:
comment = Comment.objects.filter(pk=comment_id)
This seems to work in most browsers:
function copyStylesInline(destinationNode, sourceNode) {
var containerElements = ["svg","g"];
for (var cd = 0; cd < destinationNode.childNodes.length; cd++) {
var child = destinationNode.childNodes[cd];
if (containerElements.indexOf(child.tagName) != -1) {
copyStylesInline(child, sourceNode.childNodes[cd]);
continue;
}
var style = sourceNode.childNodes[cd].currentStyle || window.getComputedStyle(sourceNode.childNodes[cd]);
if (style == "undefined" || style == null) continue;
for (var st = 0; st < style.length; st++){
child.style.setProperty(style[st], style.getPropertyValue(style[st]));
}
}
}
function triggerDownload (imgURI, fileName) {
var evt = new MouseEvent("click", {
view: window,
bubbles: false,
cancelable: true
});
var a = document.createElement("a");
a.setAttribute("download", fileName);
a.setAttribute("href", imgURI);
a.setAttribute("target", '_blank');
a.dispatchEvent(evt);
}
function downloadSvg(svg, fileName) {
var copy = svg.cloneNode(true);
copyStylesInline(copy, svg);
var canvas = document.createElement("canvas");
var bbox = svg.getBBox();
canvas.width = bbox.width;
canvas.height = bbox.height;
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, bbox.width, bbox.height);
var data = (new XMLSerializer()).serializeToString(copy);
var DOMURL = window.URL || window.webkitURL || window;
var img = new Image();
var svgBlob = new Blob([data], {type: "image/svg+xml;charset=utf-8"});
var url = DOMURL.createObjectURL(svgBlob);
img.onload = function () {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob)
{
var blob = canvas.msToBlob();
navigator.msSaveOrOpenBlob(blob, fileName);
}
else {
var imgURI = canvas
.toDataURL("image/png")
.replace("image/png", "image/octet-stream");
triggerDownload(imgURI, fileName);
}
document.removeChild(canvas);
};
img.src = url;
}
I think there is a difference between whether something SHOULD be unique or MUST be unique (i.e. enforced by web browsers).
Should IDs be unique? YES.
Must IDs be unique? NO, at least IE and FireFox allow multiple elements to have the same ID.
This works well
The following code works if you use jquery
$( "object" ).replaceWith('<object data="http://www.google.com"></object>');
I made a function to clean a list
def cleanLists(self, lista):
lista = [x.strip() for x in lista]
lista = [x.replace('\n', '') for x in lista]
lista = [x.replace('\b', '') for x in lista]
lista = [x.encode('utf8') for x in lista]
lista = [x.decode('utf8') for x in lista]
return lista
<input name="submitBnt" type="submit" value="like"/>
name is useful when using $_POST
in php and also in javascript as document.getElementByName('submitBnt')
.
Also you can use name as a CS selector like input[name="submitBnt"]
;
Hope this helps
When you go and write you shell script always put first line as #!/usr/bin/env bash . This shell doesn't omit or manipulate escape sequences. ex echo "This is first \n line" prints This is first \n line.
Your server tells you exactly what you need : [Hint: SSLProxyEngine]
You need to add that directive to your VirtualHost
before the Proxy
directives :
SSLProxyEngine on
ProxyPass /primary/store https://localhost:9763/store/
ProxyPassReverse /primary/store https://localhost:9763/store/
There is a plugin for Jquery called "Hotkeys" which allows you to bind to key down combinations.
Does this do what you are after?
Use the in_array()
function.
$array = array('kitchen', 'bedroom', 'living_room', 'dining_room');
if (in_array('kitchen', $array)) {
echo 'this array contains kitchen';
}
Just recreate the Path variable in users. Go to user variables, highlight path, then new, the type in value. Look on another computer with same version windows. Usually it is in windows 10: Path %USERPROFILE%\AppData\Local\Microsoft\WindowsApps;
Swift 5
I was surprised, but I didn't find a proper correct solution here.
This is mine:
enum CustomMath<T: BinaryInteger> {
static func pow(_ base: T, _ power: T) -> T {
var tempBase = base
var tempPower = power
var result: T = 1
while (power != 0) {
if (power % 2 == 1) {
result *= base
}
tempPower = tempPower >> 1
tempBase *= tempBase
}
return result
}
}
Example:
CustomMath.pow(1,1)
This will take care of the empty td:
<td style="min-width: 20px;"></td>
You can use an iterator.
typedef std::map<std::string, std::map<std::string, std::string>>::iterator it_type;
for(it_type iterator = m.begin(); iterator != m.end(); iterator++) {
// iterator->first = key
// iterator->second = value
// Repeat if you also want to iterate through the second map.
}
Code check:
This is offtopic here but the people over at CodeReview are more than happy to help you.
I strongly suggest you to do so, there are several things that need attention in your code. Likewise I suggest that you do start reading tutorials since there is really no good reason not to do so.
Lists:
As you said yourself: you need a list of items. The way it is now you only store a reference to one item. Lucky there is exactly that to hold a group of related objects: a List
.
Lists are very straightforward to use but take a look at the related documentation anyway.
A very simple example to keep multiple bikes in a list:
List<Motorbike> bikes = new List<Motorbike>();
bikes.add(new Bike { make = "Honda", color = "brown" });
bikes.add(new Bike { make = "Vroom", color = "red" });
And to iterate over the list you can use the foreach
statement:
foreach(var bike in bikes) {
Console.WriteLine(bike.make);
}
ldapConnection is the server adres: ldap.example.com Ldap.Connection.Path is the path inside the ADS that you like to use insert in LDAP format.
OU=Your_OU,OU=other_ou,dc=example,dc=com
You start at the deepest OU working back to the root of the AD, then add dc=X for every domain section until you have everything including the top level domain
Now i miss a parameter to authenticate, this works the same as the path for the username
CN=username,OU=users,DC=example,DC=com
Try Visual Studio's very own post-build event command line.
Try to add this in post-build:
@echo off
sc query "ServiceName" > nul
if errorlevel 1060 goto install
goto stop
:delete
echo delete
sc delete "ServiceName" > nul
echo %errorlevel%
goto install
:install
echo install
sc create "ServiceName" displayname= "Service Display Name" binpath= "$(TargetPath)" start= auto > nul
echo %errorlevel%
goto start
:start
echo start
sc start "ServiceName" > nul
echo %errorlevel%
goto end
:stop
echo stop
sc stop "ServiceName" > nul
echo %errorlevel%
goto delete
:end
If the build error with a message like Error 1 The command "@echo off sc query "ServiceName" > nul
so on, Ctrl + C then Ctrl + V the error message into Notepad and look at the last sentence of the message.
It could be saying exited with code x
. Look for the code in some common error here and see how to resolve it.
1072 -- Marked for deletion ? Close all applications that maybe using the service including services.msc and Windows event log.
1058 -- Can't be started because disabled or has no enabled associated devices ? just delete it.
1060 -- Doesn't exist ? just delete it.
1062 -- Has not been started ? just delete it.
1053 -- Didn't respond to start or control ? see event log (if logged to event log). It may be the service itself throwing an exception.
1056 -- Service is already running ? stop the service, and then delete.
More on error codes here.
And if the build error with message like this,
Error 11 Could not copy "obj\x86\Debug\ServiceName.exe" to "bin\Debug\ServiceName.exe". Exceeded retry count of 10. Failed. ServiceName
Error 12 Unable to copy file "obj\x86\Debug\ServiceName.exe" to "bin\Debug\ServiceName.exe". The process cannot access the file 'bin\Debug\ServiceName.exe' because it is being used by another process. ServiceName
open cmd, and then try to kill it first with taskkill /fi "services eq ServiceName" /f
If all is well, F5 should be sufficient to debug it.
This exception could point to the LINQ parameter that is named source:
System.Linq.Enumerable.Select[TSource,TResult](IEnumerable`1 source, Func`2 selector)
As the source
parameter in your LINQ
query (var nCounts = from sale in sal
) is 'sal
', I suppose the list named 'sal' might be null.
A solution, can be:
with open("file", "r") as fd:
lines = fd.read().splitlines()
You get the list of lines without "\r\n" or "\n".
Or, use the classic way:
with open("file", "r") as fd:
for line in fd:
line = line.strip()
You read the file, line by line and drop the spaces and newlines.
If you only want to drop the newlines:
with open("file", "r") as fd:
for line in fd:
line = line.replace("\r", "").replace("\n", "")
Et voilà.
Note: The behavior of Python 3 is a little different. To mimic this behavior, use io.open
.
See the documentation of io.open.
So, you can use:
with io.open("file", "r", newline=None) as fd:
for line in fd:
line = line.replace("\n", "")
When the newline parameter is None
: lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n'.
newline controls how universal newlines works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:
On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
In Python, a distinction between expressions and statements is rigidly enforced, in contrast to languages such as Common Lisp, Scheme, or Ruby.
So by introducing such operators, you would break the expression/statement split.
For the same reason you can't write
if x = 0:
y = 1
as you can in some other languages where such distinction is not preserved.
I always initialise them as NULL
.
I always use string.IsNullOrEmpty(someString)
to check it's value.
Simple.
In Swift you can do like this
let number : NSNumber = 95
let str : String = number.stringValue
alter table table_name charset = 'utf8';
This is a simple query i was able to use for my case, you can change the table_name as per your requirement(s).
Did you tried JQuery's scrollTo
method? http://demos.flesler.com/jquery/scrollTo/
Or you can extend JQuery and add your custom mentod:
jQuery.fn.extend({
scrollToMe: function () {
var x = jQuery(this).offset().top - 100;
jQuery('html,body').animate({scrollTop: x}, 400);
}});
Then you can call this method like:
$("#header").scrollToMe();
I would have expected your solution to work -- I though the selection event would not fire if you set the adapter before setting up the listener.
That being said, a simple boolean flag would allow you to detect the rogue first selection event and ignore it.
Not using iframes puts you in a world of handling #document security issues with cross domain and links firing unexpected ways that was not intended for originally, do you really need bad Advertisements?
You can use jquery .load function to send the page to whatever html element you want to target, assuming your not getting this from another domain.
You can use javascript .innerHTML value to set and to rewrite the element with whatever you want, but if you add another file you might be writing against 2 documents in 1... like a in another
iframes are old, another way we can add "src" into the html alone without any use for javascript. But it's old, prehistoric, and just plain OLD! Frameset makes it worse because I can put #document in those to handle multiple html files. An Old way people created navigation menu's Long and before people had FLIP phones.
1.) Yes you will have to work in Javascript if you do NOT want to use an Iframe.
2.) There is a good hack in which you can set the domain to equal each other without having to set server stuff around. Means you will have to have edit capabilities of the documents.
3.) javascript window.document is limited to the iframe itself and can NOT go above the iframe if you want to grab something through the DOM itself. Because it treats it like a separate tab, it also defines it in another document object model.
You can try:
function onlyAlphabets(e, t) {
return (e.charCode > 64 && e.charCode < 91) || (e.charCode > 96 && e.charCode < 123) || e.charCode == 32;
}
In <body>
you should have two <script>
tags:
<script src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script src="js/bootstrap.js"></script>
The first one will load jQuery from the CDN, and second one will load Bootstrap's Javascript from a local directory (in this case it's a directory called js
).
# Check delegate? first must be connected owner of view controller
# Simple implementation of the didSelectRowAt function.
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("row selection: \(indexPath.row)")
}
Working example here at : http://jsfiddle.net/tQ2CZ/1/
HTML
<div id="video_container">
<video poster="http://media.w3.org/2010/05/sintel/poster.png" preload="none" controls="" id="video" tabindex="0">
<source type="video/mp4" src="http://media.w3.org/2010/05/sintel/trailer.mp4" id="mp4"></source>
<source type="video/webm" src="http://media.w3.org/2010/05/sintel/trailer.webm" id="webm"></source>
<source type="video/ogg" src="http://media.w3.org/2010/05/sintel/trailer.ogv" id="ogv"></source>
<p>Your user agent does not support the HTML5 Video element.</p>
</video>
</div>
<div>Current Time : <span id="currentTime">0</span></div>
<div>Total time : <span id="totalTime">0</span></div>
JS
$(function(){
$('#currentTime').html($('#video_container').find('video').get(0).load());
$('#currentTime').html($('#video_container').find('video').get(0).play());
})
setInterval(function(){
$('#currentTime').html($('#video_container').find('video').get(0).currentTime);
$('#totalTime').html($('#video_container').find('video').get(0).duration);
},500)
For converting any Jupyter notebook to PDF, please follow the below instructions:
(Be inside Jupyter notebook):
On Mac OS:
command + P --> you will get a print dialog box --> change destination as PDF --> Click print
On Windows:
Ctrl + P --> you will get a print dialog box --> change destination as PDF --> Click print
If the above steps doesn't generate full PDF of the Jupyter notebook (probably because Chrome, some times, don't print all the outputs because Jupyter make a scroll for big outputs),
Try performing below steps for removing the auto scroll in the menu:-
Credits: @ÂngeloPolotto
Here's a version that uses a collection object to combine two 1-d arrays and pass them to a 3rd array. Doesn't work for multi-dimensional arrays.
Function joinArrays(arr1 As Variant, arr2 As Variant) As Variant
Dim arrToReturn() As Variant, myCollection As New Collection
For Each x In arr1: myCollection.Add x: Next
For Each y In arr2: myCollection.Add y: Next
ReDim arrToReturn(1 To myCollection.Count)
For i = 1 To myCollection.Count: arrToReturn(i) = myCollection.Item(i): Next
joinArrays = arrToReturn
End Function
There is difference between collision and duplication. Collision means hashcode and bucket is same, but in duplicate, it will be same hashcode,same bucket, but here equals method come in picture.
Collision detected and you can add element on existing key. but in case of duplication it will replace new value.
One thing to note, if you are using a freestyle job, you won't be able to access build parameters or the Jenkins JVM's environment UNLESS you are using System Groovy Script build steps. I spent hours googling and researching before gathering enough clues to figure that out.
Now which drive letter did that removable device get?
Two ways to locate e.g. a USB-disk in git Bash
:
$ cat /proc/partitions major minor #blocks name win-mounts 8 0 500107608 sda 8 1 1048576 sda1 8 2 131072 sda2 8 3 496305152 sda3 C:\ 8 4 1048576 sda4 8 5 1572864 sda5 8 16 0 sdb 8 32 0 sdc 8 48 0 sdd 8 64 0 sde 8 80 3952639 sdf 8 81 3950592 sdf1 E:\ $ mount C:/Program Files/Git on / type ntfs (binary,noacl,auto) C:/Program Files/Git/usr/bin on /bin type ntfs (binary,noacl,auto) C:/Users/se2982/AppData/Local/Temp on /tmp type ntfs (binary,noacl,posix=0,usertemp) C: on /c type ntfs (binary,noacl,posix=0,user,noumount,auto) E: on /e type vfat (binary,noacl,posix=0,user,noumount,auto) G: on /g type ntfs (binary,noacl,posix=0,user,noumount,auto) H: on /h type ntfs (binary,noacl,posix=0,user,noumount,auto)
... so; likely drive letter in this example => /e
(or E:\ if you must), when knowing that C, G, and H are other things (in Windows).
Did you try setting the style:
input {
text-align:right;
}
Just tested, this works fine (in FF3 at least):
<html>
<head>
<title>Blah</title>
<style type="text/css">
input { text-align:right; }
</style>
</head>
<body>
<input type="text" value="2">
</body>
</html>
You'll probably want to throw a class on these inputs, and use that class as the selector. I would shy away from "rightAligned" or something like that. In a class name, you want to describe what the element's function is, not how it should be rendered. "numeric" might be good, or perhaps the business function of the text boxes.
We can use append
append(l1, l2)
It also has arguments to insert element at a particular location.
Address already in use
means that the port
you are trying to allocate for your current execution is already occupied/allocated to some other process.
If you are a developer and if you are working on an application which require lots of testing, you might have an instance of your same application running in background (may be you forgot to stop it properly)
So if you encounter this error, just see which application/process is using the port.
In linux try using netstat -tulpn
. This command will list down a process list with all running processes.
Check if an application is using your port. If that application or process is another important one then you might want to use another port which is not used by any process/application.
Anyway you can stop the process which uses your port and let your application take it.
If you are in linux environment try,
netstat -tulpn
to display the processeskill <pid>
This will terminate the processIf you are using windows,
netstat -a -o -n
to check for the port usagestaskkill /F /PID <pid>
to kill that processSHOW FULL PROCESSLIST
If you don't use FULL
, "only the first 100 characters of each statement are shown in the Info
field".
When using phpMyAdmin, you should also click on the "Full texts" option ("? T ?" on top left corner of a results table) to see untruncated results.
As it turns out, autoplay cannot be done on iOS devices (iPhone, iPad, iPod touch) and Android.
See https://stackoverflow.com/a/8142187/2054512 and https://stackoverflow.com/a/3056220/2054512
Is this really possible.
Yes.
function a(x) { // <-- function_x000D_
function b(y) { // <-- inner function_x000D_
return x + y; // <-- use variables from outer scope_x000D_
}_x000D_
return b; // <-- you can even return a function._x000D_
}_x000D_
console.log(a(3)(4));
_x000D_
You actually can't manually "free" memory in C, in the sense that the memory is released from the process back to the OS ... when you call malloc()
, the underlying libc-runtime will request from the OS a memory region. On Linux, this may be done though a relatively "heavy" call like mmap()
. Once this memory region is mapped to your program, there is a linked-list setup called the "free store" that manages this allocated memory region. When you call malloc()
, it quickly looks though the free-store for a free block of memory at the size requested. It then adjusts the linked list to reflect that there has been a chunk of memory taken out of the originally allocated memory pool. When you call free()
the memory block is placed back in the free-store as a linked-list node that indicates its an available chunk of memory.
If you request more memory than what is located in the free-store, the libc-runtime will again request more memory from the OS up to the limit of the OS's ability to allocate memory for running processes. When you free memory though, it's not returned back to the OS ... it's typically recycled back into the free-store where it can be used again by another call to malloc()
. Thus, if you make a lot of calls to malloc()
and free()
with varying memory size requests, it could, in theory, cause a condition called "memory fragmentation", where there is enough space in the free-store to allocate your requested memory block, but not enough contiguous space for the size of the block you've requested. Thus the call to malloc()
fails, and you're effectively "out-of-memory" even though there may be plenty of memory available as a total amount of bytes in the free-store.
myModule.directive('jqdatepicker', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
element.datepicker({
dateFormat: 'dd/mm/yy',
onSelect: function (date) {
var ar=date.split("/");
date=new Date(ar[2]+"-"+ar[1]+"-"+ar[0]);
ngModelCtrl.$setViewValue(date.getTime());
// scope.course.launchDate = date;
scope.$apply();
}
});
}
};
});
HTML Code :
<input type="text" jqdatepicker ng-model="course.launchDate" required readonly />
I have solution without adapter. Transient map converted to xml-elements and vise versa:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "SchemaBasedProperties")
public class SchemaBasedProperties
{
@XmlTransient
Map<String, Map<String, String>> properties;
@XmlAnyElement(lax = true)
List<Object> xmlmap;
public Map<String, Map<String, String>> getProperties()
{
if (properties == null)
properties = new LinkedHashMap<String, Map<String, String>>(); // I want same order
return properties;
}
boolean beforeMarshal(Marshaller m)
{
try
{
if (properties != null && !properties.isEmpty())
{
if (xmlmap == null)
xmlmap = new ArrayList<Object>();
else
xmlmap.clear();
javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();
javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
org.w3c.dom.Document doc = db.newDocument();
org.w3c.dom.Element element;
Map<String, String> attrs;
for (Map.Entry<String, Map<String, String>> it: properties.entrySet())
{
element = doc.createElement(it.getKey());
attrs = it.getValue();
if (attrs != null)
for (Map.Entry<String, String> at: attrs.entrySet())
element.setAttribute(at.getKey(), at.getValue());
xmlmap.add(element);
}
}
else
xmlmap = null;
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
return true;
}
void afterUnmarshal(Unmarshaller u, Object p)
{
org.w3c.dom.Node node;
org.w3c.dom.NamedNodeMap nodeMap;
String name;
Map<String, String> attrs;
getProperties().clear();
if (xmlmap != null)
for (Object xmlNode: xmlmap)
if (xmlNode instanceof org.w3c.dom.Node)
{
node = (org.w3c.dom.Node) xmlNode;
nodeMap = node.getAttributes();
name = node.getLocalName();
attrs = new HashMap<String, String>();
for (int i = 0, l = nodeMap.getLength(); i < l; i++)
{
node = nodeMap.item(i);
attrs.put(node.getNodeName(), node.getNodeValue());
}
getProperties().put(name, attrs);
}
xmlmap = null;
}
public static void main(String[] args)
throws Exception
{
SchemaBasedProperties props = new SchemaBasedProperties();
Map<String, String> attrs;
attrs = new HashMap<String, String>();
attrs.put("ResId", "A_LABEL");
props.getProperties().put("LABEL", attrs);
attrs = new HashMap<String, String>();
attrs.put("ResId", "A_TOOLTIP");
props.getProperties().put("TOOLTIP", attrs);
attrs = new HashMap<String, String>();
attrs.put("Value", "hide");
props.getProperties().put("DISPLAYHINT", attrs);
javax.xml.bind.JAXBContext jc = javax.xml.bind.JAXBContext.newInstance(SchemaBasedProperties.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(props, new java.io.File("test.xml"));
Unmarshaller unmarshaller = jc.createUnmarshaller();
props = (SchemaBasedProperties) unmarshaller.unmarshal(new java.io.File("test.xml"));
System.out.println(props.getProperties());
}
}
My output as espected:
<SchemaBasedProperties>
<LABEL ResId="A_LABEL"/>
<TOOLTIP ResId="A_TOOLTIP"/>
<DISPLAYHINT Value="hide"/>
</SchemaBasedProperties>
{LABEL={ResId=A_LABEL}, TOOLTIP={ResId=A_TOOLTIP}, DISPLAYHINT={Value=hide}}
You can use element name/value pair. I need attributes... Have fun!
For Ubuntu, Ctrl + Alt + Left and Ctrl + Alt + Right work fine.
By default these keys are assigned for Ubuntu's workspace navigation.
You need to disable that by going to :
System Settings > Keyboard > Shortcuts Tab > Navigation
and disable Switch to workspace left
and Switch to workspace right
by pressing Backspace.
Or you can choose to change shortcuts in Intellij itself:
File > Settings > Keymap > Main menu > Navigate > Back/Forward
If your simple test page is located on other protocol/domain/port than your hello world node.js example you are doing cross-domain requests and violating same origin policy therefore your jQuery ajax calls (get and load) are failing silently. To get this working cross-domain you should use JSONP based format. For example node.js code:
var http = require('http');
http.createServer(function (req, res) {
console.log('request received');
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('_testcb(\'{"message": "Hello world!"}\')');
}).listen(8124);
and client side JavaScript/jQuery:
$(document).ready(function() {
$.ajax({
url: 'http://192.168.1.103:8124/',
dataType: "jsonp",
jsonpCallback: "_testcb",
cache: false,
timeout: 5000,
success: function(data) {
$("#test").append(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error ' + textStatus + " " + errorThrown);
}
});
});
There are also other ways how to get this working, for example by setting up reverse proxy or build your web application entirely with framework like express.
rm -rf ~/anaconda
It was pretty easy. It switched my pointer to Python: https://docs.continuum.io/anaconda/install#os-x-uninstall
select T.Col1, T.Col2, T.Sort
from
(
select T.Col1,
T.Col2,
T.Sort,
rank() over(partition by T.Col1, T.Col2 order by T.Sort) as rn
from
(
select Col1, Col2, 1 as Sort
from Table1
union all
select Col1, Col2, 2
from Table2
) as T
) as T
where T.rn = 1
order by T.Sort
The border-radius property is supported in IE9+, Firefox 4+, Chrome, Safari 5+, and Opera, because it is CSS3 property. so, you could use css3pie
first check this demo in IE 8 and download it from here write your css rule like this
#myAwesomeElement {
border: 1px solid #999;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
behavior: url(path/to/pie_files/PIE.htc);
}
note: added behavior: url(path/to/pie_files/PIE.htc);
in the above rule. within url() you need to specify your PIE.htc file location
This should work based on your example "2011-29-01 12:00 am"
DateTime dt;
DateTime.TryParseExact(dateTime,
"yyyy-dd-MM hh:mm tt",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt);
In addition from the command prompt run SET.
This displayed the "LOGONSERVER" value which indicates the specific domain controller you are using (there can be more than one).
Then you got to that server's NetBios Share \Servername\SYSVOL\domain.local\scripts.
The easiest answer is given by W3schools. https://www.w3schools.com/html/html_youtube.asp
<iframe width="640" height="520"
src="https://www.youtube.com/embed/<VideoID>">
</iframe>
if you are on windows then you can do a right click from the folder where you want to use git bash and select "GIT BASH HERE".
It's a conceptual problem.
Stringstream is a stream, so its iterators are forward, cannot return. In an output stringstream, you need a flush() to reinitialize it, as in any other output stream.
check it in mdpi device.. If the ad displays correctly, the error should be in "px" to "dip" conversion..
You can put your servers in the default_step
group and those vars will apply to it:
# inventory file
[default_step]
prod2
web_v2
Then just move your default_step.yml
file to group_vars/default_step.yml
.
Change the number of @grid-columns
. Then use -offset
. Changing the number of columns will allow you to control the amount of space between columns. E.g.
variables.less (approx line 294).
@grid-columns: 20;
someName.html
<div class="row">
<div class="col-md-4 col-md-offset-1">First column</div>
<div class="col-md-13 col-md-offset-1">Second column</div>
</div>
import os
def disk_stat(path):
disk = os.statvfs(path)
percent = (disk.f_blocks - disk.f_bfree) * 100 / (disk.f_blocks -disk.f_bfree + disk.f_bavail) + 1
return percent
print disk_stat('/')
print disk_stat('/data')
Why noy just use the theme styles in the table? i.e.
<table>
<thead class="ui-widget-header">
<tr>
<th>Id</th>
<th>Description</th>
</td>
</thead>
<tbody class="ui-widget-content">
<tr>
<td>...</td>
<td>...</td>
</tr>
.
.
.
</tbody>
</table>
And you don't need to use any code...
git gui
and git-cola
are graphical utilities that let you view and manipulate the index. Both include simple visual diffs for staged files, and git-cola
can also launch a more sophisticated side-by-side visual diff tool.
See my closely related answer at How to remove a file from the index in git?, and also this official catalog of Git - GUI Clients.
int i = 25;
NSString *myString = [NSString stringWithFormat:@"%d",i];
This is one of many ways.
I guess you want to do the "Iterating over Keys and Values"
As the doc here says, just add "|keys" in the variable you want and it will magically happen.
{% for key, user in users %}
<li>{{ key }}: {{ user.username|e }}</li>
{% endfor %}
It never hurts to search before asking :)
I wasn't really happy with any of the options here. This is what worked for me.
str=$(printf "%s" "first line")
str=$(printf "$str\n%s" "another line")
str=$(printf "$str\n%s" "and another line")
I know this question has been answered many times, I just propose to people that might be interested a jquery Plugin :
https://github.com/fenix92/clickClock
very basic, clear and intuitive.
These are mostly equivalent, but import *
has some restrictions that import ... = require
doesn't.
import * as
creates an identifier that is a module object, emphasis on object. According to the ES6 spec, this object is never callable or new
able - it only has properties. If you're trying to import a function or class, you should use
import express = require('express');
or (depending on your module loader)
import express from 'express';
Attempting to use import * as express
and then invoking express()
is always illegal according to the ES6 spec. In some runtime+transpilation environments this might happen to work anyway, but it might break at any point in the future without warning, which will make you sad.
If anyone needs to do this in Excel without VBA, here is a way:
=SUBSTITUTE(ADDRESS(1;colNum;4);"1";"")
where colNum is the column number
And in VBA:
Function GetColumnName(colNum As Integer) As String
Dim d As Integer
Dim m As Integer
Dim name As String
d = colNum
name = ""
Do While (d > 0)
m = (d - 1) Mod 26
name = Chr(65 + m) + name
d = Int((d - m) / 26)
Loop
GetColumnName = name
End Function
OLTP: It stands for OnLine Transaction Processing and is used for managing current day to day data information.
OLAP: It stands for OnLine Analytical Processing and is used to maintain the past history of data and mainly used for data analysis, it can also be referred to as warehouse.
You can use XMLHttpRequest, fetch API, ...
If you want to use XMLHttpRequest you can do the following
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
name: "Deska",
email: "[email protected]",
phone: "342234553"
}));
xhr.onload = function() {
var data = JSON.parse(this.responseText);
console.log(data);
};
Or if you want to use fetch API
fetch(url, {
method:"POST",
body: JSON.stringify({
name: "Deska",
email: "[email protected]",
phone: "342234553"
})
})
.then(result => {
// do something with the result
console.log("Completed with result:", result);
});
Since enums with Strings values differ from the ones that have number values it is better to filter nonNumbers from @user8363 solution.
Here is how you can get values from enum either strings, numbers of mixed:
//Helper
export const StringIsNotNumber = value => isNaN(Number(value)) === true;
// Turn enum into array
export function enumToArray(enumme) {
return Object.keys(enumme)
.filter(StringIsNotNumber)
.map(key => enumme[key]);
}
_x000D_
My domain was quite complex. I took the value returned by window.location.host
in the developer console and pasted that value in the recaptcha admin white list. Then I cleared the cache and reloaded the page.
.toDate
did not really work for me, So, Here is what i did :
futureStartAtDate = new Date(moment().locale("en").add(1, 'd').format("MMM DD, YYYY HH:MM"))
hope this helps
I didn't have an issue with this until I tried to use the Location Services, at which point I had to put the apply plugin: 'com.google.gms.google-services'
at the bottom of the file, rather than the top. The reason being that when you have it at the top there are collision issues, and by placing it at the bottom, you avoid those issue.
There is a file called config.inc.php in the phpmyadmin folder.
The file path is C:\wamp\apps\phpmyadmin4.0.4
Edit The auth_type 'cookie' to 'config' or 'http'
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['auth_type'] = 'config';
or
$cfg['Servers'][$i]['auth_type'] = 'http';
When you go to the phpmyadmin site then you will be asked for the username and password. This also secure external people from accessing your phpmyadmin application if you happen to have your web server exposed to outside connections.
Here is an example which might help someone:
Grid test = new Grid();
test.ColumnDefinitions.Add(new ColumnDefinition());
test.ColumnDefinitions.Add(new ColumnDefinition());
test.RowDefinitions.Add(new RowDefinition());
test.RowDefinitions.Add(new RowDefinition());
test.RowDefinitions.Add(new RowDefinition());
Label t1 = new Label();
t1.Content = "Test1";
Label t2 = new Label();
t2.Content = "Test2";
Label t3 = new Label();
t3.Content = "Test3";
Label t4 = new Label();
t4.Content = "Test4";
Label t5 = new Label();
t5.Content = "Test5";
Label t6 = new Label();
t6.Content = "Test6";
Grid.SetColumn(t1, 0);
Grid.SetRow(t1, 0);
test.Children.Add(t1);
Grid.SetColumn(t2, 1);
Grid.SetRow(t2, 0);
test.Children.Add(t2);
Grid.SetColumn(t3, 0);
Grid.SetRow(t3, 1);
test.Children.Add(t3);
Grid.SetColumn(t4, 1);
Grid.SetRow(t4, 1);
test.Children.Add(t4);
Grid.SetColumn(t5, 0);
Grid.SetRow(t5, 2);
test.Children.Add(t5);
Grid.SetColumn(t6, 1);
Grid.SetRow(t6, 2);
test.Children.Add(t6);
The use of variables that have yet to been defined or set (implicitly or explicitly) is often a bad thing in any language, since it tends to indicate that the logic of the program hasn't been thought through properly, and is likely to result in unpredictable behaviour.
If you need to do it in Python, the following trick, which is similar to yours, will ensure that a variable has some value before use:
try:
myVar
except NameError:
myVar = None # or some other default value.
# Now you're free to use myVar without Python complaining.
However, I'm still not convinced that's a good idea - in my opinion, you should try to refactor your code so that this situation does not occur.
It's very simple. Add
#import <CommonCrypto/CommonCrypto.h>
to a .h file (the bridging header file of your project). As a convention you can call it YourProjectName-Bridging-Header.h.
Then go to your project Build Settings and look for Swift Compiler - Code Generation. Under it, add the name of your bridging header to the entry "Objetive-C Bridging Header".
You're done. No imports required in your Swift code. Any public Objective-C headers listed in this bridging header file will be visible to Swift.
If that's a valid date/time entry then excel simply stores it as a number (days are integers and the time is the decimal part) so you can do a simple subtraction.
I'm not sure if 7/6 is 7th June or 6th July, assuming the latter then it's a future date so you can get the difference in days with
=INT(A1-TODAY())
Make sure you format result cell as general or number (not date)
Use below code snippet to achieve this.:
$('#checkAll').click(function(){
$("#checkboxes input").attr('checked','checked');
});
$('#UncheckAll').click(function(){
$("#checkboxes input").attr('checked',false);
});
Or you can do the same with single check box:
$('#checkAll').click(function(e) {
if($('#checkAll').attr('checked') == 'checked') {
$("#checkboxes input").attr('checked','checked');
$('#checkAll').val('off');
} else {
$("#checkboxes input").attr('checked', false);
$('#checkAll').val('on');
}
});
For demo: http://jsfiddle.net/creativegala/hTtxe/
Split uses regex, and the pipe char |
has special meaning in regex, so you need to escape it. There are a few ways to do this, but here's the simplest:
String[] tokens = line.split("\\|\\|");
with express it's so easy. all what you need is to use the consolidate module on node so you need to install it :
npm install consolidate --save
then you should change the default engine to html template by this:
app.set('view engine', 'html');
register the underscore template engine for the html extension:
app.engine('html', require('consolidate').underscore);
it's done !
Now for load for example an template called 'index.html':
res.render('index', { title : 'my first page'});
maybe you will need to install the underscore module.
npm install underscore --save
I hope this helped you!
This is what I use to collect single frames, but if you modify this and keep the two targets open all the time then you could "stream" it to disk using a static counter for the file name. - I can't recall where I found this, but it has been modified, thanks to whoever!
void dump_buffer()
{
IDirect3DSurface9* pRenderTarget=NULL;
IDirect3DSurface9* pDestTarget=NULL;
const char file[] = "Pickture.bmp";
// sanity checks.
if (Device == NULL)
return;
// get the render target surface.
HRESULT hr = Device->GetRenderTarget(0, &pRenderTarget);
// get the current adapter display mode.
//hr = pDirect3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT,&d3ddisplaymode);
// create a destination surface.
hr = Device->CreateOffscreenPlainSurface(DisplayMde.Width,
DisplayMde.Height,
DisplayMde.Format,
D3DPOOL_SYSTEMMEM,
&pDestTarget,
NULL);
//copy the render target to the destination surface.
hr = Device->GetRenderTargetData(pRenderTarget, pDestTarget);
//save its contents to a bitmap file.
hr = D3DXSaveSurfaceToFile(file,
D3DXIFF_BMP,
pDestTarget,
NULL,
NULL);
// clean up.
pRenderTarget->Release();
pDestTarget->Release();
}
You can create another script file separately for the functions and invoke the script file whenever you want to call the function. This will help you to keep your code clean.
Function Definition : Create a new script file
Function Call : Invoke the script file
Try adding this piece of code. It worked for me.
$opts = array(_x000D_
'ssl' => array('ciphers'=>'RC4-SHA', 'verify_peer'=>false, 'verify_peer_name'=>false)_x000D_
);_x000D_
// SOAP 1.2 client_x000D_
$params = array ('encoding' => 'UTF-8', 'verifypeer' => false, 'verifyhost' => false, 'soap_version' => SOAP_1_2, 'trace' => 1, 'exceptions' => 1, "connection_timeout" => 180, 'stream_context' => stream_context_create($opts) );_x000D_
$url = "http://www.webservicex.net/globalweather.asmx?WSDL";_x000D_
_x000D_
try{_x000D_
$client = new SoapClient($url,$params );_x000D_
}_x000D_
catch(SoapFault $fault) {_x000D_
echo '<br>'.$fault;_x000D_
}
_x000D_
To my knowledge there is no difference between NUMERIC and DECIMAL data types. They are synonymous to each other and either one can be used. DECIMAL and NUMERIC data types are numeric data types with fixed precision and scale.
Edit:
Speaking to a few collegues maybe its has something to do with DECIMAL being the ANSI SQL standard and NUMERIC being one Mircosoft prefers as its more commonly found in programming languages. ...Maybe ;)
Use a 9-patch drawable or create a Shape drawable.
I am placing JLBorges's excellent response to a similar question verbatim from cplusplus.com, as it is the most succinct explanation I've read on the subject.
In a template that we write, there are two kinds of names that could be used - dependant names and non- dependant names. A dependant name is a name that depends on a template parameter; a non-dependant name has the same meaning irrespective of what the template parameters are.
For example:
template< typename T > void foo( T& x, std::string str, int count ) { // these names are looked up during the second phase // when foo is instantiated and the type T is known x.size(); // dependant name (non-type) T::instance_count ; // dependant name (non-type) typename T::iterator i ; // dependant name (type) // during the first phase, // T::instance_count is treated as a non-type (this is the default) // the typename keyword specifies that T::iterator is to be treated as a type. // these names are looked up during the first phase std::string::size_type s ; // non-dependant name (type) std::string::npos ; // non-dependant name (non-type) str.empty() ; // non-dependant name (non-type) count ; // non-dependant name (non-type) }
What a dependant name refers to could be something different for each different instantiation of the template. As a consequence, C++ templates are subject to "two-phase name lookup". When a template is initially parsed (before any instantiation takes place) the compiler looks up the non-dependent names. When a particular instantiation of the template takes place, the template parameters are known by then, and the compiler looks up dependent names.
During the first phase, the parser needs to know if a dependant name is the name of a type or the name of a non-type. By default, a dependant name is assumed to be the name of a non-type. The typename keyword before a dependant name specifies that it is the name of a type.
Summary
Use the keyword typename only in template declarations and definitions provided you have a qualified name that refers to a type and depends on a template parameter.
dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))
na.omit(dat)
x1 x2
1 1 100
3 3 300
5 5 500
UPDATED:
TO NOT HAVE ANY
b
and quotes at first and endHow to convert
bytes
as seen to strings, even in weird situations.
As your code may have unrecognizable characters to 'utf-8'
encoding,
it's better to use just str without any additional parameters:
some_bad_bytes = b'\x02-\xdfI#)'
text = str( some_bad_bytes )[2:-1]
print(text)
Output: \x02-\xdfI
if you add 'utf-8'
parameter, to these specific bytes, you should receive error.
As PYTHON 3 standard says, text
would be in utf-8 now with no concern.
The downloads have moved, it says that on that very page:
You mean like length
or size()
?
At first you need to add semi colon (;) after quantity INT NOT NULL)
then remove ** from ,genre,quantity)**
.
to insert a value with numeric data type like int, decimal, float, etc you don't need to add single quote.
BasicResponseHandler throws if the status is not 2xx. See its javadoc.
Here is how I would do it:
HttpResponse response = client.execute( get );
int code = response.getStatusLine().getStatusCode();
InputStream body = response.getEntity().getContent();
// Read the body stream
Or you can also write a ResponseHandler starting from BasicResponseHandler source that don't throw when the status is not 2xx.
You can use the "extract" or "date_part" functions on intervals as well as timestamps, but I don't think that does what you want. For example, it gives 3 for an interval of '2 days, 3 hours'. However, you can convert an interval to a number of seconds by specifying 'epoch' as the time element you want: extract(epoch from '2 days, 3 hours'::interval)
returns 183600 (which you then divide by 3600 to convert seconds to hours).
So, putting this all together, you get basically Michael's answer: extract(epoch from timestamp1 - timestamp2)/3600
. Since you don't seem to care about which timestamp precedes which, you probably want to wrap that in abs
:
SELECT abs(extract(epoch from timestamp1 - timestamp2)/3600)
right click on project->properties->android->select target name --set target-- click ok
Yes. Bootstrap uses CSS transitions so it can be done easily without any Javascript.
The CSS:
.carousel .item {-webkit-transition: opacity 3s; -moz-transition: opacity 3s; -ms-transition: opacity 3s; -o-transition: opacity 3s; transition: opacity 3s;}
.carousel .active.left {left:0;opacity:0;z-index:2;}
.carousel .next {left:0;opacity:1;z-index:1;}
I noticed however that the transition end event was firing prematurely with the default interval of 5s and a fade transition of 3s. Bumping the carousel interval to 8s provides a nice effect.
Very smooth.
Here is a rough but more declarative solution. I haven't been able to get it down to a single annotation, but this seems to work well. Also not sure about performance on large data sets.
Given this JSON:
{
"list": [
{
"wrapper": {
"name": "Jack"
}
},
{
"wrapper": {
"name": "Jane"
}
}
]
}
And these model objects:
public class RootObject {
@JsonProperty("list")
@JsonDeserialize(contentUsing = SkipWrapperObjectDeserializer.class)
@SkipWrapperObject("wrapper")
public InnerObject[] innerObjects;
}
and
public class InnerObject {
@JsonProperty("name")
public String name;
}
Where the Jackson voodoo is implemented like:
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation
public @interface SkipWrapperObject {
String value();
}
and
public class SkipWrapperObjectDeserializer extends JsonDeserializer<Object> implements
ContextualDeserializer {
private Class<?> wrappedType;
private String wrapperKey;
public JsonDeserializer<?> createContextual(DeserializationContext ctxt,
BeanProperty property) throws JsonMappingException {
SkipWrapperObject skipWrapperObject = property
.getAnnotation(SkipWrapperObject.class);
wrapperKey = skipWrapperObject.value();
JavaType collectionType = property.getType();
JavaType collectedType = collectionType.containedType(0);
wrappedType = collectedType.getRawClass();
return this;
}
@Override
public Object deserialize(JsonParser parser, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
ObjectNode objectNode = mapper.readTree(parser);
JsonNode wrapped = objectNode.get(wrapperKey);
Object mapped = mapIntoObject(wrapped);
return mapped;
}
private Object mapIntoObject(JsonNode node) throws IOException,
JsonProcessingException {
JsonParser parser = node.traverse();
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(parser, wrappedType);
}
}
Hope this is useful to someone!
When your website is served by only one web server, for each client-server pair, a session object is created and remains in the memory of the web server. All the requests from the client go to this web server and update this session object. If some data needs to be stored in the session object over the period of interaction, it is stored in this session object and stays there as long as the session exists.
However, if your website is served by multiple web servers which sit behind a load balancer, the load balancer decides which actual (physical) web-server should each request go to. For example, if there are 3 web servers A, B and C behind the load balancer, it is possible that www.mywebsite.com/index.jsp is served from server A, www.mywebsite.com/login.jsp is served from server B and www.mywebsite.com/accoutdetails.php are served from server C.
Now, if the requests are being served from (physically) 3 different servers, each server has created a session object for you and because these session objects sit on three independent boxes, there's no direct way of one knowing what is there in the session object of the other. In order to synchronize between these server sessions, you may have to write/read the session data into a layer which is common to all - like a DB. Now writing and reading data to/from a db for this use-case may not be a good idea. Now, here comes the role of sticky-session.
If the load balancer is instructed to use sticky sessions, all of your interactions will happen with the same physical server, even though other servers are present. Thus, your session object will be the same throughout your entire interaction with this website.
To summarize, In case of Sticky Sessions, all your requests will be directed to the same physical web server while in case of a non-sticky loadbalancer may choose any webserver to serve your requests.
As an example, you may read about Amazon's Elastic Load Balancer and sticky sessions here : http://aws.typepad.com/aws/2010/04/new-elastic-load-balancing-feature-sticky-sessions.html
Let me explain what is happening here, because it isn't obvious!
First, Stream.max()
accepts an instance of Comparator
so that items in the stream can be compared against each other to find the minimum or maximum, in some optimal order that you don't need to worry too much about.
So the question is, of course, why is Integer::max
accepted? After all it's not a comparator!
The answer is in the way that the new lambda functionality works in Java 8. It relies on a concept which is informally known as "single abstract method" interfaces, or "SAM" interfaces. The idea is that any interface with one abstract method can be automatically implemented by any lambda - or method reference - whose method signature is a match for the one method on the interface. So examining the Comparator
interface (simple version):
public Comparator<T> {
T compare(T o1, T o2);
}
If a method is looking for a Comparator<Integer>
, then it's essentially looking for this signature:
int xxx(Integer o1, Integer o2);
I use "xxx" because the method name is not used for matching purposes.
Therefore, both Integer.min(int a, int b)
and Integer.max(int a, int b)
are close enough that autoboxing will allow this to appear as a Comparator<Integer>
in a method context.
The octothorpe/number-sign/hashmark has a special significance in an URL, it normally identifies the name of a section of a document. The precise term is that the text following the hash is the anchor portion of an URL. If you use Wikipedia, you will see that most pages have a table of contents and you can jump to sections within the document with an anchor, such as:
https://en.wikipedia.org/wiki/Alan_Turing#Early_computers_and_the_Turing_test
https://en.wikipedia.org/wiki/Alan_Turing
identifies the page and Early_computers_and_the_Turing_test
is the anchor. The reason that Facebook and other Javascript-driven applications (like my own Wood & Stones) use anchors is that they want to make pages bookmarkable (as suggested by a comment on that answer) or support the back button without reloading the entire page from the server.
In order to support bookmarking and the back button, you need to change the URL. However, if you change the page portion (with something like window.location = 'http://raganwald.com';
) to a different URL or without specifying an anchor, the browser will load the entire page from the URL. Try this in Firebug or Safari's Javascript console. Load http://minimal-github.gilesb.com/raganwald
. Now in the Javascript console, type:
window.location = 'http://minimal-github.gilesb.com/raganwald';
You will see the page refresh from the server. Now type:
window.location = 'http://minimal-github.gilesb.com/raganwald#try_this';
Aha! No page refresh! Type:
window.location = 'http://minimal-github.gilesb.com/raganwald#and_this';
Still no refresh. Use the back button to see that these URLs are in the browser history. The browser notices that we are on the same page but just changing the anchor, so it doesn't reload. Thanks to this behaviour, we can have a single Javascript application that appears to the browser to be on one 'page' but to have many bookmarkable sections that respect the back button. The application must change the anchor when a user enters different 'states', and likewise if a user uses the back button or a bookmark or a link to load the application with an anchor included, the application must restore the appropriate state.
So there you have it: Anchors provide Javascript programmers with a mechanism for making bookmarkable, indexable, and back-button-friendly applications. This technique has a name: It is a Single Page Interface.
p.s. There is a fourth benefit to this technique: Loading page content through AJAX and then injecting it into the current DOM can be much faster than loading a new page. In addition to the speed increase, further tricks like loading certain portions in the background can be performed under the programmer's control.
p.p.s. Given all of that, the 'bang' or exclamation mark is a further hint to Google's web crawler that the exact same page can be loaded from the server at a slightly different URL. See Ajax Crawling. Another technique is to make each link point to a server-accessible URL and then use unobtrusive Javascript to change it into an SPI with an anchor.
Here's the key link again: The Single Page Interface Manifesto
You can use on Centos or RHEL for local user:
echo $"export PATH=\$PATH:$(pwd)" >> ~/.bash_profile
This add the current directory(or you can use other directory) to the PATH, this make it permanent but take effect at the next user logon.
If you don't want do a re-logon, then can use:
source ~/.bash_profile
That reload the # User specific environment and startup programs
this comment is present in .bash_profile
I had faced similar issue. I set cafile using the command:
npm config set cafile PATH_TO_CERTIFICATE
I was able to resolve this by deleting the certificate file settings, and setting strict-ssl = false
.
For super correctness, you should use:
Rails.root.join('foo','bar')
which will allow your app to work on platforms where /
is not the directory separator, should anyone try and run it on one.
VelocityEngine velocityEngin = new VelocityEngine();
velocityEngin.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
velocityEngin.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
velocityEngin.init();
Template template = velocityEngin.getTemplate("nameOfTheTemplateFile.vtl");
you could use the above code to set the properties for velocity template. You can then give the name of the tempalte file when initializing the Template and it will find if it exists in the classpath.
All the above classes come from package org.apache.velocity*
A full example ?. Run this code : (NB: This example is best run in the console and not from within an IDE, since the System.console() method might return null in that case.)
import java.io.Console;
public class Main {
public void passwordExample() {
Console console = System.console();
if (console == null) {
System.out.println("Couldn't get Console instance");
System.exit(0);
}
console.printf("Testing password%n");
char[] passwordArray = console.readPassword("Enter your secret password: ");
console.printf("Password entered was: %s%n", new String(passwordArray));
}
public static void main(String[] args) {
new Main().passwordExample();
}
}
var table = document.getElementById("someTableID");
var totalRows = document.getElementById("someTableID").rows.length;
var totalCol = 3; // enter the number of columns in the table minus 1 (first column is 0 not 1)
//To display all values
for (var x = 0; x <= totalRows; x++)
{
for (var y = 0; y <= totalCol; y++)
{
alert(table.rows[x].cells[y].innerHTML;
}
}
//To display a single cell value enter in the row number and column number under rows and cells below:
var firstCell = table.rows[0].cells[0].innerHTML;
alert(firstCell);
//Note: if you use <th> this will be row 0, so your data will start at row 1 col 0
html code in my case
<ul class="navs">
<li id="tab1"><a href="index-2.html">home</a></li>
<li id="tab2"><a href="about.html">about</a></li>
<li id="tab3"><a href="project-02.html">Products</a></li>
<li id="tab4"><a href="contact.html">contact</a></li>
</ul>
and js code is
$('.navs li a').click(function (e) {
var $parent = $(this).parent();
document.cookie = eraseCookie("tab");
document.cookie = createCookie("tab", $parent.attr('id'),0);
});
$().ready(function () {
var $activeTab = readCookie("tab");
if (!$activeTab =="") {
$('#tab1').removeClass('ActiveTab');
}
// alert($activeTab.toString());
$('#'+$activeTab).addClass('active');
});
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
If you are running SQL Server in a local environment and not over a TCP/IP connection. Go to Protocols under SQL Server Configuration Manager, Properties, and disable TCP/IP. Once this is done then the error message will go away when restarting the service.
My solution was rather simple: backup everything from the application, uninstall it, delete everything from the remaining folders (but not the folders so I won't have to grant the same permissions again) then copy back the files from the backup.
Here a top level design approach:
def eraseElement(d,k):
if isinstance(d, dict):
if k in d:
d.pop(k)
print(d)
else:
print("Cannot find matching key")
else:
print("Not able to delete")
exp = {'A':34, 'B':55, 'C':87}
eraseElement(exp, 'C')
I'm passing the dictionary and the key I want into my function, validates if it's a dictionary and if the key is okay, and if both exist, removes the value from the dictionary and prints out the left-overs.
Output: {'B': 55, 'A': 34}
Hope that helps!
With using pathlib module, indentation isn't needed.
import pathlib
pathlib.Path("output.txt").write_text("Purchase Amount: {}" .format(TotalAmount))
As of python 3.6, f-strings is available.
pathlib.Path("output.txt").write_text(f"Purchase Amount: {TotalAmount}")
To improve the effectiveness of class='ng-cloak' approach when scripts are loaded last, make sure the following css is loaded in the head of the document:
.ng-cloak { display:none; }
we can easily stop the set interval by calling clear interval
var count = 0 , i = 5;
var vary = function intervalFunc() {
count++;
console.log(count);
console.log('hello boy');
if (count == 10) {
clearInterval(this);
}
}
setInterval(vary, 1500);
You can simply add a FontAwesome icon to your select dropdown as text. You only need a few things in CSS only, the FontAwesome CSS and the unicode. For example 
:
select {_x000D_
font-family: 'FontAwesome', 'Second Font name'_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<select>_x000D_
<option>Hi, </option>_x000D_
<option>Hi, </option>_x000D_
<option>Hi, </option>_x000D_
<option>Hi, </option>_x000D_
<option>Hi, </option>_x000D_
</select>
_x000D_
The unicodes can be found when you click on an icon: Fontawesome
According to the comment below and issue on Github, the unicode in select elements won't work on OSX (yet).
Update: from the Github issue, adding multiple
attribute to select
element makes it work on:
OSX El Capitan 10.11.4
select{_x000D_
font-family: FontAwesome, sans-serif;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<select multiple>_x000D_
<option> 500px</option>_x000D_
<option> Adjust</option>_x000D_
<option> Adn</option>_x000D_
<option> Align-center</option>_x000D_
<option> Align-justify</option>_x000D_
<option> Align-left</option>_x000D_
<option> Align-right</option>_x000D_
</select>
_x000D_
I always have to check my cheatsheet :-)
Step 1: right-click on the top of putty window and select 'Change settings'.
Step 2: type the name of the session and save.
That's it!. Enjoy!
export
is a built-in command of the bash
shell and other Bourne shell variants. It is used to mark a shell variable for export to child processes.
Write a Java program to create an array of 20 integers, and then implement the process of shifting the array to right for two elements.
public class NewClass3 {
public static void main (String args[]){
int a [] = {1,2,};
int temp ;
for(int i = 0; i<a.length -1; i++){
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
for(int p : a)
System.out.print(p);
}
}
You need to drag the EditText
from the edge of the layout and not just the other widget. You can also add constraints by just dragging the constraint point that surrounds the widget to the edge of the screen to add constraints as specified.
The modified code will look something similar to this:
app:layout_constraintLeft_toLeftOf="@+id/router_text"
app:layout_constraintTop_toTopOf="@+id/activity_main"
android:layout_marginTop="320dp"
app:layout_constraintBottom_toBottomOf="@+id/activity_main"
android:layout_marginBottom="16dp"
app:layout_constraintVertical_bias="0.29"
If you plan to build a full functional applications with more than a handful of features, I will suggest to jump right to using Eclipse RCP as the framework.
If your application won't grow too big or your requirements are just too unique to be handled by a normal business framework, you can safely jump with Swing.
At the end of the day, I'd suggest you to try both technologies to find the one suit you better. Like Netbeans vs Eclipse vs IntelliJ, there is no the absolute correct answer here and both frameworks have their own drawbacks.
Pro Swing:
Pro SWT:
You can call run-time commands from java for both Windows and Linux.
import java.io.*;
public class Test{
public static void main(String[] args)
{
try
{
Process process = Runtime.getRuntime().exec("pwd"); // for Linux
//Process process = Runtime.getRuntime().exec("cmd /c dir"); //for Windows
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line=reader.readLine())!=null)
{
System.out.println(line);
}
}
catch(Exception e)
{
System.out.println(e);
}
finally
{
process.destroy();
}
}
}
Hope it Helps.. :)
Actual Swift 3 Answer
This is the ONLY function you need. You do not need CanEdit or CommitEditingStyle functions for custom actions.
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let action1 = UITableViewRowAction(style: .default, title: "Action1", handler: {
(action, indexPath) in
print("Action1")
})
action1.backgroundColor = UIColor.lightGray
let action2 = UITableViewRowAction(style: .default, title: "Action2", handler: {
(action, indexPath) in
print("Action2")
})
return [action1, action2]
}
You can simply use matches
method of String class.
boolean result = someString.matches("stores.*store.*product.*");