The simplest way to insert a new line between echo
statements is to insert an echo
without arguments, for example:
echo Create the snapshots
echo
echo Snapshot created
That is, echo
without any arguments will print a blank line.
Another alternative to use a single echo
statement with the -e
flag and embedded newline characters \n
:
echo -e "Create the snapshots\n\nSnapshot created"
However, this is not portable, as the -e
flag doesn't work consistently in all systems. A better way if you really want to do this is using printf
:
printf "Create the snapshots\n\nSnapshot created\n"
This works more reliably in many systems, though it's not POSIX compliant. Notice that you must manually add a \n
at the end, as printf
doesn't append a newline automatically as echo
does.
It looks like you are not providing a value for the primary key field DB_ID. If that is a primary key, you must provide a unique value for that column. The only way not to provide it would be to create a database trigger that, on insert, would provide a value, most likely derived from a sequence.
If this is a restoration from another database and there is a sequence on this new instance, it might be trying to reuse a value. If the old data had unique keys from 1 - 1000 and your current sequence is at 500, it would be generating values that already exist. If a sequence does exist for this table and it is trying to use it, you would need to reconcile the values in your table with the current value of the sequence.
You can use SEQUENCE_NAME.CURRVAL to see the current value of the sequence (if it exists of course)
If you use eclipse for making your java files, you can choose to export it as a runnable jar file. I did this with my programs and I can just click on the jar and it will run just like that. This will work on both windows, as well as os x.
You should just add: timeout: <number of miliseconds>,
somewhere within $.ajax({})
.
Also, cache: false,
might help in a few scenarios.
$.ajax is well documented, you should check options there, might find something useful.
Good luck!
sp_helptext [dbname.spname] try this
All of the answers here use the Class.forName("my.vandor.Driver");
line to load the driver.
As an (better) alternative you can use the DriverManager
helper class which provides you with a handful of methods to handle your JDBC driver/s.
You might want to
DriverManager.registerDriver(driverObject);
to register your driver to it's list of driversRegisters the given driver with the DriverManager. A newly-loaded driver class should call the method registerDriver to make itself known to the DriverManager. If the driver is currently registered, no action is taken
DriverManager.deregisterDriver(driverObject);
to remove it.Removes the specified driver from the DriverManager's list of registered drivers.
Example:
Driver driver = new oracle.jdbc.OracleDriver();
DriverManager.registerDriver(driver);
Connection conn = DriverManager.getConnection(url, user, password);
// ...
// and when you don't need anything else from the driver
DriverManager.deregisterDriver(driver);
or better yet, use a DataSource
You will need to do a couple of things to get this going, since your parameter is getting multiple values you need to create a Table Type and make your store procedure accept a parameter of that type.
Split Function Works Great when you are getting One String
containing multiple values but when you are passing Multiple values you need to do something like this....
TABLE TYPE
CREATE TYPE dbo.TYPENAME AS TABLE ( arg int ) GO
Stored Procedure to Accept That Type Param
CREATE PROCEDURE mainValues @TableParam TYPENAME READONLY AS BEGIN SET NOCOUNT ON; --Temp table to store split values declare @tmp_values table ( value nvarchar(255) not null); --function splitting values INSERT INTO @tmp_values (value) SELECT arg FROM @TableParam SELECT * FROM @tmp_values --<-- For testing purpose END
EXECUTE PROC
Declare a variable of that type and populate it with your values.
DECLARE @Table TYPENAME --<-- Variable of this TYPE INSERT INTO @Table --<-- Populating the variable VALUES (331),(222),(876),(932) EXECUTE mainValues @Table --<-- Stored Procedure Executed
Result
╔═══════╗ ║ value ║ ╠═══════╣ ║ 331 ║ ║ 222 ║ ║ 876 ║ ║ 932 ║ ╚═══════╝
Another way to do it is using the StructField if you have multiple fields that needs to be modified.
Ex:
from pyspark.sql.types import StructField,IntegerType, StructType,StringType
newDF=[StructField('CLICK_FLG',IntegerType(),True),
StructField('OPEN_FLG',IntegerType(),True),
StructField('I1_GNDR_CODE',StringType(),True),
StructField('TRW_INCOME_CD_V4',StringType(),True),
StructField('ASIAN_CD',IntegerType(),True),
StructField('I1_INDIV_HHLD_STATUS_CODE',IntegerType(),True)
]
finalStruct=StructType(fields=newDF)
df=spark.read.csv('ctor.csv',schema=finalStruct)
Output:
Before
root
|-- CLICK_FLG: string (nullable = true)
|-- OPEN_FLG: string (nullable = true)
|-- I1_GNDR_CODE: string (nullable = true)
|-- TRW_INCOME_CD_V4: string (nullable = true)
|-- ASIAN_CD: integer (nullable = true)
|-- I1_INDIV_HHLD_STATUS_CODE: string (nullable = true)
After:
root
|-- CLICK_FLG: integer (nullable = true)
|-- OPEN_FLG: integer (nullable = true)
|-- I1_GNDR_CODE: string (nullable = true)
|-- TRW_INCOME_CD_V4: string (nullable = true)
|-- ASIAN_CD: integer (nullable = true)
|-- I1_INDIV_HHLD_STATUS_CODE: integer (nullable = true)
This is slightly a long procedure to cast , but the advantage is that all the required fields can be done.
It is to be noted that if only the required fields are assigned the data type, then the resultant dataframe will contain only those fields which are changed.
<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">
Enter the competition by
<span style="color: #ff0000">January 30, 2011</span>
and you could win up to $$$$ — including amazing
<span style="color: #0000a0">summer</span>
trips!
</p>
Or you may want to use CSS classes instead:
<html>
<head>
<style type="text/css">
p {
font-size:14px;
color:#538b01;
font-weight:bold;
font-style:italic;
}
.date {
color: #ff0000;
}
.season { /* OK, a bit contrived... */
color: #0000a0;
}
</style>
</head>
<body>
<p>
Enter the competition by
<span class="date">January 30, 2011</span>
and you could win up to $$$$ — including amazing
<span class="season">summer</span>
trips!
</p>
</body>
</html>
Since this question was asked in 2010, there has been real simplification in how to do simple multithreading with Python with map and pool.
The code below comes from an article/blog post that you should definitely check out (no affiliation) - Parallelism in one line: A Better Model for Day to Day Threading Tasks. I'll summarize below - it ends up being just a few lines of code:
from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(4)
results = pool.map(my_function, my_array)
Which is the multithreaded version of:
results = []
for item in my_array:
results.append(my_function(item))
Description
Map is a cool little function, and the key to easily injecting parallelism into your Python code. For those unfamiliar, map is something lifted from functional languages like Lisp. It is a function which maps another function over a sequence.
Map handles the iteration over the sequence for us, applies the function, and stores all of the results in a handy list at the end.
Implementation
Parallel versions of the map function are provided by two libraries:multiprocessing, and also its little known, but equally fantastic step child:multiprocessing.dummy.
multiprocessing.dummy
is exactly the same as multiprocessing module, but uses threads instead (an important distinction - use multiple processes for CPU-intensive tasks; threads for (and during) I/O):
multiprocessing.dummy replicates the API of multiprocessing, but is no more than a wrapper around the threading module.
import urllib2
from multiprocessing.dummy import Pool as ThreadPool
urls = [
'http://www.python.org',
'http://www.python.org/about/',
'http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html',
'http://www.python.org/doc/',
'http://www.python.org/download/',
'http://www.python.org/getit/',
'http://www.python.org/community/',
'https://wiki.python.org/moin/',
]
# Make the Pool of workers
pool = ThreadPool(4)
# Open the URLs in their own threads
# and return the results
results = pool.map(urllib2.urlopen, urls)
# Close the pool and wait for the work to finish
pool.close()
pool.join()
And the timing results:
Single thread: 14.4 seconds
4 Pool: 3.1 seconds
8 Pool: 1.4 seconds
13 Pool: 1.3 seconds
Passing multiple arguments (works like this only in Python 3.3 and later):
To pass multiple arrays:
results = pool.starmap(function, zip(list_a, list_b))
Or to pass a constant and an array:
results = pool.starmap(function, zip(itertools.repeat(constant), list_a))
If you are using an earlier version of Python, you can pass multiple arguments via this workaround).
(Thanks to user136036 for the helpful comment.)
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon);
This will not work every time for example if your drawable is layer list drawable then it gives a null response, so as an alternative you need to draw your drawable into canvas then save as bitmap, please refer below a cup of code.
public void drawableToBitMap(Context context, int drawable, int widthPixels, int heightPixels) {
try {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/", "drawable.png");
FileOutputStream fOut = new FileOutputStream(file);
Drawable drw = ResourcesCompat.getDrawable(context.getResources(), drawable, null);
if (drw != null) {
convertToBitmap(drw, widthPixels, heightPixels).compress(Bitmap.CompressFormat.PNG, 100, fOut);
}
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private Bitmap convertToBitmap(Drawable drawable, int widthPixels, int heightPixels) {
Bitmap bitmap = Bitmap.createBitmap(widthPixels, heightPixels, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, widthPixels, heightPixels);
drawable.draw(canvas);
return bitmap;
}
above code save you're drawable as drawable.png in the download directory
Thanks for the code, dbr. Just a small typo in long_poller.htm around the line
1000 /* ..after 1 seconds */
I think it should be
"1000"); /* ..after 1 seconds */
for it to work.
For those interested, I tried a Django equivalent. Start a new Django project, say lp for long polling:
django-admin.py startproject lp
Call the app msgsrv for message server:
python manage.py startapp msgsrv
Add the following lines to settings.py to have a templates directory:
import os.path
PROJECT_DIR = os.path.dirname(__file__)
TEMPLATE_DIRS = (
os.path.join(PROJECT_DIR, 'templates'),
)
Define your URL patterns in urls.py as such:
from django.views.generic.simple import direct_to_template
from lp.msgsrv.views import retmsg
urlpatterns = patterns('',
(r'^msgsrv\.php$', retmsg),
(r'^long_poller\.htm$', direct_to_template, {'template': 'long_poller.htm'}),
)
And msgsrv/views.py should look like:
from random import randint
from time import sleep
from django.http import HttpResponse, HttpResponseNotFound
def retmsg(request):
if randint(1,3) == 1:
return HttpResponseNotFound('<h1>Page not found</h1>')
else:
sleep(randint(2,10))
return HttpResponse('Hi! Have a random number: %s' % str(randint(1,10)))
Lastly, templates/long_poller.htm should be the same as above with typo corrected. Hope this helps.
I've been searching the internet for RNG for a while now. Everything I saw was either TOO complex or was just not what I was looking for. After reading a few articles I was able to come up with this simple code.
{
Random rnd = new Random(DateTime.Now.Millisecond);
int[] b = new int[10] { 5, 8, 1, 7, 3, 2, 9, 0, 4, 6 };
textBox1.Text = Convert.ToString(b[rnd.Next(10)])
}
Simple explanation,
This works well.
To obtain a random number less than 100 use
{
Random rnd = new Random(DateTime.Now.Millisecond);
int[] b = new int[10] { 5, 8, 1, 7, 3, 2, 9, 0, 4, 6 };
int[] d = new int[10] { 9, 4, 7, 2, 8, 0, 5, 1, 3, 4 };
textBox1.Text = Convert.ToString(b[rnd.Next(10)]) + Convert.ToString(d[rnd.Next(10)]);
}
and so on for 3, 4, 5, and 6 ... digit random numbers.
Hope this assists someone positively.
You can do the following
Reload
It will add a reload button on your right hand at the bottom of the vs code.
SELECT d1.Short_Code
FROM domain1 d1
LEFT JOIN domain2 d2
ON d1.Short_Code = d2.Short_Code
WHERE d2.Short_Code IS NULL
I ran into this when I upgraded from adt 14 to 15 and to get it to work I ended up just deleting the .eclipse folder (along with my settings) and re-installing the adt 15.
I have created a method that helps with getting the stackTrace:
private static String getStackTrace(Exception ex) {
StringBuffer sb = new StringBuffer(500);
StackTraceElement[] st = ex.getStackTrace();
sb.append(ex.getClass().getName() + ": " + ex.getMessage() + "\n");
for (int i = 0; i < st.length; i++) {
sb.append("\t at " + st[i].toString() + "\n");
}
return sb.toString();
}
You can use the opt(int)
method and use a classical for
loop.
sudo apt-get install ia32-libs
\n
is an escape character for strings that is replaced with the new line object. Writing \n
in a string that prints out will print out a new line instead of the \n
You could use klepto
, which provides persistent caching to memory, disk, or database.
dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import file_archive
>>> db = file_archive('foo.txt')
>>> db['1'] = 1
>>> db['max'] = max
>>> squared = lambda x: x**2
>>> db['squared'] = squared
>>> def add(x,y):
... return x+y
...
>>> db['add'] = add
>>> class Foo(object):
... y = 1
... def bar(self, x):
... return self.y + x
...
>>> db['Foo'] = Foo
>>> f = Foo()
>>> db['f'] = f
>>> db.dump()
>>>
Then, after interpreter restart...
dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import file_archive
>>> db = file_archive('foo.txt')
>>> db
file_archive('foo.txt', {}, cached=True)
>>> db.load()
>>> db
file_archive('foo.txt', {'1': 1, 'add': <function add at 0x10610a0c8>, 'f': <__main__.Foo object at 0x10510ced0>, 'max': <built-in function max>, 'Foo': <class '__main__.Foo'>, 'squared': <function <lambda> at 0x10610a1b8>}, cached=True)
>>> db['add'](2,3)
5
>>> db['squared'](3)
9
>>> db['f'].bar(4)
5
>>>
Get the code here: https://github.com/uqfoundation
If you want to have back button with back arrow you can use an image and code below
backArrow.png [email protected] [email protected]
override func viewDidLoad() {
super.viewDidLoad()
let customBackButton = UIBarButtonItem(image: UIImage(named: "backArrow") , style: .plain, target: self, action: #selector(backAction(sender:)))
customBackButton.imageInsets = UIEdgeInsets(top: 2, left: -8, bottom: 0, right: 0)
navigationItem.leftBarButtonItem = customBackButton
}
func backAction(sender: UIBarButtonItem) {
// custom actions here
navigationController?.popViewController(animated: true)
}
Use typeof
when you want to get the type at compilation time. Use GetType
when you want to get the type at execution time. There are rarely any cases to use is
as it does a cast and, in most cases, you end up casting the variable anyway.
There is a fourth option that you haven't considered (especially if you are going to cast an object to the type you find as well); that is to use as
.
Foo foo = obj as Foo;
if (foo != null)
// your code here
This only uses one cast whereas this approach:
if (obj is Foo)
Foo foo = (Foo)obj;
requires two.
Update (Jan 2020):
Example:
if(obj is Foo newLocalFoo)
{
// For example, you can now reference 'newLocalFoo' in this local scope
Console.WriteLine(newLocalFoo);
}
The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:
A data frame of four rows:
df = pd.DataFrame({'A': [1,2,3,4]})
Now trying to assign a list/array of two elements to it:
df['B'] = [3,4] # or df['B'] = np.array([3,4])
Both errors out:
ValueError: Length of values does not match length of index
Because the data frame has four rows but the list and array has only two elements.
Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:
df['B'] = pd.Series([3,4])
df
# A B
#0 1 3.0
#1 2 4.0
#2 3 NaN # NaN because the value at index 2 and 3 doesn't exist in the Series
#3 4 NaN
For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:
df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))
# A B
#0 1 1.0
#1 2 5.0
#2 7 9.0
#3 8 NaN
The bottom line is you should almost always use EBS backed instances.
Here's why
I'm a heavy user of Amazon and switched all of my instances to EBS backed storage as soon as the technology came out of beta. I've been very happy with the result.
EBS can still fail - not a silver bullet
Keep in mind that any piece of cloud-based infrastructure can fail at any time. Plan your infrastructure accordingly. While EBS-backed instances provide certain level of durability compared to ephemeral storage instances, they can and do fail. Have an AMI from which you can launch new instances as needed in any availability zone, back up your important data (e.g. databases), and if your budget allows it, run multiple instances of servers for load balancing and redundancy (ideally in multiple availability zones).
When Not To
At some points in time, it may be cheaper to achieve faster IO on Instance Store instances. There was a time when it was certainly true. Now there are many options for EBS storage, catering to many needs. The options and their pricing evolve constantly as technology changes. If you have a significant amount of instances that are truly disposable (they don't affect your business much if they just go away), do the math on cost vs. performance. EBS-backed instances can also die at any point in time, but my practical experience is that EBS is more durable.
Do somehting simple like this:
for (Object object: (ArrayList<String>) list.clone()) {
list.remove(object);
}
$('.toggle img').data('block', 'something').attr('src', 'something.jpg');
Let me clarify what you're talking about: you want to test Foo
in a testcase, which calls external method uses_some_other_method
. Instead of calling the actual method, you want to mock the return value.
class Foo:
def method_1():
results = uses_some_other_method()
def method_n():
results = uses_some_other_method()
Suppose the above code is in foo.py
and uses_some_other_method
is defined in module bar.py
. Here is the unittest:
import unittest
import mock
from foo import Foo
class TestFoo(unittest.TestCase):
def setup(self):
self.foo = Foo()
@mock.patch('foo.uses_some_other_method')
def test_method_1(self, mock_method):
mock_method.return_value = 3
self.foo.method_1(*args, **kwargs)
mock_method.assert_called_with(*args, **kwargs)
If you want to change the return value every time you passed in different arguments, mock
provides side_effect
.
For encoding to base64 in Angular2, you can use btoa() function.
Example:-
console.log(btoa("stringAngular2"));
// Output:- c3RyaW5nQW5ndWxhcjI=
For decoding from base64 in Angular2, you can use atob() function.
Example:-
console.log(atob("c3RyaW5nQW5ndWxhcjI="));
// Output:- stringAngular2
The function that I use to find the length of the string is length
, used as follows:
SELECT * FROM table ORDER BY length(column);
Instead of :
Context appContext = this.getApplicationContext();
you should use a pointer to the activity you're in (probably this
).
I got bitten by this today too, the annoying part is the getApplicationContext()
is verbatim from developer.android.com :(
This page provides great understanding about the constructor
and destructor
attribute implementation and the sections within within ELF that allow them to work. After digesting the information provided here, I compiled a bit of additional information and (borrowing the section example from Michael Ambrus above) created an example to illustrate the concepts and help my learning. Those results are provided below along with the example source.
As explained in this thread, the constructor
and destructor
attributes create entries in the .ctors
and .dtors
section of the object file. You can place references to functions in either section in one of three ways. (1) using either the section
attribute; (2) constructor
and destructor
attributes or (3) with an inline-assembly call (as referenced the link in Ambrus' answer).
The use of constructor
and destructor
attributes allow you to additionally assign a priority to the constructor/destructor to control its order of execution before main()
is called or after it returns. The lower the priority value given, the higher the execution priority (lower priorities execute before higher priorities before main() -- and subsequent to higher priorities after main() ). The priority values you give must be greater than100
as the compiler reserves priority values between 0-100 for implementation. Aconstructor
or destructor
specified with priority executes before a constructor
or destructor
specified without priority.
With the 'section' attribute or with inline-assembly, you can also place function references in the .init
and .fini
ELF code section that will execute before any constructor and after any destructor, respectively. Any functions called by the function reference placed in the .init
section, will execute before the function reference itself (as usual).
I have tried to illustrate each of those in the example below:
#include <stdio.h>
#include <stdlib.h>
/* test function utilizing attribute 'section' ".ctors"/".dtors"
to create constuctors/destructors without assigned priority.
(provided by Michael Ambrus in earlier answer)
*/
#define SECTION( S ) __attribute__ ((section ( S )))
void test (void) {
printf("\n\ttest() utilizing -- (.section .ctors/.dtors) w/o priority\n");
}
void (*funcptr1)(void) SECTION(".ctors") =test;
void (*funcptr2)(void) SECTION(".ctors") =test;
void (*funcptr3)(void) SECTION(".dtors") =test;
/* functions constructX, destructX use attributes 'constructor' and
'destructor' to create prioritized entries in the .ctors, .dtors
ELF sections, respectively.
NOTE: priorities 0-100 are reserved
*/
void construct1 () __attribute__ ((constructor (101)));
void construct2 () __attribute__ ((constructor (102)));
void destruct1 () __attribute__ ((destructor (101)));
void destruct2 () __attribute__ ((destructor (102)));
/* init_some_function() - called by elf_init()
*/
int init_some_function () {
printf ("\n init_some_function() called by elf_init()\n");
return 1;
}
/* elf_init uses inline-assembly to place itself in the ELF .init section.
*/
int elf_init (void)
{
__asm__ (".section .init \n call elf_init \n .section .text\n");
if(!init_some_function ())
{
exit (1);
}
printf ("\n elf_init() -- (.section .init)\n");
return 1;
}
/*
function definitions for constructX and destructX
*/
void construct1 () {
printf ("\n construct1() constructor -- (.section .ctors) priority 101\n");
}
void construct2 () {
printf ("\n construct2() constructor -- (.section .ctors) priority 102\n");
}
void destruct1 () {
printf ("\n destruct1() destructor -- (.section .dtors) priority 101\n\n");
}
void destruct2 () {
printf ("\n destruct2() destructor -- (.section .dtors) priority 102\n");
}
/* main makes no function call to any of the functions declared above
*/
int
main (int argc, char *argv[]) {
printf ("\n\t [ main body of program ]\n");
return 0;
}
output:
init_some_function() called by elf_init()
elf_init() -- (.section .init)
construct1() constructor -- (.section .ctors) priority 101
construct2() constructor -- (.section .ctors) priority 102
test() utilizing -- (.section .ctors/.dtors) w/o priority
test() utilizing -- (.section .ctors/.dtors) w/o priority
[ main body of program ]
test() utilizing -- (.section .ctors/.dtors) w/o priority
destruct2() destructor -- (.section .dtors) priority 102
destruct1() destructor -- (.section .dtors) priority 101
The example helped cement the constructor/destructor behavior, hopefully it will be useful to others as well.
Windows 8.1 add:
--allow-file-access-from-files
to the end of the target text box after the quotes.
EX: "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files
Works like a charm
I was following along the Vue documentation at https://vuejs.org/v2/guide/index.html when I ran into this issue.
Later they clarify the syntax:
So far, we’ve only registered components globally, using Vue.component:
Vue.component('my-component-name', { // ... options ... })
Globally registered components can be used in the template of any root Vue instance (new Vue) created afterwards – and even inside all >subcomponents of that Vue instance’s component tree.
(https://vuejs.org/v2/guide/components.html#Organizing-Components)
So as Umesh Kadam says above, just make sure the global component definition comes before the var app = new Vue({})
instantiation.
See adeneo's answer, but to make this work in Excel in all countries you should add "SEP=," to the first line of the file. This will set the standard separator in Excel and will not show up in the actual document
var csvString = "SEP=, \n" + csvRows.join("\r\n");
While you can alias your tables within your query (i.e., "SELECT u.username FROM users u;"), you have to use the actual names of the columns you're referencing. AS only impacts how the fields are returned.
Your decision should be based on
You should resist the urge to change APIs just because it's "newer, shinier, better." I follow a policy of "if it's not broken, don't kick it."
If your application requires a very sophisticated logging framework, you may want to consider why.
There is certainly a shorter notation, but that was my approach:
gulp.task('check_env', function () {
return new Promise(function (resolve, reject) {
// gulp --dev
var env = process.argv[3], isDev;
if (env) {
if (env == "--dev") {
log.info("Dev Mode on");
isDev = true;
} else {
log.info("Dev Mode off");
isDev = false;
}
} else {
if (variables.settings.isDev == true) {
isDev = true;
} else {
isDev = false;
}
}
resolve();
});
});
If you want to set the env based to the actual Git branch (master/develop):
gulp.task('set_env', function (cb) {
exec('git rev-parse --abbrev-ref HEAD', function (err, stdout, stderr) {
git__branch = stdout.replace(/(\r\n|\n|\r)/gm, "");
if (git__branch == "develop") {
log.info("?Develop Branch");
isCompressing = false;
} else if (git__branch == "master") {
log.info("Master Branch");
isCompressing = true;
} else {
//TODO: check for feature-* branch
log.warn("Unknown " + git__branch + ", maybe feat?");
//isCompressing = variables.settings.isCompressing;
}
log.info(stderr);
cb(err);
});
return;
})
P.s. For the log I added the following:
var log = require('fancy-log');
In Case you need it, thats my default Task:
gulp.task('default',
gulp.series('set_env', gulp.parallel('build_scss', 'minify_js', 'minify_ts', 'minify_html', 'browser_sync_func', 'watch'),
function () {
}));
Suggestions for optimization are welcome.
Why have all the click events as a href
links?
If instead you use span
tags with :hover
CSS and the appropriate onclick events, this will get around the issue completely.
Instead, use: sudo service redis-server start
I had the same problem, stopping/starting other services from within Ubuntu on WSL. This worked, where systemctl did not.
And one could reasonably wonder, "how would you know that the service name was 'redis-server'?" You can see them using service --status-all
Tip of the hat to @gniourf_gniourf for clearing up a fundamental misconception.
This answer attempts to provide an overview of the existing answers and to discuss their subtleties and relative merits as well as to provide background information, especially with respect to portability.
Finding files that are executable can refer to two distinct use cases:
Note that in either scenario it may make sense to use find -L ...
instead of just find ...
in order to also find symlinks to executables.
Note that the simplest file-centric case - looking for executables with the executable permissions bit set for ALL three security principals (user, group, other) - will typically, but not necessarily yield the same results as the user-centric scenario - and it's important to understand the difference.
-executable
)The accepted answer commendably recommends -executable
, IF GNU find
is available.
find
comes with most Linux distros
-executable
matches only files the current user can execute (there are edge cases.[1]).The BSD find
alternative offered by the accepted answer (-perm +111
) answers a different, file-centric question (as the answer itself states).
-perm
to answer the user-centric question is impossible, because what is needed is to relate the file's user and group identity to the current user's, whereas -perm
can only test the file's permissions.find
features, the question cannot be answered without involving external utilities.Thus, the best -perm
can do (by itself) is an approximation of -executable
. Perhaps a closer approximation than -perm +111
is -perm -111
, so as to find files that have the executable bit set for ALL security principals (user, group, other) - this strikes me as the typical real-world scenario. As a bonus, it also happens to be POSIX-compliant (use find -L
to include symlinks, see farther below for an explanation):
find . -type f -perm -111 # or: find . -type f -perm -a=x
gniourf_gniourf's answer provides a true, portable equivalent of -executable
, using -exec test -x {} \;
, albeit at the expense of performance.
Combining -exec test -x {} \;
with -perm +111
(i.e., files with at least one executable bit set) may help performance in that exec
needn't be invoked for every file (the following uses the POSIX-compliant equivalent of BSD find -perm +111
/ GNU find -perm /111
; see farther below for an explanation):
find . -type f \( -perm -u=x -o -perm -g=x -o -perm -o=x \) -exec test -x {} \; -print
-perm
)-perm
primary (known as a test in GNU find terminology).
-perm
allows you to test for any file permissions, not just executability.111
), whereas symbolic modes are strings (e.g., a=x
).u
(user), g
(group) and o
(other), or a
to refer to all three. Permissions are expressed as x
for executable, for instance, and assigned to principals using operators =
, +
and -
; for a full discussion, including of octal modes, see the POSIX spec for the chmod
utility.find
:
-
(e.g., -ug=x
) means: match files that have all the permissions specified (but matching files may have additional permissions).755
) means: match files that have this full, exact set of permissions.+
/
[2]File-centric command examples
Note:
+
or /
.!
for NOT (GNU find and BSD find also allow -not
); note that \!
is used in the examples so as to protect !
from shell history expansions-a
for AND (GNU find and BSD find also allow -and
)-o
for OR (GNU find and BSD find also allow -or
)-
, the =
and +
operators can be used interchangeably
(e.g., -u=x
is equivalent to -u+x
- unless you apply -x
later, but there's no point in doing that).,
to join partial modes; AND logic is implied; e.g., -u=x,g=x
means that both the user and the group executable bit must be set.-perm
expression with the NOT primary, !
.-print
, or -perm
; also known as actions and tests in GNU find) are implicitly joined with -a
(logical AND), and that -o
and possibly parentheses (escaped as \(
and \)
for the shell) are needed to implement OR logic.find -L ...
instead of just find ...
is used in order to also match symlinks to executables
-L
instructs find to evaluate the targets of symlinks instead of the symlinks themselves; therefore, without -L
, -type f
would ignore symlinks altogether.# Match files that have ALL executable bits set - for ALL 3 security
# principals (u (user), g (group), o (others)) and are therefore executable
# by *anyone*.
# This is the typical case, and applies to executables in _system_ locations
# (e.g., /bin) and user-installed executables in _shared_ locations
# (e.g., /usr/local/bin), for instance.
find -L . -type f -perm -a=x # -a=x is the same as -ugo=x
# The POSIX-compliant equivalent of `-perm +111` from the accepted answer:
# Match files that have ANY executable bit set.
# Note the need to group the permission tests using parentheses.
find -L . -type f \( -perm -u=x -o -perm -g=x -o -perm -o=x \)
# A somewhat contrived example to demonstrate the use of a multi-principial
# mode (comma-separated clauses) and negation:
# Match files that have _both_ the user and group executable bit set, while
# also _not_ having the other executable bit set.
find -L . -type f -perm -u=x,g=x \! -perm -o=x
[1] Description of -executable
from man find
as of GNU find 4.4.2:
Matches files which are executable and directories which are searchable (in a file name resolution sense). This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed.
[2] GNU find versions older than 4.5.12 also allowed prefix +
, but this was first deprecated and eventually removed, because combining +
with symbolic modes yields likely yields unexpected results due to being interpreted as an exact permissions mask. If you (a) run on a version before 4.5.12 and (b) restrict yourself to octal modes only, you could get away with using +
with both GNU find and BSD find, but it's not a good idea.
This is much easier than you're making it. The text node will not have the literal string " "
in it, it'll have have the corresponding character with code 160.
function replaceNbsps(str) {
var re = new RegExp(String.fromCharCode(160), "g");
return str.replace(re, " ");
}
textNode.nodeValue = replaceNbsps(textNode.nodeValue);
UPDATE
Even easier:
textNode.nodeValue = textNode.nodeValue.replace(/\u00a0/g, " ");
Finally, I've defeated my CiSCO EAP-FAST corporate wifi network, and all our Android devices are now able to connect to it.
The walk-around I've performed in order to gain access to this kind of networks from an Android device are easiest than you can imagine.
There's a Wifi Config Editor in the Google Play Store you can use to "activate" the secondary CISCO Protocols when you are setting up a EAP wifi connection.
Its name is Wifi Config Advanced Editor.
First, you have to setup your wireless network manually as close as you can to your "official" corporate wifi parameters.
Save it.
Go to the WCE and edit the parameters of the network you have created in the previous step.
There are 3 or 4 series of settings you should activate in order to force the Android device to use them as a way to connect (the main site I think you want to visit is Enterprise Configuration, but don't forget to check all the parameters to change them if needed.
As a suggestion, even if you have a WPA2 EAP-FAST Cipher, try LEAP in your setup. It worked for me as a charm.
When you finished to edit the config, go to the main Android wifi controller, and force to connect to this network.
Do not Edit the network again with the Android wifi interface.
I have tested it on Samsung Galaxy 1 and 2, Note mobile devices, and on a Lenovo Thinkpad Tablet.
All answers here provide good and working code. But someone would be dissatisfied that they all use ContentType
as return type and not JsonResult
.
Unfortunately JsonResult
is using JavaScriptSerializer
without option to disable it. The best way to get around this is to inherit JsonResult
.
I copied most of the code from original JsonResult
and created JsonStringResult
class that returns passed string as application/json
. Code for this class is below
public class JsonStringResult : JsonResult
{
public JsonStringResult(string data)
{
JsonRequestBehavior = JsonRequestBehavior.DenyGet;
Data = data;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("Get request is not allowed!");
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
response.Write(Data);
}
}
}
Example usage:
var json = JsonConvert.SerializeObject(data);
return new JsonStringResult(json);
In my case I just wanted a line break after each dd
element.
Eg, I wanted to style this:
<dl class="p">
<dt>Created</dt> <dd><time>2021-02-03T14:23:43.073Z</time></dd>
<dt>Updated</dt> <dd><time>2021-02-03T14:44:15.929Z</time></dd>
</p>
like the default style of this:
<p>
<span>Created</span> <time>2021-02-03T14:23:43.073Z</time><br>
<span>Updated</span> <time>2021-02-03T14:44:15.929Z</time>
</p>
which just looks like this:
Created 2021-02-03T14:23:43.073Z
Updated 2021-02-03T14:44:15.929Z
To do that I used this CSS:
dl.p > dt {
display: inline;
}
dl.p > dd {
display: inline;
margin: 0;
}
dl.p > dd::after {
content: "\A";
white-space: pre;
}
Or you could use this CSS:
dl.p > dt {
float: left;
margin-inline-end: 0.26em;
}
dl.p > dd {
margin: 0;
}
I also added a colon after each dt
element with this CSS:
dl.p > dt::after {
content: ":";
}
The reason why you are getting the compilation error is, you are trying to access the session in declaration block (<%! %>
) where it is not available. All the implicit objects of jsp are available in service method only. Code of declarative blocks goes outside the service method.
I'd advice you to use EL. It is a simplified approach.
${sessionScope.username}
would give you the desired output.
To add to what Brad and squadette have said, the self-closing XML syntax <script />
actually is correct XML, but for it to work in practice, your web server also needs to send your documents as properly formed XML with an XML mimetype like application/xhtml+xml
in the HTTP Content-Type header (and not as text/html
).
However, sending an XML mimetype will cause your pages not to be parsed by IE7, which only likes text/html
.
From w3:
In summary, 'application/xhtml+xml' SHOULD be used for XHTML Family documents, and the use of 'text/html' SHOULD be limited to HTML-compatible XHTML 1.0 documents. 'application/xml' and 'text/xml' MAY also be used, but whenever appropriate, 'application/xhtml+xml' SHOULD be used rather than those generic XML media types.
I puzzled over this a few months ago, and the only workable (compatible with FF3+ and IE7) solution was to use the old <script></script>
syntax with text/html
(HTML syntax + HTML mimetype).
If your server sends the text/html
type in its HTTP headers, even with otherwise properly formed XHTML documents, FF3+ will use its HTML rendering mode which means that <script />
will not work (this is a change, Firefox was previously less strict).
This will happen regardless of any fiddling with http-equiv
meta elements, the XML prolog or doctype inside your document -- Firefox branches once it gets the text/html
header, that determines whether the HTML or XML parser looks inside the document, and the HTML parser does not understand <script />
.
you can change that using label property in property panel. This screen shot is example that
I'd just like to add that one small issue with outputting the buffer strings from a spawned process with console.log()
is that it adds newlines, which can spread your spawned process output over additional lines. If you output stdout
or stderr
with process.stdout.write()
instead of console.log()
, then you'll get the console output from the spawned process 'as is'.
I saw that solution here: Node.js: printing to console without a trailing newline?
Hope that helps someone using the solution above (which is a great one for live output, even if it is from the documentation).
Create a section called <connectionStrings></connectionStrings>
in your web.config
inside <configuration></configuration>
then add different connection strings to it, for example
<configuration>
<connectionStrings>
<add name="ConnectionStringName" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=DatabaseName;Integrated Security=True;MultipleActiveResultSets=True"/>
</connectionStrings>
</configuration>
Here's a list of all the different connection string formats https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx
Updated mysqli version:
if ($result = $mysqli->query("SHOW TABLES LIKE '".$table."'")) {
if($result->num_rows == 1) {
echo "Table exists";
}
}
else {
echo "Table does not exist";
}
Original mysql version:
if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))==1)
echo "Table exists";
else echo "Table does not exist";
Referenced from the PHP docs.
There's a great example in the AngularJS docs.
It's very well commented and should get you pointed in the right direction.
A simple example, maybe more so what you're looking for is below:
HTML
<div ng-app="myDirective" ng-controller="x">
<input type="text" ng-model="test" my-directive>
</div>
JavaScript
angular.module('myDirective', [])
.directive('myDirective', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(attrs.ngModel, function (v) {
console.log('value changed, new value is: ' + v);
});
}
};
});
function x($scope) {
$scope.test = 'value here';
}
Edit: Same thing, doesn't require ngModel
jsfiddle:
JavaScript
angular.module('myDirective', [])
.directive('myDirective', function () {
return {
restrict: 'A',
scope: {
myDirective: '='
},
link: function (scope, element, attrs) {
// set the initial value of the textbox
element.val(scope.myDirective);
element.data('old-value', scope.myDirective);
// detect outside changes and update our input
scope.$watch('myDirective', function (val) {
element.val(scope.myDirective);
});
// on blur, update the value in scope
element.bind('propertychange keyup paste', function (blurEvent) {
if (element.data('old-value') != element.val()) {
console.log('value changed, new value is: ' + element.val());
scope.$apply(function () {
scope.myDirective = element.val();
element.data('old-value', element.val());
});
}
});
}
};
});
function x($scope) {
$scope.test = 'value here';
}
The easy way, try uname()
If that does not work, use gethostname() then gethostbyname() and finally gethostbyaddr()
The h_name of hostent{} should be your FQDN
I recommend Charles Web Proxy
Charles is an HTTP proxy / HTTP monitor / Reverse Proxy that enables a developer to view all of the HTTP and SSL / HTTPS traffic between their machine and the Internet. This includes requests, responses and the HTTP headers (which contain the cookies and caching information).
It's cross-platform, written in JAVA, and pretty good. Not nearly as overwhelming as Wireshark, and does a lot of the annoying stuff like setting up the proxies, etc. for you. The only bad part is that it costs money, $50 at that. Not cheap, but a useful tool.
Quoting http://php.net/manual/en/intro.mssql.php:
The MSSQL extension is not available anymore on Windows with PHP 5.3 or later. SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.
Once you downloaded that, follow the instructions at this page:
In a nutshell:
Put the driver file in your PHP extension directory.
Modify the php.ini file to include the driver. For example:extension=php_sqlsrv_53_nts_vc9.dll
Restart the Web server.
See Also (copied from that page)
The PHP Manual for the SQLSRV extension is located at http://php.net/manual/en/sqlsrv.installation.php and offers the following for Installation:
The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.
The drivers can also be used with PDO.
foreach($display_related_tags as $key => $tag_name)
{
if($tag_name == $found_tag['name'])
unset($display_related_tags[$key];
}
$ch = curl_init('http://api.imgur.com/2/upload.xml'); //initialising our url
curl_setopt($ch, CURLOPT_MUTE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //used for https headers
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); //used for https headers
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($pvars));
//the value we post
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //waiting for reponse, default value in php is zero ie, curls normally do not wait for a response
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0');
$output = curl_exec($ch); //the real execution
curl_close($ch);
echo $output;
Try this code. I am not sure about it. But i used it to send xml data to a remote url.
Here's how you might implement a counter:
counter=0
while true; do
if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
echo "Files Present" | mailx -s "File Present" -r [email protected] [email protected]
exit 0
elif [[ "$counter" -gt 20 ]]; then
echo "Counter: $counter times reached; Exiting loop!"
exit 1
else
counter=$((counter+1))
echo "Counter: $counter time(s); Sleeping for another half an hour" | mailx -s "Time to Sleep Now" -r [email protected] [email protected]
sleep 1800
fi
done
Some Explanations:
counter=$((counter+1))
- this is how you can increment a counter. The $
for counter
is optional inside the double parentheses in this case.elif [[ "$counter" -gt 20 ]]; then
- this checks whether $counter
is not greater than 20
. If so, it outputs the appropriate message and breaks out of your while loop."I mean the number of digits in an integer, i.e. "123" has a length of 3"
int i = 123;
// the "length" of 0 is 1:
int len = 1;
// and for numbers greater than 0:
if (i > 0) {
// we count how many times it can be divided by 10:
// (how many times we can cut off the last digit until we end up with 0)
for (len = 0; i > 0; len++) {
i = i / 10;
}
}
// and that's our "length":
std::cout << len;
outputs 3
Please note that MVC 3 onwards the persistence behavior of TempData has changed, now the value in TempData is persisted until it is read, and not just for the next request.
The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request. https://msdn.microsoft.com/en-in/library/dd394711%28v=vs.100%29.aspx
To complete the picture, since -Werror
might considered too "invasive",
for gcc (and llvm) a more precise solution is to transform just this warning in an error, using the option:
-Werror=implicit-function-declaration
See Make one gcc warning an error?
Regarding general use of -Werror
: Of course, having warningless code is recommendable, but in some stage of development it might slow down the prototyping.
Here is another way to run multi line commands.
apiVersion: batch/v1 kind: Job metadata: name: multiline spec: template: spec: containers: - command: - /bin/bash - -exc - | set +x echo "running below scripts" if [[ -f "if-condition.sh" ]]; then echo "Running if success" else echo "Running if failed" fi name: ubuntu image: ubuntu restartPolicy: Never backoffLimit: 1
I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering
Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date
'You said time1 doesn't change, so I left it in a singe cell.
'If that is not correct, you will have to play with this some more.
time1 = Range("A6").Value
'Looping through each of our output cells.
For Each t In Range("B7:E9") 'Change these to match your real ranges.
'Looping through each departure date/time.
'(Only one row in your example. This can be adjusted if needed.)
For Each x In Range("B2:E2") 'Change these to match your real ranges.
'Check to see if our dep time corresponds to
'the matching column in our output
If t.Column = x.Column Then
'If it does, then check to see what our time value is
If x > 0 Then
time2 = x.Value
'Apply the change to the output cell.
t.Value = time1 - time2
'Exit out of this loop and move to the next output cell.
Exit For
End If
End If
'If the columns don't match, or the x value is not a time
'then we'll move to the next dep time (x)
Next x
Next t
End Sub
EDIT
I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).
A B C D E
1 LOAD_NUMBER 1 2 3 4
2 DEPARTURE_TIME_DATE 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 20:00
4 Dry_Refrig 7585.1 0 10099.8 16700
6 1/4/2012 19:30
Using the sub I got this output:
A B C D E
7 Friday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
8 Saturday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
9 Thursday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
Use:
$(".myCheckbox").attr('checked', true); // Deprecated
$(".myCheckbox").prop('checked', true);
And if you want to check if a checkbox is checked or not:
$('.myCheckbox').is(':checked');
Late to the party here, but I often use this construct for doing ad-hoc padding of some value n
, known to be a positive, decimal:
(offset + n + '').substr(1);
Where offset
is 10^^digits.
E.g. Padding to 5 digits, where n = 123:
(1e5 + 123 + '').substr(1); // => 00123
The hexidecimal version of this is slightly more verbose:
(0x100000 + 0x123).toString(16).substr(1); // => 00123
Note 1: I like @profitehlolz's solution as well, which is the string version of this, using slice()'s nifty negative-index feature.
This is example:
$.ajax({
url: "test.html",
async: false
}).done(function(data) {
// Todo something..
}).fail(function(xhr) {
// Todo something..
});
<xsl:for-each select="person">
<xsl:for-each select="*">
<xsl:value-of select="local-name()"/> : <xsl:value-of select="."/>
</xsl:for-each>
</xsl:for-each>
If you have PHP installed on your server, you can create a php file, let's called it phpinfo.php and add this <?php echo phpinfo();?>
, and open the file in your browser, this shows information about your system environment, to quickly find info about your Apache loaded modules, locate 'Loaded Modules' on the resulting page.
If Perl is an option, you can try this:
perl -lne 'print $1 if /(regex)/' file
To implement case-insensitive matching, add the i
modifier
perl -lne 'print $1 if /(regex)/i' file
To print everything AFTER the match:
perl -lne 'if ($found){print} else{if (/regex(.*)/){print $1; $found++}}' textfile
To print the match and everything after the match:
perl -lne 'if ($found){print} else{if (/(regex.*)/){print $1; $found++}}' textfile
The very simplest approach given by mongo README help file
RUNNING
For command line options invoke:
$ ./mongod --help
To run a single server database:
$ sudo mkdir -p /data/db
$ ./mongod
$
$ # The mongo javascript shell connects to localhost and test database by default:
$ ./mongo
> help
If you are working with windows, go to your directory where you have mongo.exe
use the following commands, (I am sharing mine)
C:\Program Files\MongoDB\Server\3.6\bin>mkdir \data
C:\Program Files\MongoDB\Server\3.6\bin>mkdir \data\db
C:\Program Files\MongoDB\Server\3.6\bin>mongod ## this will start your mongoDB server
Now you need to run another CMD prompt and go to the directory where you have mongo and just run it
C:\Program Files\MongoDB\Server\3.6\bin>mongo ## this will start your mongoDB client
Hope it helped :)
If it doesn't work, run CMD as an administrator
This is more predictable then "line-height"
.loginBtn {_x000D_
background:url(images/loginBtn-center.jpg) repeat-x;_x000D_
width:175px;_x000D_
height:65px;_x000D_
margin:20px auto;_x000D_
border-radius:10px;_x000D_
-webkit-border-radius:10px;_x000D_
box-shadow:0 1px 2px #5e5d5b;_x000D_
}_x000D_
_x000D_
.loginBtn span {_x000D_
display: block;_x000D_
padding-top: 22px;_x000D_
text-align: center;_x000D_
line-height: 1em;_x000D_
}
_x000D_
<div id="loginBtn" class="loginBtn"><span>Log in</span></div>
_x000D_
.loginBtn {
display: flex;
align-items: center;
justify-content: center;
}
(Using as an example your first link)
You want to duplicate the behavior of an old HP calculator, there are two options:
You write new program that draws the calculator's display and keys, and when the user clicks on the keys, your programs does what the old calculator did. This is a Simulator
You get a dump of the calculator's firmware, then write a program that loads the firmware and interprets it the same way the microprocessor in the calculator did. This is an Emulator
The Simulator tries to duplicate the behavior of the device.
The Emulator tries to duplicate the inner workings of the device.
$_FILES['file']['tmp_name'];
will contain the temporary file name of the file on the server. This is just a placeholder on your server until you process the file
$_FILES['file']['name'];
contains the original name of the uploaded file from the user's computer.
Rollback one step. Natively.
php artisan migrate:rollback --step=1
And here's the manual page: docs.
No way to do without some hassle. For details, check Martin Bean's answer.
This is finally what did it for me (and triggers a disposition):
function onClick() {_x000D_
var pdf = new jsPDF('p', 'pt', 'letter');_x000D_
pdf.canvas.height = 72 * 11;_x000D_
pdf.canvas.width = 72 * 8.5;_x000D_
_x000D_
pdf.fromHTML(document.body);_x000D_
_x000D_
pdf.save('test.pdf');_x000D_
};_x000D_
_x000D_
var element = document.getElementById("clickbind");_x000D_
element.addEventListener("click", onClick);
_x000D_
<h1>Dsdas</h1>_x000D_
_x000D_
<a id="clickbind" href="#">Click</a>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
_x000D_
And for those of the KnockoutJS inclination, a little binding:
ko.bindingHandlers.generatePDF = {
init: function(element) {
function onClick() {
var pdf = new jsPDF('p', 'pt', 'letter');
pdf.canvas.height = 72 * 11;
pdf.canvas.width = 72 * 8.5;
pdf.fromHTML(document.body);
pdf.save('test.pdf');
};
element.addEventListener("click", onClick);
}
};
Here are the steps I followed to recover from a corrupt blob object.
1) Identify corrupt blob
git fsck --full
error: inflate: data stream error (incorrect data check)
error: sha1 mismatch 241091723c324aed77b2d35f97a05e856b319efd
error: 241091723c324aed77b2d35f97a05e856b319efd: object corrupt or missing
...
Corrupt blob is 241091723c324aed77b2d35f97a05e856b319efd
2) Move corrupt blob to a safe place (just in case)
mv .git/objects/24/1091723c324aed77b2d35f97a05e856b319efd ../24/
3) Get parent of corrupt blob
git fsck --full
Checking object directories: 100% (256/256), done.
Checking objects: 100% (70321/70321), done.
broken link from tree 0716831e1a6c8d3e6b2b541d21c4748cc0ce7180
to blob 241091723c324aed77b2d35f97a05e856b319efd
Parent hash is 0716831e1a6c8d3e6b2b541d21c4748cc0ce7180.
4) Get file name corresponding to corrupt blob
git ls-tree 0716831e1a6c8d3e6b2b541d21c4748cc0ce7180
...
100644 blob 241091723c324aed77b2d35f97a05e856b319efd dump.tar.gz
...
Find this particular file in a backup or in the upstream git repository (in my case it is dump.tar.gz). Then copy it somewhere inside your local repository.
5) Add previously corrupted file in the git object database
git hash-object -w dump.tar.gz
6) Celebrate!
git gc
Counting objects: 75197, done.
Compressing objects: 100% (21805/21805), done.
Writing objects: 100% (75197/75197), done.
Total 75197 (delta 52999), reused 69857 (delta 49296)
Use timedelta.total_seconds()
.
>>> import datetime
>>> datetime.timedelta(seconds=24*60*60).total_seconds()
86400.0
This is not an error, it is a warning from your Microsoft compiler.
Select your project and click "Properties" in the context menu.
In the dialog, chose Configuration Properties
-> C/C++
-> Preprocessor
In the field PreprocessorDefinitions add ;_CRT_SECURE_NO_WARNINGS
to turn those warnings off.
http://handbrake.fr is a nice high level tool with a lot of useful presets for mp4 for iPod, PS3, ... with both GUI and CLI interfaces for Linux, Windows and Mac OS X.
It comes with its own dependencies as a single statically linked fat binary so you have all the x264 / aac codecs included.
$ HandBrakeCLI -Z Universal -i myinputfile.mov -o myoutputfile.mp4
To list all the available presets:
$ HandBrakeCLI -z
There is no updated
dynamic table. There is just inserted
and deleted
. On an UPDATE
command, the old data is stored in the deleted
dynamic table, and the new values are stored in the inserted
dynamic table.
Think of an UPDATE
as a DELETE/INSERT
combination.
I just have the same situation as you and I have just fixed this problem.
It is the reason that you have configured even number of zookeepers which directly result in this problem,try to change your number of zookeeper node to a odd one.
for example the original status of my zookeeper cluster is consisted of 4 nodes,then just remove one of them which result in the number of node to be 3 well ,now its ok to startup zookeeper cluster
below is the output of successfully connect to zookeeper server
2013-04-22 22:07:05,654 [myid:] - INFO [main:ZooKeeper@438] - Initiating client connection, connectString=localhost:2181 sessionTimeout=30000 watcher=org.apache.zookeeper.ZooKeeperMain$MyWatcher@1321ed6
Welcome to ZooKeeper!
2013-04-22 22:07:05,704 [myid:] - INFO [main-SendThread(localhost:2181):ClientCnxn$SendThread@966] - Opening socket connection to server localhost/127.0.0.1:2181. Will not attempt to authenticate using SASL (unknown error)
JLine support is enabled
2013-04-22 22:07:05,727 [myid:] - INFO [main-SendThread(localhost:2181):ClientCnxn$SendThread@849] - Socket connection established to localhost/127.0.0.1:2181, initiating session
[zk: localhost:2181(CONNECTING) 0] 2013-04-22 22:07:05,846 [myid:] - INFO [main-SendThread(localhost:2181):ClientCnxn$SendThread@1207] - Session establishment complete on server localhost/127.0.0.1:2181, sessionid = 0x13e3211c06e0000, negotiated timeout = 30000
JDBC uses a so-called "connection URL", so you can escape "+" by "%2B", that is
useTimezone=true&serverTimezone=GMT%2B8
If you need to have the script keep working on python2 and 3 as I did, this might help someone
import sys
if sys.version_info[0] >= 3:
unicode = str
and can then just do for example
foo = unicode.lower(foo)
Back in 2010 we had the same problem and i successfully employed GoogleDocs with our small Agile Development team (8 Devs in 3 Countries).
GoogleDrawing will serve in the exact same way as a physical Scrum board would, with all the upsides of full flexibilty and also the downsides of zero automation but with the big additional upside of being virtual and accessible from anywhere with an internet connection.
It also was used for the retrospective at the end of each Sprint
GoogleSpreadsheet was used for a concise list of all the tickets from our bug tracking system (Redmine, manually transfered) and also for the (manually updated, albeit with formulas to calculate the progress) burndown chart.
The combination of these different elements is actually quite powerful, as you have the full flexibility over the content and its representation and can have your team communicate via VoIP while all are looking at the same documents and can modify them in real-time.
Here an example of the docs used in a sprint (all sensitive data removed):
As mentioned before, the only downside is the fact that you have to invest some time to maintain and prepare the data for each sprint, but for us that was hugely outweighed by the flexibility and accessibility that the Team of GoogleDocs + VoIP gave us.
This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:
var arrayOfObjects = [{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}];
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
for (var property in object) {
alert('item ' + i + ': ' + property + '=' + object[property]);
}
// If property names are known beforehand, you can also just do e.g.
// alert(object.id + ',' + object.Title);
}
If the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval()
here.
var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]';
var arrayOfObjects = eval(string);
// ...
To learn more about JSON, check MDN web docs: Working with JSON .
Make sure your iframe is already loaded. Old but reliable way without jQuery:
<iframe src="samedomain.com/page.htm" id="iframe" onload="access()"></iframe>
<script>
function access() {
var iframe = document.getElementById("iframe");
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
console.log(innerDoc.body);
}
</script>
There is a plugin for that, jquery-formatcurrency.
You can set the decimal separator (default .
) and currency symbol (default $
) for custom formatting or use the built in International Support. The format for Bahasa Indonesia (Indonesia) - Indonesian (Indonesia) coded id-ID looks closest to what you have provided.
You can use the following CSS to style the input element.
input[type="date"] {_x000D_
background-color: red;_x000D_
outline: none;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-clear-button {_x000D_
font-size: 18px;_x000D_
height: 30px;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-inner-spin-button {_x000D_
height: 28px;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-calendar-picker-indicator {_x000D_
font-size: 15px;_x000D_
}
_x000D_
<input type="date" value="From" name="from" placeholder="From" required="" />
_x000D_
Just wishing to avoid the console error, I solved this using a similar approach to Artur's earlier answer, following these steps:
This is not the greatest solution (patched local script to maintain, losing control of where messages are sent) but it solved my issue.
Please see the security warning about removing the targetOrigin URI stated here before using this solution - https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
It seems you have found your solution, but still it will be helpful to others, on this page on point based on Chrome 59.
4.Note the red triangle in the top-right of the Animation Frame Fired event. Whenever you see a red triangle, it's a warning that there may be an issue related to this event.
If you hover on these triangle you can see those are the violation handler errors and as per point 4. yes there is some issue related to that event.
You can always take a look at the .size
attribute. It is defined as an integer, and is zero (0
) when there are no elements in the array:
import numpy as np
a = np.array([])
if a.size == 0:
# Do something when `a` is empty
This doesn't work on android native browser to click "hidden input (file) element":
$('a#swaswararedirectlink')[0].click();
But this works:
$("#input-file").show();
$("#input-file")[0].click();
$("#input-file").hide();
In addition to what's already been said, don't use ToString()
on the exception object for displaying to the user. Just the Message
property should suffice, or a higher level custom message.
In terms of logging purposes, definitely use ToString()
on the Exception, not just the Message
property, as in most scenarios, you will be left scratching your head where specifically this exception occurred, and what the call stack was. The stacktrace would have told you all that.
>>> arr = numpy.array(((2,2),(2,-2)))
>>> tuple(map(tuple, arr))
((2, 2), (2, -2))
Just use var = var1 var2
and it will automatically concatenate the vars var1
and var2
:
awk '{new_var=$1$2; print new_var}' file
You can put an space in between with:
awk '{new_var=$1" "$2; print new_var}' file
Which in fact is the same as using FS
, because it defaults to the space:
awk '{new_var=$1 FS $2; print new_var}' file
$ cat file
hello how are you
i am fine
$ awk '{new_var=$1$2; print new_var}' file
hellohow
iam
$ awk '{new_var=$1 FS $2; print new_var}' file
hello how
i am
You can play around with it in ideone: http://ideone.com/4u2Aip
Update your user, domain, and proxy information in cntlm.ini
, then test your proxy with this command (run in your Cntlm installation folder):
cntlm -c cntlm.ini -I -M http://google.ro
It will ask for your password, and hopefully print your required authentication information, which must be saved in your cntlm.ini
Sample cntlm.ini
:
Username user
Domain domain
# provide actual value if autodetection fails
# Workstation pc-name
Proxy my_proxy_server.com:80
NoProxy 127.0.0.*, 192.168.*
Listen 127.0.0.1:54321
Listen 192.168.1.42:8080
Gateway no
SOCKS5Proxy 5000
# provide socks auth info if you want it
# SOCKS5User socks-user:socks-password
# printed authentication info from the previous step
Auth NTLMv2
PassNTLMv2 98D6986BCFA9886E41698C1686B58A09
Note: on linux the config file is cntlm.conf
Just remove class full
from <html>
and add it to <body>
tag. Then set style background-color:transparent !important;
for the Jumbotron div (as Amit Joki said in his answer).
SQL Server 2012+ (for both month and day):
SELECT FORMAT(GetDate(),'MMdd')
If you decide you want the year too, use:
SELECT FORMAT(GetDate(),'yyyyMMdd')
This workaround helped us so much at my job (Tech Support), we made a simple batch file we could run from anywhere (We didnt have the permissions to install it). This workaround will set the variable and then run OpenSSL for you. It also opens up the bin folder for you (cause this is where any files you create or modify will be saved). Also, this is only for Windows.
Copy this code to a file named StartOpenSSL.bat. Save this to a location of your choice. It can be run from anywhere.
@echo off
title OpenSSL
cd\openssl\bin
if exist "C:\openssl\share\openssl.cnf" (
set OPENSSL_CONF=c:/openssl/share/openssl.cnf
start explorer.exe c:\openssl\bin
echo Welcome to OpenSSL
openssl
) else (
echo Error: openssl.cnf was not found
echo File openssl.cnf needs to be present in c:\openssl\share
pause
)
exit
URLs can give a lot of clues, especially with Content Management Systems.
For example "http://abcxyz.com/node/46" looks a lot like Drupal.
Also many frameworks have standard JavaScript and CSS files they use.
Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3
NOTE: this component only works in boostrap-4 since version 1.13.0
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
<option>Mustard</option>_x000D_
<option>Ketchup</option>_x000D_
<option>Relish</option>_x000D_
</select>
_x000D_
I do not really think so, what I can find is the word "this." causes the hibernate not to include any restrictions in its query, which means it got all the records lists. About the hibernate bug that was reported, I can see it's reported as fixed but I totally failed to download the Patch.
Solution using just POST - no $_SESSION
page1.php
<form action="page2.php" method="post">
<textarea name="textarea1" id="textarea1"></textarea><br />
<input type="submit" value="submit" />
</form>
page2.php
<?php
// this page outputs the contents of the textarea if posted
$textarea1 = ""; // set var to avoid errors
if(isset($_POST['textarea1'])){
$textarea1 = $_POST['textarea1']
}
?>
<textarea><?php echo $textarea1;?></textarea>
Solution using $_SESSION and POST
page1.php
<?php
session_start(); // needs to be before anything else on page to use $_SESSION
$textarea1 = "";
if(isset($_POST['textarea1'])){
$_SESSION['textarea1'] = $_POST['textarea1'];
}
?>
<form action="page1.php" method="post">
<textarea name="textarea1" id="textarea1"></textarea><br />
<input type="submit" value="submit" />
</form>
<br /><br />
<a href="page2.php">Go to page2</a>
page2.php
<?php
session_start(); // needs to be before anything else on page to use $_SESSION
// this page outputs the textarea1 from the session IF it exists
$textarea1 = ""; // set var to avoid errors
if(isset($_SESSION['textarea1'])){
$textarea1 = $_SESSION['textarea1']
}
?>
<textarea><?php echo $textarea1;?></textarea>
WARNING!!! - This contains no validation!!!
$(this).find("select").each(function () {
$(this).find('option:selected').text();
});
Very simple:
let
is constant. var
is dynamic.Bit of description:
let
creates a constant. (sort of like an NSString
). You can't change its value once you have set it. You can still add it to other things and create new variables though.
var
creates a variable. (sort of like NSMutableString
) so you can change the value of it. But this has been answered several times.
Elements that are floated are taken out of the normal flow layout, and block elements, such as DIV's, no longer span the width of their parent. The rules change in this situation. Instead of reinventing the wheel, check out this site for some possible solutions to create the two column layout you are after: http://www.maxdesign.com.au/presentation/page_layouts/
Specifically, the "Liquid Two-Column layout".
Cheers!
If you want to safe time and lines of code you can make measuring the function execution time a one line macro:
a) Implement a time measuring class as already suggested above ( here is my implementation for android):
class MeasureExecutionTime{
private:
const std::chrono::steady_clock::time_point begin;
const std::string caller;
public:
MeasureExecutionTime(const std::string& caller):caller(caller),begin(std::chrono::steady_clock::now()){}
~MeasureExecutionTime(){
const auto duration=std::chrono::steady_clock::now()-begin;
LOGD("ExecutionTime")<<"For "<<caller<<" is "<<std::chrono::duration_cast<std::chrono::milliseconds>(duration).count()<<"ms";
}
};
b) Add a convenient macro that uses the current function name as TAG (using a macro here is important, else __FUNCTION__
will evaluate to MeasureExecutionTime
instead of the function you wanto to measure
#ifndef MEASURE_FUNCTION_EXECUTION_TIME
#define MEASURE_FUNCTION_EXECUTION_TIME const MeasureExecutionTime measureExecutionTime(__FUNCTION__);
#endif
c) Write your macro at the begin of the function you want to measure. Example:
void DecodeMJPEGtoANativeWindowBuffer(uvc_frame_t* frame_mjpeg,const ANativeWindow_Buffer& nativeWindowBuffer){
MEASURE_FUNCTION_EXECUTION_TIME
// Do some time-critical stuff
}
Which will result int the following output:
ExecutionTime: For DecodeMJPEGtoANativeWindowBuffer is 54ms
Note that this (as all other suggested solutions) will measure the time between when your function was called and when it returned, not neccesarily the time your CPU was executing the function. However, if you don't give the scheduler any change to suspend your running code by calling sleep() or similar there is no difference between.
In modern MongoDB releases you can brute force this with $slice
just off the basic aggregation result. For "large" results, run parallel queries instead for each grouping ( a demonstration listing is at the end of the answer ), or wait for SERVER-9377 to resolve, which would allow a "limit" to the number of items to $push
to an array.
db.books.aggregate([
{ "$group": {
"_id": {
"addr": "$addr",
"book": "$book"
},
"bookCount": { "$sum": 1 }
}},
{ "$group": {
"_id": "$_id.addr",
"books": {
"$push": {
"book": "$_id.book",
"count": "$bookCount"
},
},
"count": { "$sum": "$bookCount" }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 },
{ "$project": {
"books": { "$slice": [ "$books", 2 ] },
"count": 1
}}
])
Still not resolving SERVER-9377, but in this release $lookup
allows a new "non-correlated" option which takes an "pipeline"
expression as an argument instead of the "localFields"
and "foreignFields"
options. This then allows a "self-join" with another pipeline expression, in which we can apply $limit
in order to return the "top-n" results.
db.books.aggregate([
{ "$group": {
"_id": "$addr",
"count": { "$sum": 1 }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 },
{ "$lookup": {
"from": "books",
"let": {
"addr": "$_id"
},
"pipeline": [
{ "$match": {
"$expr": { "$eq": [ "$addr", "$$addr"] }
}},
{ "$group": {
"_id": "$book",
"count": { "$sum": 1 }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 }
],
"as": "books"
}}
])
The other addition here is of course the ability to interpolate the variable through $expr
using $match
to select the matching items in the "join", but the general premise is a "pipeline within a pipeline" where the inner content can be filtered by matches from the parent. Since they are both "pipelines" themselves we can $limit
each result separately.
This would be the next best option to running parallel queries, and actually would be better if the $match
were allowed and able to use an index in the "sub-pipeline" processing. So which is does not use the "limit to $push
" as the referenced issue asks, it actually delivers something that should work better.
You seem have stumbled upon the top "N" problem. In a way your problem is fairly easy to solve though not with the exact limiting that you ask for:
db.books.aggregate([
{ "$group": {
"_id": {
"addr": "$addr",
"book": "$book"
},
"bookCount": { "$sum": 1 }
}},
{ "$group": {
"_id": "$_id.addr",
"books": {
"$push": {
"book": "$_id.book",
"count": "$bookCount"
},
},
"count": { "$sum": "$bookCount" }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 }
])
Now that will give you a result like this:
{
"result" : [
{
"_id" : "address1",
"books" : [
{
"book" : "book4",
"count" : 1
},
{
"book" : "book5",
"count" : 1
},
{
"book" : "book1",
"count" : 3
}
],
"count" : 5
},
{
"_id" : "address2",
"books" : [
{
"book" : "book5",
"count" : 1
},
{
"book" : "book1",
"count" : 2
}
],
"count" : 3
}
],
"ok" : 1
}
So this differs from what you are asking in that, while we do get the top results for the address values the underlying "books" selection is not limited to only a required amount of results.
This turns out to be very difficult to do, but it can be done though the complexity just increases with the number of items you need to match. To keep it simple we can keep this at 2 matches at most:
db.books.aggregate([
{ "$group": {
"_id": {
"addr": "$addr",
"book": "$book"
},
"bookCount": { "$sum": 1 }
}},
{ "$group": {
"_id": "$_id.addr",
"books": {
"$push": {
"book": "$_id.book",
"count": "$bookCount"
},
},
"count": { "$sum": "$bookCount" }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 },
{ "$unwind": "$books" },
{ "$sort": { "count": 1, "books.count": -1 } },
{ "$group": {
"_id": "$_id",
"books": { "$push": "$books" },
"count": { "$first": "$count" }
}},
{ "$project": {
"_id": {
"_id": "$_id",
"books": "$books",
"count": "$count"
},
"newBooks": "$books"
}},
{ "$unwind": "$newBooks" },
{ "$group": {
"_id": "$_id",
"num1": { "$first": "$newBooks" }
}},
{ "$project": {
"_id": "$_id",
"newBooks": "$_id.books",
"num1": 1
}},
{ "$unwind": "$newBooks" },
{ "$project": {
"_id": "$_id",
"num1": 1,
"newBooks": 1,
"seen": { "$eq": [
"$num1",
"$newBooks"
]}
}},
{ "$match": { "seen": false } },
{ "$group":{
"_id": "$_id._id",
"num1": { "$first": "$num1" },
"num2": { "$first": "$newBooks" },
"count": { "$first": "$_id.count" }
}},
{ "$project": {
"num1": 1,
"num2": 1,
"count": 1,
"type": { "$cond": [ 1, [true,false],0 ] }
}},
{ "$unwind": "$type" },
{ "$project": {
"books": { "$cond": [
"$type",
"$num1",
"$num2"
]},
"count": 1
}},
{ "$group": {
"_id": "$_id",
"count": { "$first": "$count" },
"books": { "$push": "$books" }
}},
{ "$sort": { "count": -1 } }
])
So that will actually give you the top 2 "books" from the top two "address" entries.
But for my money, stay with the first form and then simply "slice" the elements of the array that are returned to take the first "N" elements.
The demonstration code is appropriate for usage with current LTS versions of NodeJS from v8.x and v10.x releases. That's mostly for the async/await
syntax, but there is nothing really within the general flow that has any such restriction, and adapts with little alteration to plain promises or even back to plain callback implementation.
index.js
const { MongoClient } = require('mongodb');
const fs = require('mz/fs');
const uri = 'mongodb://localhost:27017';
const log = data => console.log(JSON.stringify(data, undefined, 2));
(async function() {
try {
const client = await MongoClient.connect(uri);
const db = client.db('bookDemo');
const books = db.collection('books');
let { version } = await db.command({ buildInfo: 1 });
version = parseFloat(version.match(new RegExp(/(?:(?!-).)*/))[0]);
// Clear and load books
await books.deleteMany({});
await books.insertMany(
(await fs.readFile('books.json'))
.toString()
.replace(/\n$/,"")
.split("\n")
.map(JSON.parse)
);
if ( version >= 3.6 ) {
// Non-correlated pipeline with limits
let result = await books.aggregate([
{ "$group": {
"_id": "$addr",
"count": { "$sum": 1 }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 },
{ "$lookup": {
"from": "books",
"as": "books",
"let": { "addr": "$_id" },
"pipeline": [
{ "$match": {
"$expr": { "$eq": [ "$addr", "$$addr" ] }
}},
{ "$group": {
"_id": "$book",
"count": { "$sum": 1 },
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 }
]
}}
]).toArray();
log({ result });
}
// Serial result procesing with parallel fetch
// First get top addr items
let topaddr = await books.aggregate([
{ "$group": {
"_id": "$addr",
"count": { "$sum": 1 }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 }
]).toArray();
// Run parallel top books for each addr
let topbooks = await Promise.all(
topaddr.map(({ _id: addr }) =>
books.aggregate([
{ "$match": { addr } },
{ "$group": {
"_id": "$book",
"count": { "$sum": 1 }
}},
{ "$sort": { "count": -1 } },
{ "$limit": 2 }
]).toArray()
)
);
// Merge output
topaddr = topaddr.map((d,i) => ({ ...d, books: topbooks[i] }));
log({ topaddr });
client.close();
} catch(e) {
console.error(e)
} finally {
process.exit()
}
})()
books.json
{ "addr": "address1", "book": "book1" }
{ "addr": "address2", "book": "book1" }
{ "addr": "address1", "book": "book5" }
{ "addr": "address3", "book": "book9" }
{ "addr": "address2", "book": "book5" }
{ "addr": "address2", "book": "book1" }
{ "addr": "address1", "book": "book1" }
{ "addr": "address15", "book": "book1" }
{ "addr": "address9", "book": "book99" }
{ "addr": "address90", "book": "book33" }
{ "addr": "address4", "book": "book3" }
{ "addr": "address5", "book": "book1" }
{ "addr": "address77", "book": "book11" }
{ "addr": "address1", "book": "book1" }
You could do
<body onload="window.print()">
...
</body>
Firstly create a new class that extends the WorldView
class. I called my new class Background
. So in this new class import all the Java packages you will need in order to override the paintBackground
method. This should be:
import city.soi.platform.*;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.ImageObserver;
import javax.swing.ImageIcon;
import java.awt.geom.AffineTransform;
Next after the class name make sure that it says extends WorldView
. Something like this:
public class Background extends WorldView
Then declare the variables game of type Game
and an image variable of type Image
something like this:
private Game game;
private Image image;
Then in the constructor of this class make sure the game of type Game
is in the signature of the constructor and that in the call to super
you will have to initialise the WorldView
, initialise the game and initialise the image variables, something like this:
super(game.getCurrentLevel().getWorld(), game.getWidth(), game.getHeight());
this.game = game;
bg = (new ImageIcon("lol.png")).getImage();
Then you just override the paintBackground
method in exactly the same way as you did when overriding the paint
method in the Player
class. Just like this:
public void paintBackground(Graphics2D g)
{
float x = getX();
float y = getY();
AffineTransform transform = AffineTransform.getTranslateInstance(x,y);
g.drawImage(bg, transform, game.getView());
}
Now finally you have to declare a class level reference to the new class you just made in the Game
class and initialise this in the Game
constructor, something like this:
private Background image;
And in the Game constructor:
image = new Background(this);
Lastly all you have to do is add the background to the frame! That's the thing I'm sure we were all missing. To do that you have to do something like this after the variable frame
has been declared:
frame.add(image);
Make sure you add this code just before frame.pack();
.
Also make sure you use a background image that isn't too big!
Now that's it! Ive noticed that the game engines can handle JPEG and PNG image formats but could also support others. Even though this helps include a background image in your game, it is not perfect! Because once you go to the next level all your platforms and sprites are invisible and all you can see is your background image and any JLabels/Jbuttons you have included in the game.
I ran into the exact same problem under identical circumstances. I don't have the tnsnames.ora file, and I wanted to use SQL*Plus with Easy Connection Identifier format in command line. I solved this problem as follows.
The SQL*Plus® User's Guide and Reference gives an example:
sqlplus hr@\"sales-server:1521/sales.us.acme.com\"
Pay attention to two important points:
I found these good questions to detect service name via existing connection: 1, 2. Try this query for example:
SELECT value FROM V$SYSTEM_PARAMETER WHERE UPPER(name) = 'SERVICE_NAMES'
-n
returns line number.
-i
is for ignore-case. Only to be used if case matching is not necessary
$ grep -in null myfile.txt
2:example two null,
4:example four null,
Combine with awk
to print out the line number after the match:
$ grep -in null myfile.txt | awk -F: '{print $2" - Line number : "$1}'
example two null, - Line number : 2
example four null, - Line number : 4
Use command substitution to print out the total null count:
$ echo "Total null count :" $(grep -ic null myfile.txt)
Total null count : 2
Thanks for your answers. I didn't understand what type of object "MyTable" was (in your answers) and the following code gave me the error shown below.
DataTable dt = ds.Tables[0];
var name = from r in dt
where r.ID == 0
select r.Name;
Could not find an implementation of the query pattern for source type 'System.Data.DataTable'. 'Where' not found
So I continued my googling and found something that does work:
var rowColl = ds.Tables[0].AsEnumerable();
string name = (from r in rowColl
where r.Field<int>("ID") == 0
select r.Field<string>("NAME")).First<string>();
What do you think?
open your /etc/paths file, put /usr/local/bin on top of /usr/bin
$ sudo vi /etc/paths
/usr/local/bin
/usr/local/sbin
/usr/bin
/bin
/usr/sbin
/sbin
and Restart the terminal, @mmel
Refresh Grid Store
Ext.getCmp('GridId').getStore().reload();
This will reload the grid store and get new data.
This is not direct answer to the original question but I hope this suggestion helps someones with similar error:
When using a newer web-api with Webpack+Babel for transpiling and you get
Module parse failed: 'import' and 'export' may only appear at the top level
then you probably forgot to import a polyfill.
For example:
when using fetch()
api and targeting for es2015, you should
whatwg-fetch
polyfill to package.jsonimport {fetch} from 'whatwg-fetch'
Select Project / Specific Folder --> Right Click --> Add Files to Project -- > Select the File you want to add.
This worked for me.
Sometimes I had the same issues when I forget to add Lombok annotation processor dependency to the maven configuration
JOIN t2 ON t1.id=t2.id AND t1.date=t2.date
I have to say in all my years of PHP programming, I have never encountered a problem with isset()
returning false on a null variable. OTOH, I have encountered problems with isset()
failing on a null array entry - but array_key_exists()
works correctly in that case.
For some comparison, Icon explicitly defines an unused variable as returning &null
so you use the is-null test in Icon to also check for an unset variable. This does make things easier. On the other hand, Visual BASIC has multiple states for a variable that doesn't have a value (Null, Empty, Nothing, ...), and you often have to check for more than one of them. This is known to be a source of bugs.
Your String-based solution is perfectly OK, there is nothing "un-neat" about it. You have to realize that mathematically, numbers don't have a length, nor do they have digits. Length and digits are both properties of a physical representation of a number in a specific base, i.e. a String.
A logarithm-based solution does (some of) the same things the String-based one does internally, and probably does so (insignificantly) faster because it only produces the length and ignores the digits. But I wouldn't actually consider it clearer in intent - and that's the most important factor.
We have this issue as well (or a variant).
Try the following:
1) Add a timeout to p.WaitForExit(nnnn); where nnnn is in milliseconds.
2) Put the ReadToEnd call before the WaitForExit call. This is what we've seen MS recommend.
This is the best way for me:
cat filename.tsv |
while read FILENAME
do
sudo find /PATH_FROM/ -name "$FILENAME" -maxdepth 4 -exec cp '{}' /PATH_TO/ \; ;
done
You can also add the styling directly in the markup if you desire so:
<ng-container matColumnDef="Edit">
<th mat-header-cell *matHeaderCellDef > Edit </th>
<td mat-cell *matCellDef="let element" (click)="openModal()" style="width: 50px;"> <i class="fa fa-pencil" aria-hidden="true"></i> </td>
</ng-container>
first install fontawsome using npm
npm install --save @fortawesome/fontawesome-free
add to resources\sass\app.scss
// Fonts
@import '~@fortawesome/fontawesome-free/scss/fontawesome';
and add to resources\js\app.js
require('@fortawesome/fontawesome-free/js/all.js');
then run
npm run dev
or
npm run production
The first problem is that when you call append on a jQuery set with more than one element, a clone of the element to append is created for each and thus the attached event observer is lost.
An alternative way to do it would be to create the link for each element:
function handler() { alert('hello'); }
$('.add_to_this').append(function() {
return $('<a>Click here</a>').click(handler);
})
Another potential problem might be that the event observer is attached before the element has been added to the DOM. I'm not sure if this has anything to say, but I think the behavior might be considered undetermined. A more solid approach would probably be:
function handler() { alert('hello'); }
$('.add_to_this').each(function() {
var link = $('<a>Click here</a>');
$(this).append(link);
link.click(handler);
});
Using 'now()' as default value automatically generates time-stamp.
Visual Studio
If you are creating a setup project with VS, you can create a custom action who called a .NET method to start the service. But, it is not really recommended to use managed custom action in a MSI. See this page.
ServiceController controller = new ServiceController();
controller.MachineName = "";//The machine where the service is installed;
controller.ServiceName = "";//The name of your service installed in Windows Services;
controller.Start();
InstallShield or Wise
If you are using InstallShield or Wise, these applications provide the option to start the service. Per example with Wise, you have to add a service control action. In this action, you specify if you want to start or stop the service.
Wix
Using Wix you need to add the following xml code under the component of your service. For more information about that, you can check this page.
<ServiceInstall
Id="ServiceInstaller"
Type="ownProcess"
Vital="yes"
Name=""
DisplayName=""
Description=""
Start="auto"
Account="LocalSystem"
ErrorControl="ignore"
Interactive="no">
<ServiceDependency Id="????"/> ///Add any dependancy to your service
</ServiceInstall>
In startup.cs, add the constructor
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
Access the settings using Configuration["SecureCookies"]
i use End key, but. as you said you found a way to solve this problem in sublime text... right????
i will suggest you to install keymap of sublime text .. here and use that sortcut key to solve your same problem in vscode.
how to install
press -> ctrl + k then ctrl + M
or watch the bottom left corner there is a gear called setting click on theat you will found keymaps you will redirected to the extentions were you will have to choose your ex-editor..
The main difference is that WHERE
cannot be used on grouped item (such as SUM(number)
) whereas HAVING
can.
The reason is the WHERE
is done before the grouping and HAVING
is done after the grouping is done.
You can use a subquery:
SELECT *
FROM terms
WHERE id IN (SELECT term_id FROM terms_relation WHERE taxonomy='categ');
and if you need to show all columns from both tables:
SELECT t.*, tr.*
FROM terms t, terms_relation tr
WHERE t.id = tr.term_id
AND tr.taxonomy='categ'
Much better:
public static String fromHexString(String hex, String sourceEncoding ) throws IOException{
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buffer = new byte[512];
int _start=0;
for (int i = 0; i < hex.length(); i+=2) {
buffer[_start++] = (byte)Integer.parseInt(hex.substring(i, i + 2), 16);
if (_start >=buffer.length || i+2>=hex.length()) {
bout.write(buffer);
Arrays.fill(buffer, 0, buffer.length, (byte)0);
_start = 0;
}
}
return new String(bout.toByteArray(), sourceEncoding);
}
You can use the command wget
to download from command line. Specifically, you could use
wget http://download.oracle.com/otn-pub/java/jdk/7u10-b18/jdk-7u10-linux-x64.tar.gz
However because Oracle requires you to accept a license agreement this may not work (and I am currently unable to test it).
two liner in swift 4:
button.setAttributedTitle(.init(string: "My text", attributes: [.font: UIFont.systemFont(ofSize: 20, weight: .bold)]), for: .selected)
button.setAttributedTitle(.init(string: "My text", attributes: [.font: UIFont.systemFont(ofSize: 20, weight: .regular)]), for: .normal)
Using the width function:
$('div#somediv').width('70%');
will turn:
<div id="somediv" />
into:
<div id="somediv" style="width: 70%;"/>
Here is my answer in Python 2.7
from datetime import datetime
import tzlocal # pip install tzlocal
print datetime.now(tzlocal.get_localzone()).strftime("%Y-%m-%d %H:%M:%S %z")
from datetime import datetime
import pytz # pip install pytz
print datetime.now(pytz.timezone('Asia/Taipei')).strftime("%Y-%m-%d %H:%M:%S %z")
It will print something like
2017-08-10 20:46:24 +0800
QString qstr;
std::string str = qstr.toStdString();
However, if you're using Qt:
QTextStream out(stdout);
out << qstr;
For checking for a time of day use:
TimeSpan start = new TimeSpan(10, 0, 0); //10 o'clock
TimeSpan end = new TimeSpan(12, 0, 0); //12 o'clock
TimeSpan now = DateTime.Now.TimeOfDay;
if ((now > start) && (now < end))
{
//match found
}
For absolute times use:
DateTime start = new DateTime(2009, 12, 9, 10, 0, 0)); //10 o'clock
DateTime end = new DateTime(2009, 12, 10, 12, 0, 0)); //12 o'clock
DateTime now = DateTime.Now;
if ((now > start) && (now < end))
{
//match found
}
First create a baseViewController
and add viewDidLoad
this code "swift4":
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swiped))
swipeRight.direction = UISwipeGestureRecognizerDirection.right
self.view.addGestureRecognizer(swipeRight)
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(swiped))
swipeLeft.direction = UISwipeGestureRecognizerDirection.left
self.view.addGestureRecognizer(swipeLeft)
}
// Example Tabbar 5 pages
@objc func swiped(_ gesture: UISwipeGestureRecognizer) {
if gesture.direction == .left {
if (self.tabBarController?.selectedIndex)! < 5 {
self.tabBarController?.selectedIndex += 1
}
} else if gesture.direction == .right {
if (self.tabBarController?.selectedIndex)! > 0 {
self.tabBarController?.selectedIndex -= 1
}
}
}
}
And use this baseController
class:
class YourViewController: BaseViewController {
// its done. Swipe successful
//Now you can use all the Controller you have created without writing any code.
}
You can use something like this
<script type="text/javascript">
var myObject = {'name':'Kasun', 'address':'columbo','age': '29'}
var count = Object.keys(myObject).length;
console.log(count);
</script>
I've created a fiddle using your screenshot as a background image and stripping out the extra mark-up, and it seems to work fine
http://jsfiddle.net/fLdQG/2/ (webkit browser required)
Does this work for you? If not, can you update the fiddle with your exact mark-up and CSS?
try this
$('#id').on('mousedown', function(event){
event.preventDefault();
}
I've finally managed to do it. Answer in code snippet below:
var querystring = require('querystring');
var request = require('request');
var form = {
username: 'usr',
password: 'pwd',
opaque: 'opaque',
logintype: '1'
};
var formData = querystring.stringify(form);
var contentLength = formData.length;
request({
headers: {
'Content-Length': contentLength,
'Content-Type': 'application/x-www-form-urlencoded'
},
uri: 'http://myUrl',
body: formData,
method: 'POST'
}, function (err, res, body) {
//it works!
});
var formData = new FormData;
var alphaArray = ['A', 'B', 'C','D','E'];
for (var i = 0; i < alphaArray.length; i++) {
formData.append('listOfAlphabet', alphaArray [i]);
}
And In your request you will get array of alphabets.
With Kotlin, we can now make a generic function for this!
object RepeatHelper {
fun repeatDelayed(delay: Long, todo: () -> Unit) {
val handler = Handler()
handler.postDelayed(object : Runnable {
override fun run() {
todo()
handler.postDelayed(this, delay)
}
}, delay)
}
}
And to use, just do:
val delay = 1000L
RepeatHelper.repeatDelayed(delay) {
myRepeatedFunction()
}
I ended up using this quick piece of code that did exactly what I needed:
final JFileChooser fc = new JFileChooser();
fc.showOpenDialog(this);
try {
// Open an input stream
Scanner reader = new Scanner(fc.getSelectedFile());
}
It's simpler to use numpy
from my opinion:
import numpy as np
list1=[1,2,3]
list2=[4,5,6]
np.add(list1,list2)
Results:
For detailed parameter information, check here: numpy.add
function checkAll(class_name) {
$("." + class_name).each(function () {
if (this.checked == true)
this.checked = false;
else
this.checked = true;
});
}
Another thing that people may find useful when using the develop
method is the --user
option to install without sudo. Ex:
python setup.py develop --user
instead of
sudo python setup.py develop
use this code it is working
// index.jsp or login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>
</form>
</body>
</html>
// authentication servlet class
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class auth extends HttpServlet {
private static final long serialVersionUID = 1L;
public auth() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String username = request.getParameter("username");
String pass = request.getParameter("pass");
String sql = "select * from reg where username='" + username + "'";
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
"root", "");
Statement s = conn.createStatement();
java.sql.ResultSet rs = s.executeQuery(sql);
String un = null;
String pw = null;
String name = null;
/* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */
PrintWriter prwr1 = response.getWriter();
if(!rs.isBeforeFirst()){
prwr1.write("<h1> No Such User in Database<h1>");
} else {
/* Conditions to be executed after at least one row is returned by query execution */
while (rs.next()) {
un = rs.getString("username");
pw = rs.getString("password");
name = rs.getString("name");
}
PrintWriter pww = response.getWriter();
if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
// use this or create request dispatcher
response.setContentType("text/html");
pww.write("<h1>Welcome, " + name + "</h1>");
} else {
pww.write("wrong username or password\n");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Do you have multiple Radio Buttons on the page..
Because what I see is that you are assigning the events to all the radio button's on the page when you click on a radio button
Try this,
window.location.href="sample.html";
Here sample.html
is a next page. It will go to the next page.
This is quite simple. You have to call cancel
or cancelAll
on your NotificationManager. The parameter of the cancel method is the ID of the notification that should be canceled.
See the API: http://developer.android.com/reference/android/app/NotificationManager.html#cancel(int)
Try setting the variable CMAKE_CXX_FLAGS
instead of CMAKE_C_FLAGS
:
set (CMAKE_CXX_FLAGS "-fexceptions")
The variable CMAKE_C_FLAGS
only affects the C compiler, but you are compiling C++ code.
Adding the flag to CMAKE_EXE_LINKER_FLAGS
is redundant.
Besides not being a lazy evaluator by evaluating both operands, I think the main characteristics of bitwise operators compare each bytes of operands like in the following example:
int a = 4;
int b = 7;
System.out.println(a & b); // prints 4
//meaning in an 32 bit system
// 00000000 00000000 00000000 00000100
// 00000000 00000000 00000000 00000111
// ===================================
// 00000000 00000000 00000000 00000100
I experienced this same issue after upgrade. Upon opening the Chrome browser in the emulator, google.com could no longer be reached.
I found a post on SO that suggested the problem was with the emulator trying to use a disconnected network adapter. For me the problem was occurring when I was connected to a LAN. Disabling the wireless LAN adapter fixed the issue.
To disable the adapter:
Are you interested in counting the executable lines rather than the total file line count? If so you could try a code coverage tool such as EclEmma. As a side effect of the code coverage stats you get stats on the number of executable lines and blocks (and methods and classes). These are rolled up from the method level upwards, so you can see line counts for the packages, source roots and projects as well.
We'll get to Bootstrap in a second, but here's the fundamental CSS concepts in play in order to do this yourself. As beard of prey points out, you can do this with CSS by absolutely positioning the icon inside of the input element. Then add padding to either side so the text doesn't overlap with the icon.
So for the following HTML:
<div class="inner-addon left-addon">
<i class="glyphicon glyphicon-user"></i>
<input type="text" class="form-control" />
</div>
You can use the following CSS to left and right align glyphs:
/* enable absolute positioning */
.inner-addon {
position: relative;
}
/* style icon */
.inner-addon .glyphicon {
position: absolute;
padding: 10px;
pointer-events: none;
}
/* align icon */
.left-addon .glyphicon { left: 0px;}
.right-addon .glyphicon { right: 0px;}
/* add padding */
.left-addon input { padding-left: 30px; }
.right-addon input { padding-right: 30px; }
Note: This presumes you're using glyphicons, but works equally well with font-awesome.
For FA, just replace.glyphicon
with.fa
As buffer points out, this can be accomplished natively within Bootstrap by using Validation States with Optional Icons. This is done by giving the .form-group
element the class of .has-feedback
and the icon the class of .form-control-feedback
.
The simplest example would be something like this:
<div class="form-group has-feedback">
<label class="control-label">Username</label>
<input type="text" class="form-control" placeholder="Username" />
<i class="glyphicon glyphicon-user form-control-feedback"></i>
</div>
Pros:
Cons:
To overcome the cons, I put together this pull-request with changes to support left aligned icons. As it is a relatively large change, it has been put off until a future release, but if you need these features today, here's a simple implementation guide:
Just include the these form changes in css (also inlined via hidden stack snippet at the bottom)
*LESS: alternatively, if you are building via less, here's the form changes in less
Then, all you have to do is include the class .has-feedback-left
on any group that has the class .has-feedback
in order to left align the icon.
Since there are a lot of possible html configurations over different form types, different control sizes, different icon sets, and different label visibilities, I created a test page that shows the correct set of HTML for each permutation along with a live demo.
P.S. frizi's suggestion of adding
pointer-events: none;
has been added to bootstrap
Didn't find what you were looking for? Try these similar questions:
.has-feedback .form-control {_x000D_
padding-right: 34px;_x000D_
}_x000D_
.has-feedback .form-control.input-sm,_x000D_
.has-feedback.form-group-sm .form-control {_x000D_
padding-right: 30px;_x000D_
}_x000D_
.has-feedback .form-control.input-lg,_x000D_
.has-feedback.form-group-lg .form-control {_x000D_
padding-right: 46px;_x000D_
}_x000D_
.has-feedback-left .form-control {_x000D_
padding-right: 12px;_x000D_
padding-left: 34px;_x000D_
}_x000D_
.has-feedback-left .form-control.input-sm,_x000D_
.has-feedback-left.form-group-sm .form-control {_x000D_
padding-left: 30px;_x000D_
}_x000D_
.has-feedback-left .form-control.input-lg,_x000D_
.has-feedback-left.form-group-lg .form-control {_x000D_
padding-left: 46px;_x000D_
}_x000D_
.has-feedback-left .form-control-feedback {_x000D_
left: 0;_x000D_
}_x000D_
.form-control-feedback {_x000D_
line-height: 34px !important;_x000D_
}_x000D_
.input-sm + .form-control-feedback,_x000D_
.form-horizontal .form-group-sm .form-control-feedback {_x000D_
width: 30px;_x000D_
height: 30px;_x000D_
line-height: 30px !important;_x000D_
}_x000D_
.input-lg + .form-control-feedback,_x000D_
.form-horizontal .form-group-lg .form-control-feedback {_x000D_
width: 46px;_x000D_
height: 46px;_x000D_
line-height: 46px !important;_x000D_
}_x000D_
.has-feedback label.sr-only ~ .form-control-feedback,_x000D_
.has-feedback label.sr-only ~ div .form-control-feedback {_x000D_
top: 0;_x000D_
}_x000D_
@media (min-width: 768px) {_x000D_
.form-inline .inline-feedback {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
}_x000D_
.form-inline .has-feedback .form-control-feedback {_x000D_
top: 0;_x000D_
}_x000D_
}_x000D_
.form-horizontal .has-feedback-left .form-control-feedback {_x000D_
left: 15px;_x000D_
}
_x000D_
add option 'close' like under sample and do what you want inline function
close: function(e){
//do something
}
I did not have the /usr/local/Frameworks
folder, so this fixed it for me
sudo mkdir -p /usr/local/Frameworks
sudo chown -R $(whoami) /usr/local/Frameworks
The first line creates a new Frameworks folder for homebrew (brew) to use. The second line gives that folder your current user permissions, which are sufficient.
Used commands are as follows:
mkdir - make directories [-p no error if existing, make parent directories as needed]
chown - change file owner and group [-R operate on files and directories recursively]
whoami - print effective userid
I have OSX High Sierra
Here is a simple PHP way that I use.
If a page is requested with the .php extension then a new request is made without the .php extension. The .php extension is then no longer shown in the browser's address field.
I came up with this solution because none of the many .htaccess suggestions worked for me and it was quicker to implement this in PHP than trying to find out why the .htaccess did not work on my server.
Put this at the beginning of each PHP file (preferrably before anything else):
include_once('scripts.php');
strip_php_extension();
Then put these functions in the file 'scripts.php':
//==== Strip .php extension from requested URI
function strip_php_extension()
{
$uri = $_SERVER['REQUEST_URI'];
$ext = substr(strrchr($uri, '.'), 1);
if ($ext == 'php')
{
$url = substr($uri, 0, strrpos($uri, '.'));
redirect($url);
}
}
//==== Redirect. Try PHP header redirect, then Java, then http redirect
function redirect($url)
{
if (!headers_sent())
{
/* If headers not yet sent => do php redirect */
header('Location: '.$url);
exit;
}
else
{
/* If headers already sent => do javaScript redirect */
echo '<script type="text/javascript">';
echo 'window.location.href="'.$url.'";';
echo '</script>';
/* If javaScript is disabled => do html redirect */
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0; url='.$url.'" />';
echo '</noscript>';
exit;
}
}
Obviously you still need to have setup Apache to redirect any request without extension to the file with the extension. The above solution simply checks if the requested URI has an extension, if it does it requests the URI without the extension. Then Apache does the redirect to the file with the extension, but only the requested URI (without the extension) is shown in the browser's address field. The advantage is that all your "href" links in your code can still have the full filename, i.e. including the .php extension.
example :0.0.1-SNAPSHOT
In my strange case, Intellij remembers forever about my project even if I delete .iml
... Thus I did the following:
.iml
file.my_proj
) to my_proj_backup
.my_proj_backup
in Intellij and close.my_proj
, and open it in Intellij. Then close it.my_proj
and move my_proj_backup
back to my_proj
. Then open my_proj
in Intellij.Then it happily forgot the old my_proj
:)
If you need to refer to your host computer's localhost, such as when you want the emulator client to contact a server running on the same host, use the alias 10.0.2.2 to refer to the host computer's loopback interface. From the emulator's perspective, localhost (127.0.0.1) refers to its own loopback interface.More details: http://developer.android.com/guide/faq/commontasks.html#localhostalias
Problem here is you are trying to open a mongo shell without starting a mongo db which is listening to port 127.0.0.1:27017(deafault for mongo db) thats what the error is all about:
Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:145 exception: connect failed
The easiest solution is to open the terminal and type
$ mongod --dbpath ~/data/db
Note: dbpath here is "Users/user" where data/db directories are created
i.e., you need to create directory data and sub directory db in your user folder. For e.g say `
/Users/johnny/data
After mongo db is up. Open another terminal in new window and type
$ mongo
it will open mongo shell with your mongo db connection opened in another terminal.
I had the same problem.
when i run \tools\android.bat, i got the exception:
Exception in thread main
java.lang.NoClassDefFoundError: com/android/sdkmanager/Main
My resolved method:
\tools\android.bat
"%jar_path%;%swt_path%\swt.jar"
"%tools_dir%\%jar_path%;%tools_dir%\%swt_path%\swt.jar"
SDK Manager.exe
againAs @Hellfrost pointed out, it is literally nonsense to compare a number to two different numbers in "one operation", and I know of no C# operator that encapsulates this.
between = (0 < 5 && 5 < 10);
Is about the most-compact form I can think of.
You could make a somewhat "fluent"-looking method using extension (though, while amusing, I think it's overkill):
public static bool Between(this int x, int a, int b)
{
return (a < x) && (x < b);
}
Use:
int x = 5;
bool b = x.Between(0,10);
I'm sharing my implementation with some neat features:
Remark: Remember that to use Extension Method you have to (!) import the namespace with using
keyword (in this case using MyApplication.Helpers.Encoding
).
Code:
namespace MyApplication.Helpers.Encoding
{
public static class EncodingForBase64
{
public static string EncodeBase64(this System.Text.Encoding encoding, string text)
{
if (text == null)
{
return null;
}
byte[] textAsBytes = encoding.GetBytes(text);
return System.Convert.ToBase64String(textAsBytes);
}
public static string DecodeBase64(this System.Text.Encoding encoding, string encodedText)
{
if (encodedText == null)
{
return null;
}
byte[] textAsBytes = System.Convert.FromBase64String(encodedText);
return encoding.GetString(textAsBytes);
}
}
}
Usage example:
using MyApplication.Helpers.Encoding; // !!!
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Test1();
Test2();
}
static void Test1()
{
string textEncoded = System.Text.Encoding.UTF8.EncodeBase64("test1...");
System.Diagnostics.Debug.Assert(textEncoded == "dGVzdDEuLi4=");
string textDecoded = System.Text.Encoding.UTF8.DecodeBase64(textEncoded);
System.Diagnostics.Debug.Assert(textDecoded == "test1...");
}
static void Test2()
{
string textEncoded = System.Text.Encoding.UTF8.EncodeBase64(null);
System.Diagnostics.Debug.Assert(textEncoded == null);
string textDecoded = System.Text.Encoding.UTF8.DecodeBase64(textEncoded);
System.Diagnostics.Debug.Assert(textDecoded == null);
}
}
}
I think you should consider Java installation procedure carefully. Following is the detailed process which covers almost all possible failures.
Installing Java with apt-get is easy. First, update the package index:
sudo apt-get update
Then, check if Java is not already installed:
java -version
If it returns "The program java can be found in the following packages", Java hasn't been installed yet, so execute the following command:
sudo apt-get install default-jre
You are fine till now as I assume.
This will install the Java Runtime Environment (JRE). If you instead need the Java Development Kit (JDK), which is usually needed to compile Java applications (for example Apache Ant, Apache Maven, Eclipse and IntelliJ IDEA execute the following command:
sudo apt-get install default-jdk
That is everything that is needed to install Java.
Installing OpenJDK 7:
To install OpenJDK 7, execute the following command:
sudo apt-get install openjdk-7-jre
This will install the Java Runtime Environment (JRE). If you instead need the Java Development Kit (JDK), execute the following command:
sudo apt-get install openjdk-7-jdk
Installing Oracle JDK:
The Oracle JDK is the official JDK; however, it is no longer provided by Oracle as a default installation for Ubuntu.
You can still install it using apt-get. To install any version, first execute the following commands:
sudo apt-get install python-software-properties
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
Then, depending on the version you want to install, execute one of the following commands:
Oracle JDK 7:
sudo apt-get install oracle-java7-installer
Oracle JDK 8:
sudo apt-get install oracle-java8-installer
Greenkeeper if you're using Github. https://greenkeeper.io/
It's a Github integration and incredibly easy to set things up. When installed, it automatically creates pull requests in repositories you specify (or all if wanted) and keeps your code always up-to-date, without forcing you to do anything manually. PRs should then trigger a build on a CI service and depending on a successful or failed check you can keep figuring out what's triggering the issue or when CI passes simply merge the PR.
At the bottom, you can see that the first build failed at first and after a commit ("upgrade to node v6.9") the tests pass so I could finally merge the PR. Comes with a lot of emoji, too.
Another alternative would be https://dependencyci.com/, however I didn't test it intensively. After a first look Greenkeeper looks better in general IMO and has better integration.
This is to help lodash
users. check if your key is present by doing:
hideSelectedCompany(yourKey) {
return _.findIndex(yourArray, n => n === yourKey) === -1;
}
In this piece of code the height of left panel will gets adjusted to the height of right panel dynamically...
function resizeDiv() {
var rh=$('.pright').height()+'px'.toString();
$('.pleft').css('height',rh);
}
You can try this here http://jsfiddle.net/SriharshaCR/7q585k1x/9/embedded/result/
The accepted answer from Konstantin worked, but there were a few additional steps. After restarting Eclipse, you still have to go into software updates, find your newly available software, check the box(es) for it, and click the "install" button. Then it'll prompt you to restart again and only then will you see your new views or functionality.
Additionally, you can check the "Error Log" view for any problems with your new plugin that eclipse is complaining about.
glob.glob()
is definitely the way to do it (as per Ignacio). However, if you do need more complicated matching, you can do it with a list comprehension and re.match()
, something like so:
files = [f for f in os.listdir('.') if re.match(r'[0-9]+.*\.jpg', f)]
More flexible, but as you note, less efficient.
The apps UI only works for panels.
The best you can do is to draw a button yourself and put that into your spreadsheet. Than you can add a macro to it.
Go into "Insert > Drawing...", Draw a button and add it to the spreadsheet. Than click it and click "assign Macro...", then insert the name of the function you wish to execute there. The function must be defined in a script in the spreadsheet.
Alternatively you can also draw the button somewhere else and insert it as an image.
More info: https://developers.google.com/apps-script/guides/menus
For indian numeric system
var number = "323483.85"
var decimal = number.split(".");
var res = (decimal[0].length>3? numberWithCommas(decimal[0].substring(0,decimal[0].length-3))+ ',' :decimal[0]) + (decimal[0].length>3?decimal[0].substring(decimal[0].length-3,decimal[0].length):'') + '.' + decimal[1];
Output: 3,23,483.85
If you want to round a number, you can obtain different results depending on: how you use the Math.Round() function (if for a round-up or round-down), you're working with doubles and/or floats numbers, and you apply the midpoint rounding. Especially, when using with operations inside of it or the variable to round comes from an operation. Let's say, you want to multiply these two numbers: 0.75 * 0.95 = 0.7125. Right? Not in C#
Let's see what happens if you want to round to the 3rd decimal:
double result = 0.75d * 0.95d; // result = 0.71249999999999991
double result = 0.75f * 0.95f; // result = 0.71249997615814209
result = Math.Round(result, 3, MidpointRounding.ToEven); // result = 0.712. Ok
result = Math.Round(result, 3, MidpointRounding.AwayFromZero); // result = 0.712. Should be 0.713
As you see, the first Round() is correct if you want to round down the midpoint. But the second Round() it's wrong if you want to round up.
This applies to negative numbers:
double result = -0.75 * 0.95; //result = -0.71249999999999991
result = Math.Round(result, 3, MidpointRounding.ToEven); // result = -0.712. Ok
result = Math.Round(result, 3, MidpointRounding.AwayFromZero); // result = -0.712. Should be -0.713
So, IMHO, you should create your own wrap function for Math.Round() that fit your requirements. I created a function in which, the parameter 'roundUp=true' means to round to next greater number. That is: 0.7125 rounds to 0.713 and -0.7125 rounds to -0.712 (because -0.712 > -0.713). This is the function I created and works for any number of decimals:
double Redondea(double value, int precision, bool roundUp = true)
{
if ((decimal)value == 0.0m)
return 0.0;
double corrector = 1 / Math.Pow(10, precision + 2);
if ((decimal)value < 0.0m)
{
if (roundUp)
return Math.Round(value, precision, MidpointRounding.ToEven);
else
return Math.Round(value - corrector, precision, MidpointRounding.AwayFromZero);
}
else
{
if (roundUp)
return Math.Round(value + corrector, precision, MidpointRounding.AwayFromZero);
else
return Math.Round(value, precision, MidpointRounding.ToEven);
}
}
The variable 'corrector' is for fixing the inaccuracy of operating with floating or double numbers.
I think you can use keydown
too:
$('#fieldID').on('keydown', function (e) {
//console.log(e.which);
if (e.which === 8) {
//do something when pressing delete
return true;
} else {
//do something else
return false;
}
});
I got this error when working in the Designer. I had been developing in VS 2012, but "upgraded" to 2017 over the past couple days. Solution was to close and reopen VS.
It may be related to a bug which I've seen reported elsewhere, where the Reference Manager does not work? In that situation, the following error message is encountered when trying to add a reference in the Solution Explorer:
"Error HRESULT E_FAIL has been returned from a call to a COM component."
My workaround was to close the solution, reopen in VS2012, add the reference, close 2012 and reopen 2017. Ridiculous that 2017 should have been released with such an obvious bug.
Html.DisplayFor()
will render the DisplayTemplate that matches the property's type.
If it can't find any, I suppose it invokes .ToString()
.
If you don't know about display templates, they're partial views that can be put in a DisplayTemplates
folder inside the view folder associated to a controller.
Example:
If you create a view named String.cshtml
inside the DisplayTemplates
folder of your views folder (e.g Home
, or Shared
) with the following code:
@model string
@if (string.IsNullOrEmpty(Model)) {
<strong>Null string</strong>
}
else {
@Model
}
Then @Html.DisplayFor(model => model.Title)
(assuming that Title
is a string) will use the template and display <strong>Null string</strong>
if the string is null, or empty.
Try adding the -f
option to show the function names :
addr2line -f -e a.out 0x4005BDC
Maybe I write this too late, but I have gotten the similar problem when I have tried to override methods for reading properties.
My problem have been: 1) Read property from env if this property has been set in env 2) Read property from system property if this property have been setted in system property 3) And last, read from application properties.
So, for resolving this problem I go to my bean configuration class
@Validated
@Configuration
@ConfigurationProperties(prefix = ApplicationConfiguration.PREFIX)
@PropertySource(value = "${application.properties.path}", factory = PropertySourceFactoryCustom.class)
@Data // lombok
public class ApplicationConfiguration {
static final String PREFIX = "application";
@NotBlank
private String keysPath;
@NotBlank
private String publicKeyName;
@NotNull
private Long tokenTimeout;
private Boolean devMode;
public void setKeysPath(String keysPath) {
this.keysPath = StringUtils.cleanPath(keysPath);
}
}
And overwrite factory in @PropertySource. And then I have created my own implementation for reading properties.
public class PropertySourceFactoryCustom implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
return name != null ? new PropertySourceCustom(name, resource) : new PropertySourceCustom(resource);
}
}
And created PropertySourceCustom
public class PropertySourceCustom extends ResourcePropertySource {
public LifeSourcePropertySource(String name, EncodedResource resource) throws IOException {
super(name, resource);
}
public LifeSourcePropertySource(EncodedResource resource) throws IOException {
super(resource);
}
public LifeSourcePropertySource(String name, Resource resource) throws IOException {
super(name, resource);
}
public LifeSourcePropertySource(Resource resource) throws IOException {
super(resource);
}
public LifeSourcePropertySource(String name, String location, ClassLoader classLoader) throws IOException {
super(name, location, classLoader);
}
public LifeSourcePropertySource(String location, ClassLoader classLoader) throws IOException {
super(location, classLoader);
}
public LifeSourcePropertySource(String name, String location) throws IOException {
super(name, location);
}
public LifeSourcePropertySource(String location) throws IOException {
super(location);
}
@Override
public Object getProperty(String name) {
if (StringUtils.isNotBlank(System.getenv(name)))
return System.getenv(name);
if (StringUtils.isNotBlank(System.getProperty(name)))
return System.getProperty(name);
return super.getProperty(name);
}
}
So, this has helped me.
Shortest and quickest way to remove all the selection, is by passing empty string in jQuery .val() function :
$("#my_select").val('')
I don't know what the correct answer was in '13, but today it is:
myEditText.setKeyListener(DigitsKeyListener.getInstance(null, false, true)); // positive decimal numbers
You get everything, including the onscreen keyboard is a numeric keypad.
ALMOST everything. Espresso, in its infinite wisdom, lets typeText("...")
inexplicably bypass the filter and enter garbage...
Build success/failure noise; from term:
defaults write com.apple.Xcode PBXBuildSuccessSound ~/Library/Sounds/metal\ stamp.wav
defaults write com.apple.Xcode PBXBuildFailureSound ~/Library/Sounds/Elephant
You can directly export the query result with export option in the result grig. This export has various options to export. I think this will work.
For everyone that has Android problems in the string.xml, use \'\' instead of single quote.
1) Best practice is to make new javascript file like my.js. Make this file into your js folder in root directory -> js/my.js . 2) In my.js file add your code inside of $(document).ready(function(){}) scope.
$(document).ready(function(){
$(".icon-bg").click(function () {
$(".btn").toggleClass("active");
$(".icon-bg").toggleClass("active");
$(".container").toggleClass("active");
$(".box-upload").toggleClass("active");
$(".box-caption").toggleClass("active");
$(".box-tags").toggleClass("active");
$(".private").toggleClass("active");
$(".set-time-limit").toggleClass("active");
$(".button").toggleClass("active");
});
$(".button").click(function () {
$(".button-overlay").toggleClass("active");
});
$(".iconmelon").click(function () {
$(".box-upload-ing").toggleClass("active");
$(".iconmelon-loaded").toggleClass("active");
});
$(".private").click(function () {
$(".private-overlay").addClass("active");
$(".private-overlay-wave").addClass("active");
});
});
3) add your new js file into your html
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="/js/my.js"></script>
</head>
It presents a prompt to the user (the optional arg
of raw_input([arg])
), gets input from the user and returns the data input by the user in a string. See the docs for raw_input()
.
Example:
name = raw_input("What is your name? ")
print "Hello, %s." % name
This differs from input()
in that the latter tries to interpret the input given by the user; it is usually best to avoid input()
and to stick with raw_input()
and custom parsing/conversion code.
Note: This is for Python 2.x
`CREATE TRIGGER `category_before_ins_tr` BEFORE INSERT ON `category`
FOR EACH ROW
BEGIN
**SET @tableId= (SELECT id FROM dummy LIMIT 1);**
END;`;
The solution presented as an answer does not work, what is wrong?
$(document).ready(function(){
$('.modal').modal('show');
$('.modal').modal({
backdrop: 'static',
keyboard: false
})
});
_x000D_
<html>
<head>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/index.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<div class="text-right"><button type="button" class="btn btn-primary">print</button></div>
</div>
</div>
</div>
</div>
</body>
</html>
_x000D_
Instead of Tick
event, use Elapsed
event.
timer.Elapsed += new EventHandler(TimerEventProcessor);
and change the signiture of TimerEventProcessor method;
private void TimerEventProcessor(object sender, ElapsedEventArgs e)
{
label1.Text = _counter.ToString();
_counter += 1;
}
you cannot set this in javascript, you have to do this with html/css:
<style type="text/css" media="print">
@page { size: landscape; }
</style>
EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?
The width attribute of <td>
is deprecated in HTML 5.
Use CSS. e.g.
<td style="width:100px">
in detail, like this:
<table >
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td style="width:70%">January</td>
<td style="width:30%">$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</table>
if(list.ElementAtOrDefault(2) != null)
{
// logic
}
ElementAtOrDefault() is part of the System.Linq
namespace.
Although you have a List, so you can use list.Count > 2
.
It has to do with the new Play Store update.
Go to:
settings/apps/all/Google Play Store
Select Google Play Store
and select uninstall updates - that should solve your issue. Open up play store and purchase your app or game select bill to Verizon or whatever phone provider you use then accept. Log in to your Google account and you're done. When you close out the play store it will update again to the latest version and will allow you to bill to account.
Me, I'd do it something like this:
HTML:
onclick="myfunction({path:'/myController/myAction', ok:myfunctionOnOk, okArgs:['/myController2/myAction2','myParameter2'], cancel:myfunctionOnCancel, cancelArgs:['/myController3/myAction3','myParameter3']);"
JS:
function myfunction(params)
{
var path = params.path;
/* do stuff */
// on ok condition
params.ok(params.okArgs);
// on cancel condition
params.cancel(params.cancelArgs);
}
But then I'd also probable be binding a closure to a custom subscribed event. You need to add some detail to the question really, but being first-class functions are easily passable and getting params to them can be done any number of ways. I would avoid passing them as string labels though, the indirection is error prone.