Right click on Yourproject(in project Explorer)-->Build Project
It will compile all files in your project and updates your build folder, all without running.
Sometime we need to compile one single file out of thousand files to fix the problem. In such a case, One can create same folder structure like class path, decompile the file into java or copy java file from source code. Make required changes, compile one particular file into class with all dependency/classes in place and finally replace the class file. Finally restart the container. Once war is exploded file will not be replaced.
function groupBy(data, property) {
return data.reduce((acc, obj) => {
const key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
}
groupBy(people, 'age');
To follow up the answer above, for a .war
artifact, I found I had to apply the equivalent configuration to maven-war-plugin
, rather than maven-jar-plugin
:
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.1</version>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
</archive>
</configuration>
</plugin>
This added the version information to MANIFEST.MF
in the project's .jar
(included in WEB-INF/lib
of the .war
)
Either char(13)
or char(10)
would work. But it is recommended to use char(13) + char(10)
char(10)
= \n
- new linechar(13)
= \r
- go to the beginning of the lineIn Python 3.8 the dirs_exist_ok
keyword argument was added to shutil.copytree()
:
dirs_exist_ok
dictates whether to raise an exception in casedst
or any missing parent directory already exists.
So, the following will work in recent versions of Python, even if the destination directory already exists:
shutil.copytree(src, dest, dirs_exist_ok=True) # 3.8+ only!
One major benefit is that it's more flexible than distutils.dir_util.copy_tree()
as it takes additional arguments on files to ignore, etc. There is also a draft PEP (PEP 632, associated discussion), which suggests that distutils
may be deprecated and then removed in future versions of Python 3.
A quick one liner to get the first entry returned. This is nice for very basic queries.
<?php
$count = current($db->query("select count(*) from table")->fetch());
?>
Style ={{width : "100%"}}
try this:
StyleSheet generated: {
"width": "80%",
"textAlign": "center",
"marginTop": 21.8625,
"fontWeight": "bold",
"fontSize": 16,
"color": "rgb(24, 24, 24)",
"fontFamily": "Trajan Pro",
"textShadowColor": "rgba(255, 255, 255, 0.2)",
"textShadowOffset": {
"width": 0,
"height": 0.5
}
}
If the properties are for XML or HTML, it's safest to use XML entities. They're uglier to read, but it means that the properties file can be treated as straight ASCII, so nothing will get mangled.
Note that HTML has entities that XML doesn't, so I keep it safe by using straight XML: http://www.w3.org/TR/html4/sgml/entities.html
Actually
{
@synchronized(self) {
return [[myString retain] autorelease];
}
}
transforms directly into:
// needs #import <objc/objc-sync.h>
{
objc_sync_enter(self)
id retVal = [[myString retain] autorelease];
objc_sync_exit(self);
return retVal;
}
This API available since iOS 2.0 and imported using...
#import <objc/objc-sync.h>
After Struggling a bit with Arzoo International flight API, I've finally found the solution and the code simply works absolutely great with me. Here are the complete working code:
//Store your XML Request in a variable
$input_xml = '<AvailRequest>
<Trip>ONE</Trip>
<Origin>BOM</Origin>
<Destination>JFK</Destination>
<DepartDate>2013-09-15</DepartDate>
<ReturnDate>2013-09-16</ReturnDate>
<AdultPax>1</AdultPax>
<ChildPax>0</ChildPax>
<InfantPax>0</InfantPax>
<Currency>INR</Currency>
<PreferredClass>E</PreferredClass>
<Eticket>true</Eticket>
<Clientid>777ClientID</Clientid>
<Clientpassword>*Your API Password</Clientpassword>
<Clienttype>ArzooINTLWS1.0</Clienttype>
<PreferredAirline></PreferredAirline>
</AvailRequest>';
Now I've made a little changes in the above curl_setopt declaration as follows:
$url = "http://59.162.33.102:9301/Avalability";
//setting the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Following line is compulsary to add as it is:
curl_setopt($ch, CURLOPT_POSTFIELDS,
"xmlRequest=" . $input_xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
$data = curl_exec($ch);
curl_close($ch);
//convert the XML result into array
$array_data = json_decode(json_encode(simplexml_load_string($data)), true);
print_r('<pre>');
print_r($array_data);
print_r('</pre>');
That's it the code works absolutely fine for me. I really appreciate @hakre & @Lucas For their wonderful support.
It seems your solution is not much ugly. You can use functions and make it proffesional like these ways
new.function <- function(filename){
readChar(filename, file.info(filename)$size)
}
new.function('foo.txt')
new.function <- function(){
filename <- 'foo.txt'
return (readChar(filename, file.info(filename)$size))
}
new.function()
The Stream API was designed to make it easy to write computations in a way that was abstracted away from how they would be executed, making switching between sequential and parallel easy.
However, just because its easy, doesn't mean its always a good idea, and in fact, it is a bad idea to just drop .parallel()
all over the place simply because you can.
First, note that parallelism offers no benefits other than the possibility of faster execution when more cores are available. A parallel execution will always involve more work than a sequential one, because in addition to solving the problem, it also has to perform dispatching and coordinating of sub-tasks. The hope is that you'll be able to get to the answer faster by breaking up the work across multiple processors; whether this actually happens depends on a lot of things, including the size of your data set, how much computation you are doing on each element, the nature of the computation (specifically, does the processing of one element interact with processing of others?), the number of processors available, and the number of other tasks competing for those processors.
Further, note that parallelism also often exposes nondeterminism in the computation that is often hidden by sequential implementations; sometimes this doesn't matter, or can be mitigated by constraining the operations involved (i.e., reduction operators must be stateless and associative.)
In reality, sometimes parallelism will speed up your computation, sometimes it will not, and sometimes it will even slow it down. It is best to develop first using sequential execution and then apply parallelism where
(A) you know that there's actually benefit to increased performance and
(B) that it will actually deliver increased performance.
(A) is a business problem, not a technical one. If you are a performance expert, you'll usually be able to look at the code and determine (B), but the smart path is to measure. (And, don't even bother until you're convinced of (A); if the code is fast enough, better to apply your brain cycles elsewhere.)
The simplest performance model for parallelism is the "NQ" model, where N
is the number of elements, and Q
is the computation per element. In general, you need the product NQ to exceed some threshold before you start getting a performance benefit. For a low-Q problem like "add up numbers from 1
to N
", you will generally see a breakeven between N=1000
and N=10000
. With higher-Q problems, you'll see breakevens at lower thresholds.
But the reality is quite complicated. So until you achieve experthood, first identify when sequential processing is actually costing you something, and then measure if parallelism will help.
using
memset(members, 0, 255);
in general
memset(members, 0, sizeof members);
if the array is in scope, or
memset(members, 0, nMembers * (sizeof members[0]) );
if you only have the pointer value, and nMembers is the number of elements in the array.
EDIT Of course, now the requirement has changed from the generic task of clearing an array to purely resetting a string, memset
is overkill and just zeroing the first element suffices (as noted in other answers).
EDIT In order to use memset, you have to include string.h.
You have compiled your code with references to the correct math.h header file, but when you attempted to link it, you forgot the option to include the math library. As a result, you can compile your .o object files, but not build your executable.
As Paul has already mentioned add "-lm
" to link with the math library in the step where you are attempting to generate your executable.
Why for
sin()
in<math.h>
, do we need-lm
option explicitly; but, not forprintf()
in<stdio.h>
?
Because both these functions are implemented as part of the "Single UNIX Specification". This history of this standard is interesting, and is known by many names (IEEE Std 1003.1, X/Open Portability Guide, POSIX, Spec 1170).
This standard, specifically separates out the "Standard C library" routines from the "Standard C Mathematical Library" routines (page 277). The pertinent passage is copied below:
Standard C Library
The Standard C library is automatically searched by
cc
to resolve external references. This library supports all of the interfaces of the Base System, as defined in Volume 1, except for the Math Routines.Standard C Mathematical Library
This library supports the Base System math routines, as defined in Volume 1. The
cc
option-lm
is used to search this library.
The reasoning behind this separation was influenced by a number of factors:
The pressures that fed into the decision to put -lm
in a different library probably included, but are not limited to:
sin()
and putting it in a custom built library.In any case, it is now part of the standard to not be automatically included as part of the C language, and that's why you must add -lm
.
Click Build tab ---> Clean Project
Click Build tab ---> Build APK
Run.
You have to cast the selected item to your custom class (ComboboxItem) Try this:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
int selectedIndex = cmb.SelectedIndex;
string selectedText = this.comboBox1.Text;
string selectedValue = ((ComboboxItem)cmb.SelectedItem).Value.ToString();
ComboboxItem selectedCar = (ComboboxItem)cmb.SelectedItem;
MessageBox.Show(String.Format("Index: [{0}] CarName={1}; Value={2}", selectedIndex, selectedCar.Text, selecteVal));
}
You can add a reference to System.Configuration
in your project and then:
using System.Configuration;
then
string sValue = ConfigurationManager.AppSettings["BatchFile"];
with an app.config
file like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="BatchFile" value="blah.bat" />
</appSettings>
</configuration>
While binding a databound control, you can evaluate a field of the row in your data source with eval() function.
For example you can add a column to your gridview like that :
<asp:BoundField DataField="YourFieldName" />
And alternatively, this is the way with eval :
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lbl" runat="server" Text='<%# Eval("YourFieldName") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
It seems a little bit complex, but it's flexible, because you can set any property of the control with the eval() function :
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# "ShowDetails.aspx?id="+Eval("Id") %>'
Text='<%# Eval("Text", "{0}") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<import resource="classpath*:spring-config.xml" />
This is the most suitable one for class path configuration. Particularly when you are searching for the .xml files in a different project which is in your class path.
Had same problem recently after downgrade from Cassandra 3.0 to Cassandra 2.2 on ArchLinux.
Unlike above solutions my problem wasn't in .cassandra, but version 3.0 left its configuration in /var/lib/cassandra directory.
Following commands solved my problem:
sudo rm -R /var/lib/cassandra
sudo rm -R /var/log/cassandra
sudo rm -R /usr/share/cassandra
Then i installed cassandra and everything worked again :)
The only option I can think of is using width:100%
. If you want to have a padding on the input field too, than just place a container label
around it, move the formatting to that label instead, while also specify the padding to the label. Input fields are rigid.
Consider an entity:
public class Foo{
private<user> user;
/* with getters and setters */
}
And consider an Business Logic class:
class Foo1{
List<User> user = new ArrayList<>();
user = foo.getUser();
}
Here the user and foo.getUser()
share the same reference. But saving the two references creates a conflict.
The proper usage should be:
class Foo1 {
List<User> user = new ArrayList<>();
user.addAll(foo.getUser);
}
This avoids the conflict.
We have only single option left after reading all the fake referrer problems: i.e. The page we desire to track as referrer should be kept in session, and as ajax called then checking in session if it has referrer page value and doing the action other wise no action.
While on the other hand as he request any different page then make the referrer session value to null.
Remember that session variable is set on desire page request only.
If you are using PHP7, then you would need a PHP script like this one in order to migrate your collation:
<!DOCTYPE html>
<html>
<head>
<title>DB-Convert</title>
<style>
body { font-family:"Courier New", Courier, monospace; }
</style>
</head>
<body>
<h1>Convert your Database to utf8_general_ci!</h1>
<form action="db-convert.php" method="post">
dbname: <input type="text" name="dbname"><br>
dbuser: <input type="text" name="dbuser"><br>
dbpass: <input type="text" name="dbpassword"><br>
<input type="submit">
</form>
</body>
</html>
<?php
if ($_POST) {
$dbname = $_POST['dbname'];
$dbuser = $_POST['dbuser'];
$dbpassword = $_POST['dbpassword'];
$mysqli = new mysqli('db',$dbuser,$dbpassword);
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
$mysqli -> select_db($dbname);
$result= $mysqli->query('show tables');
while($tables = $result->fetch_array) {
foreach ($tables as $key => $value) {
$mysqli->query("ALTER TABLE $value CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci");
}}
echo "<script>alert('The collation of your database has been successfully changed!');</script>";
}
?>
I know there are a lot of answers here already, but none of them helped me. In the end I opened the file /etc/elasticsearch/jvm.options
and changed:
-Xms2G
-Xmx2G
to
-Xms256M
-Xmx256M
That solved it for me. Hopefully this helps someone else here.
use the xclip
which is command line interface to X selections
apt-get install xclip
echo "test xclip " > /tmp/test.xclip
xclip -i < /tmp/test.xclip
xclip -o > /tmp/test.xclip.out
cat /tmp/test.xclip.out # "test xclip"
enjoy.
TL;DR Remember, all git branches are themselves used for tracking the history of a set of files. Therefore, isn't every branch actually a "tracking branch", because that's what these branches are used for: to track the history of files over time. Thus we should probably be calling normal git "branches", "tracking-branches", but we don't. Instead we shorten their name to just "branches".
So that's partly why the term "tracking-branches" is so terribly confusing: to the uninitiated it can easily mean 2 different things.
In git the term "Tracking-branch" is a short name for the more complete term: "Remote-tracking-branch".
It's probably better at first if you substitute the more formal terms until you get more comfortable with these concepts.
Let's rephrase your question to this:
The key word here is 'Remote', so skip down to where you get confused and I'll describe what a Remote Tracking branch is and how it's used.
To better understand git terminology, including branches and tracking, which can initially be very confusing, I think it's easiest if you first get crystal clear on what git is and the basic structure of how it works. Without a solid understand like this I promise you'll get lost in the many details, as git has lots of complexity; (translation: lots of people use it for very important things).
The following is an introduction/overview, but you might find this excellent article also informative.
WHAT GIT IS, AND WHAT IT'S FOR
A git repository is like a family photo album: It holds historical snapshots showing how things were in past times. A "snapshot" being a recording of something, at a given moment in time.
A git repository is not limited to holding human family photos. It, rather can be used to record and organize anything that is evolving or changing over time.
The basic idea is to create a book so we can easily look backwards in time,
When you get mired down in the complexity and terminology, try to remember that a git repository is first and foremost, a repository of snapshots, and just like a photo album, it's used to both store and organize these snapshots.
SNAPSHOTS AND TRACKING
tracked - to follow a person or animal by looking for proof that they have been somewhere (dictionary.cambridge.org)
In git, "your project" refers to a directory tree of files (one or more, possibly organized into a tree structure using sub-directories), which you wish to keep a history of.
Git, via a 3 step process, records a "snapshot" of your project's directory tree at a given moment in time.
Each git snapshot of your project, is then organized by "links" pointing to previous snapshots of your project.
One by one, link-by-link, we can look backwards in time to find any previous snapshot of you, or your heritage.
For example, we can start with today's most recent snapshot of you, and then using a link, seek backwards in time, for a photo of you taken perhaps yesterday or last week, or when you were a baby, or even who your mother was, etc.
This is refereed to as "tracking; in this example it is tracking your life, or seeing where you have left a footprint, and where you have come from.
COMMITS
A commit is similar to one page in your photo album with a single snapshot, in that its not just the snapshot contained there, but also has the associated meta information about that snapshot. It includes:
A commit is the most important part of a well organized photo album.
THE FAMILY TREE OVER TIME, WITH BRANCHES AND MERGES
Disambiguation: "Tree" here refers not to a file directory tree, as used above, but rather to a family tree of related parent and child commits over time.
The git family tree structure is modeled on our own, human family trees.
In what follows to help understand links in a simple way, I'll refer to:
You should understand this instinctively, as it is based on the tree of life:
Thus all commits except brand new commits, (you could say "juvenile commits"), have one or more children pointing back at them.
With no children are pointing to a parent, then this commit is only a "growing tip", or where the next child will be born from.
With just one child pointing at a parent, this is just a simple, single parent <-- child relationship.
Line diagram of a simple, single parent chain linking backwards in time:
(older) ... <--link1-- Commit1 <--link2-- Commit2 <--link3-- Commit3 (newest)
BRANCHES
branch - A "branch" is an active line of development. The most recent commit on a branch is referred to as the tip of that branch. The tip of the branch is referenced by a branch head, which moves forward as additional development is done on the branch. A single Git repository can track an arbitrary number of branches, but your working tree is associated with just one of them (the "current" or "checked out" branch), and HEAD points to that branch. (gitglossary)
A git branch also refers to two things:
More than one child pointing --at a--> parent, is what git calls "branching".
NOTE: In reality any child, of any parent, weather first, second, or third, etc., can be seen as their own little branch, with their own growing tip. So a branch is not necessarily a long thing with many nodes, rather it is a little thing, created with just one or more commits from a given parent.
The first child of a parent might be said to be part of that same branch, whereas the successive children of that parent are what are normally called "branches".
In actuality, all children (not just the first) branch from it's parent, or you could say link, but I would argue that each link is actually the core part of a branch.
Formally, a git "branch" is just a name, like 'foo' for example, given to a specific growing tip of a family hierarchy. It's one type of what they call a "ref". (Tags and remotes which I'll explain later are also refs.)
ref - A name that begins with refs/ (e.g. refs/heads/master) that points to an object name or another ref (the latter is called a symbolic ref). For convenience, a ref can sometimes be abbreviated when used as an argument to a Git command; see gitrevisions(7) for details. Refs are stored in the repository.
The ref namespace is hierarchical. Different subhierarchies are used for different purposes (e.g. the refs/heads/ hierarchy is used to represent local branches). There are a few special-purpose refs that do not begin with refs/. The most notable example is HEAD. (gitglossary)
(You should take a look at the file tree inside your .git directory. It's where the structure of git is saved.)
So for example, if your name is Tom, then commits linked together that only include snapshots of you, might be the branch we name "Tom".
So while you might think of a tree branch as all of it's wood, in git a branch is just a name given to it's growing tips, not to the whole stick of wood leading up to it.
The special growing tip and it's branch which an arborist (a guy who prunes fruit trees) would call the "central leader" is what git calls "master".
The master branch always exists.
Line diagram of: Commit1 with 2 children (or what we call a git "branch"):
parent children
+-- Commit <-- Commit <-- Commit (Branch named 'Tom')
/
v
(older) ... <-- Commit1 <-- Commit (Branch named 'master')
Remember, a link only points from child to parent. There is no link pointing the other way, i.e. from old to new, that is from parent to child.
So a parent-commit has no direct way to list it's children-commits, or in other words, what was derived from it.
MERGING
Children have one or more parents.
With just one parent this is just a simple parent <-- child commit.
With more than one parent this is what git calls "merging". Each child can point back to more than one parent at the same time, just as in having both a mother AND father, not just a mother.
Line diagram of: Commit2 with 2 parents (or what we call a git "merge", i.e. Procreation from multiple parents):
parents child
... <-- Commit
v
\
(older) ... <-- Commit1 <-- Commit2
REMOTE
This word is also used to mean 2 different things:
remote repository - A repository which is used to track the same project but resides somewhere else. To communicate with remotes, see fetch or push. (gitglossary)
(The remote repository can even be another git repository on our own computer.) Actually there are two URLS for each remote name, one for pushing (i.e. uploading commits) and one for pulling (i.e. downloading commits) from that remote git repository.
A "remote" is a name (an identifier) which has an associated URL which points to a remote git repository. (It's been described as an alias for a URL, although it's more than that.)
You can setup multiple remotes if you want to pull or push to multiple remote repositories.
Though often you have just one, and it's default name is "origin" (meaning the upstream origin from where you cloned).
origin - The default upstream repository. Most projects have at least one upstream project which they track. By default origin is used for that purpose. New upstream updates will be fetched into remote-tracking branches named origin/name-of-upstream-branch, which you can see using git branch -r. (gitglossary)
Origin represents where you cloned the repository from.
That remote repository is called the "upstream" repository, and your cloned repository is called the "downstream" repository.
upstream - In software development, upstream refers to a direction toward the original authors or maintainers of software that is distributed as source code wikipedia
upstream branch - The default branch that is merged into the branch in question (or the branch in question is rebased onto). It is configured via branch..remote and branch..merge. If the upstream branch of A is origin/B sometimes we say "A is tracking origin/B". (gitglossary)
This is because most of the water generally flows down to you.
From time to time you might push some software back up to the upstream repository, so it can then flow down to all who have cloned it.
REMOTE TRACKING BRANCH
A remote-tracking-branch is first, just a branch name, like any other branch name.
It points at a local growing tip, i.e. a recent commit in your local git repository.
But note that it effectively also points to the same commit in the remote repository that you cloned the commit from.
remote-tracking branch - A ref that is used to follow changes from another repository. It typically looks like refs/remotes/foo/bar (indicating that it tracks a branch named bar in a remote named foo), and matches the right-hand-side of a configured fetch refspec. A remote-tracking branch should not contain direct modifications or have local commits made to it. (gitglossary)
Say the remote you cloned just has 2 commits, like this: parent42 <== child-of-4, and you clone it and now your local git repository has the same exact two commits: parent4 <== child-of-4.
Your remote tracking branch named origin now points to child-of-4.
Now say that a commit is added to the remote, so it looks like this: parent42 <== child-of-4 <== new-baby. To update your local, downstream repository you'll need to fetch new-baby, and add it to your local git repository. Now your local remote-tracking-branch points to new-baby. You get the idea, the concept of a remote-tracking-branch is simply to keep track of what had previously been the tip of a remote branch that you care about.
TRACKING IN ACTION
First we begin tracking a file with git.
Here are the basic commands involved with file tracking:
$ mkdir mydir && cd mydir && git init # create a new git repository
$ git branch # this initially reports no branches
# (IMHO this is a bug!)
$ git status -bs # -b = branch; -s = short # master branch is empty
## No commits yet on master
# ...
$ touch foo # create a new file
$ vim foo # modify it (OPTIONAL)
$ git add foo; commit -m 'your description' # start tracking foo
$ git rm --index foo; commit -m 'your description' # stop tracking foo
$ git rm foo; commit -m 'your description' # stop tracking foo & also delete foo
REMOTE TRACKING IN ACTION
$ git pull # Essentially does: get fetch; git merge # to update our clone
There is much more to learn about fetch, merge, etc, but this should get you off in the right direction I hope.
= f.input_field :title, as: :hidden, value: "some value"
Is also an option. Note, however, that it skips any wrapper defined for your form builder.
Query Analyzer buffers messages. The PRINT and RAISERROR statements both use this buffer, but the RAISERROR statement has a WITH NOWAIT option. To print a message immediately use the following:
RAISERROR ('Your message', 0, 1) WITH NOWAIT
RAISERROR will only display 400 characters of your message and uses a syntax similar to the C printf function for formatting text.
Please note that the use of RAISERROR with the WITH NOWAIT option will flush the message buffer, so all previously buffered information will be output also.
df[df['col'].astype(bool)]
Empty strings are falsy, which means you can filter on bool values like this:
df = pd.DataFrame({
'A': range(5),
'B': ['foo', '', 'bar', '', 'xyz']
})
df
A B
0 0 foo
1 1
2 2 bar
3 3
4 4 xyz
df['B'].astype(bool)
0 True
1 False
2 True
3 False
4 True
Name: B, dtype: bool
df[df['B'].astype(bool)]
A B
0 0 foo
2 2 bar
4 4 xyz
If your goal is to remove not only empty strings, but also strings only containing whitespace, use str.strip
beforehand:
df[df['B'].str.strip().astype(bool)]
A B
0 0 foo
2 2 bar
4 4 xyz
.astype
is a vectorised operation, this is faster than every option presented thus far. At least, from my tests. YMMV.
Here is a timing comparison, I've thrown in some other methods I could think of.
Benchmarking code, for reference:
import pandas as pd
import perfplot
df1 = pd.DataFrame({
'A': range(5),
'B': ['foo', '', 'bar', '', 'xyz']
})
perfplot.show(
setup=lambda n: pd.concat([df1] * n, ignore_index=True),
kernels=[
lambda df: df[df['B'].astype(bool)],
lambda df: df[df['B'] != ''],
lambda df: df[df['B'].replace('', np.nan).notna()], # optimized 1-col
lambda df: df.replace({'B': {'': np.nan}}).dropna(subset=['B']),
],
labels=['astype', "!= ''", "replace + notna", "replace + dropna", ],
n_range=[2**k for k in range(1, 15)],
xlabel='N',
logx=True,
logy=True,
equality_check=pd.DataFrame.equals)
First Method: (Tested)
Code in .aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
ddl.SelectedIndexChanged += new EventHandler(ddl_SelectedIndexChanged);
if (!Page.IsPostBack)
{
ddl.Attributes.Add("onchange", "CalcTotalAmt();");
}
}
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
//Your Code
}
JavaScript function: return true from your JS function
function CalcTotalAmt()
{
//Your Code
}
.aspx code:
<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true">
<asp:ListItem Text="a" Value="a"></asp:ListItem>
<asp:ListItem Text="b" Value="b"></asp:ListItem>
</asp:DropDownList>
Second Method: (Tested)
Code in .aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Params["__EVENTARGUMENT"] != null && Request.Params["__EVENTARGUMENT"].Equals("ddlchange"))
ddl_SelectedIndexChanged(sender, e);
if (!Page.IsPostBack)
{
ddl.Attributes.Add("onchange", "CalcTotalAmt();");
}
}
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
//Your Code
}
JavaScript function: return true from your JS function
function CalcTotalAmt() {
//Your Code
__doPostBack("ctl00$MainContent$ddl","ddlchange");
}
.aspx code:
<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true">
<asp:ListItem Text="a" Value="a"></asp:ListItem>
<asp:ListItem Text="b" Value="b"></asp:ListItem>
</asp:DropDownList>
This is a way to retrieve the body "AND" the status code and format it to a proper json or whatever format works for you. Some may argue it's the incorrect use of write format option but this works for me when I need both body and status code in my scripts to check status code and relay back the responses from server.
curl -X GET -w "%{stderr}{\"status\": \"%{http_code}\", \"body\":\"%{stdout}\"}" -s -o - “https://github.com” 2>&1
run the code above and you should get back a json in this format:
{
"status" : <status code>,
"body" : <body of response>
}
with the -w write format option, since stderr is printed first, you can format your output with the var http_code and place the body of the response in a value (body) and follow up the enclosing using var stdout. Then redirect your stderr output to stdout and you'll be able to combine both http_code and response body into a neat output
In Eclipse, right click on your project, go to Maven> Update projetc. Wait and the error will disappear. This is already configured correctly the version of Java for this project.
Sure you can:
Option Explicit
'***** User defined type
Public Type MyType
MyInt As Integer
MyString As String
MyDoubleArr(2) As Double
End Type
'***** Testing MyType as single variable
Public Sub MyFirstSub()
Dim MyVar As MyType
MyVar.MyInt = 2
MyVar.MyString = "cool"
MyVar.MyDoubleArr(0) = 1
MyVar.MyDoubleArr(1) = 2
MyVar.MyDoubleArr(2) = 3
Debug.Print "MyVar: " & MyVar.MyInt & " " & MyVar.MyString & " " & MyVar.MyDoubleArr(0) & " " & MyVar.MyDoubleArr(1) & " " & MyVar.MyDoubleArr(2)
End Sub
'***** Testing MyType as an array
Public Sub MySecondSub()
Dim MyArr(2) As MyType
Dim i As Integer
MyArr(0).MyInt = 31
MyArr(0).MyString = "VBA"
MyArr(0).MyDoubleArr(0) = 1
MyArr(0).MyDoubleArr(1) = 2
MyArr(0).MyDoubleArr(2) = 3
MyArr(1).MyInt = 32
MyArr(1).MyString = "is"
MyArr(1).MyDoubleArr(0) = 11
MyArr(1).MyDoubleArr(1) = 22
MyArr(1).MyDoubleArr(2) = 33
MyArr(2).MyInt = 33
MyArr(2).MyString = "cool"
MyArr(2).MyDoubleArr(0) = 111
MyArr(2).MyDoubleArr(1) = 222
MyArr(2).MyDoubleArr(2) = 333
For i = LBound(MyArr) To UBound(MyArr)
Debug.Print "MyArr: " & MyArr(i).MyString & " " & MyArr(i).MyInt & " " & MyArr(i).MyDoubleArr(0) & " " & MyArr(i).MyDoubleArr(1) & " " & MyArr(i).MyDoubleArr(2)
Next
End Sub
public class BaseClass
{
public BaseClass(params int[] parameters)
{
}
}
public class ChildClass : BaseClass
{
public ChildClass(params int[] parameters)
: base(parameters)
{
}
}
<!-- HTML -->
<a href="#google"></a>
<div id="google"></div>
/*CSS*/
html { scroll-behavior: smooth; }
Additionally, you can add html { scroll-behavior: smooth; } to your CSS to create a smooth scroll.
Are you looking for a particular extension? In your phpinfo();
, just hit Ctrl+F in your web browser, type in the first 3-4 letters of the extension you're looking for, and it should show you whether or not its loaded.
Usually in phpinfo()
it doesn't show you all the loaded extensions in one location, it has got a separate section for each loaded extension where it shows all of its variables, file paths, etc, so if there is no section for your extension name it probably means it isn't loaded.
Alternatively you can open your php.ini file and use the Ctrl+F method to find your extension, and see if its been commented out (usually by a semicolon near the start of the line).
Another good alternative: Marvin
I use these:
.right {display:table; margin:-18px 0 0 auto;}
.center {display:table; margin:-18px auto 0 auto;}
update T1
set T1.COST2=T1.TOT_COST+2.000,
T1.COST3=T1.TOT_COST+2.000,
T1.COST4=T1.TOT_COST+2.000,
T1.COST5=T1.TOT_COST+2.000,
T1.COST6=T1.TOT_COST+2.000,
T1.COST7=T1.TOT_COST+2.000,
T1.COST8=T1.TOT_COST+2.000,
T1.COST9=T1.TOT_COST+2.000,
T1.COST10=T1.TOT_COST+2.000,
T1.COST11=T1.TOT_COST+2.000,
T1.COST12=T1.TOT_COST+2.000,
T1.COST13=T1.TOT_COST+2.000
from DBRMAST T1
inner join DBRMAST t2 on t2.CODE=T1.CODE
Use the :first-child
selector.
In your example...
$('div.alldivs div:first-child')
This will also match any first child descendents that meet the selection criteria.
While
:first
matches only a single element, the:first-child
selector can match more than one: one for each parent. This is equivalent to:nth-child(1)
.
For the first matched only, use the :first
selector.
Alternatively, Felix Kling suggested using the direct descendent selector to get only direct children...
$('div.alldivs > div:first-child')
To remove the first and last characters, and in each case do the removal only if the character in question is a double quote:
import re
s = re.sub(r'^"|"$', '', s)
Note that the RE pattern is different than the one you had given, and the operation is sub
("substitute") with an empty replacement string (strip
is a string method but does something pretty different from your requirements, as other answers have indicated).
Well, it partly depends what you want to happen if you're actually in a derived class.
For example, suppose SuperClass
is in A.jar and SubClass
is in B.jar, and you're executing code in an instance method declared in SuperClass
but where this
refers to an instance of SubClass
. If you use this.getClass().getResource()
it will look relative to SubClass
, in B.jar. I suspect that's usually not what's required.
Personally I'd probably use Foo.class.getResourceAsStream(name)
most often - if you already know the name of the resource you're after, and you're sure of where it is relative to Foo
, that's the most robust way of doing it IMO.
Of course there are times when that's not what you want, too: judge each case on its merits. It's just the "I know this resource is bundled with this class" is the most common one I've run into.
Check if your Java JDK is installed correctly
dpkg --list | grep -i jdk
If not, install JDK
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update && sudo apt-get install oracle-java8-installer
After the installation you have to enable the jdk
update-alternatives --display java
Check if Ubuntu uses Java JDK 8
java -version
If all went right the answer should be something like this:
java version "1.8.0_91"
Java(TM) SE Runtime Environment (build 1.8.0_91-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.91-b14, mixed mode)
Check what compiler is used
javac -version
It should show something like this
javac 1.8.0_91
Finally, add JAVA_HOME to the environment variable
Edit /etc/environment
and add JAVA_HOME=/usr/lib/jvm/java-8-oracle
to the end of the file
sudo nano /etc/environment
Append to the end of the file
JAVA_HOME=/usr/lib/jvm/java-8-oracle
You will then have to reboot, you can do this from the terminal with:
sudo reboot
In case you want to remove the JDK
sudo apt-get remove oracle-java8-installer
Since different browsers seems to prefer different methods, maybe it would make sense to do a smaller test with all three methods as a part of the loading process to find out which is best to use and then use that throughout the application?
You should use this one :
$('#remote').val(null).trigger("change");
See the documentation for the print function: print()
The content of end
is printed after the thing you want to print. By default it contains a newline ("\n"
) but it can be changed to something else, like an empty string.
This is not a Hibernate specific issue (it's just SQL nature), and YES, there IS a solution for both SQL and HQL:
@Peter Lang had the right idea, and you had the correct HQL query. I guess you just needed a new clean run to pick up the query changes ;-)
The below code absolutely works and it is great if you keep all your queries in orm.xml
from CountryDTO c where ((:status is null and c.status is null) or c.status = :status) and c.type =:type
If your parameter String is null then the query will check if the row's status is null as well. Otherwise it will resort to compare with the equals sign.
Notes:
The issue may be a specific MySql quirk. I only tested with Oracle.
The above query assumes that there are table rows where c.status is null
The where clause is prioritized so that the parameter is checked first.
The parameter name 'type' may be a reserved word in SQL but it shouldn't matter since it is replaced before the query runs.
If you needed to skip the :status where_clause altogether; you can code like so:
from CountryDTO c where (:status is null or c.status = :status) and c.type =:type
and it is equivalent to:
sql.append(" where ");
if(status != null){
sql.append(" c.status = :status and ");
}
sql.append(" c.type =:type ");
You can set min-width property of CSS for body tag. Since this property is not supported by IE6, you can write like:
body{
min-width:1000px; /* Suppose you want minimum width of 1000px */
width: auto !important; /* Firefox will set width as auto */
width:1000px; /* As IE6 ignores !important it will set width as 1000px; */
}
Or:
body{
min-width:1000px; // Suppose you want minimum width of 1000px
_width: expression( document.body.clientWidth > 1000 ? "1000px" : "auto" ); /* sets max-width for IE6 */
}
You can simply do this:
.test {
position: -webkit-sticky; /* Safari */
position: sticky;
right: 0;
}
I tested and the script run ok!
INSERT INTO HISTORICAL_CAR_STATS (HISTORICAL_CAR_STATS_ID, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT)
WITH DATA AS
(
SELECT '2010' YEAR,'12' MONTH ,'ALL' MAKE,'ALL' MODEL,REGION,sum(AVG_MSRP*COUNT)/sum(COUNT) AVG_MSRP,sum(Count) COUNT
FROM HISTORICAL_CAR_STATS
WHERE YEAR = '2010' AND MONTH = '12'
AND MAKE != 'ALL' GROUP BY REGION
)
SELECT MY_SEQ.NEXTVAL, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT
FROM DATA;
you can read this article to understand more! http://www.orafaq.com/wiki/ORA-02287
Another way of setting the default to the HTML web forms editor is:
File
> New
> File
HTML Page
Open
button there is a down arrowOpen With
HTML (Web Forms) Editor
Set as Default
OK
It's worth investigating the Pipeline plugin. With the plugin you can checkout multiple VCS projects into relative directory paths. Beforehand creating a directory per VCS checkout. Then issue commands to the newly checked out VCS workspace. In my case I am using git. But you should get the idea.
node{
def exists = fileExists 'foo'
if (!exists){
new File('foo').mkdir()
}
dir ('foo') {
git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
......
}
def exists = fileExists 'bar'
if (!exists){
new File('bar').mkdir()
}
dir ('bar') {
git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
......
}
def exists = fileExists 'baz'
if (!exists){
new File('baz').mkdir()
}
dir ('baz') {
git branch: "<ref spec>", changelog: false, poll: false, url: '<clone url>'
......
}
}
TL;DR
mysql_real_escape_string()
will provide no protection whatsoever (and could furthermore munge your data) if:
MySQL's
NO_BACKSLASH_ESCAPES
SQL mode is enabled (which it might be, unless you explicitly select another SQL mode every time you connect); andyour SQL string literals are quoted using double-quote
"
characters.This was filed as bug #72458 and has been fixed in MySQL v5.7.6 (see the section headed "The Saving Grace", below).
In homage to @ircmaxell's excellent answer (really, this is supposed to be flattery and not plagiarism!), I will adopt his format:
Starting off with a demonstration...
mysql_query('SET SQL_MODE="NO_BACKSLASH_ESCAPES"'); // could already be set
$var = mysql_real_escape_string('" OR 1=1 -- ');
mysql_query('SELECT * FROM test WHERE name = "'.$var.'" LIMIT 1');
This will return all records from the test
table. A dissection:
Selecting an SQL Mode
mysql_query('SET SQL_MODE="NO_BACKSLASH_ESCAPES"');
As documented under String Literals:
There are several ways to include quote characters within a string:
A “
'
” inside a string quoted with “'
” may be written as “''
”.A “
"
” inside a string quoted with “"
” may be written as “""
”.Precede the quote character by an escape character (“
\
”).A “
'
” inside a string quoted with “"
” needs no special treatment and need not be doubled or escaped. In the same way, “"
” inside a string quoted with “'
” needs no special treatment.
If the server's SQL mode includes NO_BACKSLASH_ESCAPES
, then the third of these options—which is the usual approach adopted by mysql_real_escape_string()
—is not available: one of the first two options must be used instead. Note that the effect of the fourth bullet is that one must necessarily know the character that will be used to quote the literal in order to avoid munging one's data.
The Payload
" OR 1=1 --
The payload initiates this injection quite literally with the "
character. No particular encoding. No special characters. No weird bytes.
mysql_real_escape_string()
$var = mysql_real_escape_string('" OR 1=1 -- ');
Fortunately, mysql_real_escape_string()
does check the SQL mode and adjust its behaviour accordingly. See libmysql.c
:
ulong STDCALL
mysql_real_escape_string(MYSQL *mysql, char *to,const char *from,
ulong length)
{
if (mysql->server_status & SERVER_STATUS_NO_BACKSLASH_ESCAPES)
return escape_quotes_for_mysql(mysql->charset, to, 0, from, length);
return escape_string_for_mysql(mysql->charset, to, 0, from, length);
}
Thus a different underlying function, escape_quotes_for_mysql()
, is invoked if the NO_BACKSLASH_ESCAPES
SQL mode is in use. As mentioned above, such a function needs to know which character will be used to quote the literal in order to repeat it without causing the other quotation character from being repeated literally.
However, this function arbitrarily assumes that the string will be quoted using the single-quote '
character. See charset.c
:
/*
Escape apostrophes by doubling them up
// [ deletia 839-845 ]
DESCRIPTION
This escapes the contents of a string by doubling up any apostrophes that
it contains. This is used when the NO_BACKSLASH_ESCAPES SQL_MODE is in
effect on the server.
// [ deletia 852-858 ]
*/
size_t escape_quotes_for_mysql(CHARSET_INFO *charset_info,
char *to, size_t to_length,
const char *from, size_t length)
{
// [ deletia 865-892 ]
if (*from == '\'')
{
if (to + 2 > to_end)
{
overflow= TRUE;
break;
}
*to++= '\'';
*to++= '\'';
}
So, it leaves double-quote "
characters untouched (and doubles all single-quote '
characters) irrespective of the actual character that is used to quote the literal! In our case $var
remains exactly the same as the argument that was provided to mysql_real_escape_string()
—it's as though no escaping has taken place at all.
The Query
mysql_query('SELECT * FROM test WHERE name = "'.$var.'" LIMIT 1');
Something of a formality, the rendered query is:
SELECT * FROM test WHERE name = "" OR 1=1 -- " LIMIT 1
As my learned friend put it: congratulations, you just successfully attacked a program using mysql_real_escape_string()
...
mysql_set_charset()
cannot help, as this has nothing to do with character sets; nor can mysqli::real_escape_string()
, since that's just a different wrapper around this same function.
The problem, if not already obvious, is that the call to mysql_real_escape_string()
cannot know with which character the literal will be quoted, as that's left to the developer to decide at a later time. So, in NO_BACKSLASH_ESCAPES
mode, there is literally no way that this function can safely escape every input for use with arbitrary quoting (at least, not without doubling characters that do not require doubling and thus munging your data).
It gets worse. NO_BACKSLASH_ESCAPES
may not be all that uncommon in the wild owing to the necessity of its use for compatibility with standard SQL (e.g. see section 5.3 of the SQL-92 specification, namely the <quote symbol> ::= <quote><quote>
grammar production and lack of any special meaning given to backslash). Furthermore, its use was explicitly recommended as a workaround to the (long since fixed) bug that ircmaxell's post describes. Who knows, some DBAs might even configure it to be on by default as means of discouraging use of incorrect escaping methods like addslashes()
.
Also, the SQL mode of a new connection is set by the server according to its configuration (which a SUPER
user can change at any time); thus, to be certain of the server's behaviour, you must always explicitly specify your desired mode after connecting.
So long as you always explicitly set the SQL mode not to include NO_BACKSLASH_ESCAPES
, or quote MySQL string literals using the single-quote character, this bug cannot rear its ugly head: respectively escape_quotes_for_mysql()
will not be used, or its assumption about which quote characters require repeating will be correct.
For this reason, I recommend that anyone using NO_BACKSLASH_ESCAPES
also enables ANSI_QUOTES
mode, as it will force habitual use of single-quoted string literals. Note that this does not prevent SQL injection in the event that double-quoted literals happen to be used—it merely reduces the likelihood of that happening (because normal, non-malicious queries would fail).
In PDO, both its equivalent function PDO::quote()
and its prepared statement emulator call upon mysql_handle_quoter()
—which does exactly this: it ensures that the escaped literal is quoted in single-quotes, so you can be certain that PDO is always immune from this bug.
As of MySQL v5.7.6, this bug has been fixed. See change log:
Functionality Added or Changed
Incompatible Change: A new C API function,
mysql_real_escape_string_quote()
, has been implemented as a replacement formysql_real_escape_string()
because the latter function can fail to properly encode characters when theNO_BACKSLASH_ESCAPES
SQL mode is enabled. In this case,mysql_real_escape_string()
cannot escape quote characters except by doubling them, and to do this properly, it must know more information about the quoting context than is available.mysql_real_escape_string_quote()
takes an extra argument for specifying the quoting context. For usage details, see mysql_real_escape_string_quote().Note
Applications should be modified to use
mysql_real_escape_string_quote()
, instead ofmysql_real_escape_string()
, which now fails and produces anCR_INSECURE_API_ERR
error ifNO_BACKSLASH_ESCAPES
is enabled.References: See also Bug #19211994.
Taken together with the bug explained by ircmaxell, the following examples are entirely safe (assuming that one is either using MySQL later than 4.1.20, 5.0.22, 5.1.11; or that one is not using a GBK/Big5 connection encoding):
mysql_set_charset($charset);
mysql_query("SET SQL_MODE=''");
$var = mysql_real_escape_string('" OR 1=1 /*');
mysql_query('SELECT * FROM test WHERE name = "'.$var.'" LIMIT 1');
...because we've explicitly selected an SQL mode that doesn't include NO_BACKSLASH_ESCAPES
.
mysql_set_charset($charset);
$var = mysql_real_escape_string("' OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");
...because we're quoting our string literal with single-quotes.
$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(["' OR 1=1 /*"]);
...because PDO prepared statements are immune from this vulnerability (and ircmaxell's too, provided either that you're using PHP=5.3.6 and the character set has been correctly set in the DSN; or that prepared statement emulation has been disabled).
$var = $pdo->quote("' OR 1=1 /*");
$stmt = $pdo->query("SELECT * FROM test WHERE name = $var LIMIT 1");
...because PDO's quote()
function not only escapes the literal, but also quotes it (in single-quote '
characters); note that to avoid ircmaxell's bug in this case, you must be using PHP=5.3.6 and have correctly set the character set in the DSN.
$stmt = $mysqli->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$param = "' OR 1=1 /*";
$stmt->bind_param('s', $param);
$stmt->execute();
...because MySQLi prepared statements are safe.
Thus, if you:
OR
OR
in addition to employing one of the solutions in ircmaxell's summary, use at least one of:
NO_BACKSLASH_ESCAPES
...then you should be completely safe (vulnerabilities outside the scope of string escaping aside).
map
keeps iterators to all elements stable, in C++17 you can even move elements from one map
to the other without invalidating iterators to them (and if properly implemented without any potential allocation).map
timings for single operations are typically more consistent since they never need large allocations.unordered_map
using std::hash
as implemented in the libstdc++ is vulnerable to DoS if fed with untrusted input (it uses MurmurHash2 with a constant seed - not that seeding would really help, see https://emboss.github.io/blog/2012/12/14/breaking-murmur-hash-flooding-dos-reloaded/).Step 1. Install "Apache_OpenOffice_4.1.2" in your system Step 2. Download "unoconv" library from github or any where else.
-> C:\Program Files (x86)\OpenOffice 4\program\python.exe = Path of open office install directory
-> D:\wamp\www\doc_to_pdf\libobasis4.4-pyuno\unoconv = Path of library folder
-> D:/wamp/www/doc_to_pdf/files/'.$pdf_File_name.' = path and file name of pdf
-> D:/wamp/www/doc_to_pdf/files/'.$doc_file_name = Path of your document file.
If pdf not created than last step is Go to ->Control Panel\All Control Panel Items\Administrative Tools-> services-> find "wampapache" -> right click and click on property -> click on logon tab Than check checkbox of allow service to interact with desktop
Create sample .php file and put below code and run on wamp or xampp server
$result = exec('"C:\Program Files (x86)\OpenOffice 4\program\python.exe" D:\wamp\www\doc_to_pdf\libobasis4.4-pyuno\unoconv -f pdf -o D:/wamp/www/doc_to_pdf/files/'.$pdf_File_name.' D:/wamp/www/doc_to_pdf/files/'.$doc_file_name);
This code working for me in windows-8 operating system
It all depends on your definition of correct. There are many ways in which you can evaluate your coding style. Readability is an important one (for me). That is why I would use the my_function
way of writing function names and variable names.
My problem and the solution
I have a 32 bit third party dll which I have installed in 2008 R2 machine which is 64 bit.
I have a wcf service created in .net 4.5 framework which calls the 32 bit third party dll for process. Now I have build property set to target 'any' cpu and deployed it to the 64 bit machine.
When Ii tried to invoke the wcf service got error "80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG"
Now Ii used ProcMon.exe to trace the com registry issue and identified that the process is looking for the registry entry at HKLM\CLSID and HKCR\CLSID where there is no entry.
Came to know that Microsoft will not register the 32 bit com components to the paths HKLM\CLSID, HKCR\CLSID in 64 bit machine rather it places the entry in HKLM\Wow6432Node\CLSID and HKCR\Wow6432Node\CLSID paths.
Now the conflict is 64 bit process trying to invoke 32 bit process in 64 bit machine which will look for the registry entry in HKLM\CLSID, HKCR\CLSID. The solution is we have to force the 64 bit process to look at the registry entry at HKLM\Wow6432Node\CLSID and HKCR\Wow6432Node\CLSID.
This can be achieved by configuring the wcf service project properties to target to 'X86' machine instead of 'Any'.
After deploying the 'X86' version to the 2008 R2 server got the issue "System.BadImageFormatException: Could not load file or assembly"
Solution to this badimageformatexception is setting the 'Enable32bitApplications' to 'True' in IIS Apppool properties for the right apppool.
If like me you just updated your password and ran
git push
to run into this issue, then there's a super easy fix.
For Mac users only. You need to delete your OSX Keychain access entries for GitHub. You can do it via terminal by running the following commands.
Through the command line, you can use the credential helper directly to erase the keychain entry.
To do this, type the following command:
git credential-osxkeychain erase
host=github.com
protocol=https
# [Now Press Return]
If it's successful, nothing will print out. To test that it works, try and clone a repository from GitHub or run your previous action again like in my case git push
. If you are prompted for a password, the keychain entry was deleted.
For the Android folks coming here for Kotlin
val dirtyString = " Account Balance: $-12,345.67"
val cleanString = dirtyString.replace("[^\\d.]".toRegex(), "")
Output:
cleanString = "12345.67"
This could then be safely converted toDouble()
, toFloat()
or toInt()
if needed
I set the PHPRC variable and uncommented zend_extension=php_opcache.dll
in php.ini
and all works well.
You are doing mistake in "configuration_page.jsp" file. here in this file , function loadXMLDoc() 's line number 2 should be like this:
var config=document.getElementsByName('configselect').value;
because you have declared only the name
attribute in your <select>
tag. So you should get this element by name.
After correcting this, it will run without any JavaScript error
For anyone trying to display cronjobs in a crontab and getting frustrated on how to separate each line, use explode:
$output = shell_exec('crontab -l');
$cron_array = explode(chr(10),$output);
using '\n' doesnt seem to work but chr(10) works nicely :D
hope this saves some one some headaches.
Yes, see: link, but he used xml layouts, not activities to create new tab, so put his xml code (set paddingTop for FrameLayout - 0px) and then write the code:
public class SomeActivity extends ActivityGroup {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TabHost tab_host = (TabHost) findViewById(R.id.edit_item_tab_host);
tab_host.setup(this.getLocalActivityManager());
TabSpec ts1 = tab_host.newTabSpec("TAB_DATE");
ts1.setIndicator("tab1");
ts1.setContent(new Intent(this, Registration.class));
tab_host.addTab(ts1);
TabSpec ts2 = tab_host.newTabSpec("TAB_GEO");
ts2.setIndicator("tab2");
ts2.setContent(new Intent(this, Login.class));
tab_host.addTab(ts2);
TabSpec ts3 = tab_host.newTabSpec("TAB_TEXT");
ts3.setIndicator("tab3");
ts3.setContent(new Intent(this, Registration.class));
tab_host.addTab(ts3);
tab_host.setCurrentTab(0);
}
}
I had this problem working with pycurl and I solved it using
c.setopt(pycurl.HTTP_VERSION, pycurl.CURL_HTTP_VERSION_1_0)
like Eric Caron says.
I've never used it but Trilead, a free ISAPI filter which enables .htaccess based control, looks like what you want.
In your case it is probably taking them in DD-MM-YY format, not MM-DD-YY.
That worked for me.
string address=senderAddress.Replace("'", "\\'");
below is the given code which will convert seconds into hh-mm-ss format:
var measuredTime = new Date(null);
measuredTime.setSeconds(4995); // specify value of SECONDS
var MHSTime = measuredTime.toISOString().substr(11, 8);
Get alternative method from Convert seconds to HH-MM-SS format in JavaScript
If fptr
is NULL
, then you don't have an open file. Therefore, you can't freopen
it, you should just fopen
it.
FILE *fptr;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
fptr = fopen("scores.dat", "wb");
}
note: Since the behavior of your program varies depending on whether the file is opened in read or write modes, you most probably also need to keep a variable indicating which is the case.
int main()
{
FILE *fptr;
char there_was_error = 0;
char opened_in_read = 1;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
opened_in_read = 0;
fptr = fopen("scores.dat", "wb");
if (fptr == NULL)
there_was_error = 1;
}
if (there_was_error)
{
printf("Disc full or no permission\n");
return EXIT_FAILURE;
}
if (opened_in_read)
printf("The file is opened in read mode."
" Let's read some cached data\n");
else
printf("The file is opened in write mode."
" Let's do some processing and cache the results\n");
return EXIT_SUCCESS;
}
[u'{email:[email protected],gem:0}', u'{email:test,gem:0}', u'{email:test,gem:0}', u'{email:test,gem:0}', u'{email:test,gem:0}', u'{email:test1,gem:0}']
'u' denotes unicode characters. We can easily remove this with map function on the final list element
map(str, test)
Another way is when you are appending it to the list
test.append(str(a))
2-D Array Dynamic Memory Allocation
int **a,i;
// for any number of rows & columns this will work
a = (int **)malloc(rows*sizeof(int *));
for(i=0;i<rows;i++)
*(a+i) = (int *)malloc(cols*sizeof(int));
To add vertical modal centering to bootstrap modal.js I added this at the end of the Modal.prototype.show
function:
var $modalDialog = $('.modal-dialog'),
modalHeight = $modalDialog.height(),
browserHeight = window.innerHeight;
$modalDialog.css({'margin-top' : modalHeight >= browserHeight ? 0 : (browserHeight - modalHeight)/2});
You can do it in the following way:
myfxn <- function(var1,var2,var3){
var1*var2*var3
}
lapply(1:3,myfxn,var2=2,var3=100)
and you will get the answer:
[[1]] [1] 200
[[2]] [1] 400
[[3]] [1] 600
It is not possible. §2.3 says that "." is an unreserved character and that "URIs that differ in the replacement of an unreserved character with its corresponding percent-encoded US-ASCII octet are equivalent". Therefore, /%2E%2E/
is the same as /../
, and that will get normalized away.
(This is a combination of an answer by bobince and a comment by slowpoison.)
If you run into problems with your path, maybe you need to change the assetPublicPath
in your config/index.js
file to your sub-directory:
Looking for EventHandling, ActionListener?
or code?
JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
textfield.setText("");
//textfield.setText(null); //or use this
}
});
Also See
How to Use Buttons
Try an if statement ...
if @value is null
insert into t (value) values (default)
else
insert into t (value) values (@value)
list()
is inherently slower than []
, because
there is symbol lookup (no way for python to know in advance if you did not just redefine list to be something else!),
there is function invocation,
then it has to check if there was iterable argument passed (so it can create list with elements from it) ps. none in our case but there is "if" check
In most cases the speed difference won't make any practical difference though.
Personally, I prefer changing the method signature to:
public ResponseEntity<?>
This gives the advantage of possibly returning an error message as single item for services which, when ok, return a list of items.
When returning I don't use any type (which is unused in this case anyway):
return new ResponseEntity<>(entities, HttpStatus.OK);
For editing this is possible in nano
via +n
from command line, e.g.,
nano +16 file.txt
To open file.txt
to line 16.
Realizing that the question is old and one answer is accepted, I'll provide another answer for reference.
scale
is limited by the fact that it scales all variables. The solution below allows to scale only specific variable names while preserving other variables unchanged (and the variable names could be dynamically generated):
library(dplyr)
set.seed(1234)
dat <- data.frame(x = rnorm(10, 30, .2),
y = runif(10, 3, 5),
z = runif(10, 10, 20))
dat
dat2 <- dat %>% mutate_at(c("y", "z"), ~(scale(.) %>% as.vector))
dat2
which gives me this:
> dat
x y z
1 29.75859 3.633225 14.56091
2 30.05549 3.605387 12.65187
3 30.21689 3.318092 13.04672
4 29.53086 3.079992 15.07307
5 30.08582 3.437599 11.81096
6 30.10121 4.621197 17.59671
7 29.88505 4.051395 12.01248
8 29.89067 4.829316 12.58810
9 29.88711 4.662690 19.92150
10 29.82199 3.091541 18.07352
and
> dat2 <- dat %>% mutate_at(c("y", "z"), ~(scale(.) %>% as.vector))
> dat2
x y z
1 29.75859 -0.3004815 -0.06016029
2 30.05549 -0.3423437 -0.72529604
3 30.21689 -0.7743696 -0.58772361
4 29.53086 -1.1324181 0.11828039
5 30.08582 -0.5946582 -1.01827752
6 30.10121 1.1852038 0.99754666
7 29.88505 0.3283513 -0.94806607
8 29.89067 1.4981677 -0.74751378
9 29.88711 1.2475998 1.80753470
10 29.82199 -1.1150515 1.16367556
EDIT 1 (2016): Addressed Julian's comment: the output of scale
is Nx1 matrix so ideally we should add an as.vector
to convert the matrix type back into a vector type. Thanks Julian!
EDIT 2 (2019): Quoting Duccio A.'s comment: For the latest dplyr (version 0.8) you need to change dplyr::funcs with list, like dat %>% mutate_each_(list(~scale(.) %>% as.vector), vars=c("y","z"))
EDIT 3 (2020): Thanks to @mj_whales: the old solution is deprecated and now we need to use mutate_at
.
Why not just using
<div [ngClass]="classes"> </div>
https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html
This might be caused due to different reasons, some user have mentioned other possibilities and I add my case:
I got this error when using multi-threading (both std::pthread
and std::thread
) and the error occurred because I forgot to lock a variable which multi threads may change at the same time.
this error comes randomly in some runs but not all because ... you know accident between to threads is random.
That variable in my case was a global std::vector
which I tried to push_back()
something into it in a function called by threads.. and then I used a std::mutex
and never got this error again.
may help some
I managed this without adding markup, but instead using li:before. This obviously has all the limitations of :before
(no old IE support), but it seems to work with IE8, Firefox and Chrome after some very limited testing. It's working in our controller environment, wondering if anyone could check this. The bullet style is also limited by what's in unicode.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<style type="text/css">
li {
list-style: none;
}
li:before {
/* For a round bullet */
content:'\2022';
/* For a square bullet */
/*content:'\25A0';*/
display: block;
position: relative;
max-width: 0px;
max-height: 0px;
left: -10px;
top: -0px;
color: green;
font-size: 20px;
}
</style>
</head>
<body>
<ul>
<li>foo</li>
<li>bar</li>
</ul>
</body>
</html>
To keep the scripting in one place rather than using onClick in the HTML tag, add the following code to your script block:
$('#id-of-the-button').click(function() {document.forms[0].submit()});
Which assumes you just have the one form on the page.
from itertools import repeat, starmap
results = list(starmap(do, repeat((), 3)))
See the repeatfunc recipe from the itertools module that is actually much more powerful. If you need to just call the method but don't care about the return values you can use it in a for loop:
for _ in starmap(do, repeat((), 3)): pass
but that's getting ugly.
Using the examples from: https://docs.python.org/3.2/library/socketserver.html I determined that I needed to set the HOST port to the machine I had the server program running on. So TCPServer on 192.168.0.1 HOST = TCPServer IP 192.168.0.1 then I had to set the TCPClient side to point to the TCPServer IP. So the TCPClient HOST value = 192.168.0.1 - Sorry, that's the best I can describe it.
/media directory under project root
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urlpatterns += patterns('django.views.static',(r'^media/(?P<path>.*)','serve',{'document_root':settings.MEDIA_ROOT}), )
<img src="{{MEDIA_URL}}/image.png" >
One more possible reason if you are using Tycho and Maven to build bundles, that you have wrong execution environment (Bundle-RequiredExecutionEnvironment
) in the manifest file (manifest.mf
) defined. For example:
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Engine Plug-in
Bundle-SymbolicName: com.foo.bar
Bundle-Version: 4.6.5.qualifier
Bundle-Activator: com.foo.bar.Activator
Bundle-Vendor: Foobar Technologies Ltd.
Require-Bundle: org.eclipse.core.runtime,
org.jdom;bundle-version="1.0.0",
org.apache.commons.codec;bundle-version="1.3.0",
bcprov-ext;bundle-version="1.47.0"
Bundle-RequiredExecutionEnvironment: JavaSE-1.5
Export-Package: ...
...
Import-Package: ...
...
In my case everything else was ok. The compiler plugins (normal maven and tycho as well) were set correctly, still m2 generated old compliance level because of the manifest. I thought I share the experience.
In my case it worked perfectly
<img style="border-radius: 50%;height: 50px;width: 80px;" src="<?php echo asset("storage/TeacherImages/{$teacher->profilePic}")?>">
this is used to display image from folder i hope this will help someone looking for this type of code
Be careful when setting text with an onClick listener on the field you are setting the text. I was doing this and setting the text to an empty string. This was causing the pointer to come up to indicate where my cursor was, which will normally go away after a few seconds. When I did not wait for it to go away before leaving my page causing finish() to be called, it would cause a memory leak and crash my app. Took me a while to figure out what was causing the crash on this one..
Anyway, I would recommend using selectAll() in your on click listener rather than setText() if you can. This way, once the text is selected, the user can start typing and all of the previous text will be cleared.
pic of the suspect pointer: http://i.stack.imgur.com/juJnt.png
LocalDate.parse(
"January 08, 2017" ,
DateTimeFormatter.ofPattern( "MMMM dd, uuuu" , Locale.US )
).format( DateTimeFormatter.BASIC_ISO_DATE )
The Question and other Answers use troublesome old date-time classes, now legacy, supplanted by the java.time classes.
You have date-only values, so use a date-only class. The LocalDate
class represents a date-only value without time-of-day and without time zone.
String input = "January 08, 2017";
Locale l = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMMM dd, uuuu" , l );
LocalDate ld = LocalDate.parse( input , f );
Your desired output format is defined by the ISO 8601 standard. For a date-only value, the “expanded” format is YYYY-MM-DD such as 2017-01-08
and the “basic” format that minimizes the use of delimiters is YYYYMMDD such as 20170108
.
I strongly suggest using the expanded format for readability. But if you insist on the basic format, that formatter is predefined as a constant on the DateTimeFormatter
class named BASIC_ISO_DATE
.
String output = ld.format( DateTimeFormatter.BASIC_ISO_DATE );
See this code run live at IdeOne.com.
ld.toString(): 2017-01-08
output: 20170108
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
No, you can't change iPad's host file(without jailbreak), but can workaround.
Here is my scenario:
192.168.2.1
, running a web appI am going to test the web app running in my Mac via iPad, but I can't access directly to it.
The solution works for me:
Port
(mostly 8888
) and toggle Enable transparent HTTP proxying
.Now you can visit your web app in iPad.
Of course you can use other proxy tools like Squid or Varnish in Linux, or fiddler in Wondows.
I read through all these, but wanted something a bit more elegant. Just to remove a certain number of characters from the end of a string:
string.Concat("hello".Reverse().Skip(3).Reverse());
output:
"he"
In your example there is no big difference between str -> str
and Function.identity()
since internally it is simply t->t
.
But sometimes we can't use Function.identity
because we can't use a Function
. Take a look here:
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
this will compile fine
int[] arrayOK = list.stream().mapToInt(i -> i).toArray();
but if you try to compile
int[] arrayProblem = list.stream().mapToInt(Function.identity()).toArray();
you will get compilation error since mapToInt
expects ToIntFunction
, which is not related to Function
. Also ToIntFunction
doesn't have identity()
method.
i am a new bee ;p . And i faced the same problem. And the solution is BS Media objects. please see the code..
<div class="media">
<div class="media-left media-top">
<img src="something.png" alt="@l!" class="media-object" width="20" height="50"/>
</div>
<div class="media-body">
<h2 class="media-heading">Beside Image</h2>
</div>
</div>
You can also get this error with any version of git if the remote branch was created after your last clone/fetch and your local repo doesn't know about it yet. I solved it by doing a git fetch
first which "tells" your local repo about all the remote branches.
git fetch
git checkout test-branch
try this command, xcopy c:\ (file or directory path) F:\ /e. If you want more details refer this site [[http://www.computerhope.com/xcopyhlp.htm]]
Issue happens because Microsoft Security Update MS11-100 limits number of keys in Forms collection during HTTP POST request. To alleviate this problem you need to increase that number.
This can be done in your application Web.Config in the
<appSettings>
section (create the section directly under<configuration>
if it doesn’t exist). Add 2 lines similar to the lines below to the section:<add key="aspnet:MaxHttpCollectionKeys" value="2000" /> <add key="aspnet:MaxJsonDeserializerMembers" value="2000" />
The above example set the limit to 2000 keys. This will lift the limitation and the error should go away.
$(document).ready(function(){_x000D_
_x000D_
$(".btn1").click(function(){_x000D_
$("div.test:not(:first)").hide();_x000D_
});_x000D_
_x000D_
$(".btn2").click(function(){_x000D_
$("div.test").show();_x000D_
$("div.test:not(:first):not(:last)").hide();_x000D_
});_x000D_
_x000D_
$(".btn3").click(function(){_x000D_
$("div.test").hide();_x000D_
$("div.test:not(:first):not(:last)").show();_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<button class="btn1">Hide All except First</button>_x000D_
<button class="btn2">Hide All except First & Last</button>_x000D_
<button class="btn3">Hide First & Last</button>_x000D_
_x000D_
<br/>_x000D_
_x000D_
<div class='test'>First</div>_x000D_
<div class='test'>Second</div>_x000D_
<div class='test'>Third</div>_x000D_
<div class='test'>Last</div>
_x000D_
Step by steps of that, +
turn value to a number and if you add to an empty array +[]
...as it's empty and is equal to 0
, it will
So from there, now look into your code, it's ++[[]][+[]]+[+[]]
...
And there is plus between them ++[[]][+[]]
+ [+[]]
So these [+[]]
will return [0]
as they have an empty array which gets converted to 0
inside the other array...
So as imagine, the first value is a 2-dimensional array with one array inside... so [[]][+[]]
will be equal to [[]][0]
which will return []
...
And at the end ++
convert it and increase it to 1
...
So you can imagine, 1
+ "0"
will be "10"
...
Checkout this, This is from PHP MANUAL, This may help you.
If you're using PHP_CLI SAPI and getting error "Maximum execution time of N seconds exceeded" where N is an integer value, try to call set_time_limit(0) every M seconds or every iteration. For example:
<?php
require_once('db.php');
$stmt = $db->query($sql);
while ($row = $stmt->fetchRow()) {
set_time_limit(0);
// your code here
}
?>
Or it could be that Skype is running on the same port (it does by default).
Disable Skype or configure Skype to use another port
You need to define a Theme for your AlertDialog and reference it in your Activity's theme. The attribute is alertDialogTheme
and not alertDialogStyle
. Like this:
<style name="Theme.YourTheme" parent="@android:style/Theme.Holo">
...
<item name="android:alertDialogTheme">@style/YourAlertDialogTheme</item>
</style>
<style name="YourAlertDialogTheme">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
<item name="android:windowMinWidthMajor">@android:dimen/dialog_min_width_major</item>
<item name="android:windowMinWidthMinor">@android:dimen/dialog_min_width_minor</item>
<item name="android:windowTitleStyle">...</item>
<item name="android:textAppearanceMedium">...</item>
<item name="android:borderlessButtonStyle">...</item>
<item name="android:buttonBarStyle">...</item>
</style>
You'll be able to change color and text appearance for the title, the message and you'll have some control on the background of each area. I wrote a blog post detailing the steps to style an AlertDialog.
For my particular version of this problem, I went ahead and searched the function declaration of load_json_file(path)
within the packaging.py
file, then smuggled a print
line into it:
def load_json_file(path):
data = open(path, 'r').read()
print data
try:
return Bunch(json.loads(data))
except ValueError, e:
raise MalformedJsonFileError('%s when reading "%s"' % (str(e),
path))
That way it would print the content of the json file before entering the try-catch, and that way – even with my barely existing Python knowledge – I was able to quickly figure out why my configuration couldn't read the json file.
(It was because I had set up my text editor to write a UTF-8 BOM … stupid)
Just mentioning this because, while maybe not a good answer to the OP's specific problem, this was a rather quick method in determining the source of a very oppressing bug. And I bet that many people will stumble upon this article who are searching a more verbose solution for a MalformedJsonFileError: No JSON object could be decoded when reading …
. So that might help them.
The regular expression would be:
.+name="([^"]+)"
Then the grouping would be in the \1
How about storing the alerts as records in an array instead of properties of a single object ?
var alerts = [
{num : 1, app:'helloworld',message:'message'},
{num : 2, app:'helloagain',message:'another message'}
]
And then to add one, just use push
:
alerts.push({num : 3, app:'helloagain_again',message:'yet another message'});
If you are using a strongly-typed dataset then you should do this:
If Not ediTransactionRow.Ispay_id1Null Then
'Do processing here
End If
You are getting the error because a strongly-typed data set retrieves the underlying value and exposes the conversion through the property. For instance, here is essentially what is happening:
Public Property pay_Id1 Then
Get
return DirectCast(me.GetValue("pay_Id1", short)
End Get
'Abbreviated for clarity
End Property
The GetValue method is returning DBNull which cannot be converted to a short.
I did not find any of the answers satisfactory. All the mentioned libraries have some problem or the other like Cairo dropping support for python 3.6 (they dropped Python 2 support some 3 years ago!). Also, installing the mentioned libraries on the Mac was a pain.
Finally, I found the best solution was svglib + reportlab. Both installed without a hitch using pip and first call to convert from svg to png worked beautifully! Very happy with the solution.
Just 2 commands do the trick:
from svglib.svglib import svg2rlg
from reportlab.graphics import renderPM
drawing = svg2rlg("my.svg")
renderPM.drawToFile(drawing, "my.png", fmt="PNG")
Are there any limitations with these I should be aware of?
None of the above worked.
The solution was to copy the project locally (from the network drive).
I have the same problem with importing WinSCard.dll in my project. I deal with that importing directly from dll like this:
[DllImport("winscard.dll")]
public static extern int SCardEstablishContext(int dwScope, int pvReserved1, int pvReserved2, ref int phContext);
[DllImport("winscard.dll")]
public static extern int SCardReleaseContext(int phContext);
You could add this to separate project and then add a reference from your main project.
Building on Joan-Diego Rodriguez's routine with Jordi's approach and some of Jacek Kotowski's code - This function converts any table name for the active workbook into a usable address for SQL queries.
Note to MikeL: Addition of "[#All]" includes headings avoiding problems you reported.
Function getAddress(byVal sTableName as String) as String
With Range(sTableName & "[#All]")
getAddress= "[" & .Parent.Name & "$" & .Address(False, False) & "]"
End With
End Function
MDN has a good example on the use of setTimeout preserving "this".
Like the following:
function doSomething() {
// use 'this' to handle the selected element here
}
$(".someSelector").each(function() {
setTimeout(doSomething.bind(this), 0);
});
@ECHO OFF
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --app="https://tweetdeck.twitter.com/"
@ECHO OFF
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --app="https://web.whatsapp.com/"
The following steps are to reset the password for a user in case you forgot, this would also solve your mentioned error.
First, stop your MySQL:
sudo /etc/init.d/mysql stop
Now start up MySQL in safe mode and skip the privileges table:
sudo mysqld_safe --skip-grant-tables &
Login with root:
mysql -uroot
And assign the DB that needs to be used:
use mysql;
Now all you have to do is reset your root password of the MySQL user and restart the MySQL service:
update user set password=PASSWORD("YOURPASSWORDHERE") where User='root';
flush privileges;
quit and restart MySQL:
quit
sudo /etc/init.d/mysql stop sudo /etc/init.d/mysql start Now your root password should be working with the one you just set, check it with:
mysql -u root -p
Use this function it will enable you to pic date and time one by one then set it to global variable date. No library no XML.
Calendar date;
public void showDateTimePicker() {
final Calendar currentDate = Calendar.getInstance();
date = Calendar.getInstance();
new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
date.set(year, monthOfYear, dayOfMonth);
new TimePickerDialog(context, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
date.set(Calendar.HOUR_OF_DAY, hourOfDay);
date.set(Calendar.MINUTE, minute);
Log.v(TAG, "The choosen one " + date.getTime());
}
}, currentDate.get(Calendar.HOUR_OF_DAY), currentDate.get(Calendar.MINUTE), false).show();
}
}, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE)).show();
}
cout.fill('*');
cout << -12345 << endl; // print default value with no field width
cout << setw(10) << -12345 << endl; // print default with field width
cout << setw(10) << left << -12345 << endl; // print left justified
cout << setw(10) << right << -12345 << endl; // print right justified
cout << setw(10) << internal << -12345 << endl; // print internally justified
This produces the output:
-12345
****-12345
-12345****
****-12345
-****12345
Seems odd to me that with all us speed conscious nerds here on SO no one has presented a version that uses a compile time generated look up table for the delimiter (example implementation further down). Using a look up table and iterators should beat std::regex in efficiency, if you don't need to beat regex, just use it, its standard as of C++11 and super flexible.
Some have suggested regex already but for the noobs here is a packaged example that should do exactly what the OP expects:
std::vector<std::string> split(std::string::const_iterator it, std::string::const_iterator end, std::regex e = std::regex{"\\w+"}){
std::smatch m{};
std::vector<std::string> ret{};
while (std::regex_search (it,end,m,e)) {
ret.emplace_back(m.str());
std::advance(it, m.position() + m.length()); //next start position = match position + match length
}
return ret;
}
std::vector<std::string> split(const std::string &s, std::regex e = std::regex{"\\w+"}){ //comfort version calls flexible version
return split(s.cbegin(), s.cend(), std::move(e));
}
int main ()
{
std::string str {"Some people, excluding those present, have been compile time constants - since puberty."};
auto v = split(str);
for(const auto&s:v){
std::cout << s << std::endl;
}
std::cout << "crazy version:" << std::endl;
v = split(str, std::regex{"[^e]+"}); //using e as delim shows flexibility
for(const auto&s:v){
std::cout << s << std::endl;
}
return 0;
}
If we need to be faster and accept the constraint that all chars must be 8 bits we can make a look up table at compile time using metaprogramming:
template<bool...> struct BoolSequence{}; //just here to hold bools
template<char...> struct CharSequence{}; //just here to hold chars
template<typename T, char C> struct Contains; //generic
template<char First, char... Cs, char Match> //not first specialization
struct Contains<CharSequence<First, Cs...>,Match> :
Contains<CharSequence<Cs...>, Match>{}; //strip first and increase index
template<char First, char... Cs> //is first specialization
struct Contains<CharSequence<First, Cs...>,First>: std::true_type {};
template<char Match> //not found specialization
struct Contains<CharSequence<>,Match>: std::false_type{};
template<int I, typename T, typename U>
struct MakeSequence; //generic
template<int I, bool... Bs, typename U>
struct MakeSequence<I,BoolSequence<Bs...>, U>: //not last
MakeSequence<I-1, BoolSequence<Contains<U,I-1>::value,Bs...>, U>{};
template<bool... Bs, typename U>
struct MakeSequence<0,BoolSequence<Bs...>,U>{ //last
using Type = BoolSequence<Bs...>;
};
template<typename T> struct BoolASCIITable;
template<bool... Bs> struct BoolASCIITable<BoolSequence<Bs...>>{
/* could be made constexpr but not yet supported by MSVC */
static bool isDelim(const char c){
static const bool table[256] = {Bs...};
return table[static_cast<int>(c)];
}
};
using Delims = CharSequence<'.',',',' ',':','\n'>; //list your custom delimiters here
using Table = BoolASCIITable<typename MakeSequence<256,BoolSequence<>,Delims>::Type>;
With that in place making a getNextToken
function is easy:
template<typename T_It>
std::pair<T_It,T_It> getNextToken(T_It begin,T_It end){
begin = std::find_if(begin,end,std::not1(Table{})); //find first non delim or end
auto second = std::find_if(begin,end,Table{}); //find first delim or end
return std::make_pair(begin,second);
}
Using it is also easy:
int main() {
std::string s{"Some people, excluding those present, have been compile time constants - since puberty."};
auto it = std::begin(s);
auto end = std::end(s);
while(it != std::end(s)){
auto token = getNextToken(it,end);
std::cout << std::string(token.first,token.second) << std::endl;
it = token.second;
}
return 0;
}
Here is a live example: http://ideone.com/GKtkLQ
Would I just override the drawRect method?
Yes:
- (void)drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextAddEllipseInRect(ctx, rect);
CGContextSetFillColor(ctx, CGColorGetComponents([[UIColor blueColor] CGColor]));
CGContextFillPath(ctx);
}
Also, would it be okay to change the frame of that view within the class itself?
Ideally not, but you could.
Or do I need to change the frame from a different class?
I'd let the parent control that.
You can use the isNaN function to determine if a value does not convert to a number. Example as below:
function checkInp()
{
var x=document.forms["myForm"]["age"].value;
if (isNaN(x))
{
alert("Must input numbers");
return false;
}
}
mysqldump will not dump database events, triggers and routines unless explicitly stated when dumping individual databases;
mysqldump -uuser -p db_name --events --triggers --routines > db_name.sql
This should help if you need a publicly exposed website but you're on a dev pc. Also to answer (I can't comment yet): "How do I post to an internal only running development server with this? – stryba "
NGROK creates a secure public URL to a local webserver on your development machine (Permanent URLs available for a fee, temporary for free).
1) Run ngrok.exe to open command line (on desktop)
2) Type ngrok.exe http 80 to start a tunnel,
3) test by browsing to the displayed web address which will forward and display the local default 80 page on your dev pc
Then use some of the tools recommended above to POST to your ngrok site ('https://xxxxxx.ngrok.io') to test your local code.
The if statements in your example are unnecessary. Just do it like this:
dosomething1 || exit 1
If you take Ville Laurikari's advice and use set -e
then for some commands you may need to use this:
dosomething || true
The || true
will make the command pipeline have a true
return value even if the command fails so the the -e
option will not kill the script.
I would go for aspect-ratio, it offers way more possibilities.
/* Exact aspect ratio */
@media (aspect-ratio: 2/1) {
...
}
/* Minimum aspect ratio */
@media (min-aspect-ratio: 16/9) {
...
}
/* Maximum aspect ratio */
@media (max-aspect-ratio: 8/5) {
...
}
Both, orientation and aspect-ratio depend on the actual size of the viewport and have nothing todo with the device orientation itself.
Read more: https://dev.to/ananyaneogi/useful-css-media-query-features-o7f
If the function defined is in a file x.py
:
def greet():
print('Hello! How are you?')
In the file where you are importing the function, write this:
from x import greet
This is useful if you do not wish to import all the functions in a file.
String user = request.getParameter("uname");
out.println(user);
String pass = request.getParameter("pass");
out.println(pass);
Class.forName( "com.mysql.jdbc.Driver" );
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/rental","root","root" ) ;
out.println("hello");
Statement st = conn.createStatement();
String sql = "insert into login (user,pass) values('" + user + "','" + pass + "')";
st.executeUpdate(sql);
According to Microsoft's documentation
On the Tools menu, point to Macro, and then click Macros.
In the Macro name box, enter the name of the macro you want to assign to a keyboard shortcut key.
Click Options.
If you want to run the macro by pressing a keyboard shortcut key, enter a letter in the Shortcut key box. You can use CTRL+ letter (for lowercase letters) or CTRL+SHIFT+ letter (for uppercase letters), where letter is any letter key on the keyboard. The shortcut key cannot use a number or special character, such as @
or #
.
Note: The shortcut key will override any equivalent default Microsoft Excel shortcut keys while the workbook that contains the macro is open.
If you want to include a description of the macro, type it in the Description box.
Click OK.
Click Cancel.
Updated answer that will solve your problem and also just a general good how-to for installing Oracle Java 7 on Ubuntu can be found here: http://www.wikihow.com/Install-Oracle-Java-on-Ubuntu-Linux
As no one mentioned it before, starting from Sql Server 2016 you can also use json arrays and OPENJSON (Transact-SQL)
:
declare @filter nvarchar(max) = '[1,2]'
select *
from dbo.Test as t
where
exists (select * from openjson(@filter) as tt where tt.[value] = t.id)
You can test it in sql fiddle demo
You can also cover more complicated cases with json easier - see Search list of values and range in SQL using WHERE IN clause with SQL variable?
Or, if you want a more general approach - i.e. for nesting up to "levelN":
void Main()
{
XElement rootElement = XElement.Load(@"c:\events\test.xml");
Console.WriteLine(GetOutline(0, rootElement));
}
private string GetOutline(int indentLevel, XElement element)
{
StringBuilder result = new StringBuilder();
if (element.Attribute("name") != null)
{
result = result.AppendLine(new string(' ', indentLevel * 2) + element.Attribute("name").Value);
}
foreach (XElement childElement in element.Elements())
{
result.Append(GetOutline(indentLevel + 1, childElement));
}
return result.ToString();
}
Here is way to avoid absolute divs and tables if you know parent's height:
<div class="parent">
<div class="child"> <a href="#">Home</a>
</div>
</div>
CSS:
.parent {
line-height:80px;
border: 1px solid black;
}
.child {
line-height:normal;
display: inline-block;
vertical-align:bottom;
border: 1px solid red;
}
JsFiddle:
You can simply replace all \n
with <br/>
tag so that when page is displayed then it breaks line.
UPDATE table SET field = REPLACE(field, '\n', '<br/>')
I had this issue when deploying on prod server only. In my other environments it works... I just deleted stuff in the bin folder then republish and it work after that.
If you are looking for performance and using std::vector
, I recommend the one that this documentation link provides.
std::vector<int> myvector{10,20,20,20,30,30,20,20,10}; // 10 20 20 20 30 30 20 20 10
std::sort(myvector.begin(), myvector.end() );
const auto& it = std::unique (myvector.begin(), myvector.end()); // 10 20 30 ? ? ? ? ? ?
// ^
myvector.resize( std::distance(myvector.begin(),it) ); // 10 20 30
This means that you must declare strict mode by writing "use strict"
at the beginning of the file or the function to use block-scope declarations.
EX:
function test(){
"use strict";
let a = 1;
}
Map#merge
As of java-8 you can use Map#merge(K key, V value, BiFunction remappingFunction)
which merges a value into the Map
using remappingFunction
in case the key is already found in the Map
you want to put the pair into.
// using lambda
newMap.forEach((key, value) -> map.merge(key, value, (oldValue, newValue) -> oldValue));
// using for-loop
for (Map.Entry<Integer, String> entry: newMap.entrySet()) {
map.merge(entry.getKey(), entry.getValue(), (oldValue, newValue) -> oldValue);
}
The code iterates the newMap
entries (key
and value
) and each one is merged into map
through the method merge
. The remappingFunction
is triggered in case of duplicated key and in that case it says that the former (original) oldValue
value will be used and not rewritten.
With this solution, you don't need a temporary Map
.
Let's have an example of merging newMap
entries into map
and keeping the original values in case of the duplicated antry.
Map<Integer, String> newMap = new HashMap<>();
newMap.put(2, "EVIL VALUE"); // this will NOT be merged into
newMap.put(4, "four"); // this WILL be merged into
newMap.put(5, "five"); // this WILL be merged into
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
newMap.forEach((k, v) -> map.merge(k, v, (oldValue, newValue) -> oldValue));
map.forEach((k, v) -> System.out.println(k + " " + v));
1 one 2 two 3 three 4 four 5 five
If you mean that you have an environment variable named CLASSPATH, I'd say that's your mistake. I don't have such a thing on any machine with which I develop Java. CLASSPATH is so tied to a particular project that it's impossible to have a single, correct CLASSPATH that works for all.
I set CLASSPATH for each project using either an IDE or Ant. I do a lot of web development, so each WAR and EAR uses their own CLASSPATH.
It's ignored by IDEs and app servers. Why do you have it? I'd recommend deleting it.
If You need sth different than AUTO_INCREMENT you can still use triggers.
Taking all of the proposed answers and applying them to my situation - trying to check or uncheck a checkbox based on a retrieved value of true (should check the box) or false (should not check the box) - I tried all of the above and found that using .prop("checked", true) and .prop("checked", false) were the correct solution.
I can't add comments or up answers yet, but I felt this was important enough to add to the conversation.
Here is the longhand code for a fullcalendar modification that says if the retrieved value "allDay" is true, then check the checkbox with ID "even_allday_yn":
if (allDay)
{
$( "#even_allday_yn").prop('checked', true);
}
else
{
$( "#even_allday_yn").prop('checked', false);
}
If you want to pass props to a component inside a route, the simplest way is by utilizing the render
, like this:
<Route exact path="/details/:id" render={(props) => <DetailsPage globalStore={globalStore} {...props} /> } />
You can access the props inside the DetailPage
using:
this.props.match
this.props.globalStore
The {...props}
is needed to pass the original Route's props, otherwise you will only get this.props.globalStore
inside the DetailPage
.
UPDATE (2019-04-22) - It sounds like you want to use uncompyle6 nowadays rather than the answers I had mentioned originally.
This sounds like it works: http://code.google.com/p/unpyc/
Issue 8 says it supports 2.7: http://code.google.com/p/unpyc/updates/list
UPDATE (2013-09-03) - As noted in the comments and in other answers, you should look at https://github.com/wibiti/uncompyle2 or https://github.com/gstarnberger/uncompyle instead of unpyc.
Does this work:
$msgid = $_GET['msgid'];
$oldMessage = '';
$deletedFormat = '';
//read the entire string
$str=file_get_contents('msghistory.txt');
//replace something in the file string - this is a VERY simple example
$str=str_replace($oldMessage, $deletedFormat,$str);
//write the entire string
file_put_contents('msghistory.txt', $str);
I recently wrote a gem to simplify this process and to neaten up your views, etc etc.
Check it out at: http://github.com/platform45/easy_dates
You can use the momentjs http://momentjs.com/ Library.
var moment = require('moment');
foo = new moment(something).add(10, 'm').toDate();
This should work in the way that you describe. What error are you getting? If you could pastebin your code that would help.
http://download.oracle.com/javase/tutorial/java/javaOO/enum.html
EDIT: Are you sure you want to define a static enum? That doesn't sound right to me. An enum is much like any other object. If your code compiles and runs but gives incorrect results, this would probably be why.
This is a one line to solve the complete original question:
params.select { |k,_| k[/choice/]}.values.join('\t')
But most the solutions above are solving a case where you need to know the keys ahead of time, using slice
or simple regexp.
Here is another approach that works for simple and more complex use cases, that is swappable at runtime
data = {}
matcher = ->(key,value) { COMPLEX LOGIC HERE }
data.select(&matcher)
Now not only this allows for more complex logic on matching the keys or the values, but it is also easier to test, and you can swap the matching logic at runtime.
Ex to solve the original issue:
def some_method(hash, matcher)
hash.select(&matcher).values.join('\t')
end
params = { :irrelevant => "A String",
:choice1 => "Oh look, another one",
:choice2 => "Even more strings",
:choice3 => "But wait",
:irrelevant2 => "The last string" }
some_method(params, ->(k,_) { k[/choice/]}) # => "Oh look, another one\\tEven more strings\\tBut wait"
some_method(params, ->(_,v) { v[/string/]}) # => "Even more strings\\tThe last string"
I had been avoiding this by calling a method to run [cell.contentView bringSubviewToFront:textField]
every time my cells appeared, but then I discovered this relatively simple technique:
cell.accessoryView = textField;
Doesn't seem to have the same background-overpasting issue, and it aligns itself on its own (somewhat). Also, the textLabel auto-truncates to avoid overflowing into (or under) it, which is handy.
Perhaps you want something like:
<style name="CustomActivityTheme" parent="@android:style/Theme.Holo">
<item name="android:checkboxStyle">@style/customCheckBoxStyle</item>
</style>
<style name="customCheckBoxStyle" parent="@android:style/Widget.CompoundButton.CheckBox">
<item name="android:textColor">@android:color/black</item>
</style>
Note, the textColor item.
Like that
var purchCount = (from purchase in myBlaContext.purchases select purchase).Count();
or even easier
var purchCount = myBlaContext.purchases.Count()
Maybe it is the case that you have your path in couple of lines, you used enter to make it? If so, then part of you paths might look like that "/\nData/" instead of "/Data/", which causes the problem. Just set it to be in one line and issue is solved!
If you have only 1 separator, you can employ list comprehensions:
text = 'foo,bar,baz,qux'
sep = ','
Appending/prepending separator:
result = [x+sep for x in text.split(sep)]
#['foo,', 'bar,', 'baz,', 'qux,']
# to get rid of trailing
result[-1] = result[-1].strip(sep)
#['foo,', 'bar,', 'baz,', 'qux']
result = [sep+x for x in text.split(sep)]
#[',foo', ',bar', ',baz', ',qux']
# to get rid of trailing
result[0] = result[0].strip(sep)
#['foo', ',bar', ',baz', ',qux']
Separator as it's own element:
result = [u for x in text.split(sep) for u in (x, sep)]
#['foo', ',', 'bar', ',', 'baz', ',', 'qux', ',']
results = result[:-1] # to get rid of trailing
It appears the problem is that a user created via the method described in the mongo docs does not have permission to connect to the default database (test), even if that user was created with the "userAdminAnyDatabase" and "dbAdminAnyDatabase" roles.
Just for history:
Check that all mentioned less/css files in bundle have Build Action = "Content".
There is no error if some files from bundle missing on destination server.
I think most of these solutions are far too complicated. I assume that in your test controller you have this
@Autowired
private ObjectMapper objectMapper;
If its a rest service
@Test
public void test() throws Exception {
mockMvc.perform(post("/person"))
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(new Person()))
...etc
}
For spring mvc using a posted form I came up with this solution. (Not really sure if its a good idea yet)
private MultiValueMap<String, String> toFormParams(Object o, Set<String> excludeFields) throws Exception {
ObjectReader reader = objectMapper.readerFor(Map.class);
Map<String, String> map = reader.readValue(objectMapper.writeValueAsString(o));
MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
map.entrySet().stream()
.filter(e -> !excludeFields.contains(e.getKey()))
.forEach(e -> multiValueMap.add(e.getKey(), (e.getValue() == null ? "" : e.getValue())));
return multiValueMap;
}
@Test
public void test() throws Exception {
MultiValueMap<String, String> formParams = toFormParams(new Phone(),
Set.of("id", "created"));
mockMvc.perform(post("/person"))
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.params(formParams))
...etc
}
The basic idea is to
- first convert object to json string to get all the field names easily
- convert this json string into a map and dump it into a MultiValueMap
that spring expects. Optionally filter out any fields you dont want to include (Or you could just annotate fields with @JsonIgnore
to avoid this extra step)
$.ajax({
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
alert(location.ip);
}
});
This will work https too
Try using the following code snippet. This should solve your issue.
body, html {
overflow-x: hidden;
overflow-y: auto;
}
If customer primary contact medium is email, if email is null then phonenumber, and if phonenumber is also null then address. It would be written using COALESCE as
coalesce(email,phonenumber,address)
while the same in hive can be achieved by chaining together nvl as
nvl(email,nvl(phonenumber,nvl(address,'n/a')))
As mentioned here, you need to remove the unused references and the warnings will go.
Do you want an 'int' that looks like 20110425171213? In which case you'd be better off ToString with the appropriate format (something like 'yyyyMMddHHmmss') and then casting the string to an integer (or a long, unsigned int as it will be way more than 32 bits).
If you want an actual numeric value (the number of seconds since the year 0) then that's a very different calculation, e.g.
result = second
result += minute * 60
result += hour * 60 * 60
result += day * 60 * 60 * 24
etc.
But you'd be better off using Ticks.
If the arrays in your posted hashCode are bytes, then you will likely end up with lots of duplicates.
a[0] + a[1] will always be between 0 and 512. adding the b's will always result in a number between 0 and 768. multiply those and you get an upper limit of 400,000 unique combinations, assuming your data is perfectly distributed among every possible value of each byte. If your data is at all regular, you likely have far less unique outputs of this method.
I have recently migrated from C3P0
to HikariCP
in a Spring and Hibernate based project and it was not as easy as I had imagined and here I am sharing my findings.
For Spring Boot
see my answer here
I have the following setup
Some of the below configs are similar to some of the answers above but, there are differences.
In order to pull in the right jars, I needed to pull in the following jars
//latest driver because *brettw* see https://github.com/pgjdbc/pgjdbc/pull/849
compile 'org.postgresql:postgresql:42.2.0'
compile('com.zaxxer:HikariCP:2.7.6') {
//they are pulled in separately elsewhere
exclude group: 'org.hibernate', module: 'hibernate-core'
}
// Recommended to use HikariCPConnectionProvider by Hibernate in 4.3.6+
compile('org.hibernate:hibernate-hikaricp:4.3.8.Final') {
//they are pulled in separately elsewhere, to avoid version conflicts
exclude group: 'org.hibernate', module: 'hibernate-core'
exclude group: 'com.zaxxer', module: 'HikariCP'
}
// Needed for HikariCP logging if you use log4j
compile('org.slf4j:slf4j-simple:1.7.25')
compile('org.slf4j:slf4j-log4j12:1.7.25') {
//log4j pulled in separately, exclude to avoid version conflict
exclude group: 'log4j', module: 'log4j'
}
In order to get Spring & Hibernate to make use of Hikari Connection pool, you need to define the HikariDataSource
and feed it into sessionFactory
bean as shown below.
<!-- HikariCP Database bean -->
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<constructor-arg ref="hikariConfig" />
</bean>
<!-- HikariConfig config that is fed to above dataSource -->
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="poolName" value="SpringHikariPool" />
<property name="dataSourceClassName" value="org.postgresql.ds.PGSimpleDataSource" />
<property name="maximumPoolSize" value="20" />
<property name="idleTimeout" value="30000" />
<property name="dataSourceProperties">
<props>
<prop key="serverName">localhost</prop>
<prop key="portNumber">5432</prop>
<prop key="databaseName">dbname</prop>
<prop key="user">dbuser</prop>
<prop key="password">dbpassword</prop>
</props>
</property>
</bean>
<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">
<!-- Your Hikari dataSource below -->
<property name="dataSource" ref="dataSource"/>
<!-- your other configs go here -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.connection.provider_class">org.hibernate.hikaricp.internal.HikariCPConnectionProvider</prop>
<!-- Remaining props goes here -->
</props>
</property>
</bean>
Once the above are setup then, you need to add an entry to your log4j or logback
and set the level
to DEBUG
to see Hikari
Connection Pool start up.
<!-- Keep additivity=false to avoid duplicate lines -->
<logger additivity="false" name="com.zaxxer.hikari">
<level value="debug"/>
<!-- Your appenders goes here -->
</logger>
Via application.properties
in Spring Boot
debug=true
logging.level.com.zaxxer.hikari.HikariConfig=DEBUG
Using logback.xml
<logger name="com.zaxxer.hikari" level="DEBUG" additivity="false">
<appender-ref ref="STDOUT" />
</logger>
With the above you should be all good to go! Obviously you need to customize the HikariCP
pool configs in order to get the performance that it promises.
You can do it:
var str = "Doctor Who,Fantasy,Steven Moffat,David Tennant";
var title = str.Split(',').First();
Also you can do it this way:
var index = str.IndexOf(",");
var title = index < 0 ? str : str.Substring(0, index);
These are all nice but seq is supposedly deprecated and most only work with numeric ranges.
If you enclose your for loop in double quotes, the start and end variables will be dereferenced when you echo the string, and you can ship the string right back to BASH for execution. $i
needs to be escaped with \'s so it is NOT evaluated before being sent to the subshell.
RANGE_START=a
RANGE_END=z
echo -e "for i in {$RANGE_START..$RANGE_END}; do echo \\${i}; done" | bash
This output can also be assigned to a variable:
VAR=`echo -e "for i in {$RANGE_START..$RANGE_END}; do echo \\${i}; done" | bash`
The only "overhead" this should generate should be the second instance of bash so it should be suitable for intensive operations.
For "zip" files, you can use import zipfile
and your code will be working simply with these lines:
import zipfile
import pandas as pd
with zipfile.ZipFile("Crime_Incidents_in_2013.zip") as z:
with z.open("Crime_Incidents_in_2013.csv") as f:
train = pd.read_csv(f, header=0, delimiter="\t")
print(train.head()) # print the first 5 rows
And the result will be:
X,Y,CCN,REPORT_DAT,SHIFT,METHOD,OFFENSE,BLOCK,XBLOCK,YBLOCK,WARD,ANC,DISTRICT,PSA,NEIGHBORHOOD_CLUSTER,BLOCK_GROUP,CENSUS_TRACT,VOTING_PRECINCT,XCOORD,YCOORD,LATITUDE,LONGITUDE,BID,START_DATE,END_DATE,OBJECTID
0 -77.054968548763071,38.899775938598317,0925135...
1 -76.967309569035052,38.872119553647011,1003352...
2 -76.996184958456539,38.927921847721443,1101010...
3 -76.943077541353617,38.883686046653935,1104551...
4 -76.939209158039446,38.892278093281632,1125028...
After trying many tutorials to configure my Ubuntu 16.04 LTS behind a authenticated proxy, it worked with these steps:
Edit /etc/wgetrc
:
$ sudo nano /etc/wgetrc
Uncomment these lines:
#https_proxy = http://proxy.yoyodyne.com:18023/
#http_proxy = http://proxy.yoyodyne.com:18023/
#ftp_proxy = http://proxy.yoyodyne.com:18023/
#use_proxy = on
Change http://proxy.yoyodyne.com:18023/
to http://username:password@domain:port/
IMPORTANT: If it still doesn't work, check if your password has special characters, such as
#
,@
, ... If this is the case, escape them (for example, replacepassw@rd
withpassw%40rd
).
I just tested this and it works in Access 2010.
Say you have a SELECT query with parameters:
PARAMETERS startID Long, endID Long;
SELECT Members.*
FROM Members
WHERE (((Members.memberID) Between [startID] And [endID]));
You run that query interactively and it prompts you for [startID] and [endID]. That works, so you save that query as [MemberSubset].
Now you create an UPDATE query based on that query:
UPDATE Members SET Members.age = [age]+1
WHERE (((Members.memberID) In (SELECT memberID FROM [MemberSubset])));
You run that query interactively and again you are prompted for [startID] and [endID] and it works well, so you save it as [MemberSubsetUpdate].
You can run [MemberSubsetUpdate] from VBA code by specifying [startID] and [endID] values as parameters to [MemberSubsetUpdate], even though they are actually parameters of [MemberSubset]. Those parameter values "trickle down" to where they are needed, and the query does work without human intervention:
Sub paramTest()
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.QueryDefs("MemberSubsetUpdate")
qdf!startID = 1 ' specify
qdf!endID = 2 ' parameters
qdf.Execute
Set qdf = Nothing
End Sub
I use this to ensure the zoom level does not exceed a set level so that I know satellite images will be available.
Add a listener to the zoom_changed
event.
This has the added benefit of controlling the zoom control on the UI also.
Only execute setZoom
if you need to, so an if
statement is preferable to Math.max
or to Math.min
google.maps.event.addListener(map, 'zoom_changed', function() {
if ( map.getZoom() > 19 ) {
map.setZoom(19);
}
});
bounds = new google.maps.LatLngBounds( ... your bounds ... )
map.fitBounds(bounds);
To prevent zooming out too far:
google.maps.event.addListener(map, 'zoom_changed', function() {
if ( map.getZoom() < 6 ) {
map.setZoom(6);
}
});
bounds = new google.maps.LatLngBounds( ... your bounds ... )
map.fitBounds(bounds);
I wrote a script to patch those exe. But the best way is to fix distutil itself.
"""Fix "Fatal error in launcher: Unable to create process using ..." error. Put me besides those EXE made by pip. (They are made by distutils, and used by pip)"""
import re
import sys
import os
from glob import glob
script_path = os.path.dirname(os.path.realpath(__file__))
real_int_path = sys.executable
_t = script_path.rpartition(os.sep)[0] + os.sep + 'python.exe'
if script_path.lower().endswith('scripts') and os.path.isfile(_t):
real_int_path = _t
print('real interpreter path: ' + real_int_path)
print()
for i in glob('*.exe'):
with open(i, 'rb+') as f:
img = f.read()
match = re.search(rb'#![a-zA-Z]:\\.+\.exe', img)
if not match:
print("can't fix file: " + i)
continue
int_path = match.group()[2:].decode()
int_path_start = match.start() + 2
int_path_end = match.end()
if int_path.lower() == real_int_path.lower():
continue
print('fix interpreter path: %s in %s' % (int_path, i))
f.seek(int_path_start)
f.write(real_int_path.encode())
f.write(img[int_path_end:])
You can also get some sample swagger files online to verify this(if you have errors in your swagger doc).
i had a similar problem where i was trying to focus on a txt area in an iframe loaded from another page. in most cases it work. There was an issue where it would fire in FF when the iFrame was loaded but before it was visible. so the focus never seemed to be set correctly.
i worked around this with a simular solution to cheeming's answer above
var iframeID = document.getElementById("modalIFrame");
//focus the IFRAME element
$(iframeID).focus();
//use JQuery to find the control in the IFRAME and set focus
$(iframeID).contents().find("#emailTxt").focus();
In most browsers, there's a slightly more succinct way of removing an element from the DOM than calling .removeChild(element)
on its parent, which is to just call element.remove()
. In due course, this will probably become the standard and idiomatic way of removing an element from the DOM.
The .remove()
method was added to the DOM Living Standard in 2011 (commit), and has since been implemented by Chrome, Firefox, Safari, Opera, and Edge. It was not supported in any version of Internet Explorer.
If you want to support older browsers, you'll need to shim it. This turns out to be a little irritating, both because nobody seems to have made a all-purpose DOM shim that contains these methods, and because we're not just adding the method to a single prototype; it's a method of ChildNode
, which is just an interface defined by the spec and isn't accessible to JavaScript, so we can't add anything to its prototype. So we need to find all the prototypes that inherit from ChildNode
and are actually defined in the browser, and add .remove
to them.
Here's the shim I came up with, which I've confirmed works in IE 8.
(function () {
var typesToPatch = ['DocumentType', 'Element', 'CharacterData'],
remove = function () {
// The check here seems pointless, since we're not adding this
// method to the prototypes of any any elements that CAN be the
// root of the DOM. However, it's required by spec (see point 1 of
// https://dom.spec.whatwg.org/#dom-childnode-remove) and would
// theoretically make a difference if somebody .apply()ed this
// method to the DOM's root node, so let's roll with it.
if (this.parentNode != null) {
this.parentNode.removeChild(this);
}
};
for (var i=0; i<typesToPatch.length; i++) {
var type = typesToPatch[i];
if (window[type] && !window[type].prototype.remove) {
window[type].prototype.remove = remove;
}
}
})();
This won't work in IE 7 or lower, since extending DOM prototypes isn't possible before IE 8. I figure, though, that on the verge of 2015 most people needn't care about such things.
Once you've included them shim, you'll be able to remove a DOM element element
from the DOM by simply calling
element.remove();
I just watched the 30 minute Unity Dependency Injection IoC Screencast by David Hayden and felt that was a good explaination with examples. Here is a snippet from the show notes:
The screencast shows several common usages of the Unity IoC, such as:
If you use the JSON Serializer, you can simply store your object in string format as such
myHiddenText.value = JSON.stringify( myObject );
You can then get the value back with
myObject = JSON.parse( myHiddenText.value );
However, if you're not going to pass this value across page submits, it might be easier for you, and you'll save yourself a lot of serialization, if you just tuck it away as a global javascript variable.
Here is my preferred solution. It is taken from an answer to a similar question.
Use a VBS Script to call the batch file:
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\path\to\your\batchfile.bat" & Chr(34), 0
Set WshShell = Nothing
Copy the lines above to an editor and save the file with .VBS extension.
Answers that claim Django model's Meta
and metaclasses are "completely different" are misleading answers.
The construction of Django model class objects, that is to say the object that stands for the class definition itself (yes, classes are also objects), are indeed controlled by a metaclass called ModelBase
, and you can see that code here.
And one of the things that ModelBase
does is to create the _meta
attribute on every Django model which contains validation machinery, field details, save logic and so forth. During this operation, the stuff that is specified in the model's inner Meta
class is read and used within that process.
So, while yes, in a sense Meta
and metaclasses are different 'things', within the mechanics of Django model construction they are intimately related; understanding how they work together will deepen your insight into both at once.
This might be a helpful source of information to better understand how Django models employ metaclasses.
https://code.djangoproject.com/wiki/DevModelCreation
And this might help too if you want to better understand how objects work in general.
This one $("#yourDiv").load(" #yourDiv > *");
is the best if you are planning to just reload a <div>
Make sure to use an id
and not a class
. Also, remember to paste <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
in the <head>
section of the html file, if you haven't already. In opposite case it won't work.
In an attempt to spot a change somewhere in a particular column (here in "W", i.e. "23"), I modified Peter Alberts' answer to:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Target.Column = 23 Then Exit Sub
Application.EnableEvents = False 'to prevent endless loop
On Error GoTo Finalize 'to re-enable the events
MsgBox "You changed a cell in column W, row " & Target.Row
MsgBox "You changed it to: " & Target.Value
Finalize:
Application.EnableEvents = True
End Sub
If you're using a shell, the filepath to the Download (no "s") folder is
/storage/emulated/0/Download
Two options, either reference the new jars in your classpath or unpack all classes in the enclosing jars and re-jar the whole lot! As far as I know packaging jars within jars is not recommeneded and you'll forever have the class not found exception!
Assuming the renderDetailItem method has the following signature...
(rowData, sectionID, rowID, highlightRow)
Try doing this...
<TouchableHighlight key={rowID} underlayColor='#dddddd'>
run php artisan --version
from your console.
The version string is defined here:
https://github.com/laravel/framework/blob/master/src/Illuminate/Foundation/Application.php
/**
* The Laravel framework version.
*
* @var string
*/
const VERSION = '5.5-dev';
You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.
NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.
Example:
Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.
Returns:
Just be aware that this is not 100%!
Here are a little snippet for you to try out:
import spacy
phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
doc = nlp(phrase)
replaced = ""
for token in doc:
if token in doc.ents:
replaced+="XXXX "
else:
replaced+=token.text+" "
Read more here: https://spacy.io/usage/linguistic-features#named-entities
You could, instead of replacing with XXXX, replace based on the entity type, like:
if ent.label_ == "PERSON":
replaced += "<PERSON> "
Then:
import re, random
personames = ["Jack", "Mike", "Bob", "Dylan"]
phrase = re.replace("<PERSON>", random.choice(personames), phrase)
Firefox Screenshots is a new tool that ships with Firefox. It is not a developer tool, it is aimed at end-users of the browser.
To take a screenshot, click on the page actions menu in the address bar, and click "take a screenshot". If you then click "Save full page", it will save the full page, scrolling for you.
(source: mozilla.net)
Don't use iterators to do this. Maintain your own loop by incrementing a counter in the callback, and recursively calling the operation on the next item.
$.each(myMap, function(_, arr) {
processArray(arr, 0);
});
function processArray(arr, i) {
if (i >= arr.length) return;
setTimeout(function () {
$('#variant').fadeOut("slow", function () {
$(this).text(i + "-" + arr[i]).fadeIn("slow");
// Handle next iteration
processArray(arr, ++i);
});
}, 6000);
}
Though there's a logic error in your code. You're setting the same container to more than one different value at (roughly) the same time. Perhaps you mean for each one to update its own container.
Just to add to the many different ways this can show up.
If you using safari on iOS and you are connected to the Safari Technology Preview console - you will see the same problem. If you disconnect from the console - the problem will go away.
Of course it makes troubleshooting other issues difficult but it is a 100% repro.
I am trying to figure out what I can change in STP to stop it from doing this but have not found it yet.
In PHP:
$data = "<html>....";
exit(json_encode($data));
Then you should use AJAX to retrieve the data and do what you want with it. I suggest using JQuery: http://api.jquery.com/jQuery.getJSON/
Exit code 137 (128+9) indicates that your program exited due to receiving signal 9, which is SIGKILL
. This also explains the killed
message. The question is, why did you receive that signal?
The most likely reason is probably that your process crossed some limit in the amount of system resources that you are allowed to use. Depending on your OS and configuration, this could mean you had too many open files, used too much filesytem space or something else. The most likely is that your program was using too much memory. Rather than risking things breaking when memory allocations started failing, the system sent a kill signal to the process that was using too much memory.
As I commented earlier, one reason you might hit a memory limit after printing finished counting
is that your call to counter.items()
in your final loop allocates a list that contains all the keys and values from your dictionary. If your dictionary had a lot of data, this might be a very big list. A possible solution would be to use counter.iteritems()
which is a generator. Rather than returning all the items in a list, it lets you iterate over them with much less memory usage.
So, I'd suggest trying this, as your final loop:
for key, value in counter.iteritems():
writer.writerow([key, value])
Note that in Python 3, items
returns a "dictionary view" object which does not have the same overhead as Python 2's version. It replaces iteritems
, so if you later upgrade Python versions, you'll end up changing the loop back to the way it was.
here is the code to download file with how much % it is downloaded
<?php
$ch = curl_init();
$downloadFile = fopen( 'file name here', 'w' );
curl_setopt($ch, CURLOPT_URL, "file link here");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_BUFFERSIZE, 65536);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'downloadProgress');
curl_setopt($ch, CURLOPT_NOPROGRESS, false);
curl_setopt( $ch, CURLOPT_FILE, $downloadFile );
curl_exec($ch);
curl_close($ch);
function downloadProgress ($resource, $download_size, $downloaded_size, $upload_size, $uploaded_size) {
if($download_size!=0){
$percen= (($downloaded_size/$download_size)*100);
echo $percen."<br>";
}
}
?>
What I do in my projects is to activate the following option in the "Constant conditions & exceptions" code inspection:
Suggest @Nullable annotation for methods that may possibly return null and report nullable values passed to non-annotated parameters
When activated, all non-annotated parameters will be treated as non-null and thus you will also see a warning on your indirect call:
clazz.indirectPathToA(null);
For even stronger checks the Checker Framework may be a good choice (see this nice tutorial.
Note: I have not used that yet and there may be problems with the Jack compiler: see this bugreport
It's possible that the error didn't occur in the dot product, but after. For example try this
a = np.random.randn(12,1)
b = np.random.randn(1,5)
c = np.random.randn(5,12)
d = np.dot(a,b) * c
np.dot(a,b) will be fine; however np.dot(a, b) * c is clearly wrong (12x1 X 1x5 = 12x5 which cannot element-wise multiply 5x12) but numpy will give you
ValueError: operands could not be broadcast together with shapes (12,1) (1,5)
The error is misleading; however there is an issue on that line.
In my experience the plugins worked with http but not with the latest httpClient. Also, configuring the CORS respsonse headers on the server wasn't really an option. So, I created a proxy.conf.json file to act as a proxy server.
Read more about this here: https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md
below is my prox.conf.json file
{
"/posts": {
"target": "https://example.com",
"secure": true,
"pathRewrite": {
"^/posts": ""
},
"changeOrigin": true
}
}
I placed the proxy.conf.json file right next the the package.json file in the same directory
then I modified the start command in the package.json file like below
"start": "ng serve --proxy-config proxy.conf.json"
now, the http call from my app component is as follows
return this._http.get('/posts/pictures?method=GetPictures')
.subscribe((returnedStuff) => {
console.log(returnedStuff);
});
Lastly to run my app, I'd have to use npm start or ng serve --proxy-config proxy.conf.json
Perhaps you could just import a .js file as well and have the image replacement there, in JavaScript.
I like best Mauro Delrio's method. I also have added the following in my Project_Prefix.pch
#import "Language.h"
#define MyLocalizedString(key, alt) [Language get:key alter:alt]
So if you ever want to use the standard method (that uses NSLocalizedString) you can make a quick syntax substitution in all files.
This method works for Excel 2016, and calculates on cell value, so can be used on formula arrays (i.e. it will ignore blank cells that contain a formula).
Note: Len(#)>0 be altered to only select cell values above a certain length.
Note 2: '#' must not be an absolute reference (i.e. shouldn't contain '$').