Updated answer
Here is how to change the box model used by the input/textarea/select elements so that they all behave the same way. You need to use the box-sizing
property which is implemented with a prefix for each browser
-ms-box-sizing:content-box;
-moz-box-sizing:content-box;
-webkit-box-sizing:content-box;
box-sizing:content-box;
This means that the 2px difference we mentioned earlier does not exist..
example at http://www.jsfiddle.net/gaby/WaxTS/5/
note: On IE it works from version 8 and upwards..
Original
if you reset their borders then the select
element will always be 2 pixels less than the input
elements..
Any way you mentioned /root/.m2/settings.xml.
But in my Case i missed the settings.xml to configure in the maven preferences. so that maven will search for the relative_path pom.xml from the remote_repository which is configured in settings.xml
Historically, it's been impossible to make these things disappear as they are user settings and not considered part of the page you have control over.
However, as of 2017, the @page
at-rule has been standardized, which can be used to hide the page title and date in modern browsers:
@page { size: auto; margin: 0mm; }
Print headers/footers and print margins
When printing Web documents, margins are set in the browser's Page Setup (or Print Setup) dialog box. These margin settings, although set within the browser, are controlled at the operating system/printer driver level and are not controllable at the HTML/CSS/DOM level. (For CSS-controlled printed page headers and footers see Printing Headers .)
The settings must be big enough to encompass the printer's physical non-printing areas. Further, they must be big enough to encompass the header and footer that the browser is usually configured to print (typically the page title, page number, URL and date). Note that these headers and footers, although specified by the browser and usually configurable through user preferences, are not part of the Web page itself and therefore are not controllable by CSS. In CSS terms, they fall outside the Page Box CSS2.1 Section 13.2.
... i.e. setting a margin of 0 hides the page title because the title is printed in the margin.
Credit to Vigneswaran S for this tip.
In SQL Server Management Studio (SSMS):
You can also right click your database in the Object Explorer and go to Properties. From there, go to Options. Scroll all the way down and set Restrict Access to SINGLE_USER. Change your database name, then go back in and set it back to MULTI_USER.
If you use Spring you can use DataSourceInitializer
:
@Bean
public DataSourceInitializer dataSourceInitializer(@Qualifier("dataSource") final DataSource dataSource) {
ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
resourceDatabasePopulator.addScript(new ClassPathResource("/data.sql"));
DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
dataSourceInitializer.setDataSource(dataSource);
dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);
return dataSourceInitializer;
}
Used to set up a database during initialization and clean up a database during destruction.
You can use format strings as well.
string time = DateTime.Now.ToString("hh:mm:ss"); // includes leading zeros
string date = DateTime.Now.ToString("dd/MM/yy"); // includes leading zeros
or some shortcuts if the format works for you
string time = DateTime.Now.ToShortTimeString();
string date = DateTime.Now.ToShortDateString();
Either should work.
object[,] valueArray = (object[,])excelRange.get_Value(XlRangeValueDataType.xlRangeValueDefault);
//Get the column names
for (int k = 0; k < valueArray.GetLength(1); )
{
//add columns to the data table.
dt.Columns.Add((string)valueArray[1,++k]);
}
//Load data into data table
object[] singleDValue = new object[valueArray.GetLength(1)];
//value array first row contains column names. so loop starts from 1 instead of 0
for (int i = 1; i < valueArray.GetLength(0); i++)
{
Console.WriteLine(valueArray.GetLength(0) + ":" + valueArray.GetLength(1));
for (int k = 0; k < valueArray.GetLength(1); )
{
singleDValue[k] = valueArray[i+1, ++k];
}
dt.LoadDataRow(singleDValue, System.Data.LoadOption.PreserveChanges);
}
let x be an object then you can do it two ways
x.attr_name = s
setattr(x, 'attr_name', s)
I've created library to traverse and edit deep nested JS objects. Check out API here: https://github.com/dominik791
You can also play with the library interactively using demo app: https://dominik791.github.io/obj-traverse-demo/
Examples of usage: You should always have root object which is the first parameter of each method:
var rootObj = {
name: 'rootObject',
children: [
{
'name': 'child1',
children: [ ... ]
},
{
'name': 'child2',
children: [ ... ]
}
]
};
The second parameter is always the name of property that holds nested objects. In above case it would be 'children'
.
The third parameter is an object that you use to find object/objects that you want to find/modify/delete. For example if you're looking for object with id equal to 1, then you will pass { id: 1}
as the third parameter.
And you can:
findFirst(rootObj, 'children', { id: 1 })
to find first object
with id === 1
findAll(rootObj, 'children', { id: 1 })
to find all objects
with id === 1
findAndDeleteFirst(rootObj, 'children', { id: 1 })
to delete first matching objectfindAndDeleteAll(rootObj, 'children', { id: 1 })
to delete all matching objectsreplacementObj
is used as the last parameter in two last methods:
findAndModifyFirst(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'})
to change first found object with id === 1
to the { id: 2, name: 'newObj'}
findAndModifyAll(rootObj, 'children', { id: 1 }, { id: 2, name: 'newObj'})
to change all objects with id === 1
to the { id: 2, name: 'newObj'}
SQLite 3
Using getMetaData();
DatabaseMetaData md = conn.getMetaData();
ResultSet rset = md.getColumns(null, null, "your_table_name", null);
System.out.println("your_table_name");
while (rset.next())
{
System.out.println("\t" + rset.getString(4));
}
EDIT: This works with PostgreSQL as well
Changing the value property does not change the defaultValue
. In the code (retrieved with .html()
or innerHTML
) the value attribute will contain the defaultValue
, not the value property.
You can hide the modal and popup the window to review the carts in validateShipping() function itself.
function validateShipping(){
...
...
$('#product-options').modal('hide');
//pop the window to select items
}
r+
is used for reading, and writing mode. b
is for binary.
r+b
mode is open the binary file in read or write mode.
You can read more here.
@list($url) = explode("?", $url, 2);
If you are using python2.7 or above you can use the ability of assertRaises to be use as a context manager and do:
with self.assertRaises(TypeError):
self.testListNone[:1]
If you are using python2.6 another way beside the one given until now is to use unittest2 which is a back port of unittest new feature to python2.6, and you can make it work using the code above.
N.B: I'm a big fan of the new feature (SkipTest, test discovery ...) of unittest so I intend to use unittest2 as much as I can. I advise to do the same because there is a lot more than what unittest come with in python2.6 <.
NUMBER (precision, scale)
If a precision is not specified, the column stores values as given. If no scale is specified, the scale is zero.
A lot more info at:
http://download.oracle.com/docs/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT1832
In addition to Gilson PJ answer:
new webpack.optimize.CommonsChunkPlugin('common.js'),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.AggressiveMergingPlugin()
with
"scripts": {
"build": "NODE_ENV=production webpack -p --config ./webpack.production.config.js"
},
cause that the it tries to uglify your code twice. See https://webpack.github.io/docs/cli.html#production-shortcut-p for more information.
You can fix this by removing the UglifyJsPlugin from plugins-array or add the OccurrenceOrderPlugin and remove the "-p"-flag. so one possible solution would be
new webpack.optimize.CommonsChunkPlugin('common.js'),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.AggressiveMergingPlugin()
and
"scripts": {
"build": "NODE_ENV=production webpack --config ./webpack.production.config.js"
},
You should use let keyword as to declare local variables e.g *ngFor="let talk of talks"
If anyone is looking to grab the scope off of a 'controller as' element,.. something like this:
<div id="firstctrl" ng-controller="firstCtrl as vm">
use the following:
var vm = angular.element(document.querySelector('#firstctrl')).scope().vm;
I cloned the repository with HTTPS URL instead of SSH URL hence even after adding the SSH Key it was asking me for password on Bash Shell.
I just edited the ./.git/config
file and changed the value of url
variable by simply replacing the https://
to ssh://
E.g.
[core]
...
...
...
[remote "origin"]
url = https://<username>@bitbucket.org/<username>/<repository_name>.git
fetch = +refs/heads/*:refs/remotes/origin/*
...
...
...
Changed to:
[core]
...
...
...
[remote "origin"]
url = ssh://<username>@bitbucket.org/<username>/<repository_name>.git
fetch = +refs/heads/*:refs/remotes/origin/*
...
...
...
I know this is a little old, but for anyone stumbling across this page should know there is a difference between \n and \r\n.
The \r\n gives a CRLF end of line and the \n gives an LF end of line character. There is very little difference to the eye in general.
Create a .txt from the string and then try and open in notepad (normal not notepad++) and you will notice the difference
SHA,PCT,PRACTICE,BNF CODE,BNF NAME,ITEMS,NIC,ACT COST,QUANTITY,PERIOD
Q44,01C,N81002,0101021B0AAALAL,Sod Algin/Pot Bicarb_Susp S/F,3,20.48,19.05,2000,201901
Q44,01C,N81002,0101021B0AAAPAP,Sod Alginate/Pot Bicarb_Tab Chble 500mg,1,3.07,2.86,60,201901
The above is using 'CRLF' and the below is what 'LF only' would look like (There is a character that cant be seen where the LF shows).
SHA,PCT,PRACTICE,BNF CODE,BNF NAME,ITEMS,NIC,ACT COST,QUANTITY,PERIODQ44,01C,N81002,0101021B0AAALAL,Sod Algin/Pot Bicarb_Susp S/F,3,20.48,19.05,2000,201901Q44,01C,N81002,0101021B0AAAPAP,Sod Alginate/Pot Bicarb_Tab Chble 500mg,1,3.07,2.86,60,201901
If the Line Ends need to be corrected and the file is small enough in size, you can change the line endings in NotePad++ (or paste into word then back into Notepad - although this will make CRLF only).
This may cause some functions that read these files to potenitially no longer function (The example lines given are from GP Prescribing data - England. The file has changed from a CRLF Line end to an LF line end). This stopped an SSIS job from running and failed as couldn't read the LF line endings.
Source of Line Ending Information: https://en.wikipedia.org/wiki/Newline#Representations_in_different_character_encoding_specifications
Hope this helps someone in future :) CRLF = Windows based, LF or CF are from Unix based systems (Linux, MacOS etc.)
Another python3 implementation that involves the use of Abstract classes with super(). You should remember that
super().__init__(name, 10)
has the same effect as
Person.__init__(self, name, 10)
Remember there's a hidden 'self' in super(), So the same object passes on to the superclass init method and the attributes are added to the object that called it.
Hence super()
gets translated to Person
and then if you include the hidden self, you get the above code frag.
from abc import ABCMeta, abstractmethod
class Person(metaclass=ABCMeta):
name = ""
age = 0
def __init__(self, personName, personAge):
self.name = personName
self.age = personAge
@abstractmethod
def showName(self):
pass
@abstractmethod
def showAge(self):
pass
class Man(Person):
def __init__(self, name, height):
self.height = height
# Person.__init__(self, name, 10)
super().__init__(name, 10) # same as Person.__init__(self, name, 10)
# basically used to call the superclass init . This is used incase you want to call subclass init
# and then also call superclass's init.
# Since there's a hidden self in the super's parameters, when it's is called,
# the superclasses attributes are a part of the same object that was sent out in the super() method
def showIdentity(self):
return self.name, self.age, self.height
def showName(self):
pass
def showAge(self):
pass
a = Man("piyush", "179")
print(a.showIdentity())
$num = "+918883967576";
$str = substr($num, 3);
echo $str;
Output:8883967576
All the answers above are helpful but none solved my issue. In my production file, my STATIC_URL was https://<URL>/static
and I used the same STATIC_URL in my dev settings.py file.
This causes a silent failure in django/conf/urls/static.py.
The test elif not settings.DEBUG or '://' in prefix:
picks up the '//' in the URL and does not add the static URL pattern, causing no static files to be found.
It would be thoughtful if Django spit out an error message stating you can't use a http(s)://
with DEBUG = True
I had to change STATIC_URL to be '/static/'
I was getting this error too, although my issue was that I kept switching between two corporate networks via my Virtual Machine, with different access credentials. I had to run the command prompt:
ipconfig /renew
After this my network issues were resolved and I could connect once again to SQL.
Here's a simple and working method I found elsewhere:
string hexString = "7FF";
int hexNumber;
sscanf(hexString.c_str(), "%x", &hexNumber);
Please note that you might prefer using unsigned long integer/long integer, to receive the value. Another note, the c_str() function just converts the std::string to const char* .
So if you have a const char* ready, just go ahead with using that variable name directly, as shown below [I am also showing the usage of the unsigned long variable for a larger hex number. Do not confuse it with the case of having const char* instead of string]:
const char *hexString = "7FFEA5"; //Just to show the conversion of a bigger hex number
unsigned long hexNumber; //In case your hex number is going to be sufficiently big.
sscanf(hexString, "%x", &hexNumber);
This works just perfectly fine (provided you use appropriate data types per your need).
Your best option is through PHP: All version requests from the client side cannot be trusted since your Apache could be configured with ServerTokens Prod and ServerSignature Off. See: http://www.petefreitag.com/item/419.cfm
Here's a simple way to test it:
public class OperatorTest {
public static void main(String[] args) {
boolean a = false;
a &= b();
}
private static boolean b() {
System.out.println("b() was called");
return true;
}
}
The output is b() was called
, therefore the right-hand operand is evaluated.
So, as already mentioned by others, a &= b
is the same as a = a & b
.
This is the syntax you need:
CASE WHEN countries LIKE '%'+@selCountry+'%' THEN 'national' ELSE 'regional' END
Although, as per your original problem, I'd solve it differently, splitting the content of @selcountry int a table form and joining to it.
If there is anyone like me who is experiencing this issue using Vue.js,
simply adding .prevent will do the trick: @click.prevent="someAction"
Microsoft now has this:
https://github.com/Microsoft/VisualStudioUninstaller/releases
I allowed a windows 10 update to go through that completely f****d VS2015 so I am trying this before having to resort to a rebuild. WT*. :-(
If you want to count the number of records in your table, simply run:
SELECT COUNT(*) FROM your_table;
Paolo Bergantino's answer has the great advantage of only using the stdlib, and works for this simple example where there are no decorator arguments nor decorated function arguments.
However it has 3 major limitations if you want to tackle more general cases:
makestyle(style='bold')
decorator is non-trivial.@functools.wraps
do not preserve the signature, so if bad arguments are provided they will start executing, and might raise a different kind of error than the usual TypeError
.@functools.wraps
to access an argument based on its name. Indeed the argument can appear in *args
, in **kwargs
, or may not appear at all (if it is optional).I wrote decopatch
to solve the first issue, and wrote makefun.wraps
to solve the other two. Note that makefun
leverages the same trick than the famous decorator
lib.
This is how you would create a decorator with arguments, returning truly signature-preserving wrappers:
from decopatch import function_decorator, DECORATED
from makefun import wraps
@function_decorator
def makestyle(st='b', fn=DECORATED):
open_tag = "<%s>" % st
close_tag = "</%s>" % st
@wraps(fn)
def wrapped(*args, **kwargs):
return open_tag + fn(*args, **kwargs) + close_tag
return wrapped
decopatch
provides you with two other development styles that hide or show the various python concepts, depending on your preferences. The most compact style is the following:
from decopatch import function_decorator, WRAPPED, F_ARGS, F_KWARGS
@function_decorator
def makestyle(st='b', fn=WRAPPED, f_args=F_ARGS, f_kwargs=F_KWARGS):
open_tag = "<%s>" % st
close_tag = "</%s>" % st
return open_tag + fn(*f_args, **f_kwargs) + close_tag
In both cases you can check that the decorator works as expected:
@makestyle
@makestyle('i')
def hello(who):
return "hello %s" % who
assert hello('world') == '<b><i>hello world</i></b>'
Please refer to the documentation for details.
ES6
Arrow functions:In javascript the =>
is the symbol of an arrow function expression. A arrow function expression does not have its own this
binding and therefore cannot be used as a constructor function. for example:
var words = 'hi from outside object';_x000D_
_x000D_
let obj = {_x000D_
words: 'hi from inside object',_x000D_
talk1: () => {console.log(this.words)},_x000D_
talk2: function () {console.log(this.words)}_x000D_
}_x000D_
_x000D_
obj.talk1(); // doesn't have its own this binding, this === window_x000D_
obj.talk2(); // does have its own this binding, this is obj
_x000D_
{}
and the return
statementFor example:
let times2 = val => val * 2; _x000D_
// It is on the same line and returns an expression therefore the {} are ommited and the expression returns implictly_x000D_
// there also is only one argument, therefore the parentheses around the argument are omitted_x000D_
_x000D_
console.log(times2(3));
_x000D_
You have to convert the response to JSON using Gson.toJson(object)
.
For example:
return Response.status(Status.OK).entity(new Gson().toJson(Student)).build();
regarding AlexB's post:
\' Apostrophe or single quote
\" Double quote
escaping single quotes is only valid in single quoted json strings
escaping double quotes is only valid in double quoted json strings
example:
'Bart\'s car' -> valid
'Bart says \"Hi\"' -> invalid
If you're using mod_php, you can use apache_get_modules()
. This will return an array of all enabled modules, so to check if mod_rewrite
is enabled, you could simply do
in_array('mod_rewrite', apache_get_modules());
Unfortunately, you're most likely trying to do this with CGI, which makes it a little bit more difficult.
You can test it using the following, though
strpos(shell_exec('/usr/local/apache/bin/apachectl -l'), 'mod_rewrite') !== false
If the above condition evaluates to true
, then mod_write
is enabled.
If the 2nd company is happy for you to access their content in an IFrame then they need to take the restriction off - they can do this fairly easily in the IIS config.
There's nothing you can do to circumvent it and anything that does work should get patched quickly in a security hotfix. You can't tell the browser to just render the frame if the source content header says not allowed in frames. That would make it easier for session hijacking.
If the content is GET only you don't post data back then you could get the page server side and proxy the content without the header, but then any post back should get invalidated.
We have a Guava class for this: com.google.common.net.MediaType
.
It was released with Guava 12 as stated in the source code and in Issue 823. Sources are available, too.
Here is the way I got that:
@Component
public class ApplicationStartup implements ApplicationListener<ApplicationReadyEvent> {
/**
* This event is executed as late as conceivably possible to indicate that
* the application is ready to service requests.
*/
@Autowired
private MovieRepositoryImpl movieRepository;
@Override
public void onApplicationEvent(final ApplicationReadyEvent event) {
seedData();
}
private void seedData() {
movieRepository.save(new Movie("Example"));
// ... add more code
}
}
Thanks to the author of this article:
http://blog.netgloo.com/2014/11/13/run-code-at-spring-boot-startup/
If you want to unit test code then you need to isolate your code you want to test (in this case your service) from external resources (e.g. databases). You could probably do this with some sort of in-memory EF provider, however a much more common way is to abstract away your EF implementation e.g. with some sort of repository pattern. Without this isolation any tests you write will be integration tests, not unit tests.
As for testing EF code - I write automated integration tests for my repositories that write various rows to the database during their initialization, and then call my repository implementations to make sure that they behave as expected (e.g. making sure that results are filtered correctly, or that they are sorted in the correct order).
These are integration tests not unit tests, as the tests rely on having a database connection present, and that the target database already has the latest up-to-date schema installed.
Yeah, no checkbox for you in iOS (-:
Here, this is what I did to create a checkbox:
UIButton *checkbox;
BOOL checkBoxSelected;
checkbox = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
// 20x20 is the size of the checkbox that you want
// create 2 images sizes 20x20 , one empty square and
// another of the same square with the checkmark in it
// Create 2 UIImages with these new images, then:
[checkbox setBackgroundImage:[UIImage imageNamed:@"notselectedcheckbox.png"]
forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted=YES;
[checkbox addTarget:(nullable id) action:(nonnull SEL) forControlEvents:(UIControlEvents)];
[self.view addSubview:checkbox];
Now in the target method do the following:
-(void)checkboxSelected:(id)sender
{
checkBoxSelected = !checkBoxSelected; /* Toggle */
[checkbox setSelected:checkBoxSelected];
}
That's it!
let documentsURL = try! FileManager().url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true)
... gives you a file URL of the documents directory. The following checks if there's a file named foo.html:
let fooURL = documentsURL.appendingPathComponent("foo.html")
let fileExists = FileManager().fileExists(atPath: fooURL.path)
NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString* foofile = [documentsPath stringByAppendingPathComponent:@"foo.html"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];
"Unable to load the requested file"
Can be also caused by access permissions under linux , make sure you set the correct read permissions for the directory "views/home"
Be careful when iterating over arrays!!
It is a common misconception that using the index of the element in the array is an acceptable way of suppressing the error you are probably familiar with:
Each child in an array should have a unique "key" prop.
However, in many cases it is not! This is anti-pattern that can in some situations lead to unwanted behavior.
key
propReact uses the key
prop to understand the component-to-DOM Element relation, which is then used for the reconciliation process. It is therefore very important that the key always remains unique, otherwise there is a good chance React will mix up the elements and mutate the incorrect one. It is also important that these keys remain static throughout all re-renders in order to maintain best performance.
That being said, one does not always need to apply the above, provided it is known that the array is completely static. However, applying best practices is encouraged whenever possible.
A React developer said in this GitHub issue:
- key is not really about performance, it's more about identity (which in turn leads to better performance). randomly assigned and changing values are not identity
- We can't realistically provide keys [automatically] without knowing how your data is modeled. I would suggest maybe using some sort of hashing function if you don't have ids
- We already have internal keys when we use arrays, but they are the index in the array. When you insert a new element, those keys are wrong.
In short, a key
should be:
key
propAs per the explanation above, carefully study the following samples and try to implement, when possible, the recommended approach.
<tbody>
{rows.map((row, i) => {
return <ObjectRow key={i} />;
})}
</tbody>
This is arguably the most common mistake seen when iterating over an array in React. This approach isn't technically "wrong", it's just... "dangerous" if you don't know what you are doing. If you are iterating through a static array then this is a perfectly valid approach (e.g. an array of links in your navigation menu). However, if you are adding, removing, reordering or filtering items, then you need to be careful. Take a look at this detailed explanation in the official documentation.
class MyApp extends React.Component {
constructor() {
super();
this.state = {
arr: ["Item 1"]
}
}
click = () => {
this.setState({
arr: ['Item ' + (this.state.arr.length+1)].concat(this.state.arr),
});
}
render() {
return(
<div>
<button onClick={this.click}>Add</button>
<ul>
{this.state.arr.map(
(item, i) => <Item key={i} text={"Item " + i}>{item + " "}</Item>
)}
</ul>
</div>
);
}
}
const Item = (props) => {
return (
<li>
<label>{props.children}</label>
<input value={props.text} />
</li>
);
}
ReactDOM.render(<MyApp />, document.getElementById("app"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
_x000D_
In this snippet we are using a non-static array and we are not restricting ourselves to using it as a stack. This is an unsafe approach (you'll see why). Note how as we add items to the beginning of the array (basically unshift), the value for each <input>
remains in place. Why? Because the key
doesn't uniquely identify each item.
In other words, at first Item 1
has key={0}
. When we add the second item, the top item becomes Item 2
, followed by Item 1
as the second item. However, now Item 1
has key={1}
and not key={0}
anymore. Instead, Item 2
now has key={0}
!!
As such, React thinks the <input>
elements have not changed, because the Item
with key 0
is always at the top!
So why is this approach only sometimes bad?
This approach is only risky if the array is somehow filtered, rearranged, or items are added/removed. If it is always static, then it's perfectly safe to use. For example, a navigation menu like ["Home", "Products", "Contact us"]
can safely be iterated through with this method because you'll probably never add new links or rearrange them.
In short, here's when you can safely use the index as key
:
Had we instead, in the snippet above, pushed the added item to the end of the array, the order for each existing item would always be correct.
<tbody>
{rows.map((row) => {
return <ObjectRow key={Math.random()} />;
})}
</tbody>
While this approach will probably guarantee uniqueness of the keys, it will always force react to re-render each item in the list, even when this is not required. This a very bad solution as it greatly impacts performance. Not to mention that one cannot exclude the possibility of a key collision in the event that Math.random()
produces the same number twice.
Unstable keys (like those produced by
Math.random()
) will cause many component instances and DOM nodes to be unnecessarily recreated, which can cause performance degradation and lost state in child components.
<tbody>
{rows.map((row) => {
return <ObjectRow key={row.uniqueId} />;
})}
</tbody>
This is arguably the best approach because it uses a property that is unique for each item in the dataset. For example, if rows
contains data fetched from a database, one could use the table's Primary Key (which typically is an auto-incrementing number).
The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys
componentWillMount() {
let rows = this.props.rows.map(item => {
return {uid: SomeLibrary.generateUniqueID(), value: item};
});
}
...
<tbody>
{rows.map((row) => {
return <ObjectRow key={row.uid} />;
})}
</tbody>
This is also a good approach. If your dataset does not contain any data that guarantees uniqueness (e.g. an array of arbitrary numbers), there is a chance of a key collision. In such cases, it is best to manually generate a unique identifier for each item in the dataset before iterating over it. Preferably when mounting the component or when the dataset is received (e.g. from props
or from an async API call), in order to do this only once, and not each time the component re-renders. There are already a handful of libraries out there that can provide you such keys. Here is one example: react-key-index.
this is probably a late answer but i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializer
will have to inject it to your controller
so you can simply do the following without having to use Jquery at all ,
$http.post(url,$httpParamSerializer({param:val}))
app.controller('ctrl',function($scope,$http,$httpParamSerializer){
$http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}
require section This section contains the packages/dependencies which are better candidates to be installed/required in the production environment.
require-dev section: This section contains the packages/dependencies which can be used by the developer to test her code (or to experiment on her local machine and she doesn't want these packages to be installed on the production environment).
Here is a bare bones version:
Let's say that you have a date in Cell A1 in the format you described. For example: 19760210
.
Then this formula will give you the date you want:
=DATE(LEFT(A1,4),MID(A1,5,2),RIGHT(A1,2)).
On my system (Excel 2010) it works with strings or floats.
Here's the best answer, and the easiest! Put an extra password field in front of your input
field and set the display:none
, so that when the browser fills it in, it does it in an input
that you don't care about.
Change this:
<input type="password" name="password" size="25" class="input" id="password" value="">
to this:
<input type="password" style="display:none;">
<input type="password" name="password" size="25" class="input" id="password" value="">
Try this:
>>> import time
>>> time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(1347517119))
'2012-09-12 23:18:39'
Also in MySQL, you can FROM_UNIXTIME
like:
INSERT INTO tblname VALUES (FROM_UNIXTIME(1347517119))
For your 2nd question, it is probably because getbbb_class.end_time
is a string. You can convert it to numeric like: float(getbbb_class.end_time)
Just download minimum prefered SDK from SDK Manager, then build. Works for me.
You're looking for dir to return the directory contents.
To loop over the results, you can simply do the following:
dirlist = dir('.');
for i = 1:length(dirlist)
dirlist(i)
end
This should give you output in the following format, e.g.:
name: 'my_file'
date: '01-Jan-2010 12:00:00'
bytes: 56
isdir: 0
datenum: []
yes please download curl-devel as instructed above. also don't forget to link to lib curl:
-L/path/of/curl/lib/libcurl.a (g++)
cheers
I'm assuming you mean that you don't care which row is used to obtain the title
, id
, and commentname
values (you have "rob" for all of the rows, but I don't know if that is actually something that would be enforced or not in your data model). If so, then you can use windowing functions to return the first row for a given email address:
select
id,
title,
email,
commentname
from
(
select
*,
row_number() over (partition by email order by id) as RowNbr
from YourTable
) source
where RowNbr = 1
It works for 5.7.8:
mysql> create table t1(updated datetime NOT NULL DEFAULT '0000-00-00 00:00:00');
Query OK, 0 rows affected (0.01 sec)
mysql> show create table t1;
+-------+-------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+-------+-------------------------------------------------------------------------------------------------------------------------+
| t1 | CREATE TABLE `t1` (
`updated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 |
+-------+-------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> select version();
+-----------+
| version() |
+-----------+
| 5.7.8-rc |
+-----------+
1 row in set (0.00 sec)
You can create a SQLFiddle to recreate your issue.
If it works for MySQL 5.6 and 5.7.8, but fails on 5.7.11. Then it probably is a regression bug for 5.7.11.
Yes in SQl <> is the same as != which is not equal.....excepts for NULLS of course, in that case you need to use IS NULL or IS NOT NULL
The code you wrote will always return true
because state
cannot be both 10 and 15 for the statement to be false. if ((state != 10) && (state != 15)....
AND
is what you need not OR
.
Use $.inArray instead. This returns the index of the element in the array.
var statesArray = [10, 15, 19]; // list out all
var index = $.inArray(state, statesArray);
if(index == -1) {
console.log("Not there in array");
return true;
} else {
console.log("Found it");
return false;
}
Try this one
$('<div></div>').appendTo('body')
.html('<div><h6>Yes or No?</h6></div>')
.dialog({
modal: true, title: 'message', zIndex: 10000, autoOpen: true,
width: 'auto', resizable: false,
buttons: {
Yes: function () {
doFunctionForYes();
$(this).dialog("close");
},
No: function () {
doFunctionForNo();
$(this).dialog("close");
}
},
close: function (event, ui) {
$(this).remove();
}
});
This is Working for me
$().popover({container: 'body'})
This example will exit after 5 seconds if another instance is already running.
// unique id for global mutex - Global prefix means it is global to the machine
const string mutex_id = "Global\\{B1E7934A-F688-417f-8FCB-65C3985E9E27}";
static void Main(string[] args)
{
using (var mutex = new Mutex(false, mutex_id))
{
try
{
try
{
if (!mutex.WaitOne(TimeSpan.FromSeconds(5), false))
{
Console.WriteLine("Another instance of this program is running");
Environment.Exit(0);
}
}
catch (AbandonedMutexException)
{
// Log the fact the mutex was abandoned in another process, it will still get aquired
}
// Perform your work here.
}
finally
{
mutex.ReleaseMutex();
}
}
}
first you can do with this style:
mda="/usr/mda"
if [ ! -L "${mda}" ]; then
echo "=> File doesn't exist"
fi
if you want to do it in more advanced style you can write it like below:
#!/bin/bash
mda="$1"
if [ -e "$1" ]; then
if [ ! -L "$1" ]
then
echo "you entry is not symlink"
else
echo "your entry is symlink"
fi
else
echo "=> File doesn't exist"
fi
the result of above is like:
root@linux:~# ./sym.sh /etc/passwd
you entry is not symlink
root@linux:~# ./sym.sh /usr/mda
your entry is symlink
root@linux:~# ./sym.sh
=> File doesn't exist
|
is a metacharacter in regex. You'd need to escape it:
String[] value_split = rat_values.split("\\|");
You can find the symlinks by looking for files that have a mode of 120000
, possibly with this command:
git ls-files -s | awk '/120000/{print $4}'
Once you replace the links, I would recommend marking them as unchanged with git update-index --assume-unchanged
, rather than listing them in .git/info/exclude
.
Keep in mind the second parameter to @Html.HiddenFor will only be used to set the value when it can't find route or model data matching the field. Darin is correct, use view model.
What the OP wants to do, is delete additional properties in his Google analytics. Properties that are not his but belong to someone else.
Apparently, the only way to do this, is to contact the owner of that website who is the administrator, and asked them to remove you.
Or you can just create a new Google account, and add your properties to the new account.
None of these are real good solutions. Thank you Google for caring so much about SEO people.
To add insult to injury, if you go over 25 accounts, you must contact Google to get permission to add another.
Lesson learned: Do not add other peoples websites to your Google analytics account. Create a separate account so that if you have to start over, you don't lose any data from your websites. It's also good to have more than one Google analytics account.
run
gradle clean
then try
gradle build
it worked for me
Try this:
update table YourTable
set YourField = substring(YourField, 5, len(YourField)-3);
Instead of a List<UserRole>
, you can let your Model contain a SelectList<UserRole>
. Also add a property SelectedUserRoleId
to store... well... the selected UserRole's Id value.
Fill up the SelectList, then in your View use:
@Html.DropDownListFor(x => x.SelectedUserRoleId, x.UserRole)
and you should be fine.
See also http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist(v=vs.108).aspx.
The most important difference will be the clarity of your code. Yes, yes, what's been said above is true, but [[ ]] brings your code in line with what you would expect in high level languages, especially in regards to AND (&&), OR (||), and NOT (!) operators. Thus, when you move between systems and languages you will be able to interpret script faster which makes your life easier. Get the nitty gritty from a good UNIX/Linux reference. You may find some of the nitty gritty to be useful in certain circumstances, but you will always appreciate clear code! Which script fragment would you rather read? Even out of context, the first choice is easier to read and understand.
if [[ -d $newDir && -n $(echo $newDir | grep "^${webRootParent}") && -n $(echo $newDir | grep '/$') ]]; then ...
or
if [ -d "$newDir" -a -n "$(echo "$newDir" | grep "^${webRootParent}")" -a -n "$(echo "$newDir" | grep '/$')" ]; then ...
Font myFont = new Font ("Courier New", 1, 17);
The 17 represents the font size. Once you have that, you can put:
g.setFont (myFont);
g.drawString ("Hello World", 10, 10);
Remove the FormsModule from Declaration:[] and Add the FormsModule in imports:[]
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
ddList.Items.FindByText("oldValue").Selected = false;
ddList.Items.FindByText("newValue").Selected = true;
Alternatively, you can use jinfo
jinfo -flags <vmid>
jinfo -sysprops <vmid>
Check this out. The author provides a simple but elegant solution which doesn't require any 3rd party library. http://www.ksmpartners.com/2013/08/nicely-formatted-tabular-output-in-java/
Here is a link from developer.nokia.com wiki pages, which explains how to install Windows Phone 8 SDK on a Virtual Machine with Working Emulator
And another link here
AFAIK, it is not possible to directly install WP8 SDK in Windows 7, because WP8 sdk is VS 2012 supported and also its emulator works on a Hyper-V (which is integrated into the Windows 8).
Run Power-shell as administrator.
then run this command
Set-ExecutionPolicy Unrestricted
Use with CAUTION
Easier if the input is a string, we can use split()
decimal = input("Input decimal number: ") #123.456
# split 123.456 by dot = ['123', '456']
after_coma = decimal.split('.')[1]
# because only index 1 is taken then '456'
print(after_coma) # '456'
if you want to make a number type print(int(after_coma)) # 456
To read the result you can read it like a simple php array.
For example, getting the name
can be done like $user['name']
, and so on. The method fetch(PDO::FETCH_ASSOC)
will only return 1 tuple tho. If you want to get all tuples, you can use fetchall(PDO::FETCH_ASSOC)
. You can go through the multidimensional array and get the values just the same.
Found a great solution at https://bitsofco.de/styling-broken-images/
img { _x000D_
position: relative;_x000D_
}_x000D_
_x000D_
/* style this to fit your needs */_x000D_
/* and remove [alt] to apply to all images*/_x000D_
img[alt]:after { _x000D_
display: block;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background-color: #fff;_x000D_
font-family: 'Helvetica';_x000D_
font-weight: 300;_x000D_
line-height: 2; _x000D_
text-align: center;_x000D_
content: attr(alt);_x000D_
}
_x000D_
<img src="error">_x000D_
<br>_x000D_
<img src="broken" alt="A broken image">_x000D_
<br>_x000D_
<img src="https://images-na.ssl-images-amazon.com/images/I/218eLEn0fuL.png" alt="A bird" style="width: 120px">
_x000D_
As per Angular2 final, you do not even have to import FORM_DIRECTIVES
as suggested above by many. However, the syntax has been changed as kebab-case was dropped for the betterment.
Just replace ng-model
with ngModel
and wrap it in a box of bananas. But you have spilt the code into two files now:
app.ts:
import { Component } from '@angular/core';
@Component({
selector: 'ng-app',
template: `
<input id="name" type="text" [(ngModel)]="name" />
{{ name }}
`
})
export class DataBindingComponent {
name: string;
constructor() {
this.name = 'Jose';
}
}
app.module.ts:
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { DataBindingComponent } from './app'; //app.ts above
@NgModule({
declarations: [DataBindingComponent],
imports: [BrowserModule, FormsModule],
bootstrap: [DataBindingComponent]
})
export default class MyAppModule {}
platformBrowserDynamic().bootstrapModule(MyAppModule);
The two alternative you gave are semantically identical, but using make([]int, 0)
will result in an internal call to runtime.makeslice (Go 1.14).
You also have the option to leave it with a nil
value:
var myslice []int
As written in the Golang.org blog:
a nil slice is functionally equivalent to a zero-length slice, even though it points to nothing. It has length zero and can be appended to, with allocation.
A nil
slice will however json.Marshal()
into "null"
whereas an empty slice will marshal into "[]"
, as pointed out by @farwayer.
None of the above options will cause any allocation, as pointed out by @ArmanOrdookhani.
import os
os.mkdir('directory name') #### this command for creating directory
os.mknod('file name') #### this for creating files
os.system('touch filename') ###this is another method for creating file by using unix commands in os modules
NSArray* foo = [@"10/04/2011" componentsSeparatedByString: @"/"];
NSString* firstBit = [foo objectAtIndex: 0];
Update 7/3/2018:
Now that the question has acquired a Swift tag, I should add the Swift way of doing this. It's pretty much as simple:
let substrings = "10/04/2011".split(separator: "/")
let firstBit = substrings[0]
Although note that it gives you an array of Substring
. If you need to convert these back to ordinary strings, use map
let strings = "10/04/2011".split(separator: "/").map{ String($0) }
let firstBit = strings[0]
or
let firstBit = String(substrings[0])
Like many before pointed out you shall add
compile files('libs/gson-2.2.3.jar')
to your build.gradle file.
However I have a project in Android Studio that was migrated from Eclipse and in this case the "libs" folder is named "lib" so for me removing the "s" solved the problem.
Try this, at the end of the each loop, ids array will contain all the hexcodes.
var ids = [];
$(document).ready(function($) {
var $div = $("<div id='hexCodes'></div>").appendTo(document.body), code;
$(".color_cell").each(function() {
code = $(this).attr('id');
ids.push(code);
$div.append(code + "<br />");
});
});
Your format string is wrong. Change it to
insert = DateTime.ParseExact(line[i], "M/d/yyyy hh:mm", CultureInfo.InvariantCulture);
As mentioned above, BOOL is a signed char. bool - type from C99 standard (int).
BOOL - YES/NO. bool - true/false.
See examples:
bool b1 = 2;
if (b1) printf("REAL b1 \n");
if (b1 != true) printf("NOT REAL b1 \n");
BOOL b2 = 2;
if (b2) printf("REAL b2 \n");
if (b2 != YES) printf("NOT REAL b2 \n");
And result is
REAL b1
REAL b2
NOT REAL b2
Note that bool != BOOL. Result below is only ONCE AGAIN - REAL b2
b2 = b1;
if (b2) printf("ONCE AGAIN - REAL b2 \n");
if (b2 != true) printf("ONCE AGAIN - NOT REAL b2 \n");
If you want to convert bool to BOOL you should use next code
BOOL b22 = b1 ? YES : NO; //and back - bool b11 = b2 ? true : false;
So, in our case:
BOOL b22 = b1 ? 2 : NO;
if (b22) printf("ONCE AGAIN MORE - REAL b22 \n");
if (b22 != YES) printf("ONCE AGAIN MORE- NOT REAL b22 \n");
And so.. what we get now? :-)
String [] obj = (from c in db.Contacts
where c.FirstName.StartsWith(prefixText)
select c.FirstName).ToArray();
return obj;
StartsWith() and EndsWith() can help you a lot here. If you want to find data in between the field, then Contains() can be used.
I think you want SELECT * FROM INFORMATION_SCHEMA.TABLES
See http://dev.mysql.com/doc/refman/5.0/en/tables-table.html
You don't need a counter for back presses.
Just store a reference to the toast that is shown:
private Toast backtoast;
Then,
public void onBackPressed() {
if(USER_IS_GOING_TO_EXIT) {
if(backtoast!=null&&backtoast.getView().getWindowToken()!=null) {
finish();
} else {
backtoast = Toast.makeText(this, "Press back to exit", Toast.LENGTH_SHORT);
backtoast.show();
}
} else {
//other stuff...
super.onBackPressed();
}
}
This will call finish()
if you press back while the toast is still visible, and only if the back press would result in exiting the application.
This is a very round-about way of doing it but if you want to make a histogram where you already know the bin values but dont have the source data, you can use the np.random.randint
function to generate the correct number of values within the range of each bin for the hist function to graph, for example:
import numpy as np
import matplotlib.pyplot as plt
data = [np.random.randint(0, 9, *desired y value*), np.random.randint(10, 19, *desired y value*), etc..]
plt.hist(data, histtype='stepfilled', bins=[0, 10, etc..])
as for labels you can align x ticks with bins to get something like this:
#The following will align labels to the center of each bar with bin intervals of 10
plt.xticks([5, 15, etc.. ], ['Label 1', 'Label 2', etc.. ])
From the fine manual.
You must own the table to use ALTER TABLE.
Or be a database superuser.
ERROR: must be owner of relation contact
PostgreSQL error messages are usually spot on. This one is spot on.
you have to put this in web.config :
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000" />
</webServices>
</scripting>
</system.web.extensions>
I fixed mine by closing eclipse and deleting the whole .metadata folder inside my workspace folder.
Well, despite the fact that you asked that we not "simply" link to other resources, it's pretty foolish when there already exists a community grown (and growing) resource that's really quite good: the Git Community Book. Seriously, this 20+ questions in a question is going to be anything but concise and consistent. The Git Community Book is available as both HTML and PDF and answers many of your questions with clear, well formatted and peer reviewed answers and in a format that allows you to jump straight to your problem at hand.
Alas, if my post really upsets you then I'll delete it. Just say so.
Or just use old-school DOM methods when JQ has a monkey in the middle somewhere.
var myElement = $('#my_element')[0];
var myElClass = myElement.getAttribute('class').split(/\s+/g);
//splits class into an array based on 1+ white space characters
myElClass.push('new_class');
myElement.setAttribute('class', myElClass.join(' '));
//$(myElement) to return to JQ wrapper-land
Learn the DOM people. Even in 2016's framework-palooza it helps quite regularly. Also, if you ever hear someone compare the DOM to assembly, kick them for me.
PHP runs on the server and Javascript runs on the client, so you can't set a PHP variable to equal a Javascript variable without sending the value to the server. You can, however, set a Javascript variable to equal a PHP variable:
<script type="text/javascript">
var foo = '<?php echo $foo ?>';
</script>
To send a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible):
var variableToSend = 'foo';
$.post('file.php', {variable: variableToSend});
On your server, you would need to receive the variable sent in the post:
$variable = $_POST['variable'];
You can use this QString constructor for conversion from QByteArray to QString:
QString(const QByteArray &ba)
QByteArray data;
QString DataAsString = QString(data);
Make sure you have the Visual C++ Redistributable package installed on your machine.
The copy
command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.
Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).
I tried a variation of your command as follows in SQL*Plus (with no errors):
copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;
After I executed the above statement, I also truncate the new_emp table and executed this command:
copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;
With SQL Developer, you could do the following to perform a similar approach to copying objects:
On the tool bar, select Tools>Database copy.
Identify source and destination connections with the copy options you would like.
For object type, select table(s).
The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).
If using webdriverJs (node.js),
driver.findElement(webdriver.By.name('btnCalculate')).click().then(function() {
driver.sleep(5000);
});
The code above makes browser wait for 5 seconds after clicking the button.
df = data.frame(matrix("", ncol = 3, nrow = 10)
This is a direct conversion from your PHP code:
//Loading the variable
var mystr = '0000000020C90037:TEMP:data';
//Splitting it with : as the separator
var myarr = mystr.split(":");
//Then read the values from the array where 0 is the first
//Since we skipped the first element in the array, we start at 1
var myvar = myarr[1] + ":" + myarr[2];
// Show the resulting value
console.log(myvar);
// 'TEMP:data'
Yes it is correct. you can do it with an inner class.
This is not an answer to your original question: "Appending output of a Batch file To log file?"
For reference, it's an answer to your followup question: "What lines should i add to my batch file which will make it execute after every 30mins?"
(But I would take Jon Skeet's advice: "You probably shouldn't do that in your batch file - instead, use Task Scheduler.")
Timeout:
Example (1 second):
TIMEOUT /T 1000 /NOBREAK
Sleep:
Example (1 second):
sleep -m 1000
Alternative methods:
Here's an answer to your 2nd followup question: "Along with the Timestamp?"
Create a date and time stamp in your batch files
Example:
echo *** Date: %DATE:/=-% and Time:%TIME::=-% *** >> output.log
Are you trying to view an array with memory allocated dynamically? If not, you can view an array for C++ and C# by putting it in the watch window in the debugger, with its contents visible when you expand the array on the little (+) in the watch window by a left mouse-click.
If it's a pointer to a dynamically allocated array, to view N contents of the pointer, type "pointer, N" in the watch window of the debugger. Note, N must be an integer or the debugger will give you an error saying it can't access the contents. Then, left click on the little (+) icon that appears to view the contents.
I am reading the Pro ASP.NET MVC 4 book as well, and ran into the same problem you were having. For me, I started having the problem after making the changes prescribed in the 'Adding Model Validation' section of the book. The way I resolved the problem is by moving my database from the localdb to the full-blown SQL Server 2012 server. (BTW, I know that I am lucky I could switch to the full-blown version, so don't hate me. ;-))) There must be something with the communication to the db that is causing the problem.
setting the overflow
should take care of it, but you need to set the height of Content
also. If the height attribute is not set, the div will grow vertically as tall as it needs to, and scrollbars wont be needed.
See Example: http://jsfiddle.net/ftkbL/1/
Unfortunately, MySQL doesn't support DEFAULT
parameter values, so:
CREATE PROCEDURE `blah`
(
myDefaultParam int DEFAULT 0
)
BEGIN
-- Do something here
END
returns the error:
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to use
near 'DEFAULT 0) BEGIN END' at line 3
To work around this limitation, simply create additional procedures that assign default values to the original procedure:
DELIMITER //
DROP PROCEDURE IF EXISTS blah//
DROP PROCEDURE IF EXISTS blah2//
DROP PROCEDURE IF EXISTS blah1//
DROP PROCEDURE IF EXISTS blah0//
CREATE PROCEDURE blah(param1 INT UNSIGNED, param2 INT UNSIGNED)
BEGIN
SELECT param1, param2;
END;
//
CREATE PROCEDURE blah2(param1 INT UNSIGNED, param2 INT UNSIGNED)
BEGIN
CALL blah(param1, param2);
END;
//
CREATE PROCEDURE blah1(param1 INT UNSIGNED)
BEGIN
CALL blah2(param1, 3);
END;
//
CREATE PROCEDURE blah0()
BEGIN
CALL blah1(4);
END;
//
Then, running this:
CALL blah(1, 1);
CALL blah2(2, 2);
CALL blah1(3);
CALL blah0();
will return:
+--------+--------+
| param1 | param2 |
+--------+--------+
| 1 | 1 |
+--------+--------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
+--------+--------+
| param1 | param2 |
+--------+--------+
| 2 | 2 |
+--------+--------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
+--------+--------+
| param1 | param2 |
+--------+--------+
| 3 | 3 |
+--------+--------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
+--------+--------+
| param1 | param2 |
+--------+--------+
| 4 | 3 |
+--------+--------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
Then, if you make sure to only use the blah2()
, blah1()
and blah0()
procedures, your code will not need to be immediately updated, when you add a third parameter to the blah()
procedure.
I am also new to MVC and I received the same error and found that it is not passing proper routeValues
in the Index
view or whatever view is present to view the all data.
It was as below
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
I changed it to the as show below and started to work properly.
<td>
@Html.ActionLink("Edit", "Edit", new { EmployeeID=item.EmployeeID }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
Basically this error can also come because of improper navigation also.
Just wrote a class to compute smallest (not to be taken literally) number of edits to transform one string into another string:
http://www.raymondhill.net/finediff/
It has a static function to render a HTML version of the diff.
It's a first version, and likely to be improved, but it works just fine as of now, so I am throwing it out there in case someone needs to generate a compact diff efficiently, like I needed.
Edit: It's on Github now: https://github.com/gorhill/PHP-FineDiff
Ok, finally found the solution.
Probably due to lack of experience with ReactJS and web development...
var Task = React.createClass({
render: function() {
var percentage = this.props.children + '%';
....
<div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
...
I created the percentage variable outside in the render function.
It also works without jQuery if you do the following changes:
Add type="button"
to the edit button in order not to trigger submission of the form.
Change the name of your function from change()
to anything else.
Don't use hidden="hidden"
, use CSS instead: style="display: none;"
.
The following code works for me:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="STYLESHEET" type="text/css" href="dba_style/buttons.css" />
<title>Untitled Document</title>
</head>
<script type="text/javascript">
function do_change(){
document.getElementById("save").style.display = "block";
document.getElementById("change").style.display = "block";
document.getElementById("cancel").style.display = "block";
}
</script>
<body>
<form name="form1" method="post" action="">
<div class="buttons">
<button type="button" class="regular" name="edit" id="edit" onclick="do_change(); return false;">
<img src="dba_images/textfield_key.png" alt=""/>
Edit
</button>
<button type="submit" class="positive" name="save" id="save" style="display:none;">
<img src="dba_images/apply2.png" alt=""/>
Save
</button>
<button class="regular" name="change" id="change" style="display:none;">
<img src="dba_images/textfield_key.png" alt=""/>
change
</button>
<button class="negative" name="cancel" id="cancel" style="display:none;">
<img src="dba_images/cross.png" alt=""/>
Cancel
</button>
</div>
</form>
</body>
</html>
This worked for me:
start /d IEXPLORE.EXE www.google.com
start /d IEXPLORE.EXE www.yahoo.com
But for some reason opened them up in Firefox instead?!?
I tried this but it merely opened up sites in two different windows:
start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.google.com
start /d "C:\Program Files\Internet Explorer" IEXPLORE.EXE www.yahoo.com
Just pass the list to np.array
:
a = np.array(a)
You can also take this opportunity to set the dtype
if the default is not what you desire.
a = np.array(a, dtype=...)
strstr(request, "favicon") != NULL
You also encounter this if you run an Application on a Scheduled Task in Non-Interactive mode.
As soon as you show a Dialog it throws the error:
Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation. Specify the ServiceNotification or DefaultDesktopOnly style to display a notification from a service application.
You can see its a MessageBox causing the problem in the stack trace:
at System.Windows.Forms.MessageBox.ShowCore(IWin32Window owner, String text, String caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, MessageBoxOptions options, Boolean showHelp)
If you're running your app on a Scheduled Task send an email instead of showing a Dialog.
You can use the relationLoaded method on the model object. This saved my bacon so hopefully it helps someone else. I was given this suggestion when I asked the same question on Laracasts.
With lodash, you can create new object like this _.set:
obj = _.set({}, key, val);
Or you can set to existing object like this:
var existingObj = { a: 1 };
_.set(existingObj, 'a', 5); // existingObj will be: { a: 5 }
You should take care if you want to use dot (".") in your path, because lodash can set hierarchy, for example:
_.set({}, "a.b.c", "d"); // { "a": { "b": { "c": "d" } } }
You can create an array with all elements from a given Swift
Set
simply with
let array = Array(someSet)
This works because Set
conforms to the SequenceType
protocol
and an Array
can be initialized with a sequence. Example:
let mySet = Set(["a", "b", "a"]) // Set<String>
let myArray = Array(mySet) // Array<String>
print(myArray) // [b, a]
Apart from tuples being immutable there is also a semantic distinction that should guide their usage. Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences. Tuples have structure, lists have order.
Using this distinction makes code more explicit and understandable.
One example would be pairs of page and line number to reference locations in a book, e.g.:
my_location = (42, 11) # page number, line number
You can then use this as a key in a dictionary to store notes on locations. A list on the other hand could be used to store multiple locations. Naturally one might want to add or remove locations from the list, so it makes sense that lists are mutable. On the other hand it doesn't make sense to add or remove items from an existing location - hence tuples are immutable.
There might be situations where you want to change items within an existing location tuple, for example when iterating through the lines of a page. But tuple immutability forces you to create a new location tuple for each new value. This seems inconvenient on the face of it, but using immutable data like this is a cornerstone of value types and functional programming techniques, which can have substantial advantages.
There are some interesting articles on this issue, e.g. "Python Tuples are Not Just Constant Lists" or "Understanding tuples vs. lists in Python". The official Python documentation also mentions this
"Tuples are immutable, and usually contain an heterogeneous sequence ...".
In a statically typed language like Haskell the values in a tuple generally have different types and the length of the tuple must be fixed. In a list the values all have the same type and the length is not fixed. So the difference is very obvious.
Finally there is the namedtuple in Python, which makes sense because a tuple is already supposed to have structure. This underlines the idea that tuples are a light-weight alternative to classes and instances.
SQL Server
To list all the user defined tables of a database:
use [databasename]
select name from sysobjects where type = 'u'
To list all the columns of a table:
use [databasename]
select name from syscolumns where id=object_id('tablename')
You have to mark the single letter as optional too:
([A-Z]{1})? +.*? +
or make the whole part optional
(([A-Z]{1}) +.*? +)?
here is a ruby implementation:
It will catalog by attribute name or the result of a method call.
CatalogGenerator = ->(depth) do
if depth != 0
->(hash, key) do
hash[key] = Hash.new(&CatalogGenerator[depth - 1])
end
else
->(hash, key) do
hash[key] = []
end
end
end
def catalog(collection, root_name: :root, by:)
method_names = [*by]
log = Hash.new(&CatalogGenerator[method_names.length])
tree = collection.each_with_object(log) do |item, catalog|
path = method_names.map { |method_name| item.public_send(method_name)}.unshift(root_name.to_sym)
catalog.dig(*path) << item
end
tree.with_indifferent_access
end
students = [#<Student:0x007f891d0b4818 id: 33999, status: "on_hold", tenant_id: 95>,
#<Student:0x007f891d0b4570 id: 7635, status: "on_hold", tenant_id: 6>,
#<Student:0x007f891d0b42c8 id: 37220, status: "on_hold", tenant_id: 6>,
#<Student:0x007f891d0b4020 id: 3444, status: "ready_for_match", tenant_id: 15>,
#<Student:0x007f8931d5ab58 id: 25166, status: "in_partnership", tenant_id: 10>]
catalog students, by: [:tenant_id, :status]
# this would out put the following
{"root"=>
{95=>
{"on_hold"=>
[#<Student:0x007f891d0b4818
id: 33999,
status: "on_hold",
tenant_id: 95>]},
6=>
{"on_hold"=>
[#<Student:0x007f891d0b4570 id: 7635, status: "on_hold", tenant_id: 6>,
#<Student:0x007f891d0b42c8
id: 37220,
status: "on_hold",
tenant_id: 6>]},
15=>
{"ready_for_match"=>
[#<Student:0x007f891d0b4020
id: 3444,
status: "ready_for_match",
tenant_id: 15>]},
10=>
{"in_partnership"=>
[#<Student:0x007f8931d5ab58
id: 25166,
status: "in_partnership",
tenant_id: 10>]}}}
There's a nice article which may answer your question /only it prints the paths instead of collecting them/. Please note that you can experiment with the C++/Python samples in the online IDE.
http://www.geeksforgeeks.org/find-paths-given-source-destination/
You can't use AJAX to fetch files from the user machine. This is absolutely the wrong way to go about it.
Use the FileReader API:
<input type="file" id="file input">
js:
console.log(document.getElementById("file input").files); // list of File objects
var file = document.getElementById("file input").files[0];
var reader = new FileReader();
content = reader.readAsText(file);
console.log(content);
Then parse content
as CSV. Keep in mind that your parser currently does not deal with escaped values in CSV like: value1,value2,"value 3","value ""4"""
since your ant file's name is build.xml, you should just type ant without ant build.xml.
that is: > ant
[enter]
It depends on the type of the arguments...
For integer arguments, the single ampersand ("&")is the "bit-wise AND" operator. The double ampersand ("&&") is not defined for anything but two boolean arguments.
For boolean arguments, the single ampersand constitutes the (unconditional) "logical AND" operator while the double ampersand ("&&") is the "conditional logical AND" operator. That is to say that the single ampersand always evaluates both arguments whereas the double ampersand will only evaluate the second argument if the first argument is true.
For all other argument types and combinations, a compile-time error should occur.
Note: Your question is about escaping, not encoding. Escaping is using <, etc. to allow the parser to distinguish between "this is an XML command" and "this is some text". Encoding is the stuff you specify in the XML header (UTF-8, ISO-8859-1, etc).
First of all, like everyone else said, use an XML library. XML looks simple but the encoding+escaping stuff is dark voodoo (which you'll notice as soon as you encounter umlauts and Japanese and other weird stuff like "full width digits" (&#FF11; is 1)). Keeping XML human readable is a Sisyphus' task.
I suggest never to try to be clever about text encoding and escaping in XML. But don't let that stop you from trying; just remember when it bites you (and it will).
That said, if you use only UTF-8, to make things more readable you can consider this strategy:
<![CDATA[ ... ]]>
I'm using this in an SQL editor and it allows the developers to cut&paste SQL from a third party SQL tool into the XML without worrying about escaping. This works because the SQL can't contain umlauts in our case, so I'm safe.
for play 2.5.x
Step 1: Stop the netty server (if it is running) using control + D
Step 2: go to sbt-dist/conf
Step 3: edit this file 'sbtConfig.txt' with this
-Dhttp.port=9005
Step 4: Start the server
Step 5: http://host:9005/
Just run the below two lines when you want to exit from the application
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
You can use typeof(N)
to get the actual object type, but what you want to do is check the tag, not the type of the DOM element.
In that case, use the elem.tagName
or elem.nodeName
property.
if you want to get really creative, you can use a dictionary of tagnames and anonymous closures instead if a switch or if/else.
This is the suggested Matplotlib 3 solution from the official website HERE:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
ax = plt.subplot(111)
ax.plot(x, y)
# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
plt.show()
Therefore, I would like to separate the string by the furthest delimiter.
I know this is an old question, but this is a simple requirement for which SUBSTR and INSTR would suffice. REGEXP are still slower and CPU intensive operations than the old subtsr and instr functions.
SQL> WITH DATA AS
2 ( SELECT 'F/P/O' str FROM dual
3 )
4 SELECT SUBSTR(str, 1, Instr(str, '/', -1, 1) -1) part1,
5 SUBSTR(str, Instr(str, '/', -1, 1) +1) part2
6 FROM DATA
7 /
PART1 PART2
----- -----
F/P O
As you said you want the furthest delimiter, it would mean the first delimiter from the reverse.
You approach was fine, but you were missing the start_position in INSTR. If the start_position is negative, the INSTR
function counts back start_position number of characters from the end of string and then searches towards the beginning of string.
This has been mentioned in earlier comments but I would like to clarify that there are multiple ways to access the auth routes in your web.php file in Laravel ^5.7. depending on your version it might look a little different but they achieve the same result.
First option
Route::auth([
'register' => false, // Registration Routes...
'reset' => false, // Password Reset Routes...
'verify' => false, // Email Verification Routes...
]);
Second option
Auth::routes([
'register' => false, // Registration Routes...
'reset' => false, // Password Reset Routes...
'verify' => false, // Email Verification Routes...
]);
CPython (the classic and prevalent implementation of Python) can't have more than one thread executing Python bytecode at the same time. This means compute-bound programs will only use one core. I/O operations and computing happening inside C extensions (such as numpy) can operate simultaneously.
Other implementation of Python (such as Jython or PyPy) may behave differently, I'm less clear on their details.
The usual recommendation is to use many processes rather than many threads.
my sample code
wv = (WebView) findViewById(R.id.mywebview);
wv.getLayoutParams().height = LayoutParams.MATCH_PARENT; // LayoutParams: android.view.ViewGroup.LayoutParams
// wv.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
wv.requestLayout();//It is necesary to refresh the screen
PrintWriter out = null; // for writting in file
String newLine = System.getProperty("line.separator"); // taking new line
out.print("1st Line"+newLine); // print with new line
out.print("2n Line"+newLine); // print with new line
out.close();
That's a good problem. In order to solve that problem you will also have to disable ASLR otherwise the address of g() will be unpredictable.
Disable ASLR:
sudo bash -c 'echo 0 > /proc/sys/kernel/randomize_va_space'
Disable canaries:
gcc overflow.c -o overflow -fno-stack-protector
After canaries and ASLR are disabled it should be a straight forward attack like the ones described in Smashing the Stack for Fun and Profit
Here is a list of security features used in ubuntu: https://wiki.ubuntu.com/Security/Features You don't have to worry about NX bits, the address of g() will always be in a executable region of memory because it is within the TEXT memory segment. NX bits only come into play if you are trying to execute shellcode on the stack or heap, which is not required for this assignment.
Now go and clobber that EIP!
1. another odd testing function
Ok, the assignment was handed in 8+ years ago, but here is another solution based on bit shifting operations:
def isodd(i):
return(bool(i>>0&1))
testing gives:
>>> isodd(2)
False
>>> isodd(3)
True
>>> isodd(4)
False
2. Nearest Odd number alternative approach
However, instead of a code that says "give me this precise input (an integer odd number) or otherwise I won't do anything" I also like robust codes that say, "give me a number, any number, and I'll give you the nearest pyramid to that number".
In that case this function is helpful, and gives you the nearest odd (e.g. any number f such that 6<=f<8 is set to 7 and so on.)
def nearodd(f):
return int(f/2)*2+1
Example output:
nearodd(4.9)
5
nearodd(7.2)
7
nearodd(8)
9
Just downloaded the latest mysqlworkbench which is compatible with the latest encryption:
https://downloads.mysql.com/archives/workbench/
Note: On Mac big Sur, the latest two versions: 8.0.22 and 8.0.23 are buggy and do not work.
Use 8.0.21 until these are fixed
In addition to @canvastag, use a while
loop with shift
I think is more concise:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var poly = [5, 5, 100, 50, 50, 100, 10, 90];
// copy array
var shape = poly.slice(0);
ctx.fillStyle = '#f00'
ctx.beginPath();
ctx.moveTo(shape.shift(), shape.shift());
while(shape.length) {
ctx.lineTo(shape.shift(), shape.shift());
}
ctx.closePath();
ctx.fill();
d = {0: 'zero', '0': 'ZERO', 1: 'one', '1': 'ONE'}
print("List of enumerated d= ", list(enumerate(d.items())))
output:
List of enumerated d= [(0, (0, 'zero')), (1, ('0', 'ZERO')), (2, (1, 'one')), (3, ('1', 'ONE'))]
It is not possible to return an array from a C++ function. 8.3.5[dcl.fct]/6:
Functions shall not have a return type of type array or function[...]
Most commonly chosen alternatives are to return a value of class type where that class contains an array, e.g.
struct ArrayHolder
{
int array[10];
};
ArrayHolder test();
Or to return a pointer to the first element of a statically or dynamically allocated array, the documentation must indicate to the user whether he needs to (and if so how he should) deallocate the array that the returned pointer points to.
E.g.
int* test2()
{
return new int[10];
}
int* test3()
{
static int array[10];
return array;
}
While it is possible to return a reference or a pointer to an array, it's exceedingly rare as it is a more complex syntax with no practical advantage over any of the above methods.
int (&test4())[10]
{
static int array[10];
return array;
}
int (*test5())[10]
{
static int array[10];
return &array;
}
Not sure if there is an easier way in 2008 version.
USE [Database Name]
SELECT COLUMN_NAME,*
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'YourTableName' AND TABLE_SCHEMA='YourSchemaName'
I was facing this error while running Karma Unit Test cases Adding MatSelectModule in the imports fixes the issue
imports: [
HttpClientTestingModule,
FormsModule,
MatTableModule,
MatSelectModule,
NoopAnimationsModule
],
The first argument to a shell script is available as the variable $1
, so the simplest implementation would be
if [ "$1" == "-h" ]; then
echo "Usage: `basename $0` [somestuff]"
exit 0
fi
But what anubhava said.
An easy solution is use the property zoom
:
input[type="checkbox"] {_x000D_
zoom: 1.5;_x000D_
}
_x000D_
<input type="checkbox" />
_x000D_
Month.FEBRUARY.getValue() // February ? 2.
2
The Answer by Jon Skeet is correct.
Now we have a modern replacement for those troublesome old legacy date-time classes: the java.time classes.
java.time.Month
Among those classes is the Month
enum. An enum carries one or more predefined objects, objects that are automatically instantiated when the class loads. On Month
we have a dozen such objects, each given a name: JANUARY
, FEBRUARY
, MARCH
, and so on. Each of those is a static final public
class constant. You can use and pass these objects anywhere in your code. Example: someMethod( Month.AUGUST )
Fortunately, they have sane numbering, 1-12 where 1 is January and 12 is December.
Get a Month
object for a particular month number (1-12).
Month month = Month.of( 2 ); // 2 ? February.
Going the other direction, ask a Month
object for its month number.
int monthNumber = Month.FEBRUARY.getValue(); // February ? 2.
Many other handy methods on this class, such as knowing the number of days in each month. The class can even generate a localized name of the month.
You can get the localized name of the month, in various lengths or abbreviations.
String output =
Month.FEBRUARY.getDisplayName(
TextStyle.FULL ,
Locale.CANADA_FRENCH
);
février
Also, you should pass objects of this enum around your code base rather than mere integer numbers. Doing so provides type-safety, ensures a valid range of values, and makes your code more self-documenting. See Oracle Tutorial if unfamiliar with the surprisingly powerful enum facility in Java.
You also may find useful the Year
and YearMonth
classes.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
You can use FontAwesome "content" values and apply as follow by css. These apply "chevron right/left" icons.
.custom-slick .slick-prev:before {
content: "?";
font-family: 'FontAwesome';
font-size: 22px;
}
.custom-slick .slick-next:before {
content: "?";
font-family: 'FontAwesome';
font-size: 22px;
}
mine was DispatchQueue.main.sync inside the closer I made it DispatchQueue.main.async and it worked.
You work like with a standard block, that is a square
.circle {
width: 10em; height: 10em;
-webkit-border-radius: 5em; -moz-border-radius: 5em;
}
This is feature of CSS 3 and it is not very well suporrted, you can count on firefox and safari for sure.
<div class="circle"><span>1234</span></div>
I hope this would be helpful:
.top_image img{
display: block;
margin: 0 auto;
}
Do this:
function changeHeight() { document.getElementById('chartdiv').style.height = "200px" } <button type="button" onClick="changeHeight();"> Click Me!</button>
Depending on whether your php setup allows fopen on URLs, you could also simply fopen the url with the get arguments in the string (such as http://example.com?variable=value )
Edit: Re-reading the question I'm not certain whether you're looking to pass variables or not - if you're not you can simply send the fopen request containg http://example.com/filename.xml - feel free to ignore the variable=value part
As the comments mentioned, Go doesn't support ternary one liners. The shortest form I can think of is this:
var c int
if c = b; a > b {
c = a
}
But please don't do that, it's not worth it and will only confuse people who read your code.
No need to apologize for asking a question! Try using the RIGHT
function. It returns the last n characters of a string.
=RIGHT(A1, 1)
I had a similar problem, looking for grep/pattern regex and the "matched pattern found" as output.
At the end I used egrep (same regex on grep -e or -G didn't give me the same result of egrep) with the option -o
so, I think that could be something similar to (I'm NOT a regex Master) :
egrep -o "the*|this{1}|thoroughly{1}" filename
This has worked for me:
let webApiUrl = 'example.com/getStuff';
let tokenStr = 'xxyyzz';
axios.get(webApiUrl, { headers: {"Authorization" : `Bearer ${tokenStr}`} });
There are a few ways to get all unique combinations of a set of factors.
with(df, interaction(yad, per, drop=TRUE)) # gives labels
with(df, yad:per) # ditto
aggregate(numeric(nrow(df)), df[c("yad", "per")], length) # gives a data frame
STATIC_DEPS=true easy_install lxml
Recently I was trying to detect the home press button, because I needed it to do the same as the method "onBackPressed()". In order to do this, I had to override the method "onSupportNavigateUp()" like this:
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
It worked perfectly. =)
Well, nothing of the above answer worked for me. After a lot of research, I found a solution. Though I may be late this may help others in future.
Login to your SQL server from a terminal
mysql -u root -p
-- root password
GRANT ALL ON *.* to root@'XX.XXX.XXX.XX' IDENTIFIED BY 'password';
This should solve the permission issue.
Happy coding!!
Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:
<Style TargetType="{x:Type TabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid>
<Border Name="Border" Margin="0,0,0,0" Background="Transparent"
BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
<ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
HorizontalAlignment="Center"
ContentSource="Header" Margin="12,2,12,2"
RecognizesAccessKey="True">
<ContentPresenter.LayoutTransform>
<RotateTransform Angle="270" />
</ContentPresenter.LayoutTransform>
</ContentPresenter>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Panel.ZIndex" Value="100" />
<Setter TargetName="Border" Property="Background" Value="Red" />
<Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="Background" Value="DarkRed" />
<Setter TargetName="Border" Property="BorderBrush" Value="Black" />
<Setter Property="Foreground" Value="DarkGray" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
If you are a Windows user and you are using conda to manage the environment in Anaconda prompt, you can do the following:
Make sure you deactivate the virtual environment or restart Anaconda Prompt. Use the following command to remove virtual environment:
$ conda env remove --name $MyEnvironmentName
Alternatively, you can go to the
C:\Users\USERNAME\AppData\Local\Continuum\anaconda3\envs\MYENVIRONMENTNAME
(that's the default file path) and delete the folder manually.
Lookarounds are zero width assertions. They check for a regex (towards right or left of the current position - based on ahead or behind), succeeds or fails when a match is found (based on if it is positive or negative) and discards the matched portion. They don't consume any character - the matching for regex following them (if any), will start at the same cursor position.
Read regular-expression.info for more details.
Syntax:
(?=REGEX_1)REGEX_2
Match only if REGEX_1 matches; after matching REGEX_1, the match is discarded and searching for REGEX_2 starts at the same position.
example:
(?=[a-z0-9]{4}$)[a-z]{1,2}[0-9]{2,3}
REGEX_1 is [a-z0-9]{4}$
which matches four alphanumeric chars followed by end of line.
REGEX_2 is [a-z]{1,2}[0-9]{2,3}
which matches one or two letters followed by two or three digits.
REGEX_1 makes sure that the length of string is indeed 4, but doesn't consume any characters so that search for REGEX_2 starts at the same location. Now REGEX_2 makes sure that the string matches some other rules. Without look-ahead it would match strings of length three or five.
Syntax:
(?!REGEX_1)REGEX_2
Match only if REGEX_1 does not match; after checking REGEX_1, the search for REGEX_2 starts at the same position.
example:
(?!.*\bFWORD\b)\w{10,30}$
The look-ahead part checks for the FWORD
in the string and fails if it finds it. If it doesn't find FWORD
, the look-ahead succeeds and the following part verifies that the string's length is between 10 and 30 and that it contains only word characters a-zA-Z0-9_
Look-behind is similar to look-ahead: it just looks behind the current cursor position. Some regex flavors like javascript doesn't support look-behind assertions. And most flavors that support it (PHP, Python etc) require that look-behind portion to have a fixed length.
If you are using Python > 3.x
you don't need to install any libraries, this is directly built in the python framework. The old urllib2
package has been renamed to urllib
:
from urllib import request
response = request.urlopen("https://www.google.com")
# set the correct charset below
page_source = response.read().decode('utf-8')
print(page_source)
It may not be running.
try runnign /etc/init.d/asterisk status
If its not running, Start it using:
/etc/init.d/asterisk start
Or in RH 7:
Systemctl start asterisk
Implementation in Go
Encode part (server -> browser)
func encode (message string) (result []byte) {
rawBytes := []byte(message)
var idxData int
length := byte(len(rawBytes))
if len(rawBytes) <= 125 { //one byte to store data length
result = make([]byte, len(rawBytes) + 2)
result[1] = length
idxData = 2
} else if len(rawBytes) >= 126 && len(rawBytes) <= 65535 { //two bytes to store data length
result = make([]byte, len(rawBytes) + 4)
result[1] = 126 //extra storage needed
result[2] = ( length >> 8 ) & 255
result[3] = ( length ) & 255
idxData = 4
} else {
result = make([]byte, len(rawBytes) + 10)
result[1] = 127
result[2] = ( length >> 56 ) & 255
result[3] = ( length >> 48 ) & 255
result[4] = ( length >> 40 ) & 255
result[5] = ( length >> 32 ) & 255
result[6] = ( length >> 24 ) & 255
result[7] = ( length >> 16 ) & 255
result[8] = ( length >> 8 ) & 255
result[9] = ( length ) & 255
idxData = 10
}
result[0] = 129 //only text is supported
// put raw data at the correct index
for i, b := range rawBytes {
result[idxData + i] = b
}
return
}
Decode part (browser -> server)
func decode (rawBytes []byte) string {
var idxMask int
if rawBytes[1] == 126 {
idxMask = 4
} else if rawBytes[1] == 127 {
idxMask = 10
} else {
idxMask = 2
}
masks := rawBytes[idxMask:idxMask + 4]
data := rawBytes[idxMask + 4:len(rawBytes)]
decoded := make([]byte, len(rawBytes) - idxMask + 4)
for i, b := range data {
decoded[i] = b ^ masks[i % 4]
}
return string(decoded)
}
<% %>
Executes the ruby code within the brackets.
<%= %>
Prints something into erb file.
<%== %>
Equivalent to <%= raw %>
. Prints something verbatim (i.e. w/o escaping) into erb file. (Taken from Ruby on Rails Guides.)
<% -%>
Avoids line break after expression.
<%# %>
Comments out code within brackets; not sent to client (as opposed to HTML comments).
Visit Ruby Doc for more infos about ERB.
I know this thread is too old but recently I was wondering how to delete eclipse
app on my MacBook Pro
running macOS High Sierra
.
Bellow are the steps which I followed to delete it from my system. Added screenshots for more clear understanding.
Open the eclipse app and it will show an app icon in dock. If it is not already present in dock then please try to run the app from Spotlight Search
by pressing ?
+ space
.
Now right click on that eclipse logo from dock and click Show in Finder
under Options
.
eclipse
app in an external finder window.eclipse
) by pressing ?
+ delete
.Trash
as well if you are removing it from system completely.Thanks. Hope this helped.
I ran into this problem as well, it ended up that I had two postgres servers running at the same time. I uninstalled one of them and changed the port back to 5432 and works fine now.
based on accepted answer
$output = some_function();
echo $output;
if it results array then use json_encode it will result json array which is supportable by javascript
$output = some_function();
echo json_encode($output);
If someone wants to stop execution after you echo some result use exit method of php. It will work like return keyword
$output = some_function();
echo $output;
exit;
If you follow the steps advised in several tutorials I linked in this answer, you can get the desired effect without the somewhat complicated "manual" steps in Walker's and Vinay's answers. If you're on Ubuntu:
sudo apt-get install python-pip python-dev
The equivalent is achieved in OS X by using homebrew to install python (more details here).
brew install python
With pip
installed, you can use it to get the remaining packages (you can omit sudo
in OS X, as you're using your local python installation).
sudo pip install virtualenvwrapper
(these are the only packages you need installed globally and I doubt that it will clash with anything system-level from the OS. If you want to be super-safe, you can keep the distro's versions sudo apt-get install virtualenvwrapper
)
Note: in Ubuntu 14.04 I receive some errors with pip install, so I use pip3 install virtualenv virtualenvwrapper
and add VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
to my .bashrc/.zshrc
file.
You then append to your .bashrc
file
export WORKON_HOME
source /usr/local/bin/virtualenvwrapper.sh
and source it
. ~/.bashrc
This is basically it. Now the only decision is whether you want to create a virtualenv to include system-level packages
mkvirtualenv --system-site-packages foo
where your existing system packages don't have to be reinstalled, they are symlinked to the system interpreter's versions. Note: you can still install new packages and upgrade existing included-from-system packages without sudo - I tested it and it works without any disruptions of the system interpreter.
kermit@hocus-pocus:~$ sudo apt-get install python-pandas
kermit@hocus-pocus:~$ mkvirtualenv --system-site-packages s
(s)kermit@hocus-pocus:~$ pip install --upgrade pandas
(s)kermit@hocus-pocus:~$ python -c "import pandas; print(pandas.__version__)"
0.10.1
(s)kermit@hocus-pocus:~$ deactivate
kermit@hocus-pocus:~$ python -c "import pandas; print(pandas.__version__)"
0.8.0
The alternative, if you want a completely separated environment, is
mkvirtualenv --no-site-packages bar
or given that this is the default option, simply
mkvirtualenv bar
The result is that you have a new virtualenv where you can freely and sudolessly install your favourite packages
pip install flask
So some days I lack brain cells and:
<android.support.v7.widget.SwitchCompat
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/CustomSwitchStyle"/>
does not apply the theme because style is incorrect. I was supposed to use app:theme :P
<android.support.v7.widget.SwitchCompat
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:theme="@style/CustomSwitchStyle"/>
Whoopsies. This post was what gave me insight into my mistake...hopefully if someone stumbles across this it will help them like it did me. Thank you Gaëtan Maisse for your answer
The R file can't be generated if your layout contains errors. If your res
folder is empty, then it's safe to assume that there's no res/layout
folder with any layouts in it, but your activity is probably calling setContentView
and not finding anything -- that qualifies as a problem with your layout.
Well I would do it like this instead:
TimeSpan diff = expiryDate - DateTime.Today;
if (diff.Days > 30)
matchFound = true;
Compare only responds with an integer indicating weather the first is earlier, same or later...
If you have an Activity
object hanging around, you can use the isDestroyed()
method:
Activity activity;
// ...
if (!activity.isDestroyed()) {
// ...
}
This is nice if you have a non-anonymous AsyncTask
subclass that you use in various places.
What moves origin/HEAD "organically"?
git clone
sets it once to the spot where HEAD is on origin
git clone
What does HEAD on origin represent?
git clone
uses it in such a wayWhat sets origin/HEAD?
git clone
fetches and sets itgit fetch
updates it like any other reference, but it doesn’tgit remote set-head origin -a
fetches and sets it
Trivia
origin/HEAD
can also be set to any other value without contacting the remote: git remote set-head origin <branch>
Very easy no need create class extends LocationListener 1- Variable
private LocationManager mLocationManager;
private LocationListener mLocationListener;
private static double currentLat =0;
private static double currentLon =0;
2- onStartService()
@Override public void onStartService() {
addListenerLocation();
}
3- Method addListenerLocation()
private void addListenerLocation() {
mLocationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
currentLat = location.getLatitude();
currentLon = location.getLongitude();
Toast.makeText(getBaseContext(),currentLat+"-"+currentLon, Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
Location lastKnownLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(lastKnownLocation!=null){
currentLat = lastKnownLocation.getLatitude();
currentLon = lastKnownLocation.getLongitude();
}
}
@Override
public void onProviderDisabled(String provider) {
}
};
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 500, 10, mLocationListener);
}
4- onDestroy()
@Override
public void onDestroy() {
super.onDestroy();
mLocationManager.removeUpdates(mLocationListener);
}
Try using this instead:
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
It's bit hard to navigate Google's api but here is the relevant documentation.
One thing I had trouble finding was how to go in the other direction. From coordinates to an address. Here is the code I neded upp using. Please not that I also use jquery.
$.each(results[0].address_components, function(){
$("#CreateDialog").find('input[name="'+ this.types+'"]').attr('value', this.long_name);
});
What I'm doing is to loop through all the returned address_components
and test if their types match any input element names I have in a form. And if they do I set the value of the element to the address_components
value.
If you're only interrested in the whole formated address then you can follow Google's example
Take a look at this page on implementing graphs in python.
You could also take a look at pygraphlib on sourceforge.
public static function slugify ($text) {
$replace = [
'<' => '', '>' => '', ''' => '', '&' => '',
'"' => '', 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä'=> 'Ae',
'Ä' => 'A', 'Å' => 'A', 'A' => 'A', 'A' => 'A', 'A' => 'A', 'Æ' => 'Ae',
'Ç' => 'C', 'C' => 'C', 'C' => 'C', 'C' => 'C', 'C' => 'C', 'D' => 'D', 'Ð' => 'D',
'Ð' => 'D', 'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'E' => 'E',
'E' => 'E', 'E' => 'E', 'E' => 'E', 'E' => 'E', 'G' => 'G', 'G' => 'G',
'G' => 'G', 'G' => 'G', 'H' => 'H', 'H' => 'H', 'Ì' => 'I', 'Í' => 'I',
'Î' => 'I', 'Ï' => 'I', 'I' => 'I', 'I' => 'I', 'I' => 'I', 'I' => 'I',
'I' => 'I', '?' => 'IJ', 'J' => 'J', 'K' => 'K', 'L' => 'K', 'L' => 'K',
'L' => 'K', 'L' => 'K', '?' => 'K', 'Ñ' => 'N', 'N' => 'N', 'N' => 'N',
'N' => 'N', '?' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O',
'Ö' => 'Oe', 'Ö' => 'Oe', 'Ø' => 'O', 'O' => 'O', 'O' => 'O', 'O' => 'O',
'Œ' => 'OE', 'R' => 'R', 'R' => 'R', 'R' => 'R', 'S' => 'S', 'Š' => 'S',
'S' => 'S', 'S' => 'S', '?' => 'S', 'T' => 'T', 'T' => 'T', 'T' => 'T',
'?' => 'T', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'Ue', 'U' => 'U',
'Ü' => 'Ue', 'U' => 'U', 'U' => 'U', 'U' => 'U', 'U' => 'U', 'U' => 'U',
'W' => 'W', 'Ý' => 'Y', 'Y' => 'Y', 'Ÿ' => 'Y', 'Z' => 'Z', 'Ž' => 'Z',
'Z' => 'Z', 'Þ' => 'T', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a',
'ä' => 'ae', 'ä' => 'ae', 'å' => 'a', 'a' => 'a', 'a' => 'a', 'a' => 'a',
'æ' => 'ae', 'ç' => 'c', 'c' => 'c', 'c' => 'c', 'c' => 'c', 'c' => 'c',
'd' => 'd', 'd' => 'd', 'ð' => 'd', 'è' => 'e', 'é' => 'e', 'ê' => 'e',
'ë' => 'e', 'e' => 'e', 'e' => 'e', 'e' => 'e', 'e' => 'e', 'e' => 'e',
'ƒ' => 'f', 'g' => 'g', 'g' => 'g', 'g' => 'g', 'g' => 'g', 'h' => 'h',
'h' => 'h', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'i' => 'i',
'i' => 'i', 'i' => 'i', 'i' => 'i', 'i' => 'i', '?' => 'ij', 'j' => 'j',
'k' => 'k', '?' => 'k', 'l' => 'l', 'l' => 'l', 'l' => 'l', 'l' => 'l',
'?' => 'l', 'ñ' => 'n', 'n' => 'n', 'n' => 'n', 'n' => 'n', '?' => 'n',
'?' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'oe',
'ö' => 'oe', 'ø' => 'o', 'o' => 'o', 'o' => 'o', 'o' => 'o', 'œ' => 'oe',
'r' => 'r', 'r' => 'r', 'r' => 'r', 'š' => 's', 'ù' => 'u', 'ú' => 'u',
'û' => 'u', 'ü' => 'ue', 'u' => 'u', 'ü' => 'ue', 'u' => 'u', 'u' => 'u',
'u' => 'u', 'u' => 'u', 'u' => 'u', 'w' => 'w', 'ý' => 'y', 'ÿ' => 'y',
'y' => 'y', 'ž' => 'z', 'z' => 'z', 'z' => 'z', 'þ' => 't', 'ß' => 'ss',
'?' => 'ss', '??' => 'iy', '?' => 'A', '?' => 'B', '?' => 'V', '?' => 'G',
'?' => 'D', '?' => 'E', '?' => 'YO', '?' => 'ZH', '?' => 'Z', '?' => 'I',
'?' => 'Y', '?' => 'K', '?' => 'L', '?' => 'M', '?' => 'N', '?' => 'O',
'?' => 'P', '?' => 'R', '?' => 'S', '?' => 'T', '?' => 'U', '?' => 'F',
'?' => 'H', '?' => 'C', '?' => 'CH', '?' => 'SH', '?' => 'SCH', '?' => '',
'?' => 'Y', '?' => '', '?' => 'E', '?' => 'YU', '?' => 'YA', '?' => 'a',
'?' => 'b', '?' => 'v', '?' => 'g', '?' => 'd', '?' => 'e', '?' => 'yo',
'?' => 'zh', '?' => 'z', '?' => 'i', '?' => 'y', '?' => 'k', '?' => 'l',
'?' => 'm', '?' => 'n', '?' => 'o', '?' => 'p', '?' => 'r', '?' => 's',
'?' => 't', '?' => 'u', '?' => 'f', '?' => 'h', '?' => 'c', '?' => 'ch',
'?' => 'sh', '?' => 'sch', '?' => '', '?' => 'y', '?' => '', '?' => 'e',
'?' => 'yu', '?' => 'ya'
];
// make a human readable string
$text = strtr($text, $replace);
// replace non letter or digits by -
$text = preg_replace('~[^\\pL\d.]+~u', '-', $text);
// trim
$text = trim($text, '-');
// remove unwanted characters
$text = preg_replace('~[^-\w.]+~', '', $text);
$text = strtolower($text);
return $text;
}
Action: Start a Program
Program/script: C:\Windows\System32\cmd.exe
Add arguments: /k start "" "E:\scripts\example.bat"
Add exit
to the end of your batch file.
The cmd window will not show if you select Run whether user is logged in or not
. You need to select Run only when user is logged on
to see the window in action.
If you want to take a component class as a parameter (vs an instance), use React.ComponentClass
:
function renderGreeting(Elem: React.ComponentClass<any>) {
return <span>Hello, <Elem />!</span>;
}
String
is present in package java.lang
which is imported by default in all java programs.
Something like this:
$.getJSON("http://mywebsite.com/json/get.php?cid=15",
function(data){
$.each(data.products, function(i,product){
content = '<p>' + product.product_title + '</p>';
content += '<p>' + product.product_short_description + '</p>';
content += '<img src="' + product.product_thumbnail_src + '"/>';
content += '<br/>';
$(content).appendTo("#product_list");
});
});
Would take a json object made from a PHP array returned with the key of products. e.g:
Array('products' => Array(0 => Array('product_title' => 'Product 1',
'product_short_description' => 'Product 1 is a useful product',
'product_thumbnail_src' => '/images/15/1.jpg'
)
1 => Array('product_title' => 'Product 2',
'product_short_description' => 'Product 2 is a not so useful product',
'product_thumbnail_src' => '/images/15/2.jpg'
)
)
)
To reload the list you would simply do:
$("#product_list").empty();
And then call getJSON again with new parameters.
mongo => mongo-db console
mongodb => mongo-db server
If you're on Mac and looking for a easier way to start/stop your mongo-db server, then MongoDB Preference Pane is something that you should look into. With it, you start/stop your mongo-db instance via UI. Hope it helps!
long int n;
scanf("%ld", &n);
printf("%ld", n);
long long int n;
scanf("%lld", &n);
printf("%lld", n);
Hope you've cleared..
You could use prop
as well. Check the following code below.
$(document).ready(function(){
$('.staff_on_site').click(function(){
var rBtnVal = $(this).val();
if(rBtnVal == "yes"){
$("#no_of_staff").prop("readonly", false);
}
else{
$("#no_of_staff").prop("readonly", true);
}
});
});
I know this has already been answered, but here is an example for the people who are trying to use SQL Server Types in a vb project:
Imports System
Imports System.IO
Imports System.Runtime.InteropServices
Namespace SqlServerTypes
Public Class Utilities
<DllImport("kernel32.dll", CharSet:=CharSet.Auto, SetLastError:=True)>
Public Shared Function LoadLibrary(ByVal libname As String) As IntPtr
End Function
Public Shared Sub LoadNativeAssemblies(ByVal rootApplicationPath As String)
Dim nativeBinaryPath = If(IntPtr.Size > 4, Path.Combine(rootApplicationPath, "SqlServerTypes\x64\"), Path.Combine(rootApplicationPath, "SqlServerTypes\x86\"))
LoadNativeAssembly(nativeBinaryPath, "msvcr120.dll")
LoadNativeAssembly(nativeBinaryPath, "SqlServerSpatial140.dll")
End Sub
Private Shared Sub LoadNativeAssembly(ByVal nativeBinaryPath As String, ByVal assemblyName As String)
Dim path = System.IO.Path.Combine(nativeBinaryPath, assemblyName)
Dim ptr = LoadLibrary(path)
If ptr = IntPtr.Zero Then
Throw New Exception(String.Format("Error loading {0} (ErrorCode: {1})", assemblyName, Marshal.GetLastWin32Error()))
End If
End Sub
End Class
End Namespace
Using attr() pointing to an external domain may trigger an error like this in Chrome: "Refused to display document because display forbidden by X-Frame-Options". The workaround to this can be to move the whole iframe HTML code into the script (eg. using .html() in jQuery).
Example:
var divMapLoaded = false;
$("#container").scroll(function() {
if ((!divMapLoaded) && ($("#map").position().left <= $("#map").width())) {
$("#map-iframe").html("<iframe id=\"map-iframe\" " +
"width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"no\" " +
"marginheight=\"0\" marginwidth=\"0\" " +
"src=\"http://www.google.it/maps?t=m&cid=0x3e589d98063177ab&ie=UTF8&iwloc=A&brcurrent=5,0,1&ll=41.123115,16.853177&spn=0.005617,0.009943&output=embed\"" +
"></iframe>");
divMapLoaded = true;
}
/^(?:https?:\/\/)?(?:www\.)?([^\/]+)/i
Firstly, it's necessary to know what is a jar file.
From Oracle,
JAR (Java Archive) is a platform-independent file format that aggregates many files into one. Multiple Java applets and their requisite components (.class files, images and sounds) can be bundled in a JAR file and subsequently downloaded to a browser in a single HTTP transaction, greatly improving the download speed. The JAR format also supports compression, which reduces the file size, further improving the download time.
As you can see,
In my case it was due to 'lower_case_table_names' parameter.
The error number 39 thrown out when I tried to drop the databases which consists upper case table names with lower_case_table_names parameter is enabled.
This is fixed by reverting back the lower case parameter changes to the previous state.
If your CORS settings do not help you.
Verify the configuration S3 is correct. I had an invalid bucket name in Storage.configure
. I used a short name of bucket and it caused an error:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
I encounter same error, and incognito mode also has same issue. I resolve this issue by clear Chrome history.
You are not adding the object to the session, instead you are adding it to the request.
What you need is:
HttpSession session = request.getSession();
session.setAttribute("MySessionVariable", param);
In Servlets you have 4 scopes where you can store data.
Make sure you understand these. For more look here