Make sure you have the following condition:
[key]
if your primary key name is not Id
or ID
. public
keyword. Example:
public class MyEntity {
[key]
public Guid Id {get; set;}
}
Yes you should not install react-scripts globally, it will not work.
I think i didn't use the --save when i first created the project (on another machine), so for me this fixed the problem :
npm install --save react react-dom react-scripts
I know this answer is ridiculous, but consider just disabling this rule until the bugs are worked out or you've upgraded your tooling:
/* eslint-disable react/prop-types */ // TODO: upgrade to latest eslint tooling
Or disable project-wide in your eslintrc:
"rules": {
"react/prop-types": "off"
}
Import connect
from react-redux
and use it to connect the component with the state connect(mapStates,mapDispatch)(component)
import React from "react";
import { connect } from "react-redux";
const MyComponent = (props) => {
return (
<div>
<h1>{props.title}</h1>
</div>
);
}
}
Finally you need to map the states to the props to access them with this.props
const mapStateToProps = state => {
return {
title: state.title
};
};
export default connect(mapStateToProps)(MyComponent);
Only the states that you map will be accessible via props
Check out this answer: https://stackoverflow.com/a/36214059/4040563
For further reading : https://medium.com/@atomarranger/redux-mapstatetoprops-and-mapdispatchtoprops-shorthand-67d6cd78f132
I will add my experience using saga in production system in addition to the library author's rather thorough answer.
Pro (using saga):
Testability. It's very easy to test sagas as call() returns a pure object. Testing thunks normally requires you to include a mockStore inside your test.
redux-saga comes with lots of useful helper functions about tasks. It seems to me that the concept of saga is to create some kind of background worker/thread for your app, which act as a missing piece in react redux architecture(actionCreators and reducers must be pure functions.) Which leads to next point.
Sagas offer independent place to handle all side effects. It is usually easier to modify and manage than thunk actions in my experience.
Con:
Generator syntax.
Lots of concepts to learn.
API stability. It seems redux-saga is still adding features (eg Channels?) and the community is not as big. There is a concern if the library makes a non backward compatible update some day.
To answer the question that is asked in the beginning:
Why can't the container component call the async API, and then dispatch the actions?
Keep in mind that those docs are for Redux, not Redux plus React. Redux stores hooked up to React components can do exactly what you say, but a Plain Jane Redux store with no middleware doesn't accept arguments to dispatch
except plain ol' objects.
Without middleware you could of course still do
const store = createStore(reducer);
MyAPI.doThing().then(resp => store.dispatch(...));
But it's a similar case where the asynchrony is wrapped around Redux rather than handled by Redux. So, middleware allows for asynchrony by modifying what can be passed directly to dispatch
.
That said, the spirit of your suggestion is, I think, valid. There are certainly other ways you could handle asynchrony in a Redux + React application.
One benefit of using middleware is that you can continue to use action creators as normal without worrying about exactly how they're hooked up. For example, using redux-thunk
, the code you wrote would look a lot like
function updateThing() {
return dispatch => {
dispatch({
type: ActionTypes.STARTED_UPDATING
});
AsyncApi.getFieldValue()
.then(result => dispatch({
type: ActionTypes.UPDATED,
payload: result
}));
}
}
const ConnectedApp = connect(
(state) => { ...state },
{ update: updateThing }
)(App);
which doesn't look all that different from the original — it's just shuffled a bit — and connect
doesn't know that updateThing
is (or needs to be) asynchronous.
If you also wanted to support promises, observables, sagas, or crazy custom and highly declarative action creators, then Redux can do it just by changing what you pass to dispatch
(aka, what you return from action creators). No mucking with the React components (or connect
calls) necessary.
For XP: Start > Control Panel > Java > Security > (Set to Medium) http://www.java.com/en/download/help/java_update.xml
From Creating Pipes in C, this shows you how to fork a program to use a pipe. If you don't want to fork(), you can use named pipes.
In addition, you can get the effect of prog1 | prog2
by sending output of prog1
to stdout and reading from stdin
in prog2
. You can also read stdin by opening a file named /dev/stdin
(but not sure of the portability of that).
/*****************************************************************************
Excerpt from "Linux Programmer's Guide - Chapter 6"
(C)opyright 1994-1995, Scott Burkett
*****************************************************************************
MODULE: pipe.c
*****************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
int fd[2], nbytes;
pid_t childpid;
char string[] = "Hello, world!\n";
char readbuffer[80];
pipe(fd);
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);
/* Send "string" through the output side of pipe */
write(fd[1], string, (strlen(string)+1));
exit(0);
}
else
{
/* Parent process closes up output side of pipe */
close(fd[1]);
/* Read in a string from the pipe */
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);
}
return(0);
}
This way you always know what the size is, because a specific type is dedicated to sizes. The very own question shows that it can be an issue: is it an int
or an unsigned int
? Also, what is the magnitude (short
, int
, long
, etc.)?
Because there is a specific type assigned, you don't have to worry about the length or the signed-ness.
The actual definition can be found in the C++ Reference Library, which says:
Type:
size_t
(Unsigned integral type)Header:
<cstring>
size_t
corresponds to the integral data type returned by the language operatorsizeof
and is defined in the<cstring>
header file (among others) as an unsigned integral type.In
<cstring>
, it is used as the type of the parameternum
in the functionsmemchr
,memcmp
,memcpy
,memmove
,memset
,strncat
,strncmp
,strncpy
andstrxfrm
, which in all cases it is used to specify the maximum number of bytes or characters the function has to affect.It is also used as the return type for
strcspn
,strlen
,strspn
andstrxfrm
to return sizes and lengths.
Something like this should do the trick
function array_max_key($array) {
$max_key = -1;
$max_val = -1;
foreach ($array as $key => $value) {
if ($value > $max_val) {
$max_key = $key;
$max_val = $value;
}
}
return $max_key;
}
Why hasn't anyone suggested Activator.CreateInstance
?
http://msdn.microsoft.com/en-us/library/wccyzw83.aspx
T obj = (T)Activator.CreateInstance(typeof(T));
var myArray = [
{field: 'id', operator: 'eq', value: id},
{field: 'cStatus', operator: 'eq', value: cStatus},
{field: 'money', operator: 'eq', value: money}
];
console.log(myArray.length); //3
myArray = $.grep(myArray, function(element, index){return element.field == "money"}, true);
console.log(myArray.length); //2
Element is an object in the array.
3rd parameter true
means will return an array of elements which fails your function logic, false
means will return an array of elements which fails your function logic.
I faced the same problem while testing the changes in Symfony 4.3.2
I lowered the log level to INFO
And ran the test again
And the logged showed this:
console.ERROR: Error thrown while running command "doctrine:schema:create". Message: "[Semantical Error] The annotation "@ORM\Id" in property App\Entity\Common::$id was never imported. Did you maybe forget to add a "use" statement for this annotation?" {"exception":"[object] (Doctrine\\Common\\Annotations\\AnnotationException(code: 0): [Semantical Error] The annotation \"@ORM\\Id\" in property App\\Entity\\Common::$id was never imported. Did you maybe forget to add a \"use\" statement for this annotation? at C:\\xampp\\htdocs\\dirty7s\\vendor\\doctrine\\annotations\\lib\\Doctrine\\Common\\Annotations\\AnnotationException.php:54)","command":"doctrine:schema:create","message":"[Semantical Error] The annotation \"@ORM\\Id\" in property App\\Entity\\Common::$id was never imported. Did you maybe forget to add a \"use\" statement for this annotation?"} []
This means that some error in the code causes the:
Doctrine\ORM\ORMException: The EntityManager is closed.
So it is a good idea to check the log
In PHP 8 we can use named arguments for this problem.
So we could solve the problem described by the original poster of this question:
What if I want to use the default argument for $x and set a different argument for $y?
With:
foo(blah: "blah", y: "test");
Reference: https://wiki.php.net/rfc/named_params (in particular the "Skipping defaults" section)
Pandas DataFrame object should be thought of as a Series of Series. In other words, you should think of it in terms of columns. The reason why this is important is because when you use pd.DataFrame.iterrows
you are iterating through rows as Series. But these are not the Series that the data frame is storing and so they are new Series that are created for you while you iterate. That implies that when you attempt to assign tho them, those edits won't end up reflected in the original data frame.
Ok, now that that is out of the way: What do we do?
Suggestions prior to this post include:
pd.DataFrame.set_value
is deprecated as of Pandas version 0.21pd.DataFrame.ix
is deprecatedpd.DataFrame.loc
is fine but can work on array indexers and you can do betterMy recommendation
Use pd.DataFrame.at
for i in df.index:
if <something>:
df.at[i, 'ifor'] = x
else:
df.at[i, 'ifor'] = y
You can even change this to:
for i in df.index:
df.at[i, 'ifor'] = x if <something> else y
and what if I need to use the value of the previous row for the if condition?
for i in range(1, len(df) + 1):
j = df.columns.get_loc('ifor')
if <something>:
df.iat[i - 1, j] = x
else:
df.iat[i - 1, j] = y
When you have image into yours drawable gallery then you just need to pick the option of image view pick and drag into app activity you want to show and select the required image.
Another option:
UPDATE `table` SET the_col = current_timestamp
Looks odd, but works as expected. If I had to guess, I'd wager this is slightly faster than calling now()
.
I didn't see how to add parameters to the method call, it took me a while to find it, so I add it here. How to pass parameters in (to the javascript function), use "arguments[0]" as the parameter place and then set the parameter as input parameter in the executeScript function.
driver.executeScript("function(arguments[0]);","parameter to send in");
Sample code for How to get text from EditText
.
Android Java Syntax
EditText text = (EditText)findViewById(R.id.vnosEmaila);
String value = text.getText().toString();
Kotlin Syntax
val text = findViewById<View>(R.id.vnosEmaila) as EditText
val value = text.text.toString()
public class Palindromes {
public static void main(String[] args) {
String word = "reliefpfpfeiller";
char[] warray = word.toCharArray();
System.out.println(isPalindrome(warray));
}
public static boolean isPalindrome(char[] word){
if(word.length%2 == 0){
for(int i = 0; i < word.length/2-1; i++){
if(word[i] != word[word.length-i-1]){
return false;
}
}
}else{
for(int i = 0; i < (word.length-1)/2-1; i++){
if(word[i] != word[word.length-i-1]){
return false;
}
}
}
return true;
}
}
Unitialized variables check. Link 1 and 2 already seem to do this just fine, though.
I can't say I have used any of these intensively, though :)
It's not like that. ArrayList just uses array as internal respentation. If you add more then 60 elements then underlaying array will be exapanded. How ever you can add as much elements to this array as much RAM you have.
Create a single directory.
new File("C:\\Directory1").mkdir();
Create a directory named “Directory2 and all its sub-directories “Sub2" and “Sub-Sub2" together.
new File("C:\\Directory2\\Sub2\\Sub-Sub2").mkdirs()
Source: this perfect tutorial , you find also an example of use.
<xsl:variable name="count" select="count(/Property/long = $parPropId)"/>
Un-tested but I think that should work. I'm assuming the Property nodes are direct children of the root node and therefor taking out your descendant selector for peformance
I would recommend you having a look at the basics of conditioning in bash.
The symbol "[" is a command and must have a whitespace prior to it. If you don't give whitespace after your elif, the system interprets elif[ as a a particular command which is definitely not what you'd want at this time.
Usage:
elif(A COMPULSORY WHITESPACE WITHOUT PARENTHESIS)[(A WHITE SPACE WITHOUT PARENTHESIS)conditions(A WHITESPACE WITHOUT PARENTHESIS)]
In short, edit your code segment to:
elif [ "$seconds" -gt 0 ]
You'd be fine with no compilation errors. Your final code segment should look like this:
#!/bin/sh
if [ "$seconds" -eq 0 ];then
$timezone_string="Z"
elif [ "$seconds" -gt 0 ]
then
$timezone_string=`printf "%02d:%02d" $seconds/3600 ($seconds/60)%60`
else
echo "Unknown parameter"
fi
Try the notepad++ plugin JSMinNpp(Changed name to JSTool since 1.15)
its work for me:
constructor(private route: ActivatedRoute) {}
ngOnInit()
{
this.route.queryParams.subscribe(map => map);
this.route.snapshot.queryParams;
}
look more options How get query params from url in angular2?
If you're using compass:
compass watch --output-style compressed
You could use Jquery indeed or plain good old javascript:
var opacityPercent=30;
document.getElementById("id").style.cssText="opacity:0."+opacityPercent+"; filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity="+opacityPercent+");";
You put this in a function that you call on a setTimeout until the desired opacity is reached
You can also run the PHP script as daemon or cronjob: #!/usr/bin/php -q
Saw the error "Unrecognized attribute 'targetFramework'" in the 'Console output' page of Jenkins on a build server. This was after I changed the 'target framework' for several projects from '.NET Framework 3.5' to '.NET Framework 4' and committed my changes.
In Jenkins the project settings had to be changed. For the solution the 'MSBuild Version' had to be changed from 'v3.5' to 'v4.0'.
Nope, Model window needs to be handle by javaScriptExecutor,Because majorly model window made up of window model, This will works once model appeared then control take a place into model and click the expected element.
have to import javascriptexector
like below,
Javascriptexecutor js =(Javascriptexecutor).driver;
js.executescript(**<element to be clicked>**);
public class Main {
public static void main(String args[]) {
String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
System.out.format(format, "A", "AA", "AAA");
System.out.format(format, "B", "", "BBBBB");
System.out.format(format, "C", "CCCCC", "CCCCCCCC");
String ex[] = { "E", "EEEEEEEEEE", "E" };
System.out.format(String.format(format, (Object[]) ex));
}
}
differece in sizes of input doesnt effect the output
As per my understanding data structure is any data residing in memory of any electronic system that can be efficiently managed. Many times it is a game of memory or faster accessibility of data. In terms of memory again, there are tradeoffs done with the management of data based on cost to the company of that end product. Efficiently managed tells us how best the data can be accessed based on the primary requirement of the end product. This is a very high level explanation but data structures is a vast subjects. Most of the interviewers dive into data structures that they can afford to discuss in the interviews depending on the time they have, which are linked lists and related subjects.
Now, these data types can be divided into primitive, abstract, composite, based on the way they are logically constructed and accessed.
I hope this helps you dive in.
You forgot the #
on the id selector:
if ($("#EventStartTimeMin").val() === "") {
// ...
}
You need to convert it to milliseconds by multiplying the timestamp by 1000:
java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);
About using Tuple in Converter, it would be better to use 'object' instead of 'string', so that it works for all types of objects without limitation of 'string' object.
public class YourConverter : IMultiValueConverter
{
public object Convert(object[] values, ...)
{
Tuple<object, object> tuple = new Tuple<object, object>(values[0], values[1]);
return tuple;
}
}
Then execution logic in Command could be like this
public void OnExecute(object parameter)
{
var param = (Tuple<object, object>) parameter;
// e.g. for two TextBox object
var txtZip = (System.Windows.Controls.TextBox)param.Item1;
var txtCity = (System.Windows.Controls.TextBox)param.Item2;
}
and multi-bind with converter to create the parameters (with two TextBox objects)
<Button Content="Zip/City paste" Command="{Binding PasteClick}" >
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource YourConvert}">
<Binding ElementName="txtZip"/>
<Binding ElementName="txtCity"/>
</MultiBinding>
</Button.CommandParameter>
</Button>
May be the best way to utilize "download" button is to use JavaScript players, such as Videojs (http://docs.videojs.com/) or MediaElement.js (http://www.mediaelementjs.com/)
They do not have download button by default as a rule and moreover allow you to customize visible control buttons of the player.
This will also work
SELECT NAME
FROM GEO_LOCATION
WHERE MODIFY_ON BETWEEN SYSDATE() - INTERVAL 2 HOUR AND SYSDATE()
You can try a Java Library. FileUtils, It has many functions that write to Files.
You need to set a constraint on the table to trigger a "conflict" which you then resolve by doing a replace:
CREATE TABLE data (id INTEGER PRIMARY KEY, event_id INTEGER, track_id INTEGER, value REAL);
CREATE UNIQUE INDEX data_idx ON data(event_id, track_id);
Then you can issue:
INSERT OR REPLACE INTO data VALUES (NULL, 1, 2, 3);
INSERT OR REPLACE INTO data VALUES (NULL, 2, 2, 3);
INSERT OR REPLACE INTO data VALUES (NULL, 1, 2, 5);
The "SELECT * FROM data" will give you:
2|2|2|3.0
3|1|2|5.0
Note that the data.id is "3" and not "1" because REPLACE does a DELETE and INSERT, not an UPDATE. This also means that you must ensure that you define all necessary columns or you will get unexpected NULL values.
It has been three years since this question was asked, but I am just now coming across it. Since this answer is so far down the stack, please allow me to repeat it:
Q: I am interested if there are any limits to what types of values can be set using const in JavaScript—in particular functions. Is this valid? Granted it does work, but is it considered bad practice for any reason?
I was motivated to do some research after observing one prolific JavaScript coder who always uses const
statement for functions
, even when there is no apparent reason/benefit.
In answer to "is it considered bad practice for any reason?" let me say, IMO, yes it is, or at least, there are advantages to using function
statement.
It seems to me that this is largely a matter of preference and style. There are some good arguments presented above, but none so clear as is done in this article:
Constant confusion: why I still use JavaScript function statements by medium.freecodecamp.org/Bill Sourour, JavaScript guru, consultant, and teacher.
I urge everyone to read that article, even if you have already made a decision.
Here's are the main points:
Function statements have two clear advantages over [const] function expressions:
Advantage #1: Clarity of intent
When scanning through thousands of lines of code a day, it’s useful to be able to figure out the programmer’s intent as quickly and easily as possible.
Advantage #2: Order of declaration == order of execution
Ideally, I want to declare my code more or less in the order that I expect it will get executed.
This is the showstopper for me: any value declared using the const keyword is inaccessible until execution reaches it.
What I’ve just described above forces us to write code that looks upside down. We have to start with the lowest level function and work our way up.
My brain doesn’t work that way. I want the context before the details.
Most code is written by humans. So it makes sense that most people’s order of understanding roughly follows most code’s order of execution.
There's a good answer here:
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
or in ES6:
var text = "foo bar loo zoo moo";
text = text.toLowerCase()
.split(' ')
.map((s) => s.charAt(0).toUpperCase() + s.substring(1))
.join(' ');
packagingOptions {
exclude 'META-INF/DEPENDENCIES.txt'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
}
SELECT datname FROM pg_database WHERE datistemplate = false
#for postgres
This means the type of result the function returns, but it can be None
.
It is widespread in modern libraries oriented on Python 3.x.
For example, it there is in code of library pandas-profiling in many places for example:
def get_description(self) -> dict:
def get_rejected_variables(self, threshold: float = 0.9) -> list:
def to_file(self, output_file: Path or str, silent: bool = True) -> None:
"""Write the report to a file.
It's simple enough when you find out.
Open /etc/hosts
(unix) or C:\WINDOWS\system32\drivers\etc\hosts
.
If your domain is foo.com, then add this line:
127.0.0.1 local.foo.com
When you are testing, open local.foo.com
in your browser and it should work.
In your controller, render the new
action from your create action if validation fails, with an instance variable, @car
populated from the user input (i.e., the params
hash). Then, in your view, add a logic check (either an if block around the form
or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params
values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car
is set.
This will make exactly what you were expecting:
Objective-C:
[myButton.titleLabel setTextAlignment:UITextAlignmentCenter];
For iOS 6 or higher it's
[myButton.titleLabel setTextAlignment: NSTextAlignmentCenter];
as explained in tyler53's answer
Swift:
myButton.titleLabel?.textAlignment = NSTextAlignment.Center
Swift 4.x and above
myButton.titleLabel?.textAlignment = .center
Expanding off of what @twalberg and @iconoclast had, if you're using cmd for whatever reason, you can use:
FOR /F "usebackq" %x IN (`"git branch | grep '*' | cut -f2 -d' '"`) DO FOR /F "usebackq" %y IN (`"git merge-base %x master"`) DO git diff --name-only %x %y
I faced the same problem and now found a way to solve it. First you have to delete the database of the user that you wish to drop. Then the user can be easily deleted.
I created an user named "msf" and struggled a while to delete the user and recreate it. I followed the below steps and Got succeeded.
1) Drop the database
dropdb msf
2) drop the user
dropuser msf
Now I got the user successfully dropped.
In CSS3:
input[type=radio] {content:url(mycheckbox.png)}
input[type=radio]:checked {content:url(mycheckbox-checked.png)}
In reality:
<span class=fakecheckbox><input type=radio><img src="checkbox.png" alt=""></span>
@media screen {.fakecheckbox img {display:none}}
@media print {.fakecheckbox input {display:none;}}
and you'll need Javascript to keep <img>
and radios in sync (and ideally insert them there in a first place).
I've used <img>
, because browsers are usually configured not to print background-image
. It's better to use image than another control, because image is non-interactive and less likely to cause problems.
Use this as your WHERE condition
WHERE CHARINDEX('Apples', column) = 0
From JPA 2.1 you can use AttributeConverter.
Create an enumerated class like so:
public enum NodeType {
ROOT("root-node"),
BRANCH("branch-node"),
LEAF("leaf-node");
private final String code;
private NodeType(String code) {
this.code = code;
}
public String getCode() {
return code;
}
}
And create a converter like this:
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
@Converter(autoApply = true)
public class NodeTypeConverter implements AttributeConverter<NodeType, String> {
@Override
public String convertToDatabaseColumn(NodeType nodeType) {
return nodeType.getCode();
}
@Override
public NodeType convertToEntityAttribute(String dbData) {
for (NodeType nodeType : NodeType.values()) {
if (nodeType.getCode().equals(dbData)) {
return nodeType;
}
}
throw new IllegalArgumentException("Unknown database value:" + dbData);
}
}
On the entity you just need:
@Column(name = "node_type_code")
You luck with @Converter(autoApply = true)
may vary by container but tested to work on Wildfly 8.1.0. If it doesn't work you can add @Convert(converter = NodeTypeConverter.class)
on the entity class column.
thought I would update on this.
Found out that adding to the VB Module behind the spreadsheet does not actually register as a Macro.
So here is the solution:
Code
Function LastSavedTimeStamp() As Date
LastSavedTimeStamp = ActiveWorkbook.BuiltinDocumentProperties("Last Save Time")
End Function
Code
=LastSavedTimeStamp()
Use the DO statement, a new option in version 9.0:
DO LANGUAGE plpgsql
$$
BEGIN
CREATE TABLE "Logs"."Events"
(
EventId BIGSERIAL NOT NULL PRIMARY KEY,
PrimaryKeyId bigint NOT NULL,
EventDateTime date NOT NULL DEFAULT(now()),
Action varchar(12) NOT NULL,
UserId integer NOT NULL REFERENCES "Office"."Users"(UserId),
PrincipalUserId varchar(50) NOT NULL DEFAULT(user)
);
CREATE TABLE "Logs"."EventDetails"
(
EventDetailId BIGSERIAL NOT NULL PRIMARY KEY,
EventId bigint NOT NULL REFERENCES "Logs"."Events"(EventId),
Resource varchar(64) NOT NULL,
OldVal varchar(4000) NOT NULL,
NewVal varchar(4000) NOT NULL
);
RAISE NOTICE 'Task completed sucessfully.';
END;
$$;
Regarding the single quote, see the code below used to replace the string let's
with let us
:
command:
echo "hello, let's go"|sed 's/let'"'"'s/let us/g'
result:
hello, let us go
Please try the following way.
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
<tr>
<td colspan="2">Sum: $180</td>
</tr>
</table>
By this method, you can resume your program just by pressing any specified key you've specified that:
import keyboard
while True:
key = keyboard.read_key()
if key == 'space': # You can put any key you like instead of 'space'
break
The same method, but in another way:
import keyboard
while True:
if keyboard.is_pressed('space'): # The same. you can put any key you like instead of 'space'
break
Note: you can install the keyboard
module simply by writing this in you shell or cmd:
pip install keyboard
Sample Usage:
import paramiko
paramiko.util.log_to_file("paramiko.log")
# Open a transport
host,port = "example.com",22
transport = paramiko.Transport((host,port))
# Auth
username,password = "bar","foo"
transport.connect(None,username,password)
# Go!
sftp = paramiko.SFTPClient.from_transport(transport)
# Download
filepath = "/etc/passwd"
localpath = "/home/remotepasswd"
sftp.get(filepath,localpath)
# Upload
filepath = "/home/foo.jpg"
localpath = "/home/pony.jpg"
sftp.put(localpath,filepath)
# Close
if sftp: sftp.close()
if transport: transport.close()
<input type="text" autocomplete="off"/>
Should work. Alternatively, use:
<form autocomplete="off" … >
for the entire form (see this related question).
Use json.loads
not json.load
.
(load
loads from a file-like object, loads
from a string. So you could just as well omit the .read()
call instead.)
It's a hint to the compiler that the variable will be heavily used and that you recommend it be kept in a processor register if possible.
Most modern compilers do that automatically, and are better at picking them than us humans.
try something like this FIDDLE
try
{
navigator.device.capture.captureImage(function(mediaFiles) {
console.log("works");
});
}
catch(err)
{
alert('hi');
$("#captureImage").prop('checked', false);
}
You have four options
Finite differences require no external tools but are prone to numerical error and, if you're in a multivariate situation, can take a while.
Symbolic differentiation is ideal if your problem is simple enough. Symbolic methods are getting quite robust these days. SymPy is an excellent project for this that integrates well with NumPy. Look at the autowrap or lambdify functions or check out Jensen's blogpost about a similar question.
Automatic derivatives are very cool, aren't prone to numeric errors, but do require some additional libraries (google for this, there are a few good options). This is the most robust but also the most sophisticated/difficult to set up choice. If you're fine restricting yourself to numpy
syntax then Theano might be a good choice.
Here is an example using SymPy
In [1]: from sympy import *
In [2]: import numpy as np
In [3]: x = Symbol('x')
In [4]: y = x**2 + 1
In [5]: yprime = y.diff(x)
In [6]: yprime
Out[6]: 2·x
In [7]: f = lambdify(x, yprime, 'numpy')
In [8]: f(np.ones(5))
Out[8]: [ 2. 2. 2. 2. 2.]
u'AB'
is just a text representation of the corresponding Unicode string. Here're several methods that create exactly the same Unicode string:
L = [u'AB', u'\x41\x42', u'\u0041\u0042', unichr(65) + unichr(66)]
print u", ".join(L)
AB, AB, AB, AB
There is no u''
in memory. It is just the way to represent the unicode
object in Python 2 (how you would write the Unicode string literal in a Python source code). By default print L
is equivalent to print "[%s]" % ", ".join(map(repr, L))
i.e., repr()
function is called for each list item:
print L
print "[%s]" % ", ".join(map(repr, L))
[u'AB', u'AB', u'AB', u'AB']
[u'AB', u'AB', u'AB', u'AB']
If you are working in a REPL then a customizable sys.displayhook
is used that calls repr()
on each object by default:
>>> L = [u'AB', u'\x41\x42', u'\u0041\u0042', unichr(65) + unichr(66)]
>>> L
[u'AB', u'AB', u'AB', u'AB']
>>> ", ".join(L)
u'AB, AB, AB, AB'
>>> print ", ".join(L)
AB, AB, AB, AB
Don't encode to bytes. Print unicode directly.
In your specific case, I would create a Python list and use json.dumps()
to serialize it instead of using string formatting to create JSON text:
#!/usr/bin/env python2
import json
# ...
test = [dict(email=player.email, gem=player.gem)
for player in players]
print test
print json.dumps(test)
[{'email': u'[email protected]', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test1', 'gem': 0}]
[{"email": "[email protected]", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test1", "gem": 0}]
Even if it is really discouraged to use merge cells in Excel (use Center Across Selection
for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).
Hence, you can get the value of merged cells in range B4:B11
in several ways:
Range("B4").Value
Range("B4:B11").Cells(1).Value
Range("B4:B11").Cells(1,1).Value
You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty
.
Also note that Range("B4:B11").Value
won't work (raises an execution error number 13 if you try to Debug.Print
it) because it returns an array.
$items = array('a','b','c');
if(is_array($items)) {
foreach($items as $item) {
print $item;
}
}
Another example using COALESCE. http://sqlmag.com/t-sql/coalesce-vs-isnull
SELECT (COALESCE(SUM(val1),0) + COALESCE(SUM(val2), 0)
+ COALESCE(SUM(val3), 0) + COALESCE(SUM(val4), 0)) AS 'TOTAL'
FROM Emp
If there is trouble with the method onActivityResult
that is inside the fragment class, and you want to update something that's is also inside the fragment class, use:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == Activity.RESULT_OK)
{
// If the user had agreed to enabling Bluetooth,
// populate the ListView with all the paired devices.
this.arrayDevice = new ArrayAdapter<String>(this.getContext(), R.layout.device_item);
for(BluetoothDevice bd : this.btService.btAdapater.getBondedDevices())
{
this.arrayDevice.add(bd.getAddress());
this.btDeviceList.setAdapter(this.arrayDevice);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
Just add the this.variable
as shown in the code above. Otherwise the method will be called within the parent activity and the variable will not updated of the current instance.
I tested it also by putting this block of code into the MainActivity
, replacing this
with the HomeFragment
class and having the variables static. I got results as I expected.
So if you want to have the fragment class having its own implementation of onActivityResult
, the code example above is the answer.
If you want to try it without the try catch block, can use the following method, Create a intent and set the package of the app which you want to verify
val intent = Intent(Intent.ACTION_VIEW)
intent.data = uri
intent.setPackage("com.example.packageofapp")
and the call the following method to check if the app is installed
fun isInstalled(intent:Intent) :Boolean{
val list = context.packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
return list.isNotEmpty()
}
With
git config -l
, I now see I have acredential.helper=osxkeychain
option
That means the credential helper (initially introduced in 1.7.10) is now in effect, and will cache automatically the password for accessing a remote repository over HTTP.
(as in "GIT: Any way to set default login credentials?")
You can disable that option entirely, or only for a single repo.
You can use class .center-block
in combination with style="width:400px;max-width:100%;"
to preserve responsiveness.
Using .col-md-*
class with .center-block
will not work because of the float
on .col-md-*
.
If you don't need these methods to return something, you could make them return Runnable objects.
private Runnable methodName (final int arg) {
return (new Runnable() {
public void run() {
// do stuff with arg
}
});
}
Then use it like:
private void otherMethodName (Runnable arg){
arg.run();
}
The problem is that the DLL is registered on the 32 bit version of the windows registry, and the application is using the 64 bit version.
Solution: Go into the Project Properties, Compile tab and click "Advanced Compile Options...". Change "Target CPU" to x86, click OK, save and try again.
Source: http://www.theogray.com/blog/2009/10/comexception-regdbeclassnotreg-on-64-bit-windows
Has worked for me with an VB 6 COM DLL invoked from a .Net 4 Winforms application
I can't believe all these convoluted answers. Assuming the key is of type: string (or use 'var' if you're a lazy developer): -
List<string> listOfKeys = theCollection.Keys.ToList();
var BrowserDetect = {
init: function () {
this.browser = this.searchString(this.dataBrowser) || "Other";
this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "Unknown";
},
searchString: function (data) {
for (var i = 0; i < data.length; i++) {
var dataString = data[i].string;
this.versionSearchString = data[i].subString;
if (dataString.indexOf(data[i].subString) !== -1) {
return data[i].identity;
}
}
},
searchVersion: function (dataString) {
var index = dataString.indexOf(this.versionSearchString);
if (index === -1) {
return;
}
var rv = dataString.indexOf("rv:");
if (this.versionSearchString === "Trident" && rv !== -1) {
return parseFloat(dataString.substring(rv + 3));
} else {
return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
}
},
dataBrowser: [
{string: navigator.userAgent, subString: "Edge", identity: "MS Edge"},
{string: navigator.userAgent, subString: "MSIE", identity: "Explorer"},
{string: navigator.userAgent, subString: "Trident", identity: "Explorer"},
{string: navigator.userAgent, subString: "Firefox", identity: "Firefox"},
{string: navigator.userAgent, subString: "Opera", identity: "Opera"},
{string: navigator.userAgent, subString: "OPR", identity: "Opera"},
{string: navigator.userAgent, subString: "Chrome", identity: "Chrome"},
{string: navigator.userAgent, subString: "Safari", identity: "Safari"}
]
};
BrowserDetect.init();
var bv= BrowserDetect.browser;
if( bv == "Chrome"){
$("body").addClass("chrome");
}
else if(bv == "MS Edge"){
$("body").addClass("edge");
}
else if(bv == "Explorer"){
$("body").addClass("ie");
}
else if(bv == "Firefox"){
$("body").addClass("Firefox");
}
$(".relative").click(function(){
$(".oc").toggle('slide', { direction: 'left', mode: 'show' }, 500);
$(".oc1").css({
'width' : '100%',
'margin-left' : '0px',
});
});
I do not agree and do not recommend to return a vector
:
vector <double> vectorial(vector <double> a, vector <double> b)
{
vector <double> c{ a[1] * b[2] - b[1] * a[2], -a[0] * b[2] + b[0] * a[2], a[0] * b[1] - b[0] * a[1] };
return c;
}
This is much faster:
void vectorial(vector <double> a, vector <double> b, vector <double> &c)
{
c[0] = a[1] * b[2] - b[1] * a[2]; c[1] = -a[0] * b[2] + b[0] * a[2]; c[2] = a[0] * b[1] - b[0] * a[1];
}
I tested on Visual Studio 2017 with the following results in release mode:
8.01 MOPs by reference
5.09 MOPs returning vector
In debug mode, things are much worse:
0.053 MOPS by reference
0.034 MOPs by return vector
//import com.google.gson.JsonObject;
JsonObject complaint = new JsonObject();
complaint.addProperty("key", "value");
Server 2008
Start Task Manager Find w3wp.exe process (description IIS Worker Process) Check User Name column to find who you're IIS process is running as.
In the IIS GUI you can configure your application pool to run as a specific user: Application Pool default Advanced Settings Identity
Here's the info from Microsoft on setting up Application Pool Identites:
http://learn.iis.net/page.aspx/624/application-pool-identities/
sqlall
just prints the SQL, it doesn't execute it. syncdb
will create tables that aren't already created, but it won't modify existing tables.
The only way to change the $type
of the data is to perform an update on the data where the data has the correct type.
In this case, it looks like you're trying to change the $type
from 1 (double) to 2 (string).
So simply load the document from the DB, perform the cast (new String(x)
) and then save the document again.
If you need to do this programmatically and entirely from the shell, you can use the find(...).forEach(function(x) {})
syntax.
In response to the second comment below. Change the field bad
from a number to a string in collection foo
.
db.foo.find( { 'bad' : { $type : 1 } } ).forEach( function (x) {
x.bad = new String(x.bad); // convert field to string
db.foo.save(x);
});
Advice in KB and above didn't work for me. I discovered that if one Excel 2007 user (with or without the security update; not sure of exact circumstances that cause this) saves the file, the original error returns.
I discovered that the fastest way to repair the file again is to delete all the VBA code. Save. Then replace the VBA code (copy/paste). Save. Before attempting this, I delete the .EXD files first, because otherwise I get an error on open.
In my case, I cannot upgrade/update all users of my Excel file in various locations. Since the problem comes back after some users save the Excel file, I am going to have to replace the ActiveX control with something else.
Its very simple.
Example JSON:
{
"value":1
}
int z = jsonObject.getInt("value");
You might want to take a look at Icon fonts. http://css-tricks.com/examples/IconFont/
EDIT: I'm using Font-Awesome on my latest project. You can even bootstrap it. Simply put this in your <head>
:
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css" rel="stylesheet">
<!-- And if you want to support IE7, add this aswell -->
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome-ie7.min.css" rel="stylesheet">
And then go ahead and add some icon-links like this:
<a class="icon-thumbs-up"></a>
Here's the full cheat sheet
--edit--
Font-Awesome uses different class names in the new version, probably because this makes the CSS files drastically smaller, and to avoid ambiguous css classes. So now you should use:
<a class="fa fa-thumbs-up"></a>
EDIT 2:
Just found out github also uses its own icon font: Octicons It's free to download. They also have some tips on how to create your very own icon fonts.
"If you want to Select multiple Cells and Copy their values to the Clipboard without all those annoying quotes" (without the bugs in Peter Smallwood's multi-Cells solution) "the following code may be useful." This is an enhancement of the code given above from Peter Smallwood (which "is an enhancement of the code given above from user3616725"). This fixes the following bugs in Peter Smallwood's solution:
NOTE: You still won't be able to copy characters embedded within a Cell that would cause an exit of the target field you're Pasting that Cell into (i.e. Tab or CR when Pasting into the Edit Table Window of Access or SSMS).
Option Explicit
Sub CopyCellsWithoutAddingQuotes()
' -- Attach Microsoft Forms 2.0 Library: tools\references\Browse\FM20.DLL
' -- NOTE: You may have to temporarily insert a UserForm into your VBAProject for it to show up.
' -- Then set a Keyboard Shortcut to the "CopyCellsWithoutAddingQuotes" Macro (i.e. Crtl+E)
Dim clibboardFieldDelimiter As String
Dim clibboardLineDelimiter As String
Dim row As Range
Dim cell As Range
Dim cellValueText As String
Dim clipboardText As String
Dim isFirstRow As Boolean
Dim isFirstCellOfRow As Boolean
Dim dataObj As New dataObject
clibboardFieldDelimiter = Chr(9)
clibboardLineDelimiter = Chr(13) + Chr(10)
isFirstRow = True
isFirstCellOfRow = True
For Each row In Selection.Rows
If Not isFirstRow Then
clipboardText = clipboardText + clibboardLineDelimiter
End If
For Each cell In row.Cells
If IsEmpty(cell.Value) Then
cellValueText = ""
ElseIf IsNumeric(cell.Value) Then
cellValueText = LTrim(Str(cell.Value))
Else
cellValueText = cell.Value
End If ' -- Else Non-empty Non-numeric
If isFirstCellOfRow Then
clipboardText = clipboardText + cellValueText
isFirstCellOfRow = False
Else ' -- Not (isFirstCellOfRow)
clipboardText = clipboardText + clibboardFieldDelimiter + cellValueText
End If ' -- Else Not (isFirstCellOfRow)
Next cell
isFirstRow = False
isFirstCellOfRow = True
Next row
clipboardText = clipboardText + clibboardLineDelimiter
dataObj.SetText (clipboardText)
dataObj.PutInClipboard
End Sub
Take a look at recently released Globalization plugin to jQuery by Microsoft
Integer division $x divided by $y ...
$z = -1 & $x / $y
How does it work?
$x / $y
return the floating point division
&
perform a bit-wise AND
-1
stands for
&HFFFFFFFF
for the largest integer ... whence
$z = -1 & $x / $y
gives the integer division ...
Here is an example of using a dynamic T-SQL query and then extracting the results should you have more than one column of returned values (notice the dynamic table name):
DECLARE
@strSQLMain nvarchar(1000),
@recAPD_number_key char(10),
@Census_sub_code varchar(1),
@recAPD_field_name char(100),
@recAPD_table_name char(100),
@NUMBER_KEY varchar(10),
if object_id('[Permits].[dbo].[myTempAPD_Txt]') is not null
DROP TABLE [Permits].[dbo].[myTempAPD_Txt]
CREATE TABLE [Permits].[dbo].[myTempAPD_Txt]
(
[MyCol1] char(10) NULL,
[MyCol2] char(1) NULL,
)
-- an example of what @strSQLMain is : @strSQLMain = SELECT @recAPD_number_key = [NUMBER_KEY], @Census_sub_code=TEXT_029 FROM APD_TXT0 WHERE Number_Key = '01-7212'
SET @strSQLMain = ('INSERT INTO myTempAPD_Txt SELECT [NUMBER_KEY], '+ rtrim(@recAPD_field_name) +' FROM '+ rtrim(@recAPD_table_name) + ' WHERE Number_Key = '''+ rtrim(@Number_Key) +'''')
EXEC (@strSQLMain)
SELECT @recAPD_number_key = MyCol1, @Census_sub_code = MyCol2 from [Permits].[dbo].[myTempAPD_Txt]
DROP TABLE [Permits].[dbo].[myTempAPD_Txt]
It seems there's a list of all cookies sent to browser in array returned by php's headers_list()
which among other data returns "Set-Cookie" elements as follows:
Set-Cookie: cooke_name=cookie_value; expires=expiration_time; Max-Age=age; path=path; domain=domain
This way you can also get deleted ones since their value is deleted:
Set-Cookie: cooke_name=deleted; expires=expiration_time; Max-Age=age; path=path; domain=domain
From there on it's easy to retrieve expiration time or age for particular cookie. Keep in mind though that this array is probably available only AFTER actual call to setcookie()
has been made so it's valid for script that has already finished it's job. I haven't tested this in some other way(s) since this worked just fine for me.
This is rather old topic and I'm not sure if this is valid for all php builds but I thought it might be helpfull.
For more info see:
https://www.php.net/manual/en/function.headers-list.php
https://www.php.net/manual/en/function.headers-sent.php
Consider:
Function GetFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
This code was adapted from Ozgrid
and as jkf points out, from Mr Excel
Say you have a FaceView
which is some sort of image. You're going to have many of them on screen (or, in a collection view, table, stack view or other list).
In the class FaceView
you will need a variable "index"
class FaceView: UIView {
var index: Int
so that each FaceView can be self-aware of "which" face it is on screen.
So you must add var index: Int
to the class in question.
So you are adding many FaceView to your screen ...
let f = FaceView()
f.index = 73
.. you add f to your stack view, screen, or whatever.
You now add a click to f
f.addGestureRecognizer(UITapGestureRecognizer(target: self,
action: #selector(tapOneOfTheFaces)))
@objc func tapOneOfTheFaces(_ sender: UITapGestureRecognizer) {
if let tapped = sender.view as? CirclePerson {
print("we got it: \(tapped.index)")
You now know "which" face was clicked in your table, screen, stack view or whatever.
It's that easy.
2 from decimal numbering system in binary is as follows
10
now if you do
2 << 11
it would be , 11 zeros would be padded on the right side
1000000000000
The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator ">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension [..]
left shifting results in multiplication by 2 (*2) in terms or arithmetic
For example
2 in binary 10
, if you do <<1
that would be 100
which is 4
4 in binary 100
, if you do <<1
that would be 1000
which is 8
Also See
In my case after invalidate cache and restart the android studio fixed the problem .To do that go to
File -> invalidate cache / Restart
const is similar to static we can access both varables with class name but diff is static variables can be modified and const can not.
For everyone who is stuck with .NET 2.0, like me, try the following way (applicable to the example in the OP):
ConfigItemList.ConvertAll<string>(delegate (ConfigItemType ci)
{
return ci.Name;
}).ToArray();
where ConfigItemList is your list variable.
Use root tag
as shape
instead of selector
in your shape.xml
file, and it will resolve your problem!
I encountered the same issue after XAMPP v3.2.1 installation. I do not have Skype as most people would believe, however as a Software Developer I assumed port 80 is already in use by my other apps. So I changed it by simply using the XAMPP Control Panel:
Click on the 'Config' button corresponding to the APACHE service and choose the first option 'Apache (httpd.conf)'. In the document that opens (using any text editor - except MS Word!), locate the text:
Listen 12.34.56.78:80
Listen 80
And change this to:
Listen 12.34.56.78:83
Listen 83
This can be any non-used port number. Thanks.
Copying to the clipboard is a tricky task to do in Javascript in terms of browser compatibility. The best way to do it is using a small flash. It will work on every browser. You can check it in this article.
Here's how to do it for Internet Explorer:
function copy (str)
{
//for IE ONLY!
window.clipboardData.setData('Text',str);
}
Delete all PODs in all Namespace only (restart deployment)
kubectl get pod -A -o yaml | kubectl delete -f -
I used the instructions in this step-by-step and it worked.
http://nenadbulatovic.blogspot.co.il/2013/07/configuring-opencv-245-eclipse-cdt-juno.html
If you see this warning:
warning: receiver 'MyCoolClass' is a forward class and corresponding @interface may not exist
you need to #import
the file, but you can do that in your implementation file (.m), and use the @class
declaration in your header file.
@class
does not (usually) remove the need to #import
files, it just moves the requirement down closer to where the information is useful.
For Example
If you say @class MyCoolClass
, the compiler knows that it may see something like:
MyCoolClass *myObject;
It doesn't have to worry about anything other than MyCoolClass
is a valid class, and it should reserve room for a pointer to it (really, just a pointer). Thus, in your header, @class
suffices 90% of the time.
However, if you ever need to create or access myObject
's members, you'll need to let the compiler know what those methods are. At this point (presumably in your implementation file), you'll need to #import "MyCoolClass.h"
, to tell the compiler additional information beyond just "this is a class".
Here is a STL-like class
File "csvfile.h"
#pragma once
#include <iostream>
#include <fstream>
class csvfile;
inline static csvfile& endrow(csvfile& file);
inline static csvfile& flush(csvfile& file);
class csvfile
{
std::ofstream fs_;
const std::string separator_;
public:
csvfile(const std::string filename, const std::string separator = ";")
: fs_()
, separator_(separator)
{
fs_.exceptions(std::ios::failbit | std::ios::badbit);
fs_.open(filename);
}
~csvfile()
{
flush();
fs_.close();
}
void flush()
{
fs_.flush();
}
void endrow()
{
fs_ << std::endl;
}
csvfile& operator << ( csvfile& (* val)(csvfile&))
{
return val(*this);
}
csvfile& operator << (const char * val)
{
fs_ << '"' << val << '"' << separator_;
return *this;
}
csvfile& operator << (const std::string & val)
{
fs_ << '"' << val << '"' << separator_;
return *this;
}
template<typename T>
csvfile& operator << (const T& val)
{
fs_ << val << separator_;
return *this;
}
};
inline static csvfile& endrow(csvfile& file)
{
file.endrow();
return file;
}
inline static csvfile& flush(csvfile& file)
{
file.flush();
return file;
}
File "main.cpp"
#include "csvfile.h"
int main()
{
try
{
csvfile csv("MyTable.csv"); // throws exceptions!
// Header
csv << "X" << "VALUE" << endrow;
// Data
csv << 1 << "String value" << endrow;
csv << 2 << 123 << endrow;
csv << 3 << 1.f << endrow;
csv << 4 << 1.2 << endrow;
}
catch (const std::exception& ex)
{
std::cout << "Exception was thrown: " << e.what() << std::endl;
}
return 0;
}
Latest version here
You are just supposed to provide the predict
method with the same 2D array, but with one value that you want to process (or more). In short, you can just replace
[0.58,0.76]
With
[[0.58,0.76]]
And it should work.
EDIT: This answer became popular so I thought I'd add a little more explanation about ML. The short version: we can only use predict
on data that is of the same dimensionality as the training data (X
) was.
In the example in question, we give the computer a bunch of rows in X
(with 2 values each) and we show it the correct responses in y
. When we want to predict
using new values, our program expects the same - a bunch of rows. Even if we want to do it to just one row (with two values), that row has to be part of another array.
You can do as @Hugo of @Laurent said, or you can use git rebase
to delete the commits you want to get rid off, if you know which ones. I tend to use git rebase -i head~N
(where N is a number, allowing you to manipulate the last N commits) for this kind of operations.
To compile source.cpp
, run
g++ source.cpp
This command will compile source.cpp
to file a.out
in the same directory.
To run the compiled file, run
./a.out
If you compile another source file, with g++ source2.cpp
, the new compiled file a.out
will overwrite the a.out
generated with source.cpp
If you want to compile source.cpp
to a specific file, say compiledfile
,
run
g++ source.cpp -o compiledfile
or
g++ -o compiledfile source.cpp
This will create the compiledfile
which is the compiled binary file. to run the compiledfile
, run
./compiledfile
If g++
is not in your $PATH
, replace g++ with /usr/bin/g++
.
Once you have the source trees, e.g.
diff -ENwbur repos1/ repos2/
Even better
diff -ENwbur repos1/ repos2/ | kompare -o -
and have a crack at it in a good gui tool :)
For OSX, run the following command from the terminal:
open -na Google\ Chrome --args --disable-web-security --user-data-dir=$HOME/profile-folder-name
This will start a new instance of Google Chrome with a warning on top.
You can use [[UINavigationBar appearance] setTintColor:myColor];
Since iOS 7 you need to set [[UINavigationBar appearance] setBarTintColor:myColor];
and also [[UINavigationBar appearance] setTranslucent:NO]
.
[[UINavigationBar appearance] setBarTintColor:myColor];
[[UINavigationBar appearance] setTranslucent:NO];
This is what worked for me:
public static Map<String, Object> toMap(JSONObject jsonobj) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keys = jsonobj.keys();
while(keys.hasNext()) {
String key = keys.next();
Object value = jsonobj.get(key);
if (value instanceof JSONArray) {
value = toList((JSONArray) value);
} else if (value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
map.put(key, value);
} return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for(int i = 0; i < array.length(); i++) {
Object value = array.get(i);
if (value instanceof JSONArray) {
value = toList((JSONArray) value);
}
else if (value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
} return list;
}
Most of this is from this question: How to convert JSONObject to new Map for all its keys using iterator java
Right click the project and click "Properties". Then select "Android" from the tree on the left. You can then select the target version on the right.
(Note as per the popular comment below, make sure your properties, classpath and project files are writable otherwise it won't work)
You are seeing the result of Type Erasure. From that page...
When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. Type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created before generics.
For instance, Box<String> is translated to type Box, which is called the raw type — a raw type is a generic class or interface name without any type arguments. This means that you can't find out what type of Object a generic class is using at runtime.
This also looks like this question which has a pretty good answer as well.
use float: left;
and clear: left;
.text span {
background: rgba(165, 220, 79, 0.8);
float: left;
clear: left;
padding: 7px 10px;
color: #fff;
}
You can also use query(), i.e.:
df_filtered = df.query('a == 4 & b != 2')
select <column list> into <dest. table> from <source table>;
You could do this way.
SELECT windows_release, windows_service_pack_level,
windows_sku, os_language_version
into new_table_name
FROM sys.dm_os_windows_info OPTION (RECOMPILE);
This will remove empty lines or lines with only whitespace characters (tabs/spaces).
[IO.File]::ReadAllText("FileWithEmptyLines.txt") -replace '\s+\r\n+', "`r`n" | Out-File "c:\FileWithNoEmptyLines.txt"
I added this on my project and it seems to work:
HTMLElement.prototype.prependHtml = function (element) {
const div = document.createElement('div');
div.innerHTML = element;
this.insertBefore(div, this.firstChild);
};
HTMLElement.prototype.appendHtml = function (element) {
const div = document.createElement('div');
div.innerHTML = element;
while (div.children.length > 0) {
this.appendChild(div.children[0]);
}
};
Example:
document.body.prependHtml(`<a href="#">Hello World</a>`);
document.body.appendHtml(`<a href="#">Hello World</a>`);
One of the way to enable cross domain request on local chrome browser :
Now UI and API running on different ports will be able to work together. I hope this helps.
If you are looking for an example of Cross-domain request . I'll put it in fragments for you to get enough idea.
Angular Client
user.service.ts to call the SpringWebservice.
/** POST: Validates a user for login from Spring webservice */
loginUrl = 'http://localhost:8091/SpringWebService/login'; // URL to web api
validUser (user: User): Observable<User> {
return this.http.post<User>(this.loginUrl, user, httpOptions)
.pipe(
catchError(this.handleError('Login User', user))
);
}
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json;charset=utf-8',
'Authorization': 'my-auth-token'
})
};
login.component.html: to accept the user Name and pwd.
<form (ngSubmit)="onSubmit(loginForm)" #loginForm="ngForm">
<!-- //ngModel is a must for each form-control -->
<!-- 1st group -->
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name"
required name="name" ngModel #name="ngModel">
<div [hidden]="name.valid || name.pristine"
class="alert alert-danger">
Name is required
</div>
</div>
<!-- 2nd group -->
<div class="form-group">
<label for="pwd">Password</label>
<input type="text" class="form-control" id="pwd"
name="pwd" #pwd required ngModel>
</div>
<button type="submit" class="btn btn-success" [disabled]="!loginForm.valid">Submit</button>
</form>
login.component.ts: calls and subscribes validUser method of user.service.
userModel : User;
onSubmit(loginForm : NgForm) {
this.submitted = true;
console.log("User : "+loginForm.value.name + " Valid :"+loginForm.valid)
this.userModel.loggedIn= false;
this.userModel=new
User(loginForm.value.name.trim(),loginForm.value.pwd.trim())
// Passing the userModel to Service method to invoke WebAPI
this.userService.validUser(this.userModel).subscribe(user=>
{
if(user.loggedIn == false){
console.log("Invalid User/PWD");
}
else{
this.userService.changeUser(this.userModel);
this.router.navigate(['/home']);
}
}
);
user.ts: model.
export class User {
constructor(
public name : String,
public pwd : String,
public email ?: String, //optional
public mobile ? : number,//""
public loggedIn : boolean = false
){ }
}
Spring Webservice.
package com.rest;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
// This annotation opens door for cross-domain(Cross-origin resource sharing (CORS)) from any host
@CrossOrigin(origins="*")
public class MainController {
@RequestMapping(value="/login", method=RequestMethod.POST)
public User validUser(@RequestBody User user){
BaseResponse response = new BaseResponse();
if(user.getName().equalsIgnoreCase("shaz") && user.getPwd().equals("pwd")){
user.setLoggedIn(true);
}
else{
user.setLoggedIn(false);
}
return user;
}
}
Now when you pass name as "shaz" and pwd as "pwd" in the form and hit submit,it gets validated from the SpringWebService and the loggedIn flag is set to true and the user entity is returned in response. Based on the loggedIn status from response,the user is redirected to home page or an error is thrown.
Login Page and Network Details
Note: I have not shared the complete setup and code
Refer this: https://shahbaazdesk.wordpress.com/2018/04/03/angular5-with-spring-webservice/
You need to instantiate the class it is contained within, or make the method static.
So if it is contained within class Foo:
Foo x = new Foo();
List<Integer> stuff = x.myNumbers();
or alternatively shorthand:
List<Integer> stuff = new Foo().myNumbers();
or if you make it static like so:
public static List<Integer> myNumbers() {
List<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(11);
numbers.add(3);
return(numbers);
}
you can call it like so:
List<Integer> stuff = Foo.myNumbers();
I usually like a StringBuilder when I'm working with MailMessage. Adding new lines is easy (via the AppendLine method), and you can simply set the Message's Body equal to StringBuilder.ToString() (... for the instance of StringBuilder).
StringBuilder result = new StringBuilder("my content here...");
result.AppendLine(); // break line
You can write your own equals function:
a == b
Because you're dealing with json, you'll have standard python types: dict
, list
, etc., so you can do hard type checking if type(obj) == 'dict':
, etc.
Rough example (not tested):
def json_equals(jsonA, jsonB):
if type(jsonA) != type(jsonB):
# not equal
return False
if type(jsonA) == dict:
if len(jsonA) != len(jsonB):
return False
for keyA in jsonA:
if keyA not in jsonB or not json_equal(jsonA[keyA], jsonB[keyA]):
return False
elif type(jsonA) == list:
if len(jsonA) != len(jsonB):
return False
for itemA, itemB in zip(jsonA, jsonB):
if not json_equal(itemA, itemB):
return False
else:
return jsonA == jsonB
I code in VB and was able to add the following line to my Global.asax.vb file inside of Application_Start
ServicePointManager.SecurityProtocol = CType(3072, SecurityProtocolType) 'TLS 1.2
Pattern pattern = Pattern.compile("^[a-zA-Z0-9]*$");
Matcher matcher = pattern.matcher("Teststring123");
if(matcher.matches()) {
// yay! alphanumeric!
}
I've been using this function in my project.
function changeViewPort(key, val) {
var reg = new RegExp(key, "i"), oldval = document.querySelector('meta[name="viewport"]').content;
var newval = reg.test(oldval) ? oldval.split(/,\s*/).map(function(v){ return reg.test(v) ? key+"="+val : v; }).join(", ") : oldval+= ", "+key+"="+val ;
document.querySelector('meta[name="viewport"]').content = newval;
}
so just addEventListener:
if( /iPad|iPhone|iPod|Android/i.test(navigator.userAgent) ){
window.addEventListener("orientationchange", function() {
changeViewPort("maximum-scale", 1);
changeViewPort("maximum-scale", 10);
}
}
Just one line of coding is enough.. just try this out. and you can adjust even thicknes of icon-bar with this by adding pixels.
HTML
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#defaultNavbar1" aria-expanded="false"><span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#" <span class="icon-bar"></span><img class="img-responsive brand" src="img/brand.png">
</a></div>
CSS
.navbar-toggle, .icon-bar {
border:1px solid orange;
}
BOOM...
You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:
In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file"
field, ostensibly for backward compatibility reasons.
So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.
SELECT * FROM adds where id=(select max(id) from adds);
This query used to fetch the last record in your table.
I'm surprised I haven't seen this suggestion yet, but it gets even more specificity than testing with typeof
. Use Object.getOwnPropertyDescriptor()
if you need to know whether an object property was initialized with undefined
or if it was never initialized:
// to test someObject.someProperty
var descriptor = Object.getOwnPropertyDescriptor(someObject, 'someProperty');
if (typeof descriptor === 'undefined') {
// was never initialized
} else if (typeof descriptor.value === 'undefined') {
if (descriptor.get || descriptor.set) {
// is an accessor property, defined via getter and setter
} else {
// is initialized with `undefined`
}
} else {
// is initialized with some other value
}
Both lines you posted are fine, but you can do it purely in integers, and it will be the most efficient:
def sum_digits(n):
s = 0
while n:
s += n % 10
n //= 10
return s
or with divmod
:
def sum_digits2(n):
s = 0
while n:
n, remainder = divmod(n, 10)
s += remainder
return s
Even faster is the version without augmented assignments:
def sum_digits3(n):
r = 0
while n:
r, n = r + n % 10, n // 10
return r
> %timeit sum_digits(n)
1000000 loops, best of 3: 574 ns per loop
> %timeit sum_digits2(n)
1000000 loops, best of 3: 716 ns per loop
> %timeit sum_digits3(n)
1000000 loops, best of 3: 479 ns per loop
> %timeit sum(map(int, str(n)))
1000000 loops, best of 3: 1.42 us per loop
> %timeit sum([int(digit) for digit in str(n)])
100000 loops, best of 3: 1.52 us per loop
> %timeit sum(int(digit) for digit in str(n))
100000 loops, best of 3: 2.04 us per loop
little php script to do it:
#!/usr/bin/env php
<?php
declare(strict_types = 1);
if ($argc !== 2) {
fprintf ( STDERR, "usage: %s dir\n", $argv [0] );
die ( 1 );
}
$dir = rtrim ( $argv [1], DIRECTORY_SEPARATOR );
if (! is_readable ( $dir )) {
fprintf ( STDERR, "supplied path is not readable! (try running as an administrator?)" );
die(1);
}
if (! is_dir ( $dir )) {
fprintf ( STDERR, "supplied path is not a directory!" );
die(1);
}
$files = glob ( $dir . DIRECTORY_SEPARATOR . '*.avi' );
foreach ( $files as $file ) {
system ( "ffmpeg -i " . escapeshellarg ( $file ) . ' ' . escapeshellarg ( $file . '.mp4' ) );
}
may be this?
if some_condition and condition_a:
# do something
elif some_condition and condition_b:
# do something
# and then exit the outer if block
elif some_condition and not condition_b:
# more code here
else:
#blah
if
Can keep global variables in webpack i.e. in webpack.config.js
externals: {
'config': JSON.stringify(GLOBAL_VARIABLE: "global var value")
}
In js module can read like
var config = require('config')
var GLOBAL_VARIABLE = config.GLOBAL_VARIABLE
Hope this will help.
Using SQL_CALC_FOUND_ROWS
you can't.
The row count available through FOUND_ROWS() is transient and not intended to be available past the statement following the SELECT SQL_CALC_FOUND_ROWS statement.
As someone noted in your earlier question, using SQL_CALC_FOUND_ROWS
is frequently slower than just getting a count.
Perhaps you'd be best off doing this as as subquery:
SELECT
(select count(*) from my_table WHERE Name LIKE '%prashant%')
as total_rows,
Id, Name FROM my_table WHERE Name LIKE '%prashant%' LIMIT 0, 10;
You can keep rsouces directory in Directory NetBeans: Web Pages Eclipse: webapps
File: dispatcher-servlet.xml
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="controller" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<mvc:resources location="/resources/theme_name/" mapping="/resources/**" cache-period="10000"/>
<mvc:annotation-driven/>
</beans>
File: web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
<url-pattern>*.css</url-pattern>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
</web-app>
In JSP File
<link href="<c:url value="/resources/css/default.css"/>" rel="stylesheet" type="text/css"/>
.env
>= 5.0 (tested on 5.5)In .env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database1
DB_USERNAME=root
DB_PASSWORD=secret
DB_CONNECTION_SECOND=mysql
DB_HOST_SECOND=127.0.0.1
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=database2
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=secret
In config/database.php
'mysql' => [
'driver' => env('DB_CONNECTION'),
'host' => env('DB_HOST'),
'port' => env('DB_PORT'),
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
],
'mysql2' => [
'driver' => env('DB_CONNECTION_SECOND'),
'host' => env('DB_HOST_SECOND'),
'port' => env('DB_PORT_SECOND'),
'database' => env('DB_DATABASE_SECOND'),
'username' => env('DB_USERNAME_SECOND'),
'password' => env('DB_PASSWORD_SECOND'),
],
Note: In
mysql2
if DB_username and DB_password is same, then you can useenv('DB_USERNAME')
which is metioned in.env
first few lines.
.env
<5.0Define Connections
app/config/database.php
return array(
'default' => 'mysql',
'connections' => array(
# Primary/Default database connection
'mysql' => array(
'driver' => 'mysql',
'host' => '127.0.0.1',
'database' => 'database1',
'username' => 'root',
'password' => 'secret'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
# Secondary database connection
'mysql2' => array(
'driver' => 'mysql',
'host' => '127.0.0.1',
'database' => 'database2',
'username' => 'root',
'password' => 'secret'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
),
);
Schema
To specify which connection to use, simply run the connection()
method
Schema::connection('mysql2')->create('some_table', function($table)
{
$table->increments('id'):
});
Query Builder
$users = DB::connection('mysql2')->select(...);
Eloquent
Set the $connection
variable in your model
class SomeModel extends Eloquent {
protected $connection = 'mysql2';
}
You can also define the connection at runtime via the setConnection
method or the on
static method:
class SomeController extends BaseController {
public function someMethod()
{
$someModel = new SomeModel;
$someModel->setConnection('mysql2'); // non-static method
$something = $someModel->find(1);
$something = SomeModel::on('mysql2')->find(1); // static method
return $something;
}
}
Note Be careful about attempting to build relationships with tables across databases! It is possible to do, but it can come with some caveats and depends on what database and/or database settings you have.
Using Multiple Database Connections
When using multiple connections, you may access each connection
via the connection method on the DB
facade. The name
passed to the connection
method should correspond to one of the connections listed in your config/database.php
configuration file:
$users = DB::connection('foo')->select(...);
You may also access the raw, underlying PDO instance using the getPdo method on a connection instance:
$pdo = DB::connection()->getPdo();
Useful Links
I was being able to ping my connection but was STILL getting the 'connection refused' error. Turns out I was pinging myself! That's what the problem was.
You can set its visibility
property to hidden
.
Here is a little demonstration, where one button is used to toggle the other one:
<input type="button" id="toggler" value="Toggler" onClick="action();" />
<input type="button" id="togglee" value="Togglee" />
<script>
var hidden = false;
function action() {
hidden = !hidden;
if(hidden) {
document.getElementById('togglee').style.visibility = 'hidden';
} else {
document.getElementById('togglee').style.visibility = 'visible';
}
}
</script>
model._meta.get_all_field_names()
will give you all the model's field names, then you can use model._meta.get_field()
to work your way to the verbose name, and getattr(model_instance, 'field_name')
to get the value from the model.
NOTE: model._meta.get_all_field_names()
is deprecated in django 1.9. Instead use model._meta.get_fields()
to get the model's fields and field.name
to get each field name.
Besides Console.OutputEncoding = System.Text.Encoding.UTF8;
for some characters you need to install extra fonts (ie. Chinese).
In Windows 10 first go to Region & language settings and install support for required language:
After that you can go to Command Prompt Proporties (or Defaults if you like) and choose some font that supports your language (like KaiTi in Chinese case):
Unless I'm misunderstanding, you lost your .ssh
directory containing your private key on your local machine and so you want to remove the public key which was on a server and which allowed key-based login.
In that case, it will be stored in the .ssh/authorized_keys
file in your home directory on the server. You can just edit this file with a text editor and delete the relevant line if you can identify it (even easier if it's the only entry!).
I hope that key wasn't your only method of access to the server and you have some other way of logging in and editing the file. You can either manually add a new public key to authorised_keys
file or use ssh-copy-id
. Either way, you'll need password authentication set up for your account on the server, or some other identity or access method to get to the authorized_keys
file on the server.
ssh-add
adds identities to your SSH agent which handles management of your identities locally and "the connection to the agent is forwarded over SSH remote logins, and the user can thus use the privileges given by the identities anywhere in the network in a secure way." (man page), so I don't think it's what you want in this case. It doesn't have any way to get your public key onto a server without you having access to said server via an SSH login as far as I know.
The value returned by Date.prototype.toLocaleString is implementation dependent, so you get what you get. You can try to parse the string to remove seconds, but it may be different in different browsers so you'd need to make allowance for every browser in use.
Creating your own, unambiguous format isn't difficult using Date methods. For example:
function formatTimeHHMMA(d) {
function z(n){return (n<10?'0':'')+n}
var h = d.getHours();
return (h%12 || 12) + ':' + z(d.getMinutes()) + ' ' + (h<12? 'AM' :'PM');
}
You can create a folder with os.makedirs()
and use os.path.exists() to see if it already exists:
newpath = r'C:\Program Files\arbitrary'
if not os.path.exists(newpath):
os.makedirs(newpath)
If you're trying to make an installer: Windows Installer does a lot of work for you.
Call a custom function?
http://msdn.microsoft.com/en-us/library/ms155798.aspx
You could always put a case statement in there to handle different types of 'blank' data.
You can use jquery's load function here.
$("#your_element_id").load("file_name.html");
If you need more info, here is the link.
try this it worked in my case
backgroundImage: `url("${Background}")`
This is from Apple doc
Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.
You get the error message Class "HomeCell" has no initializers because your variables is in an indeterminate state. Either you create initializers or you make them optional types, using ! or ?
This can also be controlled with the apache configuration. Check the httpd.conf and/or .htaccess for something like the following:
php_value upload_max_filesize 10M
@Override
public void onClick(View v) {
int pos = getAdapterPosition();
}
Simple as that, on ViewHolder
var x = 1234567;
x.toString().length;
This process will also work forFloat Number
and for Exponential number
also.
To clarify an already posted solution due to questions in the comments
import numpy
array = numpy.array([49, 51, 53, 56])
array = array - 13
will output:
array([36, 38, 40, 43])
(This is for the benefit of others who may refer)
You can simply use cin and a char array. The cin input is delimited by the first whitespace it encounters.
#include<iostream>
using namespace std;
main()
{
char word[50];
cin>>word;
while(word){
//Do stuff with word[]
cin>>word;
}
}
You can use mx.DateTime module
import mx.DateTime as mt
t1 = mt.now()
t2 = mt.now()
print int((t2-t1).seconds)
The solutions which use input="number"
step="0.01"
work great for me in Chrome, however do not work in some browsers, specifically Frontmotion Firefox 35 in my case.. which I must support.
My solution was to jQuery with Igor Escobar's jQuery Mask plugin, as follows:
$(document).ready(function () {
$('.usd_input').mask('00000.00', { reverse: true });
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>
<input type="text" autocomplete="off" class="usd_input" name="dollar_amt">
_x000D_
This works well, of course one should check the submitted value afterward :) NOTE, if I did not have to do this for browser compatibility I would use the above answer by @Rich Bradshaw.
The difference between XML and JSON is that XML is a meta-language/markup language and JSON is a lightweight data-interchange. That is, XML syntax is designed specifically to have no inherent semantics. Particular element names don't mean anything until a particular processing application processes them in a particular way. By contrast, JSON syntax has specific semantics built in stuff between {} is an object, stuff between [] is an array, etc.
A JSON parser, therefore, knows exactly what every JSON document means. An XML parser only knows how to separate markup from data. To deal with the meaning of an XML document, you have to write additional code.
To illustrate the point, let me borrow Guffa's example:
{ "persons": [
{
"name": "Ford Prefect",
"gender": "male"
},
{
"name": "Arthur Dent",
"gender": "male"
},
{
"name": "Tricia McMillan",
"gender": "female"
} ] }
The XML equivalent he gives is not really the same thing since while the JSON example is semantically complete, the XML would require to be interpreted in a particular way to have the same effect. In effect, the JSON is an example uses an established markup language of which the semantics are already known, whereas the XML example creates a brand new markup language without any predefined semantics.
A better XML equivalent would be to define a (fictitious) XJSON language with the same semantics as JSON, but using XML syntax. It might look something like this:
<xjson>
<object>
<name>persons</name>
<value>
<array>
<object>
<value>Ford Prefect</value>
<gender>male</gender>
</object>
<object>
<value>Arthur Dent</value>
<gender>male</gender>
</object>
<object>
<value>Tricia McMillan</value>
<gender>female</gender>
</object>
</array>
</value>
</object>
</xjson>
Once you wrote an XJSON processor, it could do exactly what JSON processor does, for all the types of data that JSON can represent, and you could translate data losslessly between JSON and XJSON.
So, to complain that XML does not have the same semantics as JSON is to miss the point. XML syntax is semantics-free by design. The point is to provide an underlying syntax that can be used to create markup languages with any semantics you want. This makes XML great for making up ad-hoc data and document formats, because you don't have to build parsers for them, you just have to write a processor for them.
But the downside of XML is that the syntax is verbose. For any given markup language you want to create, you can come up with a much more succinct syntax that expresses the particular semantics of your particular language. Thus JSON syntax is much more compact than my hypothetical XJSON above.
If follows that for really widely used data formats, the extra time required to create a unique syntax and write a parser for that syntax is offset by the greater succinctness and more intuitive syntax of the custom markup language. It also follows that it often makes more sense to use JSON, with its established semantics, than to make up lots of XML markup languages for which you then need to implement semantics.
It also follows that it makes sense to prototype certain types of languages and protocols in XML, but, once the language or protocol comes into common use, to think about creating a more compact and expressive custom syntax.
It is interesting, as a side note, that SGML recognized this and provided a mechanism for specifying reduced markup for an SGML document. Thus you could actually write an SGML DTD for JSON syntax that would allow a JSON document to be read by an SGML parser. XML removed this capability, which means that, today, if you want a more compact syntax for a specific markup language, you have to leave XML behind, as JSON does.
You can also use switch case like
String columndata2 = "";
if (cell.getColumnIndex() == 1) {// To match column index
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BLANK:
columndata2 = "";
break;
case Cell.CELL_TYPE_NUMERIC:
columndata2 = "" + cell.getNumericCellValue();
break;
case Cell.CELL_TYPE_STRING:
columndata2 = cell.getStringCellValue();
break;
}
}
System.out.println("Cell Value "+ columndata2);
throw $e->getMessage();
You try to throw a string
As a sidenote: Exceptions are usually to define exceptional states of the application and not for error messages after validation. Its not an exception, when a user gives you invalid data
Ok, Im assuming you want to put the .left inside the container so I suggest you edit your html. The key is the position:absolute
and right:0
#right {
background-color: red;
height: 300px;
width: 300px;
z-index: 999999;
margin-top: 0px;
position: absolute;
right:0;
}
here is the full code: http://jsfiddle.net/T9FJL/
and at the same time for Cordova (a.k.a Phonegap), React-Native and all other development platforms
Format : 9-Patch PNG (recommended)
Dimensions
- LDPI:
- Portrait: 200x320px
- Landscape: 320x200px
- MDPI:
- Portrait: 320x480px
- Landscape: 480x320px
- HDPI:
- Portrait: 480x800px
- Landscape: 800x480px
- XHDPI:
- Portrait: 720px1280px
- Landscape: 1280x720px
- XXHDPI
- Portrait: 960x1600px
- Landscape: 1600x960px
- XXXHDPI
- Portrait: 1280x1920px
- Landscape: 1920x1280px
Note: Preparing XXXHDPI is not needed and also maybe XXHDPI size too because of the repeating areas of 9-patch images. On the other hand, if only Portrait sizes are used the App size could be more less. More pictures mean more space is need.
I think there is no an exact size for the all devices. I use Xperia Z 5". If you develop a crossplatform-webview app you should consider a lot of things (whether screen has softkey navigation buttons or not, etc). Therefore, I think there is only one suitable solution. The solution is to prepare a 9-patch splash screen (find How to design a new splash screen
heading below).
That's it!
Cordova specific code
To be added lines into the config.xml for 9-patch splash screens
<preference name="SplashScreen" value="screen" />
<preference name="SplashScreenDelay" value="6000" />
<platform name="android">
<splash src="res/screen/android/ldpi.9.png" density="ldpi"/>
<splash src="res/screen/android/mdpi.9.png" density="mdpi"/>
<splash src="res/screen/android/hdpi.9.png" density="hdpi"/>
<splash src="res/screen/android/xhdpi.9.png" density="xhdpi"/>
</platform>
To be added lines into the config.xml when using non-9-patch splash screens
<platform name="android">
<splash src="res/screen/android/splash-land-hdpi.png" density="land-hdpi"/>
<splash src="res/screen/android/splash-land-ldpi.png" density="land-ldpi"/>
<splash src="res/screen/android/splash-land-mdpi.png" density="land-mdpi"/>
<splash src="res/screen/android/splash-land-xhdpi.png" density="land-xhdpi"/>
<splash src="res/screen/android/splash-port-hdpi.png" density="port-hdpi"/>
<splash src="res/screen/android/splash-port-ldpi.png" density="port-ldpi"/>
<splash src="res/screen/android/splash-port-mdpi.png" density="port-mdpi"/>
<splash src="res/screen/android/splash-port-xhdpi.png" density="port-xhdpi"/>
</platform>
I would describe a simple way to create proper splash screen using this way. Assume we're designing a 1280dp x 720dp - xhdpi (x-large) screen. I've written for the sake of example the below;
In Photoshop: File -> New in new dialog window set your screens
Width: 720 Pixels Height: 1280 Pixels
I guess the above sizes mean Resolution is 320 Pixels/Inch. But to ensure you can change resolution value to 320 in your dialog window. In this case Pixels/Inch = DPI
Congratulations... You have a 720dp x 1280dp splash screen template.
After you designed your splash screen, if you want to design 9-Patch splash screen, you should insert 1 pixel gap for every side. For this reason you should increase +2 pixel your canvas size's width and height ( now your image sizes are 722 x 1282 ).
I've left the blank 1 pixel gap at every side as directed the below.
Changing the canvas size by using Photoshop:
- Open a splash screen png file in Photoshop
- Click onto the lock icon next to the 'Background' name in the Layers field (to leave blank instead of another color like white) if there is like the below:
- Change the canvas size from Image menu ( Width: 720 pixels to 722 pixels and Height: 1280 pixels to 1282 pixels). Now, should see 1 pixel gap at every side of the splash screen image.
Then you can use C:\Program Files (x86)\Android\android-studio\sdk\tools\draw9patch.bat to convert a 9-patch file. For that open your splash screen on draw9patch app. You should define your logo and expandable areas. Notice the black line the following example splash screen. The black line's thickness is just 1 px ;) Left and Top sides black lines define your splash screen's must display area. Exactly as your designed. Right and Bottom lines define the addable and removable area (automatically repeating areas).
Just do that: Zoom your image's top edge on draw9patch application. Click and drag your mouse to draw line. And press shift + click and drag your mouse to erase line.
If you develop a cross-platform app (like Cordova/PhoneGap) you can find the following address almost all mabile OS splash screen sizes. Click for Windows Phone, WebOS, BlackBerry, Bada-WAC and Bada splash screen sizes.
https://github.com/phonegap/phonegap/wiki/App-Splash-Screen-Sizes
And if you need IOS, Android etc. app icon sizes you can visit here.
Format : PNG (recommended)
Dimensions
- Tablet (iPad)
- Non-Retina (1x)
- Portrait: 768x1024px
- Landscape: 1024x768px
- Retina (2x)
- Portrait: 1536x2048px
- Landscape: 2048x1536px
- Handheld (iPhone, iPod)
- Non-Retina (1x)
- Portrait: 320x480px
- Landscape: 480x320px
- Retina (2x)
- Portrait: 640x960px
- Landscape: 960x640px
- iPhone 5 Retina (2x)
- Portrait: 640x1136px
- Landscape: 1136x640px
- iPhone 6 (2x)
- Portrait: 750x1334px
- Landscape: 1334x750px
- iPhone 6 Plus (3x)
- Portrait: 1242x2208px
- Landscape: 2208x1242px
Build a new list with a list comprehension:
new_items = [x if x % 2 else None for x in items]
You can modify the original list in-place if you want, but it doesn't actually save time:
items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for index, item in enumerate(items):
if not (item % 2):
items[index] = None
Here are (Python 3.6.3) timings demonstrating the non-timesave:
In [1]: %%timeit
...: items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
...: for index, item in enumerate(items):
...: if not (item % 2):
...: items[index] = None
...:
1.06 µs ± 33.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [2]: %%timeit
...: items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
...: new_items = [x if x % 2 else None for x in items]
...:
891 ns ± 13.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
And Python 2.7.6 timings:
In [1]: %%timeit
...: items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
...: for index, item in enumerate(items):
...: if not (item % 2):
...: items[index] = None
...:
1000000 loops, best of 3: 1.27 µs per loop
In [2]: %%timeit
...: items = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
...: new_items = [x if x % 2 else None for x in items]
...:
1000000 loops, best of 3: 1.14 µs per loop
Here is a very basic but modern implementation of required radio buttons with native HTML5 validation:
fieldset {
display: block;
margin-left: 0;
margin-right: 0;
padding-top: 0;
padding-bottom: 0;
padding-left: 0;
padding-right: 0;
border: none;
}
body {font-size: 15px; font-family: serif;}
input {
background: transparent;
border-radius: 0px;
border: 1px solid black;
padding: 5px;
box-shadow: none!important;
font-size: 15px; font-family: serif;
}
input[type="submit"] {padding: 5px 10px; margin-top: 5px;}
label {display: block; padding: 0 0 5px 0;}
form > div {margin-bottom: 1em; overflow: auto;}
.hidden {
opacity: 0;
position: absolute;
pointer-events: none;
}
.checkboxes label {display: block; float: left;}
input[type="radio"] + span {
display: block;
border: 1px solid black;
border-left: 0;
padding: 5px 10px;
}
label:first-child input[type="radio"] + span {border-left: 1px solid black;}
input[type="radio"]:checked + span {background: silver;}
_x000D_
<form>
<div>
<label for="name">Name (optional)</label>
<input id="name" type="text" name="name">
</div>
<fieldset>
<legend>Gender</legend>
<div class="checkboxes">
<label for="male"><input id="male" type="radio" name="gender" value="male" class="hidden" required="required"><span>Male</span></label>
<label for="female"><input id="female" type="radio" name="gender" value="female" class="hidden" required="required"><span>Female </span></label>
<label for="other"><input id="other" type="radio" name="gender" value="other" class="hidden" required="required"><span>Other</span></label>
</div>
</fieldset>
<input type="submit" value="Send" />
</form>
_x000D_
Although I am a big fan of the minimalistic approach of using native HTML5 validation, you might want to replace it with Javascript validation on the long run. Javascript validation gives you far more control over the validation process and it allows you to set real classes (instead of pseudo classes) to improve the styling of the (in)valid fields. This native HTML5 validation can be your fall-back in case of broken (or lack of) Javascript. You can find an example of that here, along with some other suggestions on how to make Better forms, inspired by Andrew Cole.
Google recently changed the terms of use of its Google Maps APIs; if you were already using them on a website (different from localhost) prior to June 22nd, 2016, nothing will change for you; otherwise, you will get the aforementioned issue and need an API key in order to fix your error. The free API key is valid up to 25,000 map loads per day.
In this article you will find everything you may need to know regarding the topic, including a tutorial to fix your error:
Google Maps API error: MissingKeyMapError [SOLVED]
Also, remember to replace YOUR_API_KEY with your actual API key!
Relatively effective approach with _sorted_
a numpy
arrays:
b = np.array([1,3,3, 8, 12, 12,12])
numpy.hstack([b[0], [x[0] for x in zip(b[1:], b[:-1]) if x[0]!=x[1]]])
Outputs:
array([ 1, 3, 8, 12])
A good example given in book: Practical Python By Magnus Lie Hetland
>>> zip(range(5), xrange(100000000))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
I wouldn’t recommend using range instead of xrange in the preceding example—although only the first five numbers are needed, range calculates all the numbers, and that may take a lot of time. With xrange, this isn’t a problem because it calculates only those numbers needed.
Yes I read @Brian's answer: In python 3, range() is a generator anyway and xrange() does not exist.
#!/usr/bin/env python
import sys
import yaml
def main(argv):
with open(argv[0]) as stream:
try:
#print(yaml.load(stream))
return 0
except yaml.YAMLError as exc:
print(exc)
return 1
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
This is more of an IDE feature than a language feature. Netbeans allows you to define your own folding definitions using the following definition:
// <editor-fold defaultstate="collapsed" desc="user-description">
...any code...
// </editor-fold>
As noted in the article, this may be supported by other editors too, but there are no guarantees.
Unfortunately @BrianFreud's answer doesn't fit my needs, I had a little different need, and I know that is not the answer for @BrianFreud's question, but I am leaving it here because a lot of persons got here with my same need. I needed something like 'How to get a file or blob from an URL?', and the current correct answer does not fit my needs because its not cross-domain.
I have a website that consumes images from an Amazon S3/Azure Storage, and there I store objects named with uniqueidentifiers:
sample: http://****.blob.core.windows.net/systemimages/bf142dc9-0185-4aee-a3f4-1e5e95a09bcf
Some of this images should be download from our system interface. To avoid passing this traffic through my HTTP server, since this objects does not require any security to be accessed (except by domain filtering), I decided to make a direct request on user's browser and use local processing to give the file a real name and extension.
To accomplish that I have used this great article from Henry Algus: http://www.henryalgus.com/reading-binary-files-using-jquery-ajax/
1. First step: Add binary support to jquery
/**
*
* jquery.binarytransport.js
*
* @description. jQuery ajax transport for making binary data type requests.
* @version 1.0
* @author Henry Algus <[email protected]>
*
*/
// use this transport for "binary" data type
$.ajaxTransport("+binary", function (options, originalOptions, jqXHR) {
// check for conditions and support for blob / arraybuffer response type
if (window.FormData && ((options.dataType && (options.dataType == 'binary')) || (options.data && ((window.ArrayBuffer && options.data instanceof ArrayBuffer) || (window.Blob && options.data instanceof Blob))))) {
return {
// create new XMLHttpRequest
send: function (headers, callback) {
// setup all variables
var xhr = new XMLHttpRequest(),
url = options.url,
type = options.type,
async = options.async || true,
// blob or arraybuffer. Default is blob
dataType = options.responseType || "blob",
data = options.data || null,
username = options.username || null,
password = options.password || null;
xhr.addEventListener('load', function () {
var data = {};
data[options.dataType] = xhr.response;
// make callback and send data
callback(xhr.status, xhr.statusText, data, xhr.getAllResponseHeaders());
});
xhr.open(type, url, async, username, password);
// setup custom headers
for (var i in headers) {
xhr.setRequestHeader(i, headers[i]);
}
xhr.responseType = dataType;
xhr.send(data);
},
abort: function () {
jqXHR.abort();
}
};
}
});
2. Second step: Make a request using this transport type.
function downloadArt(url)
{
$.ajax(url, {
dataType: "binary",
processData: false
}).done(function (data) {
// just my logic to name/create files
var filename = url.substr(url.lastIndexOf('/') + 1) + '.png';
var blob = new Blob([data], { type: 'image/png' });
saveAs(blob, filename);
});
}
Now you can use the Blob created as you want to, in my case I want to save it to disk.
3. Optional: Save file on user's computer using FileSaver
I have used FileSaver.js to save to disk the downloaded file, if you need to accomplish that, please use this javascript library:
https://github.com/eligrey/FileSaver.js/
I expect this to help others with more specific needs.
Slightly unrelated to your problem, so here's one for Google.
If you didn't mysqldump the SQL, it might be that your SQL is broken.
I just got this error by accidentally having an unclosed string literal in my code. Sloppy fingers happen.
That's a fantastic error message to get for a runaway string, thanks for that MySQL!
Note that Math.hypot
is part of the ES2015 standard. There's also a good polyfill on the MDN doc for this feature.
So getting the distance becomes as easy as Math.hypot(x2-x1, y2-y1)
.
how do you write out the parameters os.path.dirname
.... command?
import os, sys
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.dirname(CURRENT_DIR))
You can do git push --force
but be aware that you are rewriting history and anyone using the repo will have issue with this.
If you want to prevent this problem, don't use reset, but instead use git revert
you have forgotten width of parent
.parent {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
position: absolute;_x000D_
width:100%_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child">text</div>_x000D_
</div>
_x000D_
From the diff man page:
-q
Report only whether the files differ, not the details of the differences.
-r
When comparing directories, recursively compare any subdirectories found.
Example command:
diff -qr dir1 dir2
Example output (depends on locale):
$ ls dir1 dir2
dir1:
same-file different only-1
dir2:
same-file different only-2
$ diff -qr dir1 dir2
Files dir1/different and dir2/different differ
Only in dir1: only-1
Only in dir2: only-2
This code extracts the YouTube video duration using the YouTube API v3 by passing a video ID. It worked for me.
<?php
function getDuration($videoID){
$apikey = "YOUR-Youtube-API-KEY"; // Like this AIcvSyBsLA8znZn-i-aPLWFrsPOlWMkEyVaXAcv
$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$videoID&key=$apikey");
$VidDuration =json_decode($dur, true);
foreach ($VidDuration['items'] as $vidTime)
{
$VidDuration= $vidTime['contentDetails']['duration'];
}
preg_match_all('/(\d+)/',$VidDuration,$parts);
return $parts[0][0] . ":" .
$parts[0][1] . ":".
$parts[0][2]; // Return 1:11:46 (i.e.) HH:MM:SS
}
echo getDuration("zyeubYQxHyY"); // Video ID
?>
You can get your domain's own YouTube API key on https://console.developers.google.com and generate credentials for your own requirement.
Reference article: Show red color border for invalid input fields angualrjs
I used ng-class on all input fields.like below
<input type="text" ng-class="{submitted:newEmployee.submitted}" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/>
when I click on save button I am changing newEmployee.submitted value to true(you can check it in my question). So when I click on save, a class named submitted gets added to all input fields(there are some other classes initially added by angularjs).
So now my input field contains classes like this
class="ng-pristine ng-invalid submitted"
now I am using below css code to show red border on all invalid input fields(after submitting the form)
input.submitted.ng-invalid
{
border:1px solid #f00;
}
Thank you !!
Update:
We can add the ng-class at the form element instead of applying it to all input elements. So if the form is submitted, a new class(submitted) gets added to the form element. Then we can select all the invalid input fields using the below selector
form.submitted .ng-invalid
{
border:1px solid #f00;
}
A variation on the MutableInt approach that might be even faster, if a bit of a hack, is to use a single-element int array:
Map<String,int[]> map = new HashMap<String,int[]>();
...
int[] value = map.get(key);
if (value == null)
map.put(key, new int[]{1} );
else
++value[0];
It would be interesting if you could rerun your performance tests with this variation. It might be the fastest.
Edit: The above pattern worked fine for me, but eventually I changed to use Trove's collections to reduce memory size in some very large maps I was creating -- and as a bonus it was also faster.
One really nice feature is that the TObjectIntHashMap
class has a single adjustOrPutValue
call that, depending on whether there is already a value at that key, will either put an initial value or increment the existing value. This is perfect for incrementing:
TObjectIntHashMap<String> map = new TObjectIntHashMap<String>();
...
map.adjustOrPutValue(key, 1, 1);
A view uses a query to pull data from the underlying tables.
A materialized view is a table on disk that contains the result set of a query.
Materialized views are primarily used to increase application performance when it isn't feasible or desirable to use a standard view with indexes applied to it. Materialized views can be updated on a regular basis either through triggers or by using the ON COMMIT REFRESH
option. This does require a few extra permissions, but it's nothing complex. ON COMMIT REFRESH
has been in place since at least Oracle 10.
Change clean to
rm -f .lambda .lambda_t .activity .activity_t_lambda
I.e. don't prompt for remove; don't complain if file doesn't exist.
By the answer of rudivonstaden
txtBlock.Text = await response.Content.ReadAsStringAsync();
but if you don't want to make the method async you can use
txtBlock.Text = response.Content.ReadAsStringAsync();
txtBlock.Text.Wait();
Wait() it's important, bec?use we are doing async operations and we must wait for the task to complete before going ahead.
For 3.x version
$( '.modal' ).modal( 'hide' ).data( 'bs.modal', null );
For 2.x version (risky; read comments below) When you create bootstrap modal three elements on your page being changed. So if you want to completely rollback all changes, you have to do it manually for each of it.
$( '.modal' ).remove();
$( '.modal-backdrop' ).remove();
$( 'body' ).removeClass( "modal-open" );
Benjamin Gruenbaum answer is of course great,. But I can also see were Nathan Hagen point of view with the level of abstraction seem vague. Having short object properties like e & v
don't help either, but of course that could be changed.
In Javascript there is standard Error object, called Error
,. Ideally you always throw an instance / descendant of this. The advantage is that you can do instanceof Error
, and you know something is an error.
So using this idea, here is my take on the problem.
Basically catch the error, if the error is not of type Error, wrap the error inside an Error object. The resulting array will have either resolved values, or Error objects you can check on.
The instanceof inside the catch, is in case you use some external library that maybe did reject("error")
, instead of reject(new Error("error"))
.
Of course you could have promises were you resolve an error, but in that case it would most likely make sense to treat as an error anyway, like the last example shows.
Another advantage of doing it this, array destructing is kept simple.
const [value1, value2] = PromiseAllCatch(promises);
if (!(value1 instanceof Error)) console.log(value1);
Instead of
const [{v: value1, e: error1}, {v: value2, e: error2}] = Promise.all(reflect..
if (!error1) { console.log(value1); }
You could argue that the !error1
check is simpler than an instanceof, but your also having to destruct both v & e
.
function PromiseAllCatch(promises) {_x000D_
return Promise.all(promises.map(async m => {_x000D_
try {_x000D_
return await m;_x000D_
} catch(e) {_x000D_
if (e instanceof Error) return e;_x000D_
return new Error(e);_x000D_
}_x000D_
}));_x000D_
}_x000D_
_x000D_
_x000D_
async function test() {_x000D_
const ret = await PromiseAllCatch([_x000D_
(async () => "this is fine")(),_x000D_
(async () => {throw new Error("oops")})(),_x000D_
(async () => "this is ok")(),_x000D_
(async () => {throw "Still an error";})(),_x000D_
(async () => new Error("resolved Error"))(),_x000D_
]);_x000D_
console.log(ret);_x000D_
console.log(ret.map(r =>_x000D_
r instanceof Error ? "error" : "ok"_x000D_
).join(" : ")); _x000D_
}_x000D_
_x000D_
test();
_x000D_
An explicit default initialization can help:
struct foo {
bool a {};
bool b {};
bool c {};
} bar;
Behavior bool a {}
is same as bool b = bool();
and return false
.
This worked for my purposes. Pretty basic and simple, but it did what I needed (which was to get a personal photo of mine onto the internet so I could use its URL).
Go to photos.google.com and open any image that you wish to embed in your website.
Tap the Share Icon and then choose "Get Link" to generate a shareable link for that image.
Go to j.mp/EmbedGooglePhotos, paste that link and it will instantly generate the embed code for that picture.
Open your website template, paste the generated code and save. The image will now serve directly from your Google Photos account.
Check this video tutorial out if you have trouble.
You might have to re-check the order in which you are merging the files, it should be something like:
Most answers here do not realize the problem, the user wants to have a COPY of the elements from first list to the second list, destination list elements are new objects and not reference to the elements of original list. (means changing an element of second list should not change values for corresponding element of source list.) For the mutable objects we cannot use ArrayList(Collection) constructor because it will simple refer to the original list element and will not copy. You need to have a list cloner for each object when copying.
This probably isnt relevant here. But to eliminate these html entites from an entire document, you can do something like this: (Assume document = page and please forgive the sloppy code, but if you have ideas as to how to make it better, Im all ears - Im new to this).
import re
import HTMLParser
regexp = "&.+?;"
list_of_html = re.findall(regexp, page) #finds all html entites in page
for e in list_of_html:
h = HTMLParser.HTMLParser()
unescaped = h.unescape(e) #finds the unescaped value of the html entity
page = page.replace(e, unescaped) #replaces html entity with unescaped value
Here's an approach that leaves the default collapse behavior unchanged while allowing a new section of navigation to always remain visible. Its an augmentation of navbar
; navbar-header-menu
is a CSS class I have created and is not part of Bootstrap proper.
Place this in the navbar-header
element after navbar-brand
:
<div class="navbar-header-menu">
<ul class="nav navbar-nav">
<li class="active"><a href="#">I'm always visible</a></li>
</ul>
<form class="navbar-form" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
Add this CSS:
.navbar-header-menu {
float: left;
}
.navbar-header-menu > .navbar-nav {
float: left;
margin: 0;
}
.navbar-header-menu > .navbar-nav > li {
float: left;
}
.navbar-header-menu > .navbar-nav > li > a {
padding-top: 15px;
padding-bottom: 15px;
}
.navbar-header-menu > .navbar-nav .open .dropdown-menu {
position: absolute;
float: left;
width: auto;
margin-top: 0;
background-color: #fff;
border: 1px solid #ccc;
border: 1px solid rgba(0,0,0,.15);
-webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175);
box-shadow: 0 6px 12px rgba(0,0,0,.175);
}
.navbar-header-menu > .navbar-form {
float: left;
width: auto;
padding-top: 0;
padding-bottom: 0;
margin-right: 0;
margin-left: 0;
border: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.navbar-header-menu > .navbar-form > .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
.navbar-header-menu > .navbar-left {
float: left;
}
.navbar-header-menu > .navbar-right {
float: right !important;
}
.navbar-header-menu > *.navbar-right:last-child {
margin-right: -15px !important;
}
Check the fiddle: http://jsfiddle.net/L2txunqo/
Caveat: navbar-right
can be used to sort elements visually but is not guaranteed to pull the element to the furthest right portion of the screen. The fiddle demonstrates that behavior with the navbar-form
.
If you want to get a floating point value with two decimal places limited at the time of calling input,
Check this out ~
a = eval(format(float(input()), '.2f')) # if u feed 3.1415 for 'a'.
print(a) # output 3.14 will be printed.
The Version 56.0.2924.87 which I am in now, Undocks the DevTools automatically if you are NOT in a desktop. Otherwise Open a NEW new Chrome tab and Inspect to Dock the DevTools back into the window.
SELECT *
FROM
<table_name>
WHERE
<date_field>
BETWEEN
DATE_SUB(NOW(), INTERVAL 1 MONTH) AND NOW();
Similarly, You can select records for 1 month, 2 months etc.
UPDATE: DELETE from a trigger works on both MSSql 7 and MSSql 2008.
I'm no relational guru, nor a SQL standards wonk. However - contrary to the accepted answer - MSSQL deals just fine with both recursive and nested trigger evaluation. I don't know about other RDBMSs.
The relevant options are 'recursive triggers' and 'nested triggers'. Nested triggers are limited to 32 levels, and default to 1. Recursive triggers are off by default, and there's no talk of a limit - but frankly, I've never turned them on, so I don't know what happens with the inevitable stack overflow. I suspect MSSQL would just kill your spid (or there is a recursive limit).
Of course, that just shows that the accepted answer has the wrong reason, not that it's incorrect. However, prior to INSTEAD OF triggers, I recall writing ON INSERT triggers that would merrily UPDATE the just inserted rows. This all worked fine, and as expected.
A quick test of DELETEing the just inserted row also works:
CREATE TABLE Test ( Id int IDENTITY(1,1), Column1 varchar(10) )
GO
CREATE TRIGGER trTest ON Test
FOR INSERT
AS
SET NOCOUNT ON
DELETE FROM Test WHERE Column1 = 'ABCDEF'
GO
INSERT INTO Test (Column1) VALUES ('ABCDEF')
--SCOPE_IDENTITY() should be the same, but doesn't exist in SQL 7
PRINT @@IDENTITY --Will print 1. Run it again, and it'll print 2, 3, etc.
GO
SELECT * FROM Test --No rows
GO
You have something else going on here.
HTML: text/html
, full-stop.
XHTML: application/xhtml+xml
, or only if following HTML compatbility guidelines, text/html
. See the W3 Media Types Note.
XML: text/xml
, application/xml
(RFC 2376).
There are also many other media types based around XML, for example application/rss+xml
or image/svg+xml
. It's a safe bet that any unrecognised but registered ending in +xml
is XML-based. See the IANA list for registered media types ending in +xml
.
(For unregistered x-
types, all bets are off, but you'd hope +xml
would be respected.)
I find this simple T-SQL query useful for returning valid e-mail addresses
SELECT email
FROM People
WHERE email LIKE '%_@__%.__%'
AND PATINDEX('%[^a-z,0-9,@,.,_]%', REPLACE(email, '-', 'a')) = 0
The PATINDEX bit eliminates all e-mail addresses containing characters that are not in the allowed a-z, 0-9, '@', '.', '_' & '-' set of characters.
It can be reversed to do what you want like this:
SELECT email
FROM People
WHERE NOT (email LIKE '%_@__%.__%'
AND PATINDEX('%[^a-z,0-9,@,.,_]%', REPLACE(email, '-', 'a')) = 0)
Using regex, the result is in $matches[1]:
$str = "test.txt ; 131 136 80 89 119 17 60 123 210 121 188 42 136 200 131 198"
$str -match "^(.*?)\s\;"
$matches[1]
test.txt
With Express 3.0:
<%- include myview.ejs %>
the path is relative from the caller who includes the file, not from the views directory set with app.set("views", "path/to/views")
.
(Update: the newest syntax for ejs v3.0.1 is <%- include('myview.ejs') %>
)
The answer that the OP accepted is wildly different from the question I thought was asked. I thought the OP wanted a way to auto-align =
signs or +
signs, similar to the tabularize plugin for vim.
For this task, I found the Columns4Eclipse plugin to be just what I needed.
SQL Server equivalents to Excel's string-based DEC2HEX, HEX2DEC functions:
--Convert INT to hex string:
PRINT CONVERT(VARCHAR(8),CONVERT(VARBINARY(4), 16777215),2) --DEC2HEX
--Convert hex string to INT:
PRINT CONVERT(INT,CONVERT(VARBINARY(4),'00FFFFFF',2)) --HEX2DEC
forward to nikobelia
For those who using jenkins to run the play book, I just added to my jenkins job before running the ansible-playbook the he environment variable ANSIBLE_HOST_KEY_CHECKING = False For instance this:
export ANSIBLE_HOST_KEY_CHECKING=False
ansible-playbook 'playbook.yml' \
--extra-vars="some vars..." \
--tags="tags_name..." -vv
I used maxlength and minlength with or without required
and it worked for me very well for HTML5.
<input id="passcode" type="password" minlength="8" maxlength="10">
_x000D_
`
There is another method with Java 8 in a null-safe way.
List<SomeBean> wsListCopy = Optional.ofNullable(wsList)
.map(Collection::stream)
.orElseGet(Stream::empty)
.collect(Collectors.toList());
If you want to skip one element.
List<SomeBean> wsListCopy = Optional.ofNullable(wsList)
.map(Collection::stream)
.orElseGet(Stream::empty)
.skip(1)
.collect(Collectors.toList());
With Java 9+, the stream method of Optional can be used
Optional.ofNullable(wsList)
.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList())
__FILE__
use examples based on localhost server results:
echo __FILE__;
// C:\LocalServer\www\templates\page.php
echo strrchr( __FILE__ , '\\' );
// \page.php
echo substr( strrchr( __FILE__ , '\\' ), 1);
// page.php
echo basename(__FILE__, '.php');
// page
I have used the following procedure.
Procedure to install the apk files in Android Emulator(AVD):
Check your installed directory(ex: C:\Program Files (x86)\Android\android-sdk\platform-tools), whether it has the adb.exe or not). If not present in this folder, then download the attachment here, extract the zip files. You will get adb files, copy and paste those three files inside tools folder
Run AVD manager from C:\Program Files (x86)\Android\android-sdk and start the Android Emulator.
Copy and paste the apk file inside the C:\Program Files (x86)\Android\android-sdk\platform-tools
Go to Start -> Run -> cmd
Type cd “C:\Program Files (x86)\Android\android-sdk\platform-tools”
Type adb install example.apk
After getting success command
Go to Application icon in Android emulator, we can see the your application