For me it was very important to get email logging working. After some time I discover that this need only 2 lines of code more in Atif example.
public class HandleErrorWithElmahAttribute : HandleErrorAttribute
{
static ElmahMVCMailModule error_mail_log = new ElmahMVCMailModule();
public override void OnException(ExceptionContext context)
{
error_mail_log.Init(HttpContext.Current.ApplicationInstance);
[...]
}
[...]
}
I hope this will help someone :)
Modern browsers support a Content Security Policy or CSP. This is the highest level of web security and strongly recommended if you can apply it because it completely blocks all XSS attacks.
Both of your suggestions break with CSP enabled because they allow inline Javascript (which could be injected by a hacker) to execute in your page.
The best practice is to subscribe to the event in Javascript, as in Konrad Rudolph's answer.
I found that none of the answers here applied to my specific use case, so I thought I would share my solution.
I was looking to redirect an unauthentciated user to public version of an app page with any possible URL params. Example:
/app/4903294/my-great-car?email=coolguy%40gmail.com to
/public/4903294/my-great-car?email=coolguy%40gmail.com
Here's the solution that worked for me.
return redirect(url_for('app.vehicle', vid=vid, year_make_model=year_make_model, **request.args))
Hope this helps someone!
I've refined Twan's answer a bit, because:
nil
leads to hanging issues when you go back to the root view controller and make a swipe gesture before navigating elsewhere.The following example assumes iOS 7:
{
id savedGestureRecognizerDelegate;
}
- (void)viewWillAppear:(BOOL)animated
{
savedGestureRecognizerDelegate = self.navigationController.interactivePopGestureRecognizer.delegate;
self.navigationController.interactivePopGestureRecognizer.delegate = self;
}
- (void)viewWillDisappear:(BOOL)animated
{
self.navigationController.interactivePopGestureRecognizer.delegate = savedGestureRecognizerDelegate;
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer == self.navigationController.interactivePopGestureRecognizer) {
return NO;
}
// add whatever logic you would otherwise have
return YES;
}
Think about somebody doing help(yourmodule)
at the interactive interpreter's prompt — what do they want to know? (Other methods of extracting and displaying the information are roughly equivalent to help
in terms of amount of information). So if you have in x.py
:
"""This module does blah blah."""
class Blah(object):
"""This class does blah blah."""
then:
>>> import x; help(x)
shows:
Help on module x:
NAME
x - This module does blah blah.
FILE
/tmp/x.py
CLASSES
__builtin__.object
Blah
class Blah(__builtin__.object)
| This class does blah blah.
|
| Data and other attributes defined here:
|
| __dict__ = <dictproxy object>
| dictionary for instance variables (if defined)
|
| __weakref__ = <attribute '__weakref__' of 'Blah' objects>
| list of weak references to the object (if defined)
As you see, the detailed information on the classes (and functions too, though I'm not showing one here) is already included from those components' docstrings; the module's own docstring should describe them very summarily (if at all) and rather concentrate on a concise summary of what the module as a whole can do for you, ideally with some doctested examples (just like functions and classes ideally should have doctested examples in their docstrings).
I don't see how metadata such as author name and copyright / license helps the module's user — it can rather go in comments, since it could help somebody considering whether or not to reuse or modify the module.
If you want connect to user@'%'
from localhost use mysql -h192.168.0.1 -uuser -p
.
AND
and OR
are just syntactic sugar for &&
and ||
, like in JavaScript, or other C styled syntax languages.
It appears AND
and OR
have lower precedence than their C style equivalents.
Use the pandas.DataFrame.round() method like this:
df = df.round({'value1': 0})
Any columns not included will be left as is.
Worked for me:
$(".filter-mobile").click(function() {
if ($("#menuProdutos").height() > 0) {
$("#menuProdutos").animate({
height: 0
}, 200);
} else {
$("#menuProdutos").animate({
height: 500
}, 200);
}
});
Your original code uses FileInputStream, which is for accessing file system hosted files.
The constructor you used will attempt to locate a file named a.txt in the www.somewebsite.com subfolder of the current working directory (the value of system property user.dir). The name you provide is resolved to a file using the File class.
URL objects are the generic way to solve this. You can use URLs to access local files but also network hosted resources. The URL class supports the file:// protocol besides http:// or https:// so you're good to go.
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e("Rest response",response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Rest response",error.toString());
}
}){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String,String>();
params.put("name","xyz");
return params;
}
@Override
public Map<String,String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String,String>();
params.put("content-type","application/fesf");
return params;
}
};
requestQueue.add(stringRequest);
I wanted to put the .gif file in a GUI but displayed with other elements. And the .gif file would be taken from the java project and not from an URL.
1 - Top of the interface would be a list of elements where we can choose one
2 - Center would be the animated GIF
3 - Bottom would display the element chosen from the list
Here is my code (I need 2 java files, the first (Interf.java) calls the second (Display.java)):
1 - Interf.java
public class Interface_for {
public static void main(String[] args) {
Display Fr = new Display();
}
}
2 - Display.java
INFOS: Be shure to create a new source folder (NEW > source folder) in your java project and put the .gif inside for it to be seen as a file.
I get the gif file with the code below, so I can it export it in a jar project(it's then animated).
URL url = getClass().getClassLoader().getResource("fire.gif");
public class Display extends JFrame {
private JPanel container = new JPanel();
private JComboBox combo = new JComboBox();
private JLabel label = new JLabel("A list");
private JLabel label_2 = new JLabel ("Selection");
public Display(){
this.setTitle("Animation");
this.setSize(400, 350);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
container.setLayout(new BorderLayout());
combo.setPreferredSize(new Dimension(190, 20));
//We create te list of elements for the top of the GUI
String[] tab = {"Option 1","Option 2","Option 3","Option 4","Option 5"};
combo = new JComboBox(tab);
//Listener for the selected option
combo.addActionListener(new ItemAction());
//We add elements from the top of the interface
JPanel top = new JPanel();
top.add(label);
top.add(combo);
container.add(top, BorderLayout.NORTH);
//We add elements from the center of the interface
URL url = getClass().getClassLoader().getResource("fire.gif");
Icon icon = new ImageIcon(url);
JLabel center = new JLabel(icon);
container.add(center, BorderLayout.CENTER);
//We add elements from the bottom of the interface
JPanel down = new JPanel();
down.add(label_2);
container.add(down,BorderLayout.SOUTH);
this.setContentPane(container);
this.setVisible(true);
this.setResizable(false);
}
class ItemAction implements ActionListener{
public void actionPerformed(ActionEvent e){
label_2.setText("Chosen option: "+combo.getSelectedItem().toString());
}
}
}
Using the Datejs library, this can be as easy as:
Date.parse("05/05/2010").toString("MMMM yyyy");
// parse date convert to
// string with
// custom format
Use the spool:
spool myoutputfile.txt
select * from users;
spool off;
Note that this will create myoutputfile.txt in the directory from which you ran SQL*Plus.
If you need to run this from a SQL file (e.g., "tmp.sql") when SQLPlus starts up and output to a file named "output.txt":
tmp.sql:
select * from users;
Command:
sqlplus -s username/password@sid @tmp.sql > output.txt
Mind you, I don't have an Oracle instance in front of me right now, so you might need to do some of your own work to debug what I've written from memory.
This really is beyond the capabilities of shell script. Shell script and the standard Unix tools are okay at parsing line oriented files, but things change when you talk about XML. Even simple tags can present a problem:
<MYTAG>Data</MYTAG>
<MYTAG>
Data
</MYTAG>
<MYTAG param="value">Data</MYTAG>
<MYTAG><ANOTHER_TAG>Data
</ANOTHER_TAG><MYTAG>
Imagine trying to write a shell script that can read the data enclosed in . The three very, very simply XML examples all show different ways this can be an issue. The first two examples are the exact same syntax in XML. The third simply has an attribute attached to it. The fourth contains the data in another tag. Simple sed
, awk
, and grep
commands cannot catch all possibilities.
You need to use a full blown scripting language like Perl, Python, or Ruby. Each of these have modules that can parse XML data and make the underlying structure easier to access. I've use XML::Simple in Perl. It took me a few tries to understand it, but it did what I needed, and made my programming much easier.
Decorating one of the action params with [FromBody] solved the issue for me:
public async Task<IHttpActionResult> SetAmountOnEntry(string id, [FromBody]int amount)
However ASP.NET would infer it correctly if complex object was used in the method parameter:
public async Task<IHttpActionResult> UpdateEntry(string id, MyEntry entry)
Imagine you are showing someone how to code something with a bunch of "random" numbers. By using numpy seed they can use the same seed number and get the same set of "random" numbers.
So it's not exactly random because an algorithm spits out the numbers but it looks like a randomly generated bunch.
There are some open source alternatives:
If you need a solution anyway (e.g. because you have too many implementations of the abstract class and the testing would always repeat the same procedures) then you could create an abstract test class with an abstract factory method which will be excuted by the implementation of that test class. This examples works or me with TestNG:
The abstract test class of Car
:
abstract class CarTest {
// the factory method
abstract Car createCar(int speed, int fuel);
// all test methods need to make use of the factory method to create the instance of a car
@Test
public void testGetSpeed() {
Car car = createCar(33, 44);
assertEquals(car.getSpeed(), 33);
...
Implementation of Car
class ElectricCar extends Car {
private final int batteryCapacity;
public ElectricCar(int speed, int fuel, int batteryCapacity) {
super(speed, fuel);
this.batteryCapacity = batteryCapacity;
}
...
Unit test class ElectricCarTest
of the Class ElectricCar
:
class ElectricCarTest extends CarTest {
// implementation of the abstract factory method
Car createCar(int speed, int fuel) {
return new ElectricCar(speed, fuel, 0);
}
// here you cann add specific test methods
...
If you only need to get rid of warning outputs on the screen, you might want to clear the console screen right after importing the tensorflow by using this simple command (Its more effective than disabling all debugging logs in my experience):
In windows:
import os
os.system('cls')
In Linux or Mac:
import os
os.system('clear')
If you are using version 1
Recaptcha.reload();
If you are using version 2
grecaptcha.reset();
If total no is: 200 and getting 50 number
then take percentage of 50 in 200 is:
(50/200)*100 = 25%
You might want to consider using some algorithms instead:
// read in the data:
std::copy(std::istream_iterator<double>(input),
std::istream_iterator<double>(),
std::back_inserter(v));
sum = std::accumulate(v.begin(), v.end(), 0);
average = sum / v.size();
You can modify the values with std::transform
, though until we get lambda expressions (C++0x) it may be more trouble than it's worth:
class difference {
double base;
public:
difference(double b) : base(b) {}
double operator()(double v) { return v-base; }
};
std::transform(v.begin(), v.end(), v.begin(), difference(average));
The good news is that if you need to make a case-sensitive query, it is very easy to do:
SELECT * FROM `table` WHERE BINARY `column` = 'value'
The standard option grep -l
(that is a lowercase L) could do this.
From the Unix standard:
-l
(The letter ell.) Write only the names of files containing selected
lines to standard output. Pathnames are written once per file searched.
If the standard input is searched, a pathname of (standard input) will
be written, in the POSIX locale. In other locales, standard input may be
replaced by something more appropriate in those locales.
You also do not need -H
in this case.
Given this file:
$ cat words.txt
line1 word1 word2
line2 word3 word4
line3 word5 word6
If you just want one word at a time (ignoring the meaning of spaces vs line breaks in the file):
with open('words.txt','r') as f:
for line in f:
for word in line.split():
print(word)
Prints:
line1
word1
word2
line2
...
word6
Similarly, if you want to flatten the file into a single flat list of words in the file, you might do something like this:
with open('words.txt') as f:
flat_list=[word for line in f for word in line.split()]
>>> flat_list
['line1', 'word1', 'word2', 'line2', 'word3', 'word4', 'line3', 'word5', 'word6']
Which can create the same output as the first example with print '\n'.join(flat_list)
...
Or, if you want a nested list of the words in each line of the file (for example, to create a matrix of rows and columns from a file):
with open('words.txt') as f:
matrix=[line.split() for line in f]
>>> matrix
[['line1', 'word1', 'word2'], ['line2', 'word3', 'word4'], ['line3', 'word5', 'word6']]
If you want a regex solution, which would allow you to filter wordN
vs lineN
type words in the example file:
import re
with open("words.txt") as f:
for line in f:
for word in re.findall(r'\bword\d+', line):
# wordN by wordN with no lineN
Or, if you want that to be a line by line generator with a regex:
with open("words.txt") as f:
(word for line in f for word in re.findall(r'\w+', line))
assuming certain column names...
INSERT one
newToner = Toner(toner_id = 1,
toner_color = 'blue',
toner_hex = '#0F85FF')
dbsession.add(newToner)
dbsession.commit()
INSERT multiple
newToner1 = Toner(toner_id = 1,
toner_color = 'blue',
toner_hex = '#0F85FF')
newToner2 = Toner(toner_id = 2,
toner_color = 'red',
toner_hex = '#F01731')
dbsession.add_all([newToner1, newToner2])
dbsession.commit()
UPDATE
q = dbsession.query(Toner)
q = q.filter(Toner.toner_id==1)
record = q.one()
record.toner_color = 'Azure Radiance'
dbsession.commit()
or using a fancy one-liner using MERGE
record = dbsession.merge(Toner( **kwargs))
Try this
function readRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
//var values = rows.getValues();
var Names = sheet.getRange("A2:A7");
var Name = [
Names.getCell(1, 1).getValue(),
Names.getCell(2, 1).getValue(),
.....
Names.getCell(5, 1).getValue()]
You can define arrays simply as follows, instead of allocating and then assigning.
var arr = [1,2,3,5]
Your initial error was because of the following line, and ones like it
var Name[0] = Name_cell.getValue();
Since Name
is already defined and you are assigning the values to its elements, you should skip the var
, so just
Name[0] = Name_cell.getValue();
Pro tip: For most issues that, like this one, don't directly involve Google services, you are better off Googling for the way to do it in javascript in general.
Just add public properties to the user control.
You can add [Category("MyCategory")]
and [Description("A property that controls the wossname")]
attributes to make it nicer, but as long as it's a public property it should show up in the property panel.
Easiest solution, works if you have already a tag or not, and removes it automatically so it wont keep adding equal tags, have fun
function changeURL(tag)
{
if(window.location.href.indexOf("?") > -1) {
if(window.location.href.indexOf("&"+tag) > -1){
var url = window.location.href.replace("&"+tag,"")+"&"+tag;
}
else
{
var url = window.location.href+"&"+tag;
}
}else{
if(window.location.href.indexOf("?"+tag) > -1){
var url = window.location.href.replace("?"+tag,"")+"?"+tag;
}
else
{
var url = window.location.href+"?"+tag;
}
}
window.location = url;
}
THEN
changeURL("i=updated");
Your program crashes because it used memory that does not belong to you. It may be used by someone else or not - if you are lucky you crash, if not the problem may stay hidden for a long time and come back and bite you later.
As far as malloc/free implementation goes - entire books are devoted to the topic. Basically the allocator would get bigger chunks of memory from the OS and manage them for you. Some of the problems an allocator must address are:
If $_SERVER['HTTP_REFERER']
variable doesn't seems to work, then you can either use Google Analytics or AddThis Analytics.
You can get this type of error if you add third party libraries in your project that require native frameworks not included in your project.
You need to look inside the .h and .m files of your newly added library and see what frameworks it requires, then include those frameworks in your project (Target > Build Phases > Link Binary With Libraries).
The only character that needs escaping is <
. (>
is meaningless outside of a tag).
Therefore, your "magic" code is:
safestring = unsafestring.replace(/</g,'<');
If you're storing an object as binary data in the database, then you really should use a BLOB
datatype. The database is able to store it more efficiently, and you don't have to worry about encodings and the like. JDBC provides methods for creating and retrieving blobs in terms of streams. Use Java 6 if you can, it made some additions to the JDBC API that make dealing with blobs a whole lot easier.
If you absolutely need to store the data as a String, I would recommend XStream for XML-based storage (much easier than XMLEncoder
), but alternative object representations might be just as useful (e.g. JSON). Your approach depends on why you actually need to store the object in this way.
There is no performance difference.
A const_iterator
is an iterator that points to const value (like a const T*
pointer); dereferencing it returns a reference to a constant value (const T&
) and prevents modification of the referenced value: it enforces const
-correctness.
When you have a const reference to the container, you can only get a const_iterator
.
Edited: I mentionned “The const_iterator
returns constant pointers” which is not accurate, thanks to Brandon for pointing it out.
Edit: For COW objects, getting a non-const iterator (or dereferencing it) will probably trigger the copy. (Some obsolete and now disallowed implementations of std::string
use COW.)
Here's a fun solution:
/**
* Filter-map. Like map, but skips undefined values.
*
* @param callback
*/
function fmap(callback) {
return this.reduce((accum, ...args) => {
let x = callback(...args);
if(x !== undefined) {
accum.push(x);
}
return accum;
}, []);
}
Use with the bind operator:
[1,2,-1,3]::fmap(x => x > 0 ? x * 2 : undefined); // [2,4,6]
You could use this:
a = ((4.0, 4, 4.0), (3.0, 3, 3.6), (3.5, 6, 4.8))
a = np.array(a)
a[:,0]
returns >>> array([4. , 3. , 3.5])
Try this. It works for me:
yarn run lint --fix
or
npm run lint -- --fix
Matt's answer is fine, but just to avoid this to propagate to other elements inside the navbar (like when you also have a dropdown), use
.navbar-nav > li > a {
line-height: 50px;
}
There are numerous ways to store credentials while still using boto3.resource(). I'm using the AWS CLI method myself. It works perfectly.
A few answers have been given, but it appears that the best method is to use is:
id -u
This appears to be more reliable than the other methods, and it seems that it return an id of 0 even if the script is run through sudo
.
You can create a new List and add the elements to it:
For example:
List<A> a = getListOfA();
List<Object> newList = new ArrayList<>();
newList.addAll(a);
You can do it online (like many things in life) here:
It's same as vikasdumca's steps, but thought to share the link.
run the following command
sudo apt-get install python-software-properties
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
then
sudo apt-get install oracle-java8-installer
this would install oracle java 8 on ubuntu properly.
find it from this post
you can find more info on "Managing Java" or "Setting the "JAVA_HOME" environment variable" from the post.
The easiest way is to use Resource Manager
Then you can select each density
And after importing you can see the 6 different versions of this image
Check PHP's strtotime
-function to convert your set date/time to a timestamp: http://php.net/manual/en/function.strtotime.php
If strtotime
can't handle your date/time format correctly ("4:00PM" will probably work but not "at 4PM"), you'll need to use string-functions, e.g. substr
to parse/correct your format and retrieve your timestamp through another function, e.g. mktime
.
Then compare the resulting timestamp with the current date/time (if ($calulated_timestamp > time()) { /* date in the future */ }
) to see whether the set date/time is in the past or the future.
I suggest to read the PHP-doc on date/time-functions and get back here with some of your source-code once you get stuck.
This is what I've been using. Haven't seen any issues.
destroy: function(){
this.remove();
this.unbind();
}
This solved my problem when I had to deal with HTML page with embedded JavaScript
WebElement empSalary = driver.findElement(By.xpath(PayComponentAmount));
Actions mouse2 = new Actions(driver);
mouse2.clickAndHold(empSalary).sendKeys(Keys.chord(Keys.CONTROL, "a"), "1234").build().perform();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].onchange()", empSalary);
On modern macOS, the correct path is /Library/Java/JavaVirtualMachines
.
You can also avail yourself of the command /usr/libexec/java_home
, which will scan that directory for you and return a list.
For variables describing distances, you would use \newlength
(and manipulate the values with \setlength
, \addlength
, \settoheight
, \settolength
and \settodepth
).
Similarly you have access to \newcounter
for things like section and figure numbers which should increment throughout the document. I've used this one in the past to provide code samples that were numbered separatly of other figures...
Also of note is \makebox
which allows you to store a bit of laid-out document for later re-use (and for use with \settolength
...).
Perhaps late for the party, but this works for me:
function joinArray() {
local delimiter="${1}"
local output="${2}"
for param in ${@:3}; do
output="${output}${delimiter}${param}"
done
echo "${output}"
}
Just add a background image to all images using css:
img {
background: url('loading.gif') no-repeat;
}
To compile the CUDA 8.0 examples on Ubuntu 16.10, I did:
sudo apt-get install gcc-5 g++-5
cd /path/to/NVIDIA_CUDA-8.0_Samples
# Find the path to the library (this should be in NVIDIA's Makefiles)
LIBLOC=`find /usr/lib -name "libnvcuvid.so.*" | head -n1 | perl -pe 's[/usr/lib/(nvidia-\d+)/.*][$1]'`
# Substitute that path into the makefiles for the hard-coded, incorrect one
find . -name "*.mk" | xargs perl -pi -e "s/nvidia-\d+/$LIBLOC/g"
# Make using the supported compiler
HOST_COMPILER=g++-5 make
This has the advantage of not modifying the whole system or making symlinks to just the binaries (that could cause library linking problems.)
The logged error does say that port 3820 is the problem, but I would suggest investigating all the ports that your app is trying to listen on. I ran into this problem and the issue was a port that I'd forgotten about - not the "main" one that I was looking for.
You can connect two iPhones and transfer data via Bluetooth using either the high-level GameKit framework or the lower-level (but still easy to work with) Bonjour discovery mechanisms. Bonjour also works transparently between Bluetooth and WiFi on the iPhone under 3.0, so it's a good choice if you would like to support iPhone-to-iPhone data transfers on those two types of networks.
For more information, you can also look at the responses to these questions:
Only 1 emulator or device may be open at a time. Make sure you don't have multiple emulators running.
One of Androids powerful feature is the AsyncTask class.
To work with it, you have to first extend it and override doInBackground
(...).
doInBackground
automatically executes on a worker thread, and you can add some
listeners on the UI Thread to get notified about status update, those functions are
called: onPreExecute()
, onPostExecute()
and onProgressUpdate()
You can find a example here.
Refer to below post for other alternatives:
You can specify it in your IDE. For example, for Eclipse in Run Configurations ? VM arguments. You can enter -Xmx800m -Xms500m
as
The easiest way I found (just I use eval() to convert string gotten from input to tuple to read again for form instance or other place)
This trick works very well
#model.py
class ClassName(models.Model):
field_name = models.CharField(max_length=100)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.field_name:
self.field_name= eval(self.field_name)
#form.py
CHOICES = [('pi', 'PI'), ('ci', 'CI')]
class ClassNameForm(forms.ModelForm):
field_name = forms.MultipleChoiceField(choices=CHOICES)
class Meta:
model = ClassName
fields = ['field_name',]
Try memory profiler. memory profiler
Line # Mem usage Increment Line Contents
==============================================
3 @profile
4 5.97 MB 0.00 MB def my_func():
5 13.61 MB 7.64 MB a = [1] * (10 ** 6)
6 166.20 MB 152.59 MB b = [2] * (2 * 10 ** 7)
7 13.61 MB -152.59 MB del b
8 13.61 MB 0.00 MB return a
Swift 3:
self.btn.sendActions(for: .touchUpInside)
You can use .sortBy
, it will always return an ascending list:
_.sortBy([2, 3, 1], function(num) {
return num;
}); // [1, 2, 3]
But you can use the .reverse method to get it descending:
var array = _.sortBy([2, 3, 1], function(num) {
return num;
});
console.log(array); // [1, 2, 3]
console.log(array.reverse()); // [3, 2, 1]
Or when dealing with numbers add a negative sign to the return to descend the list:
_.sortBy([-3, -2, 2, 3, 1, 0, -1], function(num) {
return -num;
}); // [3, 2, 1, 0, -1, -2, -3]
Under the hood .sortBy
uses the built in .sort([handler])
:
// Default is ascending:
[2, 3, 1].sort(); // [1, 2, 3]
// But can be descending if you provide a sort handler:
[2, 3, 1].sort(function(a, b) {
// a = current item in array
// b = next item in array
return b - a;
});
It's called and
and or
in Python.
You can simply do it with below command
git stash save --include-untracked
or
git stash save -u
For more about git stash Visit this post (Click Here)
Js is a single threaded.
Browser can be divided into three parts:
1)Event Loop
2)Web API
3)Event Queue
Event Loop runs for forever i.e kind of infinite loop.Event Queue is where all your function are pushed on some event(example:click) this is one by one carried out of queue and put into Event loop which execute this function and prepares it self for next one after first one is executed.This means Execution of one function doesn't starts till the function before it in queue is executed in event loop.
Now let us think we pushed two functions in a queue one is for getting a data from server and another utilises that data.We pushed the serverRequest() function in queue first then utiliseData() function. serverRequest function goes in event loop and makes a call to server as we never know how much time it will take to get data from server so this process is expected to take time and so we busy our event loop thus hanging our page, that's where Web API come into role it take this function from event loop and deals with server making event loop free so that we can execute next function from queue.The next function in queue is utiliseData() which goes in loop but because of no data available it goes waste and execution of next function continues till end of the queue.(This is called Async calling i.e we can do something else till we get data)
Let suppose our serverRequest() function had a return statement in a code, when we get back data from server Web API will push it in queue at the end of queue. As it get pushed at end in queue we cannot utilise its data as there is no function left in our queue to utilise this data.Thus it is not possible to return something from Async Call.
Thus Solution to this is callback or promise.
A Image from one of the answers here, Correctly explains callback use... We give our function(function utilising data returned from server) to function calling server.
function doAjax(callbackFunc, method, url) {
var xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.open(method, url);
xmlHttpReq.onreadystatechange = function() {
if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
callbackFunc(xmlHttpReq.responseText);
}
}
xmlHttpReq.send(null);
}
In my Code it is called as
function loadMyJson(categoryValue){
if(categoryValue==="veg")
doAjax(print,"GET","http://localhost:3004/vegetables");
else if(categoryValue==="fruits")
doAjax(print,"GET","http://localhost:3004/fruits");
else
console.log("Data not found");
}
As zserge's comment suggested,
Timber is very nice, but if you already have an existing project - you may try github.com/zserge/log . It's a drop-in replacement for android.util.Log and has most of the the features that Timber has and even more.
his log library provides simple enable/disable log printing switch as below.
In addition, it only requires to change import
lines, and nothing needs to change for Log.d(...);
statement.
if (!BuildConfig.DEBUG)
Log.usePrinter(Log.ANDROID, false); // from now on Log.d etc do nothing and is likely to be optimized with JIT
I found the easiest way is using str(timedelta)
. It will return a sting formatted like 3 days, 21:06:40.001000
, and you can parse hours and minutes using simple string operations or regular expression.
This orders a list vertically without bullet points. In just one line!
li {
display: block;
}
Please find the below code:
If ComboBox21.Value = "Delimited file" Then
'Const txtFldrPath As String = "C:\Users\513090.CTS\Desktop\MACRO" 'Change to folder path containing text files
Dim myValue2 As String
myValue2 = ComboBox22.Value
Dim txtFldrPath As Variant
txtFldrPath = InputBox("Give the file path")
'Dim CurrentFile As String: CurrentFile = Dir(txtFldrPath & "\" & "LL.txt")
Dim strLine() As String
Dim LineIndex As Long
Dim myValue As Variant
On Error GoTo Errhandler
myValue = InputBox("Give the DELIMITER")
Application.ScreenUpdating = False
Application.DisplayAlerts = False
While txtFldrPath <> vbNullString
LineIndex = 0
Close #1
'Open txtFldrPath & "\" & CurrentFile For Input As #1
Open txtFldrPath For Input As #1
While Not EOF(1)
LineIndex = LineIndex + 1
ReDim Preserve strLine(1 To LineIndex)
Line Input #1, strLine(LineIndex)
Wend
Close #1
With ActiveWorkbook.Sheets(myValue2).Range("A1").Resize(LineIndex, 1)
.Value = WorksheetFunction.Transpose(strLine)
.TextToColumns Other:=True, OtherChar:=myValue
End With
'ActiveSheet.UsedRange.EntireColumn.AutoFit
'ActiveSheet.Copy
'ActiveWorkbook.SaveAs xlsFldrPath & "\" & Replace(CurrentFile, ".txt", ".xls"), xlNormal
'ActiveWorkbook.Close False
' ActiveSheet.UsedRange.ClearContents
CurrentFile = Dir
Wend
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End If
If you use the relative version on http://www.foo.com/abc your browser will look at http://www.foo.com/abc/kitten.png for the image and would get 404 - Not found.
Try this: Set your image crop dimensions and use this line in your CSS:
object-fit: cover;
Try this setup:
a = [["a","b","c",],["d","e"],["f","g","h"]]
To print the 2nd element in the 1st list ("b"), use print a[0][1]
- For the 2nd element in 3rd list ("g"): print a[2][1]
The first brackets reference which nested list you're accessing, the second pair references the item in that list.
in my project wsgi.py file i have this code (it works with virtualenv,django,apache2 in windows and python 3.4)
import os
import sys
DJANGO_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)),'..')
sys.path.append(DJANGO_PATH)
sys.path.append('c:/myproject/env/Scripts')
sys.path.append('c:/myproject/env/Lib/site-packages')
activate_this = 'c:/myproject/env/scripts/activate_this.py'
exec(open(activate_this).read())
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
application = get_wsgi_application()
in virtualhost file conf i have
<VirtualHost *:80>
ServerName mysite
WSGIScriptAlias / c:/myproject/myproject/myproject/wsgi.py
DocumentRoot c:/myproject/myproject/
<Directory "c:/myproject/myproject/myproject/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
I disagree with that this:
String s = myObj == null ? "" : myObj.ToString();
is a hack in any way. I think it's a good example of clear code. It's absolutely obvious what you want to achieve and that you're expecting null.
UPDATE:
I see now that you were not saying that this was a hack. But it's implied in the question that you think this way is not the way to go. In my mind it's definitely the clearest solution.
If you revise your regular expression like this:
drupal-6.14/(?=sites(?!/all|/default)).*
^^
...then it will match all inputs that contain drupal-6.14/
followed by sites
followed by anything other than /all
or /default
. For example:
drupal-6.14/sites/foo
drupal-6.14/sites/bar
drupal-6.14/sitesfoo42
drupal-6.14/sitesall
Changing ?=
to ?!
to match your original regex simply negates those matches:
drupal-6.14/(?!sites(?!/all|/default)).*
^^
So, this simply means that drupal-6.14/
now cannot be followed by sites
followed by anything other than /all
or /default
. So now, these inputs will satisfy the regex:
drupal-6.14/sites/all
drupal-6.14/sites/default
drupal-6.14/sites/all42
But, what may not be obvious from some of the other answers (and possibly your question) is that your regex will also permit other inputs where drupal-6.14/
is followed by anything other than sites
as well. For example:
drupal-6.14/foo
drupal-6.14/xsites
Conclusion: So, your regex basically says to include all subdirectories of drupal-6.14
except those subdirectories of sites
whose name begins with anything other than all
or default
.
Use Array list http://developer.android.com/reference/java/util/ArrayList.html
i don't like the idea of using Reflection for that.
Not only dangerous for missing it in some refactoring, but it can also be denied by SecurityManager
.
FutureTask
is a good option as the other options from the java.util.concurrent package.
My favorite for simple tasks:
Executors.newSingleThreadExecutor().submit(task);
little bit shorter than creating a Thread (task is a Callable or a Runnable)
This works for me.
Create a network with
docker network create --subnet=172.17.0.0/16 selnet
Run docker image
docker run --net selnet --ip 172.18.0.2 hub
At first, I got
docker: Error response from daemon: Invalid address 172.17.0.2: It does not belong to any of this network's subnets.
ERRO[0000] error waiting for container: context canceled
Solution: Increased the 2nd quadruple of the IP [.18. instead of .17.]
Use raw_input
instead of input
:)
If you use
input
, then the data you type is is interpreted as a Python Expression which means that you end up with gawd knows what type of object in your target variable, and a heck of a wide range of exceptions that can be generated. So you should NOT useinput
unless you're putting something in for temporary testing, to be used only by someone who knows a bit about Python expressions.
raw_input
always returns a string because, heck, that's what you always type in ... but then you can easily convert it to the specific type you want, and catch the specific exceptions that may occur. Hopefully with that explanation, it's a no-brainer to know which you should use.
Note: this is only for Python 2. For Python 3, raw_input()
has become plain input()
and the Python 2 input()
has been removed.
The easiest way I think:
void Update()
{
BeginInvoke((Action)delegate()
{
//do your update
});
}
If you want to display links coming from your state or store in Vue 2.0, you can do like this:
<a v-bind:href="''">
{{ url_link }}
</a>
Time of Sleep Function is in milliseconds (ms)
if you want 3 minutes, thats the way to do it:
WScript.Sleep(1000 * 60 * 3)
FYI: I had the same issue with Visual Studio 2015. After many of hours trying, I can now do msbuild myproject.csproj /p:DeployOnBuild=true /p:PublishProfile=myprofile
.
I had to edit my .csproj file to get it working. It contained a line like this:
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets"
Condition="false" />
I changed this line as follows:
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v14.0\WebApplications\Microsoft.WebApplication.targets" />
(I changed 10.0 to 14.0, not sure whether this was necessary. But I definitely had to remove the condition part.)
Remove the spaces from the original string and split on semicolon
$address = "[email protected]; [email protected]; [email protected]"
$addresses = $address.replace(' ','').split(';')
Or all in one line:
$addresses = "[email protected]; [email protected]; [email protected]".replace(' ','').split(';')
$addresses
becomes:
@('[email protected]','[email protected]','[email protected]')
DOUBLE columns are not the same as DECIMAL columns, and you will get in trouble if you use DOUBLE columns for financial data.
DOUBLE is actually just a double precision (64 bit instead of 32 bit) version of FLOAT. Floating point numbers are approximate representations of real numbers and they are not exact. In fact, simple numbers like 0.01 do not have an exact representation in FLOAT or DOUBLE types.
DECIMAL columns are exact representations, but they take up a lot more space for a much smaller range of possible numbers. To create a column capable of holding values from 0.0001 to 99.9999 like you asked you would need the following statement
CREATE TABLE your_table
(
your_column DECIMAL(6,4) NOT NULL
);
The column definition follows the format DECIMAL(M, D) where M is the maximum number of digits (the precision) and D is the number of digits to the right of the decimal point (the scale).
This means that the previous command creates a column that accepts values from -99.9999 to 99.9999. You may also create an UNSIGNED DECIMAL column, ranging from 0.0000 to 99.9999.
For more information on MySQL DECIMAL the official docs are always a great resource.
Bear in mind that all of this information is true for versions of MySQL 5.0.3 and greater. If you are using previous versions, you really should upgrade.
Just like other answers but fix a bug.
When label.width
is controlled by auto layout, sometimes text will be cropped.
@IBDesignable
class InsetLabel: UILabel {
@IBInspectable var topInset: CGFloat = 4.0
@IBInspectable var leftInset: CGFloat = 4.0
@IBInspectable var bottomInset: CGFloat = 4.0
@IBInspectable var rightInset: CGFloat = 4.0
var insets: UIEdgeInsets {
get {
return UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
}
set {
topInset = newValue.top
leftInset = newValue.left
bottomInset = newValue.bottom
rightInset = newValue.right
}
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
var adjSize = super.sizeThatFits(size)
adjSize.width += leftInset + rightInset
adjSize.height += topInset + bottomInset
return adjSize
}
override var intrinsicContentSize: CGSize {
let systemContentSize = super.intrinsicContentSize
let adjustSize = CGSize(width: systemContentSize.width + leftInset + rightInset, height: systemContentSize.height + topInset + bottomInset)
if adjustSize.width > preferredMaxLayoutWidth && preferredMaxLayoutWidth != 0 {
let constraintSize = CGSize(width: bounds.width - (leftInset + rightInset), height: .greatestFiniteMagnitude)
let newSize = super.sizeThatFits(constraintSize)
return CGSize(width: systemContentSize.width, height: ceil(newSize.height) + topInset + bottomInset)
} else {
return adjustSize
}
}
override func drawText(in rect: CGRect) {
super.drawText(in: rect.inset(by: insets))
}
}
You can use something like
SET @cnt = (SELECT COUNT(*) FROM User)
or
SELECT @cnt = (COUNT(*) FROM User)
For this to work the SELECT must return a single column and a single result and the SELECT statement must be in parenthesis.
Edit: Have you tried something like this?
DECLARE @OOdate DATETIME
SET @OOdate = Select OO.Date from OLAP.OutageHours as OO where OO.OutageID = 1
Select COUNT(FF.HALID)
from Outages.FaultsInOutages as OFIO
inner join Faults.Faults as FF
ON FF.HALID = OFIO.HALID
WHERE @OODate = FF.FaultDate
AND OFIO.OutageID = 1
I'd create the array and then append the object literals to it.
var myColumnDefs = [];
for ( var i=0 ; i < oFullResponse.results.length; i++) {
console.log(oFullResponse.results[i].label);
myColumnDefs[myColumnDefs.length] = {key:oFullResponse.results[i].label, sortable:true, resizeable:true};
}
This works with me :
1- select the cells which shall be be affected by the drop down list .
2- home -> conditional formating -> new rule .
3- format only cells that contain .
4- in format only cells with ... select specific text , in formatting rule "= select Elementary from your drop down list"
if drop list in another sheet then when select Elementary we see "=Sheet3!$F$2" in the new rule , with your own sheet and cell number.
5- format -> fill -> select color -> ok.
6-ok .
do the same for each element in drop down list then you will see the magic !
As I'm beginner for vba, I'm willing to get a deep knowledge of vba of how all excel in-built functions work form there back.
So as on the above question I have putted my basic efforts.
Function multi_add(a As Range, ParamArray b() As Variant) As Double
Dim ele As Variant
Dim i As Long
For Each ele In a
multi_add = a + ele.Value **- a**
Next ele
For i = LBound(b) To UBound(b)
For Each ele In b(i)
multi_add = multi_add + ele.Value
Next ele
Next i
End Function
- a: This is subtracted for above code cause a count doubles itself so what values you adds it will add first value twice.
I got same issue on Catalina mac. I also installed the R from the source in following diretory. ./Documents/R-4.0.3
Now from the terminal type
ls -a
and open
vim .bash_profile
type
export LANG="en_US.UTF-8"
save with :wq
then type
source .bash_profile
and then open
./Documents/R-4.0.3/bin/R
./Documents/R-4.0.3/bin/Rscript
I always have to run "source /Users/yourComputerName/.bash_profile" before running R scripts.
I believe that there can still be and valid logic on views. But for this kind of things I agree with @BigMike, it is better placed on the model. Having said that the problem can be solved in three ways:
Your answer (assuming this works, I haven't tried this):
<div class="details @(@Model.Details.Count > 0 ? "show" : "hide")">
Second option:
@if (Model.Details.Count > 0) {
<div class="details show">
}
else {
<div class="details hide">
}
Third option:
<div class="@("details " + (Model.Details.Count>0 ? "show" : "hide"))">
Three books come to mind for me.
I also love the writing of Paul Graham.
open(destination, 'wb').write(open(source, 'rb').read())
Open the source file in read mode, and write to destination file in write mode.
I would sugest to init the Class from RSC:
import Foundation
import UIKit
// Don't forget the delegate!
class ViewController: UIViewController, UITextFieldDelegate {
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@IBOutlet var myTextField : UITextField?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.myTextField.delegate = self;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
self.view.endEditing(true);
return false;
}
}
The splat and spread operators are part of ES6, the planned next version of Javascript. So far only Firefox supports them. This code works in FF16+:
var arr = ['quick', 'brown', 'lazy'];
var sprintf = function(str, ...args)
{
for (arg of args) {
str = str.replace(/%s/, arg);
}
return str;
}
sprintf.apply(null, ['The %s %s fox jumps over the %s dog.', ...arr]);
sprintf('The %s %s fox jumps over the %s dog.', 'slow', 'red', 'sleeping');
Note the awkard syntax for spread. The usual syntax of sprintf('The %s %s fox jumps over the %s dog.', ...arr);
is not yet supported. You can find an ES6 compatibility table here.
Note also the use of for...of
, another ES6 addition. Using for...in
for arrays is a bad idea.
Remove the project from the server from the Server View. Then run the project under the same server.
The problem is as @BalusC told corrupt of server.xml of tomcat which is configured in the eclipse. So when you do the above process server.xml will be recreated .
You can use the apply
function of the Series
object:
>>> df = pd.DataFrame([[' a ', 10], [' c ', 5]])
>>> df[0][0]
' a '
>>> df[0] = df[0].apply(lambda x: x.strip())
>>> df[0][0]
'a'
Note the usage of
strip
and not theregex
which is much faster
Another option - use the apply
function of the DataFrame object:
>>> df = pd.DataFrame([[' a ', 10], [' c ', 5]])
>>> df.apply(lambda x: x.apply(lambda y: y.strip() if type(y) == type('') else y), axis=0)
0 1
0 a 10
1 c 5
In general, questions regarding "magic" variables in Perl can be answered by looking in the Perl predefined variables documentation a la:
perldoc perlvar
However, when you search this documentation for $1, etc., you'll find references in a number of places except the section on these "digit" variables. You have to search for
$<digits>
I would have added this to Brian's answer either by commenting or editing, but I don't have enough rep. If someone adds this I'll remove this answer.
Chrome supports WebDatabase API (which is powered by sqlite), but looks like W3C stopped its development.
If you have been given a database file and have not installed the correct server (either SQLite or MySQL), try this tool: https://dbconvert.com/sqlite/mysql/ The trial version allows converting the first 50 records of each table, the rest of the data is watermarked. This is a Windows program, and can either dump into a running database server, or can dump output to a .sql file
You shouldn't do string comparisons with ==. That operator will only check to see if it is the same instance, not the same value. Use the .equals method to check for the same value.
classname.getResourceAsStream() loads a file via the classloader of classname. If the class came from a jar file, that is where the resource will be loaded from.
FileInputStream is used to read a file from the filesystem.
You could use a function similar to this also, it would allow you to add in different cases where you would like to change values:
Public Function strReplace(varValue As Variant) as Variant
Select Case varValue
Case "Avenue"
strReplace = "Ave"
Case "North"
strReplace = "N"
Case Else
strReplace = varValue
End Select
End Function
Then your SQL would read something like:
SELECT strReplace(Address) As Add FROM Tablename
Here is settings.xml
--> C:\maven\conf\settings.xml
function getMeta(url){
$("<img/>",{
load : function(){
alert(this.width+' '+this.height);
},
src : url
});
}
function getMeta(url){
var img = new Image();
img.onload = function(){
alert( this.width+' '+ this.height );
};
img.src = url;
}
function getMeta(url){
var img = new Image();
img.addEventListener("load", function(){
alert( this.naturalWidth +' '+ this.naturalHeight );
});
img.src = url;
}
Use the above simply as: getMeta( "http://example.com/img.jpg" );
https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement
The last place I had to unbox something was when writing some code that retrieved some data from a database (I wasn't using LINQ to SQL, just plain old ADO.NET):
int myIntValue = (int)reader["MyIntValue"];
Basically, if you're working with older APIs before generics, you'll encounter boxing. Other than that, it isn't that common.
So here is a simple example of how to use classes: Suppose you are a finance institute. You want your customer's accounts to be managed by a computer. So you need to model those accounts. That is where classes come in. Working with classes is called object oriented programming. With classes you model real world objects in your computer. So, what do we need to model a simple bank account? We need a variable that saves the balance and one that saves the customers name. Additionally, some methods to in- and decrease the balance. That could look like:
class bankaccount():
def __init__(self, name, money):
self.name = name
self.money = money
def earn_money(self, amount):
self.money += amount
def withdraw_money(self, amount):
self.money -= amount
def show_balance(self):
print self.money
Now you have an abstract model of a simple account and its mechanism.
The def __init__(self, name, money)
is the classes' constructor. It builds up the object in memory. If you now want to open a new account you have to make an instance of your class. In order to do that, you have to call the constructor and pass the needed parameters. In Python a constructor is called by the classes's name:
spidermans_account = bankaccount("SpiderMan", 1000)
If Spiderman wants to buy M.J. a new ring he has to withdraw some money. He would call the withdraw
method on his account:
spidermans_account.withdraw_money(100)
If he wants to see the balance he calls:
spidermans_account.show_balance()
The whole thing about classes is to model objects, their attributes and mechanisms. To create an object, instantiate it like in the example. Values are passed to classes with getter and setter methods like `earn_money()´. Those methods access your objects variables. If you want your class to store another object you have to define a variable for that object in the constructor.
You should use datetime.datetime.strptime
:
import datetime
dt = datetime.datetime.strptime(string_date, fmt)
fmt
will need to be the appropriate format for your string. You'll find the reference on how to build your format here.
No promises are just wrapper on callbacks
example You can use javascript native promises with node js
my cloud 9 code link : https://ide.c9.io/adx2803/native-promises-in-node
/**
* Created by dixit-lab on 20/6/16.
*/
var express = require('express');
var request = require('request'); //Simplified HTTP request client.
var app = express();
function promisify(url) {
return new Promise(function (resolve, reject) {
request.get(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
resolve(body);
}
else {
reject(error);
}
})
});
}
//get all the albums of a user who have posted post 100
app.get('/listAlbums', function (req, res) {
//get the post with post id 100
promisify('http://jsonplaceholder.typicode.com/posts/100').then(function (result) {
var obj = JSON.parse(result);
return promisify('http://jsonplaceholder.typicode.com/users/' + obj.userId + '/albums')
})
.catch(function (e) {
console.log(e);
})
.then(function (result) {
res.end(result);
}
)
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
//run webservice on browser : http://localhost:8081/listAlbums
Here ya go:
viewNoteDateMonth.text = [[displayDate objectAtIndex:2] uppercaseString];
Btw:
"april"
is lowercase
? [NSString lowercaseString]
"APRIL"
is UPPERCASE
? [NSString uppercaseString]
"April May"
is Capitalized/Word Caps
? [NSString capitalizedString]
"April may"
is Sentence caps
? (method missing; see workaround below)
Hence what you want is called "uppercase", not "capitalized". ;)
As for "Sentence Caps" one has to keep in mind that usually "Sentence" means "entire string". If you wish for real sentences use the second method, below, otherwise the first:
@interface NSString ()
- (NSString *)sentenceCapitalizedString; // sentence == entire string
- (NSString *)realSentenceCapitalizedString; // sentence == real sentences
@end
@implementation NSString
- (NSString *)sentenceCapitalizedString {
if (![self length]) {
return [NSString string];
}
NSString *uppercase = [[self substringToIndex:1] uppercaseString];
NSString *lowercase = [[self substringFromIndex:1] lowercaseString];
return [uppercase stringByAppendingString:lowercase];
}
- (NSString *)realSentenceCapitalizedString {
__block NSMutableString *mutableSelf = [NSMutableString stringWithString:self];
[self enumerateSubstringsInRange:NSMakeRange(0, [self length])
options:NSStringEnumerationBySentences
usingBlock:^(NSString *sentence, NSRange sentenceRange, NSRange enclosingRange, BOOL *stop) {
[mutableSelf replaceCharactersInRange:sentenceRange withString:[sentence sentenceCapitalizedString]];
}];
return [NSString stringWithString:mutableSelf]; // or just return mutableSelf.
}
@end
I did this and now my app is working properly,
res.sendFile('your drive://your_subfolders//file.html');
Go on using tabTextAppearance as you did but
1) to fix the capital letter side effect add textAllCap in your style :
<style name="MyTabLayoutTextAppearance" parent="TextAppearance.AppCompat.Widget.ActionBar.Title.Inverse">
<item name="android:textSize">14sp</item>
<item name="android:textAllCaps">true</item>
</style>
2) to fix the selected tab color side effect add in TabLayout xml the following library attributes :
app:tabSelectedTextColor="@color/color1"
app:tabTextColor="@color/color2"
Hope this helps.
Setting cookie in the express is easy
npm install cookie parser
const cookieParser = require('cookie-parser');
app.use(cookieParser());
res.cookie('cookieName', '1', { expires: new Date(Date.now() + 900000), httpOnly: true })
console.dir(req.cookies.cookieName)
If you're interested in the mechanics of two's complement, here's the absolutely inefficient, but illustrative low-level way this is made:
private static int makeAbsolute(int number){
if(number >=0){
return number;
} else{
return (~number)+1;
}
}
I found this topic while searching for run script for startup and shutdown Windows 10. Those answers above didn't working. For me on windows 10 worked when I put scripts to task scheduler. How to do this: press window key and write Task scheduler, open it, then on the right is Add task... button. Here you can add scripts. PS: I found action for startup and logout user, there is not for shutdown.
All of this can be very confusing for an app developer that's simply using TLS to connect to their own web servers. Because ATS (App Transport Security) is becoming more important and we are encouraged to convert everything to https - I think more developers are going to encounter this issue.
My app simply exchanges data between our server and the user using the https protocol. Seeing the words "USES ENCRYPTION" in the disclaimers is a bit scary so I gave the US government office a call at their office and spoke to a representative of the Bureau of Industry and Security (BIS) http://www.bis.doc.gov/index.php/about-bis/contact-bis.
The representative asked me about my app and since it passed the "primary function test" in that it had nothing to do with security/communications and simply uses https as a channel for connecting my customer data to our servers - it fell in the EAR99 category which means it's exempt from getting government permission (see https://www.bis.doc.gov/index.php/licensing/commerce-control-list-classification/export-control-classification-number-eccn)
I hope this helps other app developers.
The Form has a KeyPreview property that you can use to intercept the keypress.
if "ABCD" in "xxxxABCDyyyy":
# whatever
android:editable="false"
should work, but it is deprecated, you should be using android:inputType="none"
instead.
Alternatively, if you want to do it in the code you could do this :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);
This is also a viable alternative :
EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);
If you're going to make your EditText
non-editable, may I suggest using the TextView
widget instead of the EditText
, since using a EditText seems kind of pointless in that case.
EDIT: Altered some information since I've found that android:editable
is deprecated, and you should use android:inputType="none"
, but there is a bug about it on android code; So please check this.
If you know you're on bash, and still get this error, make sure you write the if with spaces.
[[1==1]] # This outputs error
[[ 1==1 ]] # OK
I had this, I added EXIT
and initially it didn't work, I guess per requiring the called program exiting
advice mentioned in another response here, however it now works without further ado - not sure what's caused this, but the point to note is that I'm calling a data file .html
rather than the program that handles it browser.exe
, I did not edit anything else but suffice it to say it's much neater just using a bat file to access the main access pages of those web documents and only having title.bat
, contents.bat
, index.bat
in the root folder with the rest of the content in a subfolder.
i.e.: contents.bat reads
cd subfolder
"contents.html"
exit
It also looks better if I change the bat file icons for just those items to suit the context they are in too, but that's another matter, hiding the bat files in the subfolder and creating custom icon shortcuts to them in the root folder with the images called for the customisation also hidden.
Probably this is you are looking for (from this post):
Oracle SQL developer is NOT support on 64 bits JDK. To solve it, install a 32 bits / x86 JDK and update your SQL developer config file, so that it points to the 32 bits JDK.
Fix it! Edit the “sqldeveloper.conf“, which can be found under “{ORACLE_HOME}\sqldeveloper\sqldeveloper\bin\sqldeveloper.conf“, make sure “SetJavaHome” is point to your 32 bits JDK.
Update: Based on @FGreg answer below, in the Sql Developer version 4.XXX you can do it in user-specific config file:
Update 2: Based on @krm answer below, if your SQL Developer and JDK "bits" versions are not same, you can try to set the value of SetJavaHome property in product.conf
SetJavaHome C:\Program Files\Java\jdk1.7.0_80
The product.conf file is in my case located in the following directory:
C:\Users\username\AppData\Roaming\sqldeveloper\1.0.0.0.0
Use filter
, or if the number of dictionaries in exampleSet
is too high, use ifilter
of the itertools
module. It would return an iterator, instead of filling up your system's memory with the entire list at once:
from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
print elem
Or even shorter, with only standard modern Javascript:
var first_link = document.getElementsByTagName('a')[0];
first_link.dispatchEvent(new MouseEvent('click'));
The new MouseEvent
constructor takes a required event type name, then an optional object (at least in Chrome). So you could, for example, set some properties of the event:
first_link.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true}));
Empty-ness and "NULL-ness" are two different concepts. As others mentioned the former can be achieved via std::string::empty()
, the latter can be achieved with boost::optional<std::string>
, e.g.:
boost::optional<string> myStr;
if (myStr) { // myStr != NULL
// ...
}
This should should work: =IF(A1=1, B1)
The 3rd argument stating the value of the cell if the condition is not met is optional.
You can run this command from the DB2 command line processor (CLP) or from inside a SQL application by calling the ADMIN_CMD
stored procedure
EXPORT TO result.csv OF DEL MODIFIED BY NOCHARDEL
SELECT col1, col2, coln FROM testtable;
There are lots of options for IMPORT
and EXPORT
that you can use to create a data file that meets your needs. The NOCHARDEL
qualifier will suppress double quote characters that would otherwise appear around each character column.
Keep in mind that any SELECT
statement can be used as the source for your export, including joins or even recursive SQL. The export utility will also honor the sort order if you specify an ORDER BY
in your SELECT
statement.
Add this code in your project level build.gradle file.
subprojects {
project.configurations.all {
resolutionStrategy.eachDependency { details ->
if (details.requested.group == 'com.android.support'
&& !details.requested.name.contains('multidex') ) {
details.useVersion "version which should be used - in your case 28.0.0-beta2"
}
}
}
}
Sample Code :
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.0'
classpath 'io.fabric.tools:gradle:1.31.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
subprojects {
project.configurations.all {
resolutionStrategy.eachDependency { details ->
if (details.requested.group == 'com.android.support'
&& !details.requested.name.contains('multidex') ) {
details.useVersion "28.0.0"
}
}
}
}
I am doing this using scipy stat module and lambda:
import scipy.stats
lst = [1,2,3,4,5,6,7,5]
most_freq_val = lambda x: scipy.stats.mode(x)[0][0]
print(most_freq_val(lst))
Result:
most_freq_val = 5
Filter your log to just Error and look for FATAL EXCEPTION
Nick answers its fine but you will have functions which repeats itsself while scrolling or will not work at all if user has the window zoomed. I came up with an easy fix just math.round the first height and it works just as assumed.
if (Math.round($(window).scrollTop()) + $(window).innerHeight() == $(document).height()){
loadPagination();
$(".go-up").css("display","block").show("slow");
}
First you should try with Proguard (This clean all code unused)
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
minSdkVersion 16
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
I just want to share the fact that my apk file was saved to my app "Data" directory and that I needed to change the permissions on the apk file to be world readable in order to allow it to be installed that way, otherwise the system was throwing "Parse error: There is a Problem Parsing the Package"; so using solution from @Horaceman that makes:
File file = new File(dir, "App.apk");
file.setReadable(true, false);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
startActivity(intent);
You should form the command with the contents of the textboxes:
sql = "insert into Main (Firt Name, Last Name) values(" + textbox2.Text + "," + textbox3.Text+ ")";
This, of course, provided that you manage to open the connection correctly.
It would be helpful to know what's happening with your current code. If you are getting some error displayed in that message box, it would be great to know what it's saying.
You should also validate the inputs before actually running the command (i.e. make sure they don't contain malicious code...).
Lookups in lists are O(n), lookups in dictionaries are amortized O(1), with regard to the number of items in the data structure. If you don't need to associate values, use sets.
Both dictionaries and sets use hashing and they use much more memory than only for object storage. According to A.M. Kuchling in Beautiful Code, the implementation tries to keep the hash 2/3 full, so you might waste quite some memory.
If you do not add new entries on the fly (which you do, based on your updated question), it might be worthwhile to sort the list and use binary search. This is O(log n), and is likely to be slower for strings, impossible for objects which do not have a natural ordering.
JavaScript:
document.getElementsByTagName('head')[0].appendChild( ... );
Make DOM element like so:
link=document.createElement('link');
link.href='href';
link.rel='rel';
document.getElementsByTagName('head')[0].appendChild(link);
As stated, use TextView.setText(Html.fromHtml(String))
And use these tags in your Html formatted string:
<a href="...">
<b>
<big>
<blockquote>
<br>
<cite>
<dfn>
<div align="...">
<em>
<font size="..." color="..." face="...">
<h1>
<h2>
<h3>
<h4>
<h5>
<h6>
<i>
<img src="...">
<p>
<small>
<strike>
<strong>
<sub>
<sup>
<tt>
<u>
http://commonsware.com/blog/Android/2010/05/26/html-tags-supported-by-textview.html
Try calling it like: obj.some_function( '1', 2, '3', g="foo", h="bar" )
. After the required positional arguments, you can specify specific optional arguments by name.
You have to cast the selected item to your custom class (ComboboxItem) Try this:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
int selectedIndex = cmb.SelectedIndex;
string selectedText = this.comboBox1.Text;
string selectedValue = ((ComboboxItem)cmb.SelectedItem).Value.ToString();
ComboboxItem selectedCar = (ComboboxItem)cmb.SelectedItem;
MessageBox.Show(String.Format("Index: [{0}] CarName={1}; Value={2}", selectedIndex, selectedCar.Text, selecteVal));
}
If you want to use asynchronous method you need to use callback function by $promise, here is example:
var Regions = $resource('mocks/regions.json');
$scope.regions = Regions.query();
$scope.regions.$promise.then(function (result) {
$scope.regions = result;
});
I don't know of any full Chrome component, but you could use WebKit, which is the rendering engine that Chrome uses. The Mono project made WebKit Sharp, which might work for you.
You can/should set your parameter to value to DBNull.Value;
if (variable == "")
{
cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = DBNull.Value;
}
else
{
cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = variable;
}
Or you can leave your server side set to null and not pass the param at all.
if(window.matchMedia('(max-width: 768px)').matches)
{
$(".article-item").text(function(i, text) {
if (text.length >= 150) {
text = text.substring(0, 250);
var lastIndex = text.lastIndexOf(" ");
text = text.substring(0, lastIndex) + '...';
}
$(this).text(text);
});
}
From the shell if you want to show all results you could do db.collection.find().toArray()
to get all results without it.
There is no easy way to remove the "outdated" stuff from an existing workspace. Using the "clean" parameter will not really help, as many of the files you refer to are "free form data", only known to the plugins that are no longer available.
Your best bet is to optimize the re-import, where I would like to point out the following:
${old_workspace}/.metadata/.plugins/org.eclipse.core.runtime/.settings
folder from the old to the new workspace. This is surely the fastest way, but it may lead to weird behaviour, because some of your plugins may depend on these settings and on some of the mentioned "free form data" stored elsewhere. (There are even people symlinking these folders over multiple workspaces, but this really requires to use the same plugins on all workspaces.)Bundles the following extensions for the Visual Studio 2010 JScript editor
Brace Matching
Adds support for automatically highlighting the matching opening or closing brace to the one currently at the cursor. Supports matching parenthesis: (), square brackets: [], and curly braces: {}. Braces in strings, comments and regular expression literals are ignored.
Outlining / Cold-folding
Adds support for automatically creating outlining regions for JScript blocks. Blocks are detected via opening and closing curly braces. Braces in strings, comments and regular expression literals are ignored.
Current Word Highlighting
Adds support for highlighting all instances of the word currently at the cursor.
IntelliSense Doc-Comments Support
Adds support for the element in JScript IntelliSense doc-comments to allow display of new lines in IntelliSense tooltips.
Monolithic kernel design is much older than the microkernel idea, which appeared at the end of the 1980's.
Unix and Linux kernels are monolithic, while QNX, L4 and Hurd are microkernels. Mach was initially a microkernel (not Mac OS X), but later converted into a hybrid kernel. Minix (before version 3) wasn't a pure microkernel because device drivers were compiled as part of the kernel.
Monolithic kernels are usually faster than microkernels. The first microkernel Mach was 50% slower than most monolithic kernels, while later ones like L4 were only 2% or 4% slower than the monolithic designs.
Monolithic kernels are big in size, while microkernels are small in size - they usually fit into the processor's L1 cache (first generation microkernels).
In monolithic kernels, the device drivers reside in the kernel space while in the microkernels the device drivers are user-space.
Since monolithic kernels' device drivers reside in the kernel space, monolithic kernels are less secure than microkernels, and failures (exceptions) in the drivers may lead to crashes (displayed as BSODs in Windows). Microkernels are more secure than monolithic kernels, hence more often used in military devices.
Monolithic kernels use signals and sockets to implement inter-process communication (IPC), microkernels use message queues. 1st gen microkernels didn't implement IPC well and were slow on context switches - that's what caused their poor performance.
Adding a new feature to a monolithic system means recompiling the whole kernel or the corresponding kernel module (for modular monolithic kernels), whereas with microkernels you can add new features or patches without recompiling.
The following snippet (uses java.time.format of Java 8) maybe used to iterate over a date range :
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// Any chosen date format maybe taken
LocalDate startDate = LocalDate.parse(startDateString,formatter);
LocalDate endDate = LocalDate.parse(endDateString,formatter);
if(endDate.isBefore(startDate))
{
//error
}
LocalDate itr = null;
for (itr = startDate; itr.isBefore(endDate)||itr.isEqual(itr); itr = itr.plusDays(1))
{
//Processing goes here
}
The plusMonths()/plusYears() maybe chosen for time unit increment. Increment by a single day is being done in above illustration.
You can't checkout a single directory of a repository because the entire repository is handled by the single .git folder in the root of the project instead of subversion's myriad of .svn directories.
The problem with working on plugins in a single repository is that making a commit to, e.g., mytheme will increment the revision number for myplugin, so even in subversion it is better to use separate repositories.
The subversion paradigm for sub-projects is svn:externals which translates somewhat to submodules in git (but not exactly in case you've used svn:externals before.)
mercurial_keyring installation on Mac OSX using MacPorts:
sudo port install py-keyring
sudo port install py-mercurial_keyring
Add the following to ~/.hgrc:
# Add your username if you haven't already done so.
[ui]
username = [email protected]
[extensions]
mercurial_keyring =
Many times we might want to perform Table pagination using jquery.Here i ll give you the answer and reference link
Jquery
$(document).ready(function(){
$('#data').after('<div id="nav"></div>');
var rowsShown = 4;
var rowsTotal = $('#data tbody tr').length;
var numPages = rowsTotal/rowsShown;
for(i = 0;i < numPages;i++) {
var pageNum = i + 1;
$('#nav').append('<a href="#" rel="'+i+'">'+pageNum+'</a> ');
}
$('#data tbody tr').hide();
$('#data tbody tr').slice(0, rowsShown).show();
$('#nav a:first').addClass('active');
$('#nav a').bind('click', function(){
$('#nav a').removeClass('active');
$(this).addClass('active');
var currPage = $(this).attr('rel');
var startItem = currPage * rowsShown;
var endItem = startItem + rowsShown;
$('#data tbody tr').css('opacity','0.0').hide().slice(startItem, endItem).
css('display','table-row').animate({opacity:1}, 300);
});
});
JSfiddle: https://jsfiddle.net/u9d1ewsh/
Use a color with an alpha value like #33------
, and set it as background of your editText using the XML attribute android:background=" "
.
255 * 0.2 = 51 ? in hex 33
Many Git history browsers, including git log
(and 'git log --graph'), gitk (in Tcl/Tk, part of Git), QGit (in Qt), tig (text mode interface to git, using ncurses), Giggle (in GTK+), TortoiseGit and git-cheetah support path limiting (e.g. gitk path/to/file
).
I really like explanation by Jeremy west.... another approach which is really easy for understanding is given here http://courses.washington.edu/css343/zander/NotesProbs/heapcomplexity
since, buildheap depends using depends on heapify and shiftdown approach is used which depends upon sum of the heights of all nodes. So, to find the sum of height of nodes which is given by S = summation from i = 0 to i = h of (2^i*(h-i)), where h = logn is height of the tree solving s, we get s = 2^(h+1) - 1 - (h+1) since, n = 2^(h+1) - 1 s = n - h - 1 = n- logn - 1 s = O(n), and so complexity of buildheap is O(n).
There's actually a good reason:
The non-static access does not always work, for reasons of ambiguity.
Suppose we have two classes, A and B, the latter being a subclass of A, with static fields with the same name:
public class A {
public static String VALUE = "Aaa";
}
public class B extends A {
public static String VALUE = "Bbb";
}
Direct access to the static variable:
A.VALUE (="Aaa")
B.VALUE (="Bbb")
Indirect access using an instance (gives a compiler warning that VALUE should be statically accessed):
new B().VALUE (="Bbb")
So far, so good, the compiler can guess which static variable to use, the one on the superclass is somehow farther away, seems somehow logical.
Now to the point where it gets tricky: Interfaces can also have static variables.
public interface C {
public static String VALUE = "Ccc";
}
public interface D {
public static String VALUE = "Ddd";
}
Let's remove the static variable from B, and observe following situations:
B implements C, D
B extends A implements C
B extends A implements C, D
B extends A implements C
where A implements D
B extends A implements C
where C extends D
The statement new B().VALUE
is now ambiguous, as the compiler cannot decide which static variable was meant, and will report it as an error:
error: reference to VALUE is ambiguous
both variable VALUE in C and variable VALUE in D match
And that's exactly the reason why static variables should be accessed in a static way.
finally solved my problem.
I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.
SELECT * FROM `table` t1 join `table` t2 WHERE (t1.name=t2.name) && (t1.id!=t2.id)
Close and re-open the tab. That should do the trick.
For only one line, you need
...
<View android:id="@+id/primerdivisor"
android:layout_height="2dp"
android:layout_width="fill_parent"
android:background="#ffffff" />
...
Another simple way I found for using in LAN is
ssh [username@ip] uname -n
If you need to login command line will be
sshpass -p "[password]" ssh [username@ip] uname -n
<input type="number" name="numericInput" size="2" min="0" maxlength="2" value="0" />
ActiveX is only supported by IE - the other browsers use a plugin architecture called NPAPI. However, there's a cross-browser plugin framework called Firebreath that you might find useful.
"Confirm" in Javascript stops the whole process until it gets a mouse response on its buttons. If that is what you are looking for, you can refer jquery-ui but if you have nothing running behind your process while receiving the response and you control the flow programatically, take a look at this. You will have to hard-code everything by yourself but you have complete command over customization. https://www.w3schools.com/howto/howto_css_modals.asp
If what you want is the total number of records in the table appended to each row you can do something like
SELECT *
FROM my_table
CROSS JOIN (SELECT COUNT(*) AS COUNT_OF_RECS_IN_MY_TABLE
FROM MY_TABLE)
A really simple explanation that I found useful: the nosniff response header is a way to keep a website more secure.
From Security Researcher, Scott Helme, here:
It prevents Google Chrome and Internet Explorer from trying to mime-sniff the content-type of a response away from the one being declared by the server.
That's something controlled by your terminal, not by printf
.
printf
simply sends a \t
to the output stream (which can be a tty, a file etc), it doesn't send a number of spaces.
Do you have to use the java 8 idioms (steams)? Perphaps a simple solution would be to move the complexity to a map alike data structure that holds numbers as key (without repeating) and the times it ocurrs as a value. You could them iterate that map an only do something with those numbers that are ocurrs > 1.
import java.lang.Math;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
public class RemoveDuplicates
{
public static void main(String[] args)
{
List<Integer> numbers = Arrays.asList(new Integer[]{1,2,1,3,4,4});
Map<Integer,Integer> countByNumber = new HashMap<Integer,Integer>();
for(Integer n:numbers)
{
Integer count = countByNumber.get(n);
if (count != null) {
countByNumber.put(n,count + 1);
} else {
countByNumber.put(n,1);
}
}
System.out.println(countByNumber);
Iterator it = countByNumber.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
}
}
}
An int variable holds a 32 bit signed integer value. An Integer (with capital I) holds a reference to an object of (class) type Integer, or to null.
Java automatically casts between the two; from Integer to int whenever the Integer object occurs as an argument to an int operator or is assigned to an int variable, or an int value is assigned to an Integer variable. This casting is called boxing/unboxing.
If an Integer variable referencing null is unboxed, explicitly or implicitly, a NullPointerException is thrown.
Macmade's solution doesn't work for me anymore on my Jekyll instance on Github Pages anymore but I found this solution on an issue for the kramdown github repo. For OP's example it would look like this:
1. item 1
2. item 2
```
Code block
```
{:start="3"}
3. item 3
Solved my issues handily.
I was struggling with similar problem (with mail) in one of my git's post_receive hooks and finally I found out, that sendmail actually works better for that kind of things, especially if you know a bit of how e-mails are constructed (and it seems like you know). I know this answer comes very late, but maybe it will be of some use to others too. I made use of heredoc operator and use of the feature, that it expands variables, so it can also run inlined scripts. Just check this out (bash script):
#!/bin/bash
recipients=(
'[email protected]'
'[email protected]'
# '[email protected]'
);
sender='[email protected]';
subject='Oh, who really cares, seriously...';
sendmail -t <<-MAIL
From: ${sender}
`for r in "${recipients[@]}"; do echo "To: ${r}"; done;`
Subject: ${subject}
Content-Type: text/html; charset=UTF-8
<html><head><meta charset="UTF-8"/></head>
<body><p>Ladies and gents, here comes the report!</p>
<pre>`mysql -u ***** -p***** -H -e "SELECT * FROM users LIMIT 20"`</pre>
</body></html>
MAIL
Note of backticks in the MAIL part to generate some output and remember, that <<-
operator strips only tabs (not spaces) from the beginning of lines, so in that case copy-paste will not work (you need to replace indentation with proper tabs). Or use <<
operator and make no indentation at all. Hope this will help someone. Of course you can use backticks outside o MAIL part and save the output into some variable, that you can later use in the MAIL part — matter of taste and readability. And I know, #!/bin/bash
does not always work on every system.
I would recommend reviewing this page on How to Write Go Code
It documents both how to structure your project in a go build
friendly way, and also how to write tests. Tests do not need to be a cmd using the main
package. They can simply be TestX named functions as part of each package, and then go test
will discover them.
The structure suggested in that link in your question is a bit outdated, now with the release of Go 1. You no longer would need to place a pkg
directory under src
. The only 3 spec-related directories are the 3 in the root of your GOPATH: bin, pkg, src . Underneath src, you can simply place your project mypack
, and underneath that is all of your .go files including the mypack_test.go
go build
will then build into the root level pkg and bin.
So your GOPATH might look like this:
~/projects/
bin/
pkg/
src/
mypack/
foo.go
bar.go
mypack_test.go
export GOPATH=$HOME/projects
$ go build mypack
$ go test mypack
Update: as of >= Go 1.11, the Module system is now a standard part of the tooling and the GOPATH concept is close to becoming obsolete.
you could just use the floatval
function
echo floatval('125.00');
// 125
echo floatval('966.70');
// 966.7
echo floatval('844.011');
// 844.011
I found this more useful for getting the absolute file location.
File file = new File("\\TestHello\\test.txt");
System.out.println(file.getAbsoluteFile());
You need DATE_ADD/DATE_SUB
:
AND v.date > (DATE_SUB(CURDATE(), INTERVAL 2 MONTH))
AND v.date < (DATE_SUB(CURDATE(), INTERVAL 1 MONTH))
should work.
I'm a big fan of using EPPlus to perform these types of actions. EPPlus is a library you can reference in your project and easily create/modify spreadsheets on a server. I use it for any project that requires an export function.
Here's a nice blog entry that shows how to use the library, though the library itself should come with some samples that explain how to use it.
Third party libraries are a lot easier to use than Microsoft COM objects, in my opinion. I would suggest giving it a try.
Check your encoding, i got something similar once because of the BOM.
Make sure the core.js file is encoded in utf-8 without BOM
The following should work but it wouldn't be SEO compatible. It's best to put the title in the title tag.
<script type="text/javascript">
$(document).ready(function() {
document.title = 'blah';
});
</script>
It's declaring the string as nvarchar
data type, rather than varchar
You may have seen Transact-SQL code that passes strings around using an N prefix. This denotes that the subsequent string is in Unicode (the N actually stands for National language character set). Which means that you are passing an NCHAR, NVARCHAR or NTEXT value, as opposed to CHAR, VARCHAR or TEXT.
To quote from Microsoft:
Prefix Unicode character string constants with the letter N. Without the N prefix, the string is converted to the default code page of the database. This default code page may not recognize certain characters.
If you want to know the difference between these two data types, see this SO post:
for cakephp3+:
$url = $this->request->scheme().'://'.$this->request->domain().$this->request->here(false);
will get eg: http://bgq.dev/home/index?t44=333
A "const function", denoted with the keyword const
after a function declaration, makes it a compiler error for this class function to change a member variable of the class. However, reading of a class variables is okay inside of the function, but writing inside of this function will generate a compiler error.
Another way of thinking about such "const function" is by viewing a class function as a normal function taking an implicit this
pointer. So a method int Foo::Bar(int random_arg)
(without the const at the end) results in a function like int Foo_Bar(Foo* this, int random_arg)
, and a call such as Foo f; f.Bar(4)
will internally correspond to something like Foo f; Foo_Bar(&f, 4)
. Now adding the const at the end (int Foo::Bar(int random_arg) const
) can then be understood as a declaration with a const this pointer: int Foo_Bar(const Foo* this, int random_arg)
. Since the type of this
in such case is const, no modifications of member variables are possible.
It is possible to loosen the "const function" restriction of not allowing the function to write to any variable of a class. To allow some of the variables to be writable even when the function is marked as a "const function", these class variables are marked with the keyword mutable
. Thus, if a class variable is marked as mutable, and a "const function" writes to this variable then the code will compile cleanly and the variable is possible to change. (C++11)
As usual when dealing with the const
keyword, changing the location of the const key word in a C++ statement has entirely different meanings. The above usage of const
only applies when adding const
to the end of the function declaration after the parenthesis.
const
is a highly overused qualifier in C++: the syntax and ordering is often not straightforward in combination with pointers. Some readings about const
correctness and the const
keyword:
This is a barebones look at what I've done to float one image over another.
img {_x000D_
position: absolute;_x000D_
top: 25px;_x000D_
left: 25px;_x000D_
}_x000D_
.imgA1 {_x000D_
z-index: 1;_x000D_
}_x000D_
.imgB1 {_x000D_
z-index: 3;_x000D_
}
_x000D_
<img class="imgA1" src="https://placehold.it/200/333333">_x000D_
<img class="imgB1" src="https://placehold.it/100">
_x000D_
From your IDE, create a remote debug configuration, configure it for the default JPDA Tomcat port which is port 8000.
From the command line:
Linux:
cd apache-tomcat/bin
export JPDA_SUSPEND=y
./catalina.sh jpda run
Windows:
cd apache-tomcat\bin
set JPDA_SUSPEND=y
catalina.bat jpda run
Execute the remote debug configuration from your IDE, and Tomcat will start running and you are now able to set breakpoints in the IDE.
Note:
The JPDA_SUSPEND=y
line is optional, it is useful if you want that Apache Tomcat doesn't start its execution until step 3 is completed, useful if you want to troubleshoot application initialization issues.
find and xargs are your friends. Use them to filter the file list rather than grep's --exclude
Try something like
find . -not -name '*.png' -o -type f -print | xargs grep -icl "foo="
The advantage of getting used to this, is that it is expandable to other use cases, for example to count the lines in all non-png files:
find . -not -name '*.png' -o -type f -print | xargs wc -l
To remove all non-png files:
find . -not -name '*.png' -o -type f -print | xargs rm
etc.
As pointed out in the comments, if some files may have spaces in their names, use -print0
and xargs -0
instead.
In light of apparent dislike for how I've attempted to answer the OP's question. The literal answer is, a promise is something shared w/ other objects, while a deferred should be kept private. Primarily, a deferred (which generally extends Promise) can resolve itself, while a promise might not be able to do so.
If you're interested in the minutiae, then examine Promises/A+.
So far as I'm aware, the overarching purpose is to improve clarity and loosen coupling through a standardized interface. See suggested reading from @jfriend00:
Rather than directly passing callbacks to functions, something which can lead to tightly coupled interfaces, using promises allows one to separate concerns for code that is synchronous or asynchronous.
Personally, I've found deferred especially useful when dealing with e.g. templates that are populated by asynchronous requests, loading scripts that have networks of dependencies, and providing user feedback to form data in a non-blocking manner.
Indeed, compare the pure callback form of doing something after loading CodeMirror in JS mode asynchronously (apologies, I've not used jQuery in a while):
/* assume getScript has signature like: function (path, callback, context)
and listens to onload && onreadystatechange */
$(function () {
getScript('path/to/CodeMirror', getJSMode);
// onreadystate is not reliable for callback args.
function getJSMode() {
getScript('path/to/CodeMirror/mode/javascript/javascript.js',
ourAwesomeScript);
};
function ourAwesomeScript() {
console.log("CodeMirror is awesome, but I'm too impatient.");
};
});
To the promises formulated version (again, apologies, I'm not up to date on jQuery):
/* Assume getScript returns a promise object */
$(function () {
$.when(
getScript('path/to/CodeMirror'),
getScript('path/to/CodeMirror/mode/javascript/javascript.js')
).then(function () {
console.log("CodeMirror is awesome, but I'm too impatient.");
});
});
Apologies for the semi-pseudo code, but I hope it makes the core idea somewhat clear. Basically, by returning a standardized promise, you can pass the promise around, thus allowing for more clear grouping.
I happen to miss spaces in my query and this error comes.
Ex: $sql= "SELECT * FROM";
$sql .= "table1";
Though the example might look simple, when coding complex queries, the probability for this error is high. I was missing space before word "table1".
(Updated for Spring 3.0)
I go with Spring MVC as well.
You need to download Spring from here
To configure your web-app to use Spring add the following servlet to your web.xml
<web-app>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
You then need to create your Spring config file /WEB-INF/spring-dispatcher-servlet.xml
Your first version of this file can be as simple as:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.acme.foo" />
<mvc:annotation-driven />
</beans>
Spring will then automatically detect classes annotated with @Controller
A simple controller is then:
package com.acme.foo;
import java.util.logging.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/person")
public class PersonController {
Logger logger = Logger.getAnonymousLogger();
@RequestMapping(method = RequestMethod.GET)
public String setupForm(ModelMap model) {
model.addAttribute("person", new Person());
return "details.jsp";
}
@RequestMapping(method = RequestMethod.POST)
public String processForm(@ModelAttribute("person") Person person) {
logger.info(person.getId());
logger.info(person.getName());
logger.info(person.getSurname());
return "success.jsp";
}
}
And the details.jsp
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<form:form commandName="person">
<table>
<tr>
<td>Id:</td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td>Name:</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Surname:</td>
<td><form:input path="surname" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Save Changes" /></td>
</tr>
</table>
</form:form>
This is just the tip of the iceberg with regards to what Spring can do...
Hope this helps.
Import namespace :
using System.Configuration;
Create ConfigurationElement Company :
public class Company : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return this["name"] as string;
}
}
[ConfigurationProperty("code", IsRequired = true)]
public string Code
{
get
{
return this["code"] as string;
}
}
}
ConfigurationElementCollection:
public class Companies
: ConfigurationElementCollection
{
public Company this[int index]
{
get
{
return base.BaseGet(index) as Company ;
}
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
public new Company this[string responseString]
{
get { return (Company) BaseGet(responseString); }
set
{
if(BaseGet(responseString) != null)
{
BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
}
BaseAdd(value);
}
}
protected override System.Configuration.ConfigurationElement CreateNewElement()
{
return new Company();
}
protected override object GetElementKey(System.Configuration.ConfigurationElement element)
{
return ((Company)element).Name;
}
}
and ConfigurationSection:
public class RegisterCompaniesConfig
: ConfigurationSection
{
public static RegisterCompaniesConfig GetConfig()
{
return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
}
[System.Configuration.ConfigurationProperty("Companies")]
[ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
public Companies Companies
{
get
{
object o = this["Companies"];
return o as Companies ;
}
}
}
and you must also register your new configuration section in web.config (app.config):
<configuration>
<configSections>
<section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>
then you load your config with
var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
do something ..
}
I'd just like to add a general note of caution.
If all you are doing is getting the current time from the computer's internal clock to put a date/time on the display or a report, then all is well. But if you are saving the date/time information for later reference or are computing date/times, beware!
Let's say you determine that a cruise ship arrived in Honolulu on 20 Dec 2007 at 15:00 UTC. And you want to know what local time that was.
1. There are probably at least three 'locals' involved. Local may mean Honolulu, or it may mean where your computer is located, or it may mean the location where your customer is located.
2. If you use the built-in functions to do the conversion, it will probably be wrong. This is because daylight savings time is (probably) currently in effect on your computer, but was NOT in effect in December. But Windows does not know this... all it has is one flag to determine if daylight savings time is currently in effect. And if it is currently in effect, then it will happily add an hour even to a date in December.
3. Daylight savings time is implemented differently (or not at all) in various political subdivisions. Don't think that just because your country changes on a specific date, that other countries will too.
Here's a function to pretty up your json: pretty_json
Best way to customize Action bar onClickListener is onSupportNavigateUp()
This code will be helpful link for helping code
This could be an alternative to Gustavo Eduardo Belduma's answer:
import datetime
first_day_of_the_month = datetime.date.today().replace(day=1)
Have you tried using the official JQueryUI implementation (not jQuery only) : ?
This is quite simple.
Assuming the data is stored in a column called A in a table called T, you can use
select A, count(A) from T group by A
Since the main
method is static
and the fxn()
method is not, you can't call the method without first creating a Two
object. So either you change the method to:
public static int fxn(int y) {
y = 5;
return y;
}
or change the code in main
to:
Two two = new Two();
x = two.fxn(x);
Read more on static
here in the Java Tutorials.
Try using
Decimal(19,4)
this usually works with every other DB as well