This may happen due to the following reasons:
INSTALLED_APPS
list in settings.py
(You have to add either the app name or the dotted path to the subclass of AppConfig in apps.py in the app folder, depending on the version of django you are using). Refer documentation: INSTALLED_APPS migrations
folder inside those apps. (Solution: just create that folder).__init__.py
file inside migrations
folder of those apps. (Solution: Just create an empty file with name __init__.py)__init__.py
file inside the app folder. (Solution: Just create an empty file with name __init__.py)models.py
file in the appmodels.py
doesn't inherit django.db.models.Model
models.py
Note:
A common mistake is to add migrations
folder in .gitignore
file. When cloned from remote repo, migrations
folder and/or __init__.py
files will be missing in local repo. This causes problem.
I suggest to gitignore migration files by adding the following lines to .gitignore
file
*/migrations/*
!*/migrations/__init__.py
Use a .gitignore file. This allows you to ignore certain files. http://git-scm.com/docs/gitignore
Here's an example Eclipse one, which handles your classpath and project files: https://github.com/github/gitignore/blob/master/Global/Eclipse.gitignore
You need to declare your event in the class from myObject :
public event EventHandler<EventArgs> myMethod; //you should name it as an event, like ObjectChanged.
then myNameEvent is the callback to handle the event, and it can be in any other class
Reset and sync local repository with remote branch
The command: Remember to replace origin and master with the remote and branch that you want to synchronize with.
git fetch origin && git reset --hard origin/master && git clean -f -d
Or step-by-step:
git fetch origin
git reset --hard origin/master
git clean -f -d
Your local branch is now an exact copy (commits and all) of the remote branch.
Command output:
Here is an example of running the command on a local clone of the Forge a git repository.
sharkbook:forge lbaxter$ git fetch origin && git reset --hard origin/master && git clean -f -d
HEAD is now at 356cd85 FORGE-680
Removing forge-example-plugin/
Removing plugin-container-api/
Removing plugin-container/
Removing shell/.forge_settings
sharkbook:forge lbaxter$
It seems like two different scenarios are being mixed together in this discussion:
Scenario 1
Using my parent repository's pointers to submodules, I want to check out the commit in each submodule that the parent repository is pointing to, possibly after first iterating through all submodules and updating/pulling these from remote.
This is, as pointed out, done with
git submodule foreach git pull origin BRANCH
git submodule update
Scenario 2, which I think is what OP is aiming at
New stuff has happened in one or more submodules, and I want to 1) pull these changes and 2) update the parent repository to point to the HEAD (latest) commit of this/these submodules.
This would be done by
git submodule foreach git pull origin BRANCH
git add module_1_name
git add module_2_name
......
git add module_n_name
git push origin BRANCH
Not very practical, since you would have to hardcode n paths to all n submodules in e.g. a script to update the parent repository's commit pointers.
It would be cool to have an automated iteration through each submodule, updating the parent repository pointer (using git add
) to point to the head of the submodule(s).
For this, I made this small Bash script:
git-update-submodules.sh
#!/bin/bash
APP_PATH=$1
shift
if [ -z $APP_PATH ]; then
echo "Missing 1st argument: should be path to folder of a git repo";
exit 1;
fi
BRANCH=$1
shift
if [ -z $BRANCH ]; then
echo "Missing 2nd argument (branch name)";
exit 1;
fi
echo "Working in: $APP_PATH"
cd $APP_PATH
git checkout $BRANCH && git pull --ff origin $BRANCH
git submodule sync
git submodule init
git submodule update
git submodule foreach "(git checkout $BRANCH && git pull --ff origin $BRANCH && git push origin $BRANCH) || true"
for i in $(git submodule foreach --quiet 'echo $path')
do
echo "Adding $i to root repo"
git add "$i"
done
git commit -m "Updated $BRANCH branch of deployment repo to point to latest head of submodules"
git push origin $BRANCH
To run it, execute
git-update-submodules.sh /path/to/base/repo BRANCH_NAME
Elaboration
First of all, I assume that the branch with name $BRANCH (second argument) exists in all repositories. Feel free to make this even more complex.
The first couple of sections is some checking that the arguments are there. Then I pull the parent repository's latest stuff (I prefer to use --ff (fast-forwarding) whenever I'm just doing pulls. I have rebase off, BTW).
git checkout $BRANCH && git pull --ff origin $BRANCH
Then some submodule initializing, might be necessary, if new submodules have been added or are not initialized yet:
git submodule sync
git submodule init
git submodule update
Then I update/pull all submodules:
git submodule foreach "(git checkout $BRANCH && git pull --ff origin $BRANCH && git push origin $BRANCH) || true"
Notice a few things: First of all, I'm chaining some Git commands using &&
- meaning previous command must execute without error.
After a possible successful pull (if new stuff was found on the remote), I do a push to ensure that a possible merge-commit is not left behind on the client. Again, it only happens if a pull actually brought in new stuff.
Finally, the final || true
is ensuring that script continues on errors. To make this work, everything in the iteration must be wrapped in the double-quotes and the Git commands are wrapped in parentheses (operator precedence).
My favourite part:
for i in $(git submodule foreach --quiet 'echo $path')
do
echo "Adding $i to root repo"
git add "$i"
done
Iterate all submodules - with --quiet
, which removes the 'Entering MODULE_PATH' output. Using 'echo $path'
(must be in single-quotes), the path to the submodule gets written to output.
This list of relative submodule paths is captured in an array ($(...)
) - finally iterate this and do git add $i
to update the parent repository.
Finally, a commit with some message explaining that the parent repository was updated. This commit will be ignored by default, if nothing was done. Push this to origin, and you're done.
I have a script running this in a Jenkins job that chains to a scheduled automated deployment afterwards, and it works like a charm.
I hope this will be of help to someone.
For Windows you can use the Git Credential Manager (GCM) plugin. It is currently maintained by Microsoft. The nice thing is that it saves the password in the Windows Credential Store, not as plain text.
There is an installer on the releases page of the project. This will also install the official version of Git for Windows with the credential manager built-in. It allows two-factor authentication for GitHub (and other servers). And has a graphical interface for initially logging in.
For Cygwin users (or users already using the official Git for Windows), you might prefer the manual install. Download the zip package from the releases page. Extract the package, and then run the install.cmd
file. This will install to your ~/bin
folder. (Be sure your ~/bin
directory is in your PATH.) You then configure it using this command:
git config --global credential.helper manager
Git will then run the git-credential-manager.exe
when authenticating to any server.
I was getting the same the error inside a shared function, but it was only happening for some calls to this shared function. I eventually realized that one of classes calling the shared function wasn't wrapping it inside of a Unit of Work. Once I updated this classes functions with a Unit of Work everything worked as expected.
So just posting this for any future visitors who run into this same error, but for whom the accepted answer doesn't apply.
Just to inform for furthers developers, and thankfully to Basil Bourque, I just wanna add my stone to this topic.
If you want simply get the HH:MM:SS format then do this:
LocalTime hour = ZonedDateTime.now().toLocalTime().truncatedTo(ChronoUnit.SECONDS);
Cheers.
P.S.: This will work only at least with Java 8 !
PHP 7
// Validate a domain name
var_dump(filter_var('mandrill._domainkey.mailchimp.com', FILTER_VALIDATE_DOMAIN));
# string(33) "mandrill._domainkey.mailchimp.com"
// Validate an hostname (here, the underscore is invalid)
var_dump(filter_var('mandrill._domainkey.mailchimp.com', FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME));
# bool(false)
It is not documented here: http://www.php.net/filter.filters.validate and a bug request for this is located here: https://bugs.php.net/bug.php?id=72013
You can use the Lambda functions of Java 8 to achieve this without looping
String string = "1, 2, 3, 4";
List<Integer> list = Arrays.asList(string.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
Whenever this happens the first thing I check is the PHP memory limit.
Magento overrides the normal error handler with it's own, but when the error is "Out of memory" that custom handler cannot run, so nothing is seen.
var conditionalStatement = conditionSetting.Value;
//order of replace matters, remove == before =, incase of ===
conditionalStatement = conditionalStatement.Replace("==", "~").Replace("!=", "~").Replace('=', '~').Replace('!', '~').Replace('>', '~').Replace('<', '~').Replace(">=", "~").Replace("<=", "~");
var listOfValidConditions = new List<string>() { "!=", "==", ">", "<", ">=", "<=" };
if (conditionalStatement.Count(x => x == '~') != 1)
{
result.InvalidFieldList.Add(new KeyFieldData(batch.DECurrentField, "The IsDoubleKeyCondition does not contain a supported conditional statement. Contact System Administrator."));
result.Status = ValidatorStatus.Fail;
return result;
}
Needed to do something similar to test conditional statements from a string.
Replaced what i was looking for with a single character and counted the instances of the single character.
Obviously the single character you're using will need to be checked to not exist in the string before this happens to avoid incorrect counts.
Wrap your input stream in a buffered reader then use the read method to read one byte at a time until the end of stream.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Reader {
public static void main(String[] args) throws IOException {
BufferedReader buffer = new BufferedReader(
new InputStreamReader(System.in));
int c = 0;
while((c = buffer.read()) != -1) {
char character = (char) c;
System.out.println(character);
}
}
}
If you want to load the file, as part of your app functionality, then the best approach would be to include and reference to that file.
Another approach is to ask for the file, and load it during runtime. This can be done with the FileAPI. There is also another StackOverflow answer about using it: How to open a local disk file with Javascript?
I will include a slightly modified version for using it in React:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null
};
this.handleFileSelect = this.handleFileSelect.bind(this);
}
displayData(content) {
this.setState({data: content});
}
handleFileSelect(evt) {
let files = evt.target.files;
if (!files.length) {
alert('No file select');
return;
}
let file = files[0];
let that = this;
let reader = new FileReader();
reader.onload = function(e) {
that.displayData(e.target.result);
};
reader.readAsText(file);
}
render() {
const data = this.state.data;
return (
<div>
<input type="file" onChange={this.handleFileSelect}/>
{ data && <p> {data} </p> }
</div>
);
}
}
Bootstrap does the same thing (... as the selected answer below).
@media print {
a[href]:after {
content: " (" attr(href) ")";
}
}
Just remove it from there, or override it in your own print stylesheet:
@media print {
a[href]:after {
content: none !important;
}
}
One option that might work for some cases is to make your custom class inherit from dict
. This seems like a logical choice if it acts like a dict; maybe it should be a dict. This way, you get dict-like iteration for free.
class MyDict(dict):
def __init__(self, custom_attribute):
self.bar = custom_attribute
mydict = MyDict('Some name')
mydict['a'] = 1
mydict['b'] = 2
print mydict.bar
for k, v in mydict.items():
print k, '=>', v
Output:
Some name
a => 1
b => 2
With the release of iOS 7 (September 18th, 2013) apple increased the over-the-air cellular download limit to 100MBs.
Maximum app size remains 2GBs.
What you can do is to use the with
statement, and write the two steps on one line:
>>> with open('pagehead.section.htm', 'r') as fin: output = fin.read();
>>> print(output)
some content
The with
statement will take care to call __exit__
function of the given object even if something bad happened in your code; it's close to the try... finally
syntax. For object returned by open
, __exit__
corresponds to file closure.
This statement has been introduced with Python 2.6.
Simply you can use this..
$("ul li a").click(function() {
$(this).parent().find(">ul")...Something;
}
See example : https://codepen.io/gmkhussain/pen/XzjgRE
set.seed
is a base function that it is able to generate (every time you want) together other functions (rnorm
, runif
, sample
) the same random value.
Below an example without set.seed
> set.seed(NULL)
> rnorm(5)
[1] 1.5982677 -2.2572974 2.3057461 0.5935456 0.1143519
> rnorm(5)
[1] 0.15135371 0.20266228 0.95084266 0.09319339 -1.11049182
> set.seed(NULL)
> runif(5)
[1] 0.05697712 0.31892399 0.92547023 0.88360393 0.90015169
> runif(5)
[1] 0.09374559 0.64406494 0.65817582 0.30179009 0.19760375
> set.seed(NULL)
> sample(5)
[1] 5 4 3 1 2
> sample(5)
[1] 2 1 5 4 3
Below an example with set.seed
> set.seed(123)
> rnorm(5)
[1] -0.56047565 -0.23017749 1.55870831 0.07050839 0.12928774
> set.seed(123)
> rnorm(5)
[1] -0.56047565 -0.23017749 1.55870831 0.07050839 0.12928774
> set.seed(123)
> runif(5)
[1] 0.2875775 0.7883051 0.4089769 0.8830174 0.9404673
> set.seed(123)
> runif(5)
[1] 0.2875775 0.7883051 0.4089769 0.8830174 0.9404673
> set.seed(123)
> sample(5)
[1] 3 2 5 4 1
> set.seed(123)
> sample(5)
[1] 3 2 5 4 1
The primary goal of a hashmap is to store a data set and provide near constant time lookups on it using a unique key. There are two common styles of hashmap implementation:
Separate chaining is preferable if the hashmap may have a poor hash function, it is not desirable to pre-allocate storage for potentially unused slots, or entries may have variable size. This type of hashmap may continue to function relatively efficiently even when the load factor exceeds 1.0. Obviously, there is extra memory required in each entry to store linked list pointers.
Hashmaps using open addressing have potential performance advantages when the load factor is kept below a certain threshold (generally about 0.7) and a reasonably good hash function is used. This is because they avoid potential cache misses and many small memory allocations associated with a linked list, and perform all operations in a contiguous, pre-allocated array. Iteration through all elements is also cheaper. The catch is hashmaps using open addressing must be reallocated to a larger size and rehashed to maintain an ideal load factor, or they face a significant performance penalty. It is impossible for their load factor to exceed 1.0.
Some key performance metrics to evaluate when creating a hashmap would include:
Here is a flexible hashmap implementation I made. I used open addressing and linear probing for collision resolution.
The thing to look at is what HTML is being spit out by the control. In this case it puts out a table to create the menu. The hover style is set on the TD and once you select a menu item the control posts back and adds the selected style to the A tag of the link within the TD.
So you have two different items that are being manipulated here. One is a TD element and another is an A element. So, you have to make your CSS work accordingly. If I add the below CSS to a page with the menu then I get the expected behavior of the background color changing in either case. You may be doing some different CSS manipulation that may or may not apply to those elements.
<style>
.StaticHoverStyle
{
background: #000000;
}
.StaticSelectedStyle
{
background: blue;
}
</style>
A simple way to getting resource ID from string. Here resourceName is the name of resource ImageView in drawable folder which is included in XML file as well.
int resID = getResources().getIdentifier(resourceName, "id", getPackageName());
ImageView im = (ImageView) findViewById(resID);
Context context = im.getContext();
int id = context.getResources().getIdentifier(resourceName, "drawable",
context.getPackageName());
im.setImageResource(id);
You cannot move a running docker container from one host to another.
You can commit the changes in your container to an image with docker commit
, move the image onto a new host, and then start a new container with docker run
. This will preserve any data that your application has created inside the container.
Nb: It does not preserve data that is stored inside volumes; you need to move data volumes manually to new host.
There is an alternative approach, which does not have I18n problems (allowing ',' or '.' but not both): Decimal.TryParse
.
Just try converting, ignoring the value.
bool IsDecimalFormat(string input) {
Decimal dummy;
return Decimal.TryParse(input, out dummy);
}
This is significantly faster than using a regular expression, see below.
(The overload of Decimal.TryParse
can be used for finer control.)
Performance test results: Decimal.TryParse: 0.10277ms, Regex: 0.49143ms
Code (PerformanceHelper.Run
is a helper than runs the delegate for passed iteration count and returns the average TimeSpan
.):
using System;
using System.Text.RegularExpressions;
using DotNetUtils.Diagnostics;
class Program {
static private readonly string[] TestData = new string[] {
"10.0",
"10,0",
"0.1",
".1",
"Snafu",
new string('x', 10000),
new string('2', 10000),
new string('0', 10000)
};
static void Main(string[] args) {
Action parser = () => {
int n = TestData.Length;
int count = 0;
for (int i = 0; i < n; ++i) {
decimal dummy;
count += Decimal.TryParse(TestData[i], out dummy) ? 1 : 0;
}
};
Regex decimalRegex = new Regex(@"^[0-9]([\.\,][0-9]{1,3})?$");
Action regex = () => {
int n = TestData.Length;
int count = 0;
for (int i = 0; i < n; ++i) {
count += decimalRegex.IsMatch(TestData[i]) ? 1 : 0;
}
};
var paserTotal = 0.0;
var regexTotal = 0.0;
var runCount = 10;
for (int run = 1; run <= runCount; ++run) {
var parserTime = PerformanceHelper.Run(10000, parser);
var regexTime = PerformanceHelper.Run(10000, regex);
Console.WriteLine("Run #{2}: Decimal.TryParse: {0}ms, Regex: {1}ms",
parserTime.TotalMilliseconds,
regexTime.TotalMilliseconds,
run);
paserTotal += parserTime.TotalMilliseconds;
regexTotal += regexTime.TotalMilliseconds;
}
Console.WriteLine("Overall averages: Decimal.TryParse: {0}ms, Regex: {1}ms",
paserTotal/runCount,
regexTotal/runCount);
}
}
I would make a wrapper so you can be non-invasive. Minimally, for example...:
class CaseInsensitively(object):
def __init__(self, s):
self.__s = s.lower()
def __hash__(self):
return hash(self.__s)
def __eq__(self, other):
# ensure proper comparison between instances of this class
try:
other = other.__s
except (TypeError, AttributeError):
try:
other = other.lower()
except:
pass
return self.__s == other
Now, if CaseInsensitively('MICHAEL89') in whatever:
should behave as required (whether the right-hand side is a list, dict, or set). (It may require more effort to achieve similar results for string inclusion, avoid warnings in some cases involving unicode
, etc).
I just wanted to add to this discussion that I am just compiling on VS and GCC, and used to use include guards. I have now switched to #pragma once
, and the only reason for me is not performance or portability or standard as I don't really care what is standard as long as VS and GCC support it, and that is that:
#pragma once
reduces possibilities for bugs.
It is all too easy to copy and paste a header file to another header file, modify it to suit ones needs, and forget to change the name of the include guard. Once both are included, it takes you a while to track down the error, as the error messages aren't necessarily clear.
I guess this is probably a non issue for most but I tried to solve it. I think I have a pretty decent solution. In case anyone else stumbles upon this issue.
function randomNums($gen, $trim, $low, $high)
{
$results_to_gen = $gen;
$low_range = $low;
$high_range = $high;
$trim_results_to= $trim;
$items = array();
$results = range( 1, $results_to_gen);
$i = 1;
foreach($results as $result)
{
$result = mt_rand( $low_range, $high_range);
$items[] = $result;
}
$unique = array_unique( $items, SORT_NUMERIC);
$countem = count( $unique);
$unique_counted = $countem -$trim_results_to;
$sum = array_slice($unique, $unique_counted);
foreach ($sum as $key)
{
$output = $i++.' : '.$key.'<br>';
echo $output;
}
}
randomNums(1100, 1000 ,890000, 899999);
As others have said, std::max_element()
and std::min_element()
return iterators, which need to be dereferenced to obtain the value.
The advantage of returning an iterator (rather than just the value) is that it allows you to determine the position of the (first) element in the container with the maximum (or minimum) value.
For example (using C++11 for brevity):
#include <vector>
#include <algorithm>
#include <iostream>
int main()
{
std::vector<double> v {1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0};
auto biggest = std::max_element(std::begin(v), std::end(v));
std::cout << "Max element is " << *biggest
<< " at position " << std::distance(std::begin(v), biggest) << std::endl;
auto smallest = std::min_element(std::begin(v), std::end(v));
std::cout << "min element is " << *smallest
<< " at position " << std::distance(std::begin(v), smallest) << std::endl;
}
This yields:
Max element is 5 at position 4
min element is 1 at position 0
Using std::minmax_element()
as suggested in the comments above may be faster for large data sets, but may give slightly different results. The values for my example above would be the same, but the position of the "max" element would be 9
since...
If several elements are equivalent to the largest element, the iterator to the last such element is returned.
You can use:
\set list '''foobar'''
SELECT * FROM dbo.PubLists WHERE name = :list;
That will do
You must have some virtual function declared in one of the parent classes and never implemented in any of the child classes. Make sure that all virtual functions are implemented somewhere in the inheritence chain. If a class's definition includes a pure virtual function that is never implemented, an instance of that class cannot ever be constructed.
I was playing around with C# code an I accidentally found the solution to your problem haha
This is the code for the Principal view:
`@model dynamic
@Html.Partial("_Partial", Model as IDictionary<string, object>)`
Then in the Partial view:
`@model dynamic
@if (Model != null) {
foreach (var item in Model)
{
<div>@item.text</div>
}
}`
It worked for me, I hope this will help you too!!
Using replace()
with regular expressions is the most flexible/powerful. It's also the only way to globally replace every instance of a search pattern in JavaScript. The non-regex variant of replace()
will only replace the first instance.
For example:
var str = "foo gar gaz";
// returns: "foo bar gaz"
str.replace('g', 'b');
// returns: "foo bar baz"
str = str.replace(/g/gi, 'b');
In the latter example, the trailing /gi
indicates case-insensitivity and global replacement (meaning that not just the first instance should be replaced), which is what you typically want when you're replacing in strings.
To remove characters, use an empty string as the replacement:
var str = "foo bar baz";
// returns: "foo r z"
str.replace(/ba/gi, '');
In your Jenkins installation directory there is a jenkins.xml, where you can set various options. Add the parameter -Xmx with the size you want to the arguments-tag (or increase the size if its already there).
In some cases it's very useful to change font-size with relative font sizing units. For example:
.btn {font-size: 3vw;}
Demo: http://www.bootply.com/7VN5OCVhhF
1vw is 1% of the viewport width. More info: http://www.sitepoint.com/new-css3-relative-font-size/
WPF contains the following MessageBox:
if (MessageBox.Show("Do you want to Save?", "Confirm",
MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
{
}
An extra pair of rabbits' ears should do the trick.
start "" "C:\Program...
START
regards the first quoted parameter as the window-title, unless it's the only parameter - and any switches up until the executable name are regarded as START
switches.
Use <div id="rectangle" style="width:number px; height:number px; background-color:blue"></div>
This will create a blue rectangle.
So before MySQL 8.0 there is no ROW_NUMBER() function. Accpted answer rewritten to support older versions of MySQL:
SET @row_number = 0;
SELECT t.A, t.B, t.C, (@row_number:=@row_number + 1) AS number
FROM dbo.tableZ AS t ORDER BY t.A;
You can read a CSV file with headers into a NumPy structured array with np.genfromtxt. For example:
import numpy as np
csv_fname = 'file.csv'
with open(csv_fname, 'w') as fp:
fp.write("""\
"A","B","C","D","E","F","timestamp"
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291111964948E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291113113366E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291120650486E12
""")
# Read the CSV file into a Numpy record array
r = np.genfromtxt(csv_fname, delimiter=',', names=True, case_sensitive=True)
print(repr(r))
which looks like this:
array([(611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111196e+12),
(611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111311e+12),
(611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29112065e+12)],
dtype=[('A', '<f8'), ('B', '<f8'), ('C', '<f8'), ('D', '<f8'), ('E', '<f8'), ('F', '<f8'), ('timestamp', '<f8')])
You can access a named column like this r['E']
:
array([1715.37476, 1715.37476, 1715.37476])
Note: this answer previously used np.recfromcsv to read the data into a NumPy record array. While there was nothing wrong with that method, structured arrays are generally better than record arrays for speed and compatibility.
i know i am late for this answer but the correct answer seems to be
See :help getcompletion():
:echo getcompletion('', 'color')
which you can assign to a variable:
:let foo = getcompletion('', 'color')
or use in an expression register:
:put=getcompletion('', 'color')
This is not my answer, this solution is provided by u/romainl in this post on reddit.
I write a method to show the four corners of the data and monkey-patch to dataframe to do so:
def _sw(df, up_rows=10, down_rows=5, left_cols=4, right_cols=3, return_df=False):
''' display df data at four corners
A,B (up_pt)
C,D (down_pt)
parameters : up_rows=10, down_rows=5, left_cols=4, right_cols=3
usage:
df = pd.DataFrame(np.random.randn(20,10), columns=list('ABCDEFGHIJKLMN')[0:10])
df.sw(5,2,3,2)
df1 = df.set_index(['A','B'], drop=True, inplace=False)
df1.sw(5,2,3,2)
'''
#pd.set_printoptions(max_columns = 80, max_rows = 40)
ncol, nrow = len(df.columns), len(df)
# handle columns
if ncol <= (left_cols + right_cols) :
up_pt = df.ix[0:up_rows, :] # screen width can contain all columns
down_pt = df.ix[-down_rows:, :]
else: # screen width can not contain all columns
pt_a = df.ix[0:up_rows, 0:left_cols]
pt_b = df.ix[0:up_rows, -right_cols:]
pt_c = df[-down_rows:].ix[:,0:left_cols]
pt_d = df[-down_rows:].ix[:,-right_cols:]
up_pt = pt_a.join(pt_b, how='inner')
down_pt = pt_c.join(pt_d, how='inner')
up_pt.insert(left_cols, '..', '..')
down_pt.insert(left_cols, '..', '..')
overlap_qty = len(up_pt) + len(down_pt) - len(df)
down_pt = down_pt.drop(down_pt.index[range(overlap_qty)]) # remove overlap rows
dt_str_list = down_pt.to_string().split('\n') # transfer down_pt to string list
# Display up part data
print up_pt
start_row = (1 if df.index.names[0] is None else 2) # start from 1 if without index
# Display omit line if screen height is not enought to display all rows
if overlap_qty < 0:
print "." * len(dt_str_list[start_row])
# Display down part data row by row
for line in dt_str_list[start_row:]:
print line
# Display foot note
print "\n"
print "Index :",df.index.names
print "Column:",",".join(list(df.columns.values))
print "row: %d col: %d"%(len(df), len(df.columns))
print "\n"
return (df if return_df else None)
DataFrame.sw = _sw #add a method to DataFrame class
Here is the sample:
>>> df = pd.DataFrame(np.random.randn(20,10), columns=list('ABCDEFGHIJKLMN')[0:10])
>>> df.sw()
A B C D .. H I J
0 -0.8166 0.0102 0.0215 -0.0307 .. -0.0820 1.2727 0.6395
1 1.0659 -1.0102 -1.3960 0.4700 .. 1.0999 1.1222 -1.2476
2 0.4347 1.5423 0.5710 -0.5439 .. 0.2491 -0.0725 2.0645
3 -1.5952 -1.4959 2.2697 -1.1004 .. -1.9614 0.6488 -0.6190
4 -1.4426 -0.8622 0.0942 -0.1977 .. -0.7802 -1.1774 1.9682
5 1.2526 -0.2694 0.4841 -0.7568 .. 0.2481 0.3608 -0.7342
6 0.2108 2.5181 1.3631 0.4375 .. -0.1266 1.0572 0.3654
7 -1.0617 -0.4743 -1.7399 -1.4123 .. -1.0398 -1.4703 -0.9466
8 -0.5682 -1.3323 -0.6992 1.7737 .. 0.6152 0.9269 2.1854
9 0.2361 0.4873 -1.1278 -0.2251 .. 1.4232 2.1212 2.9180
10 2.0034 0.5454 -2.6337 0.1556 .. 0.0016 -1.6128 -0.8093
..............................................................
15 1.4091 0.3540 -1.3498 -1.0490 .. 0.9328 0.3668 1.3948
16 0.4528 -0.3183 0.4308 -0.1818 .. 0.1295 1.2268 0.1365
17 -0.7093 1.3991 0.9501 2.1227 .. -1.5296 1.1908 0.0318
18 1.7101 0.5962 0.8948 1.5606 .. -0.6862 0.9558 -0.5514
19 1.0329 -1.2308 -0.6896 -0.5112 .. 0.2719 1.1478 -0.1459
Index : [None]
Column: A,B,C,D,E,F,G,H,I,J
row: 20 col: 10
>>> df.sw(4,2,3,4)
A B C .. G H I J
0 -0.8166 0.0102 0.0215 .. 0.3671 -0.0820 1.2727 0.6395
1 1.0659 -1.0102 -1.3960 .. 1.0984 1.0999 1.1222 -1.2476
2 0.4347 1.5423 0.5710 .. 1.6675 0.2491 -0.0725 2.0645
3 -1.5952 -1.4959 2.2697 .. 0.4856 -1.9614 0.6488 -0.6190
4 -1.4426 -0.8622 0.0942 .. -0.0947 -0.7802 -1.1774 1.9682
..............................................................
18 1.7101 0.5962 0.8948 .. -0.8592 -0.6862 0.9558 -0.5514
19 1.0329 -1.2308 -0.6896 .. -0.3954 0.2719 1.1478 -0.1459
Index : [None]
Column: A,B,C,D,E,F,G,H,I,J
row: 20 col: 10
Ask Tom on pagination and very, very useful analytic functions.
This is excerpt from that page:
select * from (
select /*+ first_rows(25) */
object_id,object_name,
row_number() over
(order by object_id) rn
from all_objects
)
where rn between :n and :m
order by rn;
The main difference is when compiled in debug mode, pdb files are also created which allow debugging (so you can step through the code when its running). This however means that the code isn't optimized as much.
LocalDate // Represents an entire day, without time-of-day and without time zone.
.now( // Capture the current date.
ZoneId.of( "Asia/Tokyo" ) // Returns a `ZoneId` object.
) // Returns a `LocalDate` object.
.atStartOfDay( // Determines the first moment of the day as seen on that date in that time zone. Not all days start at 00:00!
ZoneId.of( "Asia/Tokyo" )
) // Returns a `ZonedDateTime` object.
Get the full length of the today as seen in a time zone.
Using Half-Open approach, where the beginning is inclusive while the ending is exclusive. This approach solves the flaw in your code that fails to account for the very last second of the day.
ZoneId zoneId = ZoneId.of( "Africa/Tunis" ) ;
LocalDate today = LocalDate.now( zoneId ) ;
ZonedDateTime zdtStart = today.atStartOfDay( zoneId ) ;
ZonedDateTime zdtStop = today.plusDays( 1 ).atStartOfDay( zoneId ) ;
zdtStart.toString() = 2020-01-30T00:00+01:00[Africa/Tunis]
zdtStop.toString() = 2020-01-31T00:00+01:00[Africa/Tunis]
See the same moments in UTC.
Instant start = zdtStart.toInstant() ;
Instant stop = zdtStop.toInstant() ;
start.toString() = 2020-01-29T23:00:00Z
stop.toString() = 2020-01-30T23:00:00Z
If you want the entire day of a date as seen in UTC rather than in a time zone, use OffsetDateTime
.
LocalDate today = LocalDate.now( ZoneOffset.UTC ) ;
OffsetDateTime odtStart = today.atTime( OffsetTime.MIN ) ;
OffsetDateTime odtStop = today.plusDays( 1 ).atTime( OffsetTime.MIN ) ;
odtStart.toString() = 2020-01-30T00:00+18:00
odtStop.toString() = 2020-01-31T00:00+18:00
These OffsetDateTime
objects will already be in UTC, but you can call toInstant
if you need such objects which are always in UTC by definition.
Instant start = odtStart.toInstant() ;
Instant stop = odtStop.toInstant() ;
start.toString() = 2020-01-29T06:00:00Z
stop.toString() = 2020-01-30T06:00:00Z
Tip: You may be interested in adding the ThreeTen-Extra library to your project to use its Interval
class to represent this pair of Instant
objects. This class offers useful methods for comparison such as abuts
, overlaps
, contains
, and more.
Interval interval = Interval.of( start , stop ) ;
interval.toString() = 2020-01-29T06:00:00Z/2020-01-30T06:00:00Z
The answer by mprivat is correct. His point is to not try to obtain end of a day, but rather compare to "before start of next day". His idea is known as the "Half-Open" approach where a span of time has a beginning that is inclusive while the ending is exclusive.
Joda-Time 2.3 offers a method for this very purpose, to obtain first moment of the day: withTimeAtStartOfDay()
. Similarly in java.time, LocalDate::atStartOfDay
.
Search StackOverflow for "joda half-open" to see more discussion and examples.
See this post, Time intervals and other ranges should be half-open, by Bill Schneider.
The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them.
Use java.time classes. The java.time framework is the official successor of the highly successful Joda-Time library.
The java.time framework is built into Java 8 and later. Back-ported to Java 6 & 7 in the ThreeTen-Backport project, further adapted to Android in the ThreeTenABP project.
An Instant
is a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = Instant.now();
Apply a time zone to get the wall-clock time for some locality.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
To get the first moment of the day go through the LocalDate
class and its atStartOfDay
method.
ZonedDateTime zdtStart = zdt.toLocalDate().atStartOfDay( zoneId );
Using Half-Open approach, get first moment of following day.
ZonedDateTime zdtTomorrowStart = zdtStart.plusDays( 1 );
Currently the java.time framework lacks an Interval
class as described below for Joda-Time. However, the ThreeTen-Extra project extends java.time with additional classes. This project is the proving ground for possible future additions to java.time. Among its classes is Interval
. Construct an Interval
by passing a pair of Instant
objects. We can extract an Instant
from our ZonedDateTime
objects.
Interval today = Interval.of( zdtStart.toInstant() , zdtTomorrowStart.toInstant() );
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
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
UPDATE: The Joda-Time project is now in maintenance-mode, and advises migration to the java.time classes. I am leaving this section intact for history.
Joda-Time has three classes to represent a span of time in various ways: Interval
, Period
, and Duration
. An Interval
has a specific beginning and ending on the timeline of the Universe. This fits our need to represent "a day".
We call the method withTimeAtStartOfDay
rather than set time of day to zeros. Because of Daylight Saving Time and other anomalies the first moment of the day may not be 00:00:00
.
Example code using Joda-Time 2.3.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( timeZone );
DateTime todayStart = now.withTimeAtStartOfDay();
DateTime tomorrowStart = now.plusDays( 1 ).withTimeAtStartOfDay();
Interval today = new Interval( todayStart, tomorrowStart );
If you must, you can convert to a java.util.Date.
java.util.Date date = todayStart.toDate();
In my case it was renaming a file to an existing file in other folder(Group) by mistake, just rename it to what it was then the error disappeared
May be it is the problem of using len()
for an integer value.
does not posses the len attribute in Python.
Error as:I will give u an example:
number= 1
print(len(num))
Instead of use ths,
data = [1,2,3,4]
print(len(data))
using (SqlConnection sqlConnection1 = new SqlConnection("Your Connection String")) {
using (SqlCommand cmd = new SqlCommand()) {
Int32 rowsAffected;
cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
rowsAffected = cmd.ExecuteNonQuery();
}}
You can also find the name of the current on screen activity using
adb shell dumpsys window windows | grep 'mCurrentFocus'
I came across this question as I was looking to install simplejson for Python 2.6. I needed to use the 'object_pairs_hook' of json.load() in order to load a json file as an OrderedDict. Being familiar with more recent versions of Python I didn't realize that the json module for Python 2.6 doesn't include the 'object_pairs_hook' so I had to install simplejson for this purpose. From personal experience this is why i use simplejson as opposed to the standard json module.
I suspect the error is caused by this:
foreach (KeyValuePair<int, int> kvp in rankings)
rankings is a dictionary, which is IEnumerable. By using it in a foreach loop, you're specifying that you want each KeyValuePair from the dictionary in a deferred manner. That is, the next KeyValuePair is not returned until your loop iterates again.
But you're modifying the dictionary inside your loop:
rankings[kvp.Key] = rankings[kvp.Key] + 4;
which isn't allowed...so you get the exception.
You could simply do this
foreach (KeyValuePair<int, int> kvp in rankings.ToArray())
public abstract class Node {
List<Node> children;
public List<Node> getChidren() {
if (children == null) {
children = new ArrayList<>();
}
return chidren;
}
}
As simple as it gets and very easy to use. To use it, extend it:
public class MenuItem extends Node {
String label;
String href;
...
}
If it doesn't work with npm uninstall <module_name>
try it globally by typing -g
.
Maybe you just need to do it as an superUser/administrator with sudo npm uninstall <module_name>
.
I hit this same issue trying to install Dashcast on Centos 7. The fix was adding -fPIC
at the end of each of the CFLAGS in the x264 Makefile. Then I had to run make distclean
for both x264 and ffmpeg and rebuild.
Task.Delay(0)
as in the accepted answer was a good approach, as it is a cached copy of a completed Task
.
As of 4.6 there's now Task.CompletedTask
which is more explicit in its purpose, but not only does Task.Delay(0)
still return a single cached instance, it returns the same single cached instance as does Task.CompletedTask
.
The cached nature of neither is guaranteed to remain constant, but as implementation-dependent optimisations that are only implementation-dependent as optimisations (that is, they'd still work correctly if the implementation changed to something that was still valid) the use of Task.Delay(0)
was better than the accepted answer.
If the application is already open (even in background), it will be restored by "start" command. Exit the program if running then /max or /min will work
You can also use Microsoft Visual Studio compiler instead of Cygwin or MinGW in Windows environment as the compiler for CLion.
Just go to find Actions in Help and type "Registry" without " and enable CLion.enable.msvc Now configure toolchain with Microsoft Visual Studio Compiler. (You need to download it if not already downloaded)
follow this link for more details: https://www.jetbrains.com/help/clion/quick-tutorial-on-configuring-clion-on-windows.html
You should use npm-run-all (or concurrently
, parallelshell
), because it has more control over starting and killing commands. The operators &
, |
are bad ideas because you'll need to manually stop it after all tests are finished.
This is an example for protractor testing through npm:
scripts: {
"webdriver-start": "./node_modules/protractor/bin/webdriver-manager update && ./node_modules/protractor/bin/webdriver-manager start",
"protractor": "./node_modules/protractor/bin/protractor ./tests/protractor.conf.js",
"http-server": "./node_modules/http-server/bin/http-server -a localhost -p 8000",
"test": "npm-run-all -p -r webdriver-start http-server protractor"
}
-p
= Run commands in parallel.
-r
= Kill all commands when one of them finishes with an exit code of zero.
Running npm run test
will start Selenium driver, start http server (to serve you files) and run protractor tests. Once all tests are finished, it will close the http server and the selenium driver.
If you are using AFNetworking library to download image and that images are using in UITableview then You can use below code in cellForRowAtIndexPath
[self setImageWithURL:user.user_ProfilePicturePath toControl:cell.imgView];
-(void)setImageWithURL:(NSURL*)url toControl:(id)ctrl
{
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:nil success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
if (image) {
if([ctrl isKindOfClass:[UIButton class]])
{
UIButton btn =(UIButton)ctrl;
[btn setBackgroundImage:image forState:UIControlStateNormal];
}
else
{
UIImageView imgView = (UIImageView)ctrl;
imgView.image = image;
}
}
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"No Image");
}];
[operation start];}
If you actually know the text you are going to replace you could use
$('#one').contents(':contains("Hi I am text")')[0].nodeValue = '"Hi I am replace"';
Or
$('#one').contents(':not(*)')[1].nodeValue = '"Hi I am replace"';
$('#one').contents(':not(*)')
selects non-element child nodes in this case text nodes and the second node is the one we want to replace.
The inclusion of your comparison class (or more specifically the AsEnumerable
call you needed to use to get it to work) meant that the sorting logic went from being based on the database server to being on the database client (your application). This meant that your client now needs to retrieve and then process a larger number of records, which will always be less efficient that performing the lookup on the database where the approprate indexes can be used.
You should try to develop a where clause that satisfies your requirements instead, see Using an IEqualityComparer with a LINQ to Entities Except clause for more details.
As a hack, you could consider having a special handling on the client side, converting 'Null' string to something that will never occur, for example, XXNULLXX and converting back on the server.
It is not pretty, but it may solve the issue for such a boundary case.
Gummi is the best LaTeX editor. It is a free, open source, cross-platform, program, featuring a live preview pane.
http://gummi.midnightcoding.org/
e4 http://gummi.midnightcoding.org/wp-content/uploads/20091012-1large(1).png
Do you realy want to return null ? Something you can do, is maybe initialise savedkey with 0 value and return 0 as a null value. It can be more simple.
Rename your variable name
to myname
, bacause name
is a generic property of window
and is not writable in the same window.
And replace
onclick='myfunction(\''" + name + "'\')'
With
onclick='myfunction(myname)'
Working example:
var myname = "Mathew";_x000D_
document.write('<button id="button" type="button" onclick="myfunction(myname);">click</button>');_x000D_
function myfunction(name) {_x000D_
alert(name);_x000D_
}
_x000D_
@Tom, thank you very much for pointing out this solution. It works great for me.
I was looking for a way to just exclude one column from printing and from the example above. To exclude the second column you can do something like this
library(data.table)
dt <- data.table(a=1:2, b=2:3, c=3:4)
dt[,.SD,.SDcols=-2]
dt[,.SD,.SDcols=c(1,3)]
This is an improvement on the accepted answer:
.box {_x000D_
margin-top: 1em;_x000D_
margin-bottom: 1em;_x000D_
background-color: #CCC;_x000D_
}_x000D_
_x000D_
.fixed-ar::before {_x000D_
content: "";_x000D_
float: left;_x000D_
width: 1px;_x000D_
margin-left: -1px;_x000D_
}_x000D_
.fixed-ar::after {_x000D_
content: "";_x000D_
display: table;_x000D_
clear: both;_x000D_
}_x000D_
_x000D_
.fixed-ar-16-9::before {_x000D_
padding-top: 56.25%;_x000D_
}_x000D_
.fixed-ar-3-2::before {_x000D_
padding-top: 66.66%;_x000D_
}_x000D_
.fixed-ar-4-3::before {_x000D_
padding-top: 75%;_x000D_
}_x000D_
.fixed-ar-1-1::before {_x000D_
padding-top: 100%;_x000D_
}_x000D_
_x000D_
.width-50 {_x000D_
display: inline-block;_x000D_
width: 50%;_x000D_
}_x000D_
.width-20 {_x000D_
display: inline-block;_x000D_
width: 20%;_x000D_
}
_x000D_
<div class="box fixed-ar fixed-ar-16-9">16:9 full width</div>_x000D_
<hr>_x000D_
<div class="box fixed-ar fixed-ar-16-9 width-50">16:9</div>_x000D_
<hr>_x000D_
<div class="box fixed-ar fixed-ar-16-9 width-20">16:9</div>_x000D_
<div class="box fixed-ar fixed-ar-3-2 width-20">3:2</div>_x000D_
<div class="box fixed-ar fixed-ar-4-3 width-20">4:3</div>_x000D_
<div class="box fixed-ar fixed-ar-1-1 width-20">1:1</div>_x000D_
<hr>_x000D_
<div class="box fixed-ar fixed-ar-16-9 width-20">16:9</div>_x000D_
<div class="box fixed-ar fixed-ar-16-9 width-50">16:9</div>
_x000D_
Note : Use it if calculating / adding days from current date.
Be aware: this answer has issues (see comments)
var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);
It should be like
var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));
One way to do that is to set the cascade option on you "One" side of relationship:
class Employee {
//
@OneToMany(cascade = {CascadeType.PERSIST})
private Set<Vehicles> vehicles = new HashSet<Vehicles>();
//
}
by this, when you call
Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);
it will save the vehicles too.
There is another workaround you can use to update using a join. This example below assumes you want to de-normalize a table by including a lookup value (in this case storing a users name in the table). The update includes a join to find the name and the output is evaluated in a CASE statement that supports the name being found or not found. The key to making this work is ensuring all the columns coming out of the join have unique names. In the sample code, notice how b.user_name conflicts with the a.user_name column and must be aliased with the unique name "user_user_name".
UPDATE
(
SELECT a.user_id, a.user_name, b.user_name as user_user_name
FROM some_table a
LEFT OUTER JOIN user_table b ON a.user_id = b.user_id
WHERE a.user_id IS NOT NULL
)
SET user_name = CASE
WHEN user_user_name IS NOT NULL THEN user_user_name
ELSE 'UNKNOWN'
END;
First, you have to lookup the correct ArrayList
in the HashMap
:
ArrayList<String> myAList = theHashMap.get(courseID)
Then, add the new grade to the ArrayList
:
myAList.add(newGrade)
i have one trick :
you can do this to prevent doubly encode. Every time first decode then again encode;
$string = urldecode($string);
Then do again
$string = urlencode($string);
Performing this way we can avoid double encode :)
The command
x/i $pc
can be set to run all the time using the usual configuration mechanism.
A simple solution is to install jshon
library :
jshon -l < /tmp/test.json
2
commons.apache.org
MultiValueMap class
h/H = 12/24 hours means you will write hh:mm = 12 hours format and HH:mm = 24 hours format
Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers
error
means that Access-Control-Allow-Origin
field of HTTP header is not handled or allowed by response. Remove Access-Control-Allow-Origin
field from the request header.
A PDB file contains information used by the debugger. It is not required to run your application and it does not need to be included in your released version.
You can disable pdb files from being created in Visual Studio. If you are building from the command line or a script then omit the /Debug
switch.
The reason expr[expr[2] == 'hesc']
doesn't work is that for a data frame, x[y]
selects columns, not rows. If you want to select rows, change to the syntax x[y,]
instead:
> expr[expr[2] == 'hesc',]
expr_value cell_type
4 5.929771 hesc
5 5.873096 hesc
6 5.665857 hesc
The main reason is we can't create object of an interface, and IEnumerable is an interface. We need to create object of the class which implements the interface. This is the main reason we can't directly create object of IEnumerable.
The most effective way:
if (array.indexOf(element) > -1) {
alert('Bingooo')
}
Component
import { Component, ElementRef, ViewChild, AfterViewInit} from '@angular/core';
...
@ViewChild('input1', {static: false}) inputEl: ElementRef;
ngAfterViewInit() {
setTimeout(() => this.inputEl.nativeElement.focus());
}
HTML
<input type="text" #input1>
Here it is:
s = "123"
try:
i = int(s)
except ValueError as verr:
pass # do job to handle: s does not contain anything convertible to int
except Exception as ex:
pass # do job to handle: Exception occurred while converting to int
The toolz library has the partition
function for this:
from toolz.itertoolz.core import partition
list(partition(2, [1, 2, 3, 4]))
[(1, 2), (3, 4)]
Does not work, need --pos
to evaluate double:
String version = System.getProperty("java.version");
System.out.println("version:" + version);
int pos = 0, count = 0;
for (; pos < version.length() && count < 2; pos++) {
if (version.charAt(pos) == '.') {
count++;
}
}
--pos; //EVALUATE double
double dversion = Double.parseDouble(version.substring(0, pos));
System.out.println("dversion:" + dversion);
return dversion;
}
You can format a number, say x
, up to decimal places as you wish. Here x
is a number with many decimal places. Suppose we wish to show up to 8 decimal places of this number:
x = 1111111234.6547389758965789345
y = formatC(x, digits = 8, format = "f")
# [1] "1111111234.65473890"
Here format="f"
gives floating numbers in the usual decimal places say, xxx.xxx, and digits
specifies the number of digits. By contrast, if you wanted to get an integer to display you would use format="d"
(much like sprintf
).
For what it is worth, mine was fixed after I went to target->Build Phases->Link Binary With Libraries, deleted the libstdc++.tbd reference, then added a reference to libstdc++.6.0.9.tbd.
According to a slideshow about Facebook's Messaging system, Facebook uses the comet technology to "push" message to web browsers. Facebook's comet server is built on the open sourced Erlang web server mochiweb.
In the picture below, the phrase "channel clusters" means "comet servers".
Many other big web sites build their own comet server, because there are differences between every company's need. But build your own comet server on a open source comet server is a good approach.
You can try icomet, a C1000K C++ comet server built with libevent. icomet also provides a JavaScript library, it is easy to use as simple as:
var comet = new iComet({
sign_url: 'http://' + app_host + '/sign?obj=' + obj,
sub_url: 'http://' + icomet_host + '/sub',
callback: function(msg){
// on server push
alert(msg.content);
}
});
icomet supports a wide range of Browsers and OSes, including Safari(iOS, Mac), IEs(Windows), Firefox, Chrome, etc.
It is a little tricky. First you can use keytool to put the private key into PKCS12 format, which is more portable/compatible than Java's various keystore formats. Here is an example taking a private key with alias 'mykey' in a Java keystore and copying it into a PKCS12 file named myp12file.p12
.
[note that on most screens this command extends beyond the right side of the box: you need to scroll right to see it all]
keytool -v -importkeystore -srckeystore .keystore -srcalias mykey -destkeystore myp12file.p12 -deststoretype PKCS12
Enter destination keystore password:
Re-enter new password:
Enter source keystore password:
[Storing myp12file.p12]
Now the file myp12file.p12
contains the private key in PKCS12 format which may be used directly by many software packages or further processed using the openssl pkcs12
command. For example,
openssl pkcs12 -in myp12file.p12 -nocerts -nodes
Enter Import Password:
MAC verified OK
Bag Attributes
friendlyName: mykey
localKeyID: 54 69 6D 65 20 31 32 37 31 32 37 38 35 37 36 32 35 37
Key Attributes: <No Attributes>
-----BEGIN RSA PRIVATE KEY-----
MIIC...
.
.
.
-----END RSA PRIVATE KEY-----
Prints out the private key unencrypted.
Note that this is a private key, and you are responsible for appreciating the security implications of removing it from your Java keystore and moving it around.
First of all, two things that we need to understand,
bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND"),
mServiceConn, Context.BIND_AUTO_CREATE);
here mServiceConn
is instance of ServiceConnection
class(inbuilt) it is actually interface
that we need to implement with two (1st for network connected and 2nd network not connected) method to monitor network connection state.
IBinder
Object. So, IBinder
object is our handler which accesses all the methods of Service
by using (.) operator. .
MyService myService;
public ServiceConnection myConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
Log.d("ServiceConnection","connected");
myService = binder;
}
//binder comes from server to communicate with method's of
public void onServiceDisconnected(ComponentName className) {
Log.d("ServiceConnection","disconnected");
myService = null;
}
}
myservice.serviceMethod();
Here myService
is object and serviceMethod is method in service.
and by this way communication is established between client and server.
You are running Python 2 code on Python 3. In Python 3, the module has been renamed to http.client
.
You could try to run the 2to3
tool on your code, and try to have it translated automatically. References to httplib
will automatically be rewritten to use http.client
instead.
If you are using Postgres (and since we're in 2017 now) you might want to give their :money
column type a try.
add_column :products, :price, :money, default: 0
When you work with unsigned types, modular arithmetic (also known as "wrap around" behavior) is taking place. To understand this modular arithmetic, just have a look at these clocks:
9 + 4 = 1 (13 mod 12), so to the other direction it is: 1 - 4 = 9 (-3 mod 12). The same principle is applied while working with unsigned types. If the result type is unsigned
, then modular arithmetic takes place.
Now look at the following operations storing the result as an unsigned int
:
unsigned int five = 5, seven = 7;
unsigned int a = five - seven; // a = (-2 % 2^32) = 4294967294
int one = 1, six = 6;
unsigned int b = one - six; // b = (-5 % 2^32) = 4294967291
When you want to make sure that the result is signed
, then stored it into signed
variable or cast it to signed
. When you want to get the difference between numbers and make sure that the modular arithmetic will not be applied, then you should consider using abs()
function defined in stdlib.h
:
int c = five - seven; // c = -2
int d = abs(five - seven); // d = 2
Be very careful, especially while writing conditions, because:
if (abs(five - seven) < seven) // = if (2 < 7)
// ...
if (five - seven < -1) // = if (-2 < -1)
// ...
if (one - six < 1) // = if (-5 < 1)
// ...
if ((int)(five - seven) < 1) // = if (-2 < 1)
// ...
but
if (five - seven < 1) // = if ((unsigned int)-2 < 1) = if (4294967294 < 1)
// ...
if (one - six < five) // = if ((unsigned int)-5 < 5) = if (4294967291 < 5)
// ...
Also u can consider this
$('#select_2').find('option:selected').text();
which might be a little faster solution though I am not sure.
Consider the hex() method of the bytes
type on Python 3.5 and up:
>>> array_alpha = [ 133, 53, 234, 241 ]
>>> print(bytes(array_alpha).hex())
8535eaf1
EDIT: it's also much faster than hexlify
(modified @falsetru's benchmarks above)
from timeit import timeit
N = 10000
print("bytearray + hexlify ->", timeit(
'binascii.hexlify(data).decode("ascii")',
setup='import binascii; data = bytearray(range(255))',
number=N,
))
print("byte + hex ->", timeit(
'data.hex()',
setup='data = bytes(range(255))',
number=N,
))
Result:
bytearray + hexlify -> 0.011218150997592602
byte + hex -> 0.005952142993919551
Google has recently launched design support library and there is one component called TextInputLayout and it supports showing an error via setErrorEnabled(boolean)
and setError(CharSequence)
.
How to use it?
Step 1: Wrap your EditText with TextInputLayout:
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/layoutUserName">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="hint"
android:id="@+id/editText1" />
</android.support.design.widget.TextInputLayout>
Step 2: Validate input
// validating input on a button click
public void btnValidateInputClick(View view) {
final TextInputLayout layoutUserName = (TextInputLayout) findViewById(R.id.layoutUserName);
String strUsername = layoutLastName.getEditText().getText().toString();
if(!TextUtils.isEmpty(strLastName)) {
Snackbar.make(view, strUsername, Snackbar.LENGTH_SHORT).show();
layoutUserName.setErrorEnabled(false);
} else {
layoutUserName.setError("Input required");
layoutUserName.setErrorEnabled(true);
}
}
I have created an example over my Github repository, checkout the example if you wish to!
Use this XPath expression:
/*/*/X/node()
This selects any node (element, text node, comment or processing instruction) that is a child of any X
element that is a grand-child of the top element of the XML document.
To verify what is selected, here is this XSLT transformation that outputs exactly the selected nodes:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="/">
<xsl:copy-of select="/*/*/X/node()"/>
</xsl:template>
</xsl:stylesheet>
and it produces exactly the wanted, correct result:
First Text Node #1
<y> Y can Have Child Nodes #
<child> deep to it </child>
</y> Second Text Node #2
<z />
Explanation:
As defined in the W3 XPath 1.0 Spec, "child::node()
selects all the children of the context node, whatever their node type." This means that any element, text-node, comment-node and processing-instruction node children are selected by this node-test.
node()
is an abbreviation of child::node()
(because child::
is the primary axis and is used when no axis is explicitly specified).
Just for information, the below
window.open("data:application/pdf," + encodeURI(pdfString));
does not work anymore in Chrome. Yesterday, I came across with the same issue and tried this solution, but did not work (it is 'Not allowed to navigate top frame to data URL'). You cannot open the data URL directly in a new window anymore. But, you can wrap it in iframe and make it open in a new window like below. =)
let pdfWindow = window.open("")
pdfWindow.document.write(
"<iframe width='100%' height='100%' src='data:application/pdf;base64, " +
encodeURI(yourDocumentBase64VarHere) + "'></iframe>"
)
String s=null;
String is not initialized for null. if any string operation tried it can throw null pointer exception
String t="null";
It is a string literal with value string "null" same like t = "xyz". It will not throw null pointer.
String u="";
It is as empty string , It will not throw null pointer.
I agree with Rob's post about having a custom attribute in the controller. Apparently I don't have enough rep to comment. Here's the jsfiddle that was requested:
sample html
<div ng-controller="MyCtrl">
<ul>
<li ng-repeat="link in links" ng-class="{active: $route.current.activeNav == link.type}"> <a href="{{link.uri}}">{{link.name}}</a>
</li>
</ul>
</div>
sample app.js
angular.module('MyApp', []).config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/a', {
activeNav: 'a'
})
.when('/a/:id', {
activeNav: 'a'
})
.when('/b', {
activeNav: 'b'
})
.when('/c', {
activeNav: 'c'
});
}])
.controller('MyCtrl', function ($scope, $route) {
$scope.$route = $route;
$scope.links = [{
uri: '#/a',
name: 'A',
type: 'a'
}, {
uri: '#/b',
name: 'B',
type: 'b'
}, {
uri: '#/c',
name: 'C',
type: 'c'
}, {
uri: '#/a/detail',
name: 'A Detail',
type: 'a'
}];
});
For me, I had typed image with a lower case "i" instead of Image. So I did:
from PIL import Image
NOT from PIL import image
I solved this issue in Windows using this format for the full path:
sdk.dir=C:/Users/xxxx/AppData/Local/Android/Sdk
HttpServerUtility.UrlEncode
will use HttpUtility.UrlEncode
internally. There is no specific difference. The reason for existence of Server.UrlEncode
is compatibility with classic ASP.
Write one table per join, like this:
select tab1.a,tab2.b,tab3.c,tab4.d
from
table1 tab1
inner join table2 tab2 on tab2.fg = tab1.fg
left join table3 tab3 on tab3.xxx = tab1.xxx and tab3.desc = "XYZ"
left join table4 tab4 on tab4.xya = tab3.xya and tab4.ss = tab3.ss
left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk
Note that while my query contains actual left join, your query apparently doesn't.
Since the conditions are in the where, your query should behave like inner joins. (Although I admit I don't know Informix, so maybe I'm wrong there).
The specfific Informix extension used in the question works a bit differently with regards to left joins. Apart from the exact syntax of the join itself, this is mainly in the fact that in Informix, you can specify a list of outer joined tables. These will be left outer joined, and the join conditions can be put in the where clause. Note that this is a specific extension to SQL. Informix also supports 'normal' left joins, but you can't combine the two in one query, it seems.
In Oracle this extension doesn't exist, and you can't put outer join conditions in the where clause, since the conditions will be executed regardless.
So look what happens when you move conditions to the where clause:
select tab1.a,tab2.b,tab3.c,tab4.d
from
table1 tab1
inner join table2 tab2 on tab2.fg = tab1.fg
left join table3 tab3 on tab3.xxx = tab1.xxx
left join table4 tab4 on tab4.xya = tab3.xya
left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk
where
tab3.desc = "XYZ" and
tab4.ss = tab3.ss
Now, only rows will be returned for which those two conditions are true. They cannot be true when no row is found, so if there is no matching row in table3 and/or table4, or if ss
is null in either of the two, one of these conditions is going to return false, and no row is returned. This effectively changed your outer join to an inner join, and as such changes the behavior significantly.
PS: left join
and left outer join
are the same. It means that you optionally join the second table to the first (the left one). Rows are returned if there is only data in the 'left' part of the join. In Oracle you can also right [outer] join
to make not the left, but the right table the leading table. And there is and even full [outer] join
to return a row if there is data in either table.
using(var stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Png);
techObject.Last().Image = Image.FromStream(stream);
bitmap.Dispose();
// Without this code, I had an OutOfMemory exception.
GC.Collect();
GC.WaitForPendingFinalizers();
//
}
jut add allowfullscreen="true"
to iframe
<iframe src="URL here" allowfullscreen="true"> </iframe>
This question shows precisely why I like to do things the way I mentioned in my question is const after type id acceptable?
In short, I find the easiest way to remember the rule is that the "const" goes after the thing it applies to. So in your question, "int const *" means that the int is constant, while "int * const" would mean that the pointer is constant.
If someone decides to put it at the very front (eg: "const int *"), as a special exception in that case it applies to the thing after it.
Many people like to use that special exception because they think it looks nicer. I dislike it, because it is an exception, and thus confuses things.
Try to clean and rebuild the project. I had the absolutely same question, this solved it.
Didn't exactly get your intent. Do check Apache Commons configuration library http://commons.apache.org/configuration/
You can have multiple values against a key as in
key=value1,value2
and you can read this into an array as configuration.getAsStringArray("key")
If you can't use bat files to set up your environment, then your only likely option is to set up a system wide environment variable. You can find these by doing
I don't know if you'd have to restart visual studio, but seems unlikely. HTH
FileReader API with jQuery, simple example.
( function ( $ ) {_x000D_
// Add click event handler to button_x000D_
$( '#load-file' ).click( function () {_x000D_
if ( ! window.FileReader ) {_x000D_
return alert( 'FileReader API is not supported by your browser.' );_x000D_
}_x000D_
var $i = $( '#file' ), // Put file input ID here_x000D_
input = $i[0]; // Getting the element from jQuery_x000D_
if ( input.files && input.files[0] ) {_x000D_
file = input.files[0]; // The file_x000D_
fr = new FileReader(); // FileReader instance_x000D_
fr.onload = function () {_x000D_
// Do stuff on onload, use fr.result for contents of file_x000D_
$( '#file-content' ).append( $( '<div/>' ).html( fr.result ) )_x000D_
};_x000D_
//fr.readAsText( file );_x000D_
fr.readAsDataURL( file );_x000D_
} else {_x000D_
// Handle errors here_x000D_
alert( "File not selected or browser incompatible." )_x000D_
}_x000D_
} );_x000D_
} )( jQuery );
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="file" id="file" />_x000D_
<input type='button' id='load-file' value='Load'>_x000D_
<div id="file-content"></div>
_x000D_
To read as text... uncomment //fr.readAsText(file);
line and comment fr.readAsDataURL(file);
It can be done using SQL Server Import and Export Wizard. But if you're familiar with SSIS and don't want to run the SQL Server Import and Export Wizard, create an SSIS package that uses the Excel Source and the SQL Server Destination in the data flow.
Got the fix in css.
td.disabledAnchor a{
pointer-events: none !important;
cursor: default;
color:Gray;
}
Above css when applied to the anchor tag will disable the click event.
For details checkout this link
Avoid loops. What you want to do is:
import numpy as np
data=np.loadtxt(fname="data.txt")## to load the above two column
print data
print data.sum(axis=1)
Use the System.Runtime.InteropServices.Marshal
class:
String SecureStringToString(SecureString value) {
IntPtr valuePtr = IntPtr.Zero;
try {
valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value);
return Marshal.PtrToStringUni(valuePtr);
} finally {
Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
}
}
If you want to avoid creating a managed string object, you can access the raw data using Marshal.ReadInt16(IntPtr, Int32)
:
void HandleSecureString(SecureString value) {
IntPtr valuePtr = IntPtr.Zero;
try {
valuePtr = Marshal.SecureStringToGlobalAllocUnicode(value);
for (int i=0; i < value.Length; i++) {
short unicodeChar = Marshal.ReadInt16(valuePtr, i*2);
// handle unicodeChar
}
} finally {
Marshal.ZeroFreeGlobalAllocUnicode(valuePtr);
}
}
Since functions in Javascript can be called with any number of arguments, and the document doesn't place any restriction on the onFulfilled()
method's arguments besides the below clause, I think that you can pass multiple arguments to the onFulfilled()
method as long as the promise's value is the first argument.
2.2.2.1 it must be called after promise is fulfilled, with promise’s value as its first argument.
I had this issue for days and nothing I found anywhere online helped me, I'm posting my answer here in case it helps anyone else.
In my case, I was working on a microservice being called through remoting, and my @Transactional annotation at the service level was not being picked up by the remote proxy.
Adding a delegate class between the service and dao layers and marking the delegate method as transactional fixed this for me.
@bku_drytt's solution didn't do it for me.
I solved it by additionally changing every occurence of 14.0
to 12.0
and v140
to v120
manually in the .vcxproj files.
Then it compiled!
im
is "image process name"
example /f /im notepad.exe
is specified to kill image process name (program) notepad.exe
To break completely out of a foreach loop, break is used;
To go to the next iteration in the loop, continue is used;
Break is useful if you’re looping through a collection of Objects (like Rows in a Datatable) and you are searching for a particular match, when you find that match, there’s no need to continue through the remaining rows, so you want to break out.
Continue is useful when you have accomplished what you need to in side a loop iteration. You’ll normally have continue after an if.
The problem with SOAP is that it is in conflict with the ideals behind the HTTP stack. Any middleware should be able to work with HTTP requests without understanding the content of the request or response, but for example a regular HTTP caching server won't work with SOAP requests without knowing only which parts of the SOAP content matter for caching. SOAP just uses HTTP as a wrapper for its own communications protocol, like a proxy.
If you want to modify the line width flexibly you can use "scale_size_manual," this is the same procedure for picking the color, fill, alpha, etc.
library(ggplot2)
library(tidyr)
x = seq(0,10,0.05)
df <- data.frame(A = 2 * x + 10,
B = x**2 - x*6,
C = 30 - x**1.5,
X = x)
df = gather(df,A,B,C,key="Model",value="Y")
ggplot( df, aes (x=X, y=Y, size=Model, colour=Model ))+
geom_line()+
scale_size_manual( values = c(4,2,1) ) +
scale_color_manual( values = c("orange","red","navy") )
I was looking for the solution on net and the below works for me. Ref.
And you call the function like this :
SELECT * FROM dbo.split('ram shyam hari gopal',' ')
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[Split](@String VARCHAR(8000), @Delimiter CHAR(1))
RETURNS @temptable TABLE (items VARCHAR(8000))
AS
BEGIN
DECLARE @idx INT
DECLARE @slice VARCHAR(8000)
SELECT @idx = 1
IF len(@String)<1 OR @String IS NULL RETURN
WHILE @idx!= 0
BEGIN
SET @idx = charindex(@Delimiter,@String)
IF @idx!=0
SET @slice = LEFT(@String,@idx - 1)
ELSE
SET @slice = @String
IF(len(@slice)>0)
INSERT INTO @temptable(Items) VALUES(@slice)
SET @String = RIGHT(@String,len(@String) - @idx)
IF len(@String) = 0 break
END
RETURN
END
here is some code for more robust imcrop ( a bit like in matlab )
def imcrop(img, bbox):
x1,y1,x2,y2 = bbox
if x1 < 0 or y1 < 0 or x2 > img.shape[1] or y2 > img.shape[0]:
img, x1, x2, y1, y2 = pad_img_to_fit_bbox(img, x1, x2, y1, y2)
return img[y1:y2, x1:x2, :]
def pad_img_to_fit_bbox(img, x1, x2, y1, y2):
img = np.pad(img, ((np.abs(np.minimum(0, y1)), np.maximum(y2 - img.shape[0], 0)),
(np.abs(np.minimum(0, x1)), np.maximum(x2 - img.shape[1], 0)), (0,0)), mode="constant")
y1 += np.abs(np.minimum(0, y1))
y2 += np.abs(np.minimum(0, y1))
x1 += np.abs(np.minimum(0, x1))
x2 += np.abs(np.minimum(0, x1))
return img, x1, x2, y1, y2
There's a theme available specifically for this
options: {
theme: 'maximized'
}
from the Google chart docs:
Currently only one theme is available:
'maximized' - Maximizes the area of the chart, and draws the legend and all of the labels inside the chart area. Sets the following options:
chartArea: {width: '100%', height: '100%'},
legend: {position: 'in'},
titlePosition: 'in', axisTitlesPosition: 'in',
hAxis: {textPosition: 'in'}, vAxis: {textPosition: 'in'}
You can combine data from the two tables, order by goals highest first and then choose the top two like this:
MySQL
select *
from (
select * from tblMadrid
union all
select * from tblBarcelona
) alldata
order by goals desc
limit 0,2;
SQL Server
select top 2 *
from (
select * from tblMadrid
union all
select * from tblBarcelona
) alldata
order by goals desc;
If you only want Messi and Ronaldo
select * from tblBarcelona where name = 'messi'
union all
select * from tblMadrid where name = 'ronaldo'
To ensure that messi is at the top of the result, you can do something like this:
select * from (
select * from tblBarcelona where name = 'messi'
union all
select * from tblMadrid where name = 'ronaldo'
) stars
order by name;
As per January 13,2018 Do as follow:
I just want to add some tips, when you using sort , be careful about your locale that effects the order of the key comparison. I usually explicitly use LC_ALL=C to make locale what I want.
Solved it as follows,
in CSS
#my{
zoom: 100%;
}
Now, it loads in 100% zoom by default. Tested it by giving 290% zoom and it loaded by that zoom percentage on default, it's upto the user if he wants to change zoom.
Though this is not the best way to do it, there is another effective solution
Check the page code of stack over flow, even they have buttons and they use un ordered lists to solve this problem.
As soon as you call contains
, containsAll
, equals
, hashCode
, remove
, retainAll
, size
or toArray
, you'd have to traverse the elements anyway.
If you're occasionally only calling methods such as isEmpty
or clear
I suppose you'd be better of by creating the collection lazily. You could for instance have a backing ArrayList
for storing previously iterated elements.
I don't know of any such class in any library, but it should be a fairly simple exercise to write up.
Mysql Developers Team announced that version 8.0 will have Common Table Expressions in MySQL (CTEs). So it will be possible to write queries like this:
WITH RECURSIVE my_cte AS
(
SELECT 1 AS n
UNION ALL
SELECT 1+n FROM my_cte WHERE n<10
)
SELECT * FROM my_cte;
+------+
| n |
+------+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
+------+
10 rows in set (0,00 sec)
Map implicitly returns while forEach does not.
This is why when you're coding a JSX application, you almost always use map instead of forEach to display content in React.
Update April 29th 2014:
My answer is kind of old by now and I guess you rather want to use some kind of high level library such as Retrofit.
Based on this blog I came up with the following solution: http://blog.tacticalnuclearstrike.com/2010/01/using-multipartentity-in-android-applications/
You will have to download additional libraries to get MultipartEntity
running!
1) Download httpcomponents-client-4.1.zip from http://james.apache.org/download.cgi#Apache_Mime4J and add apache-mime4j-0.6.1.jar to your project.
2) Download httpcomponents-client-4.1-bin.zip from http://hc.apache.org/downloads.cgi and add httpclient-4.1.jar, httpcore-4.1.jar and httpmime-4.1.jar to your project.
3) Use the example code below.
private DefaultHttpClient mHttpClient;
public ServerCommunication() {
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
mHttpClient = new DefaultHttpClient(params);
}
public void uploadUserPhoto(File image) {
try {
HttpPost httppost = new HttpPost("some url");
MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("Title", new StringBody("Title"));
multipartEntity.addPart("Nick", new StringBody("Nick"));
multipartEntity.addPart("Email", new StringBody("Email"));
multipartEntity.addPart("Description", new StringBody(Settings.SHARE.TEXT));
multipartEntity.addPart("Image", new FileBody(image));
httppost.setEntity(multipartEntity);
mHttpClient.execute(httppost, new PhotoUploadResponseHandler());
} catch (Exception e) {
Log.e(ServerCommunication.class.getName(), e.getLocalizedMessage(), e);
}
}
private class PhotoUploadResponseHandler implements ResponseHandler<Object> {
@Override
public Object handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
HttpEntity r_entity = response.getEntity();
String responseString = EntityUtils.toString(r_entity);
Log.d("UPLOAD", responseString);
return null;
}
}
First, bootstrap-theme.css
is nothing else but equivalent of Bootstrap 2.x style in Bootstrap 3. If you really want to use it, just add it ALONG with bootstrap.css
(minified version will work too).
Option Explicit
Const ConnectionStrngAccessPW As String = _"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\BARON\Desktop\Test_DB-PW.accdb;
Jet OLEDB:Database Password=123pass;"
Const ConnectionStrngAccess As String = _"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\BARON\Desktop\Test_DB.accdb;
Persist Security Info=False;"
'C:\Users\BARON\Desktop\Test.accdb
Sub ModifyingExistingDataOnAccessDB()
Dim TableConn As ADODB.Connection
Dim TableData As ADODB.Recordset
Set TableConn = New ADODB.Connection
Set TableData = New ADODB.Recordset
TableConn.ConnectionString = ConnectionStrngAccess
TableConn.Open
On Error GoTo CloseConnection
With TableData
.ActiveConnection = TableConn
'.Source = "SELECT Emp_Age FROM Roster WHERE Emp_Age > 40;"
.Source = "Roster"
.LockType = adLockOptimistic
.CursorType = adOpenForwardOnly
.Open
On Error GoTo CloseRecordset
Do Until .EOF
If .Fields("Emp_Age").Value > 40 Then
.Fields("Emp_Age").Value = 40
.Update
End If
.MoveNext
Loop
.MoveFirst
MsgBox "Update Complete"
End With
CloseRecordset:
TableData.CancelUpdate
TableData.Close
CloseConnection:
TableConn.Close
Set TableConn = Nothing
Set TableData = Nothing
End Sub
Sub AddingDataToAccessDB()
Dim TableConn As ADODB.Connection
Dim TableData As ADODB.Recordset
Dim r As Range
Set TableConn = New ADODB.Connection
Set TableData = New ADODB.Recordset
TableConn.ConnectionString = ConnectionStrngAccess
TableConn.Open
On Error GoTo CloseConnection
With TableData
.ActiveConnection = TableConn
.Source = "Roster"
.LockType = adLockOptimistic
.CursorType = adOpenForwardOnly
.Open
On Error GoTo CloseRecordset
Sheet3.Activate
For Each r In Range("B3", Range("B3").End(xlDown))
MsgBox "Adding " & r.Offset(0, 1)
.AddNew
.Fields("Emp_ID").Value = r.Offset(0, 0).Value
.Fields("Emp_Name").Value = r.Offset(0, 1).Value
.Fields("Emp_DOB").Value = r.Offset(0, 2).Value
.Fields("Emp_SOD").Value = r.Offset(0, 3).Value
.Fields("Emp_EOD").Value = r.Offset(0, 4).Value
.Fields("Emp_Age").Value = r.Offset(0, 5).Value
.Fields("Emp_Gender").Value = r.Offset(0, 6).Value
.Update
Next r
MsgBox "Update Complete"
End With
CloseRecordset:
TableData.Close
CloseConnection:
TableConn.Close
Set TableConn = Nothing
Set TableData = Nothing
End Sub
You need to use HAVING
, not WHERE
.
The difference is: the WHERE
clause filters which rows MySQL selects. Then MySQL groups the rows together and aggregates the numbers for your COUNT
function.
HAVING
is like WHERE
, only it happens after the COUNT
value has been computed, so it'll work as you expect. Rewrite your subquery as:
( -- where that pid is in the set:
SELECT c2.pid -- of pids
FROM Catalog AS c2 -- from catalog
WHERE c2.pid = c1.pid
HAVING COUNT(c2.sid) >= 2)
You can't search LONGs directly. LONGs can't appear in the WHERE clause. They can appear in the SELECT list though so you can use that to narrow down the number of rows you'd have to examine.
Oracle has recommended converting LONGs to CLOBs for at least the past 2 releases. There are fewer restrictions on CLOBs.
I would just like to add another useful advantage of using %timeit to answer by mu ? that:
PS: I know this should be a comment to answer above but I currently don't have enough reputation for that, hope what I write will be helpful to someone and help me earn enough reputation to comment next time.
In my case, I experienced this error because my webapp was .NET v4, and the application pool was configured for .NET v2.
Double-clicking on the application pool brings up a popup window, where we can select the desired version of .NET Framework.
We can use javascript DOMParser
for special characters conversion.
const parser = new DOMParser();
const convertedValue = (parser.parseFromString("' & ' < >", "application/xml").body.innerText;
a = {'name': 'your_name','class': 4}
if 'name' in a: del a['name']
You should define a key name while storing data to local storage which should be a string and value should be a string
localStorage.setItem('dataSource', this.dataSource.length);
and to print, you should use getItem
console.log(localStorage.getItem('dataSource'));
You need to set a name on the <select>
tag like so:
<select name="select_catalog" id="select_catalog">
You can get it in php with this:
$_POST['select_catalog'];
DecimalFormat df=new DecimalFormat("0.00");
Use this code to get exact two decimal points. Even if the value is 0.0 it will give u 0.00 as output.
Instead if you use:
DecimalFormat df=new DecimalFormat("#.00");
It wont convert 0.2659 into 0.27. You will get an answer like .27.
You should create new SSH key set for that Docker image, as you probably don't want to embed there your own private key. To make it work, you'll have to add that key to deployment keys in your git repository. Here's complete recipe:
Generate ssh keys with ssh-keygen -q -t rsa -N '' -f repo-key
which will give you repo-key and repo-key.pub files.
Add repo-key.pub to your repository deployment keys.
On GitHub, go to [your repository] -> Settings -> Deploy keys
Add something like this to your Dockerfile:
ADD repo-key / RUN \ chmod 600 /repo-key && \ echo "IdentityFile /repo-key" >> /etc/ssh/ssh_config && \ echo -e "StrictHostKeyChecking no" >> /etc/ssh/ssh_config && \ // your git clone commands here...
Note that above switches off StrictHostKeyChecking, so you don't need .ssh/known_hosts. Although I probably like more the solution with ssh-keyscan in one of the answers above.
Solution using Java 8 and Stream Api:
private static <K, V> List<V> createListFromMapEntries (Map<K, V> map){
return map.values().stream().collect(Collectors.toList());
}
Usage:
public static void main (String[] args)
{
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
List<String> result = createListFromMapEntries(map);
result.forEach(System.out :: println);
}
You can use Except:
List<car> list1 = GetTheList();
List<car> list2 = GetSomeOtherList();
List<car> result = list2.Except(list1).ToList();
You probably don't even need those temporary variables:
List<car> result = GetSomeOtherList().Except(GetTheList()).ToList();
Note that Except
does not modify either list - it creates a new list with the result.
To run the .bat, and have access to the last exit code, run it as:
& .\my-app\my-fle.bat
There are 3 main issues with multithreading:
1) Race Conditions
2) Caching / stale memory
3) Complier and CPU optimisations
volatile
can solve 2 & 3, but can't solve 1. synchronized
/explicit locks can solve 1, 2 & 3.
1) Consider this thread unsafe code:
x++;
While it may look like one operation, it's actually 3: reading the current value of x from memory, adding 1 to it, and saving it back to memory. If few threads try to do it at the same time, the result of the operation is undefined. If x
originally was 1, after 2 threads operating the code it may be 2 and it may be 3, depending on which thread completed which part of the operation before control was transferred to the other thread. This is a form of race condition.
Using synchronized
on a block of code makes it atomic - meaning it make it as if the 3 operations happen at once, and there's no way for another thread to come in the middle and interfere. So if x
was 1, and 2 threads try to preform x++
we know in the end it will be equal to 3. So it solves the race condition problem.
synchronized (this) {
x++; // no problem now
}
Marking x
as volatile
does not make x++;
atomic, so it doesn't solve this problem.
2) In addition, threads have their own context - i.e. they can cache values from main memory. That means that a few threads can have copies of a variable, but they operate on their working copy without sharing the new state of the variable among other threads.
Consider that on one thread, x = 10;
. And somewhat later, in another thread, x = 20;
. The change in value of x
might not appear in the first thread, because the other thread has saved the new value to its working memory, but hasn't copied it to the main memory. Or that it did copy it to the main memory, but the first thread hasn't updated its working copy. So if now the first thread checks if (x == 20)
the answer will be false
.
Marking a variable as volatile
basically tells all threads to do read and write operations on main memory only. synchronized
tells every thread to go update their value from main memory when they enter the block, and flush the result back to main memory when they exit the block.
Note that unlike data races, stale memory is not so easy to (re)produce, as flushes to main memory occur anyway.
3) The complier and CPU can (without any form of synchronization between threads) treat all code as single threaded. Meaning it can look at some code, that is very meaningful in a multithreading aspect, and treat it as if it’s single threaded, where it’s not so meaningful. So it can look at a code and decide, in sake of optimisation, to reorder it, or even remove parts of it completely, if it doesn’t know that this code is designed to work on multiple threads.
Consider the following code:
boolean b = false;
int x = 10;
void threadA() {
x = 20;
b = true;
}
void threadB() {
if (b) {
System.out.println(x);
}
}
You would think that threadB could only print 20 (or not print anything at all if threadB if-check is executed before setting b
to true), as b
is set to true only after x
is set to 20, but the compiler/CPU might decide to reorder threadA, in that case threadB could also print 10. Marking b
as volatile
ensures that it won’t be reordered (or discarded in certain cases). Which mean threadB could only print 20 (or nothing at all). Marking the methods as syncrhonized will achieve the same result. Also marking a variable as volatile
only ensures that it won’t get reordered, but everything before/after it can still be reordered, so synchronization can be more suited in some scenarios.
Note that before Java 5 New Memory Model, volatile didn’t solve this issue.
Since a dict
is iterable, you can apply the classic nested container iterable formula to this problem with only a couple of minor changes. Here's a Python 2 version (see below for 3):
import collections
def nested_dict_iter(nested):
for key, value in nested.iteritems():
if isinstance(value, collections.Mapping):
for inner_key, inner_value in nested_dict_iter(value):
yield inner_key, inner_value
else:
yield key, value
Test:
list(nested_dict_iter({'a':{'b':{'c':1, 'd':2},
'e':{'f':3, 'g':4}},
'h':{'i':5, 'j':6}}))
# output: [('g', 4), ('f', 3), ('c', 1), ('d', 2), ('i', 5), ('j', 6)]
In Python 2, It might be possible to create a custom Mapping
that qualifies as a Mapping
but doesn't contain iteritems
, in which case this will fail. The docs don't indicate that iteritems
is required for a Mapping
; on the other hand, the source gives Mapping
types an iteritems
method. So for custom Mappings
, inherit from collections.Mapping
explicitly just in case.
In Python 3, there are a number of improvements to be made. As of Python 3.3, abstract base classes live in collections.abc
. They remain in collections
too for backwards compatibility, but it's nicer having our abstract base classes together in one namespace. So this imports abc
from collections
. Python 3.3 also adds yield from
, which is designed for just these sorts of situations. This is not empty syntactic sugar; it may lead to faster code and more sensible interactions with coroutines.
from collections import abc
def nested_dict_iter(nested):
for key, value in nested.items():
if isinstance(value, abc.Mapping):
yield from nested_dict_iter(value)
else:
yield key, value
Above answer is very correct but I'm giving an easy step to do it:
private static final long[] THREE_CYCLES = new long[] { 100, 1000, 1000, 1000, 1000, 1000 };
public void longVibrate(View v)
{
vibrateMulti(THREE_CYCLES);
}
private void vibrateMulti(long[] cycles) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification();
notification.vibrate = cycles;
notificationManager.notify(0, notification);
}
And then in your xml file:
<button android:layout_height="wrap_content"
android:layout_width ="wrap_content"
android:onclick ="longVibrate"
android:text ="VibrateThrice">
</button>
That's the easiest way.
Use repr:
a = "Hello\tWorld\nHello World"
print(repr(a))
# 'Hello\tWorld\nHello World'
Note you do not get \s
for a space. I hope that was a typo...?
But if you really do want \s
for spaces, you could do this:
print(repr(a).replace(' ',r'\s'))
SELECT d1.Short_Code
FROM domain1 d1
LEFT JOIN domain2 d2
ON d1.Short_Code = d2.Short_Code
WHERE d2.Short_Code IS NULL
You can just do this:
git remote add origin ssh://user@host:1234/srv/git/example
1234
is the ssh port being used
If the two files are not sorted yet, you can use:
comm -12 <(sort a.txt) <(sort b.txt)
and it will work, avoiding the error message comm: file 2 is not in sorted order
when doing comm -12 a.txt b.txt
.
Try declaring the unit of width:
e1.style.width = "400px"; // width in PIXELS
Here's how I did it:
table.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
public void valueChanged(ListSelectionEvent event) {
// do some actions here, for example
// print first column value from selected row
System.out.println(table.getValueAt(table.getSelectedRow(), 0).toString());
}
});
This code reacts on mouse click and item selection from keyboard.
I set CurrentCulture
and CurrentUICulture
my custom base controller
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-GB");
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-GB");
}
The code was most likely compiled with a later JDK (without using cross-compilation options) and is being run on an earlier JRE. While upgrading the JRE is one solution, it would be better to use the cross-compilation options to ensure the code will run on whatever JRE is intended as the minimum version for the app.
I solved this problem this way. I used kotlin.
var timer = Timer()
var DELAY:Long = 2000
editText.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
Log.e("TAG","timer start")
timer = Timer()
timer.schedule(object : TimerTask() {
override fun run() {
//do something
}
}, DELAY)
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
Log.e("TAG","timer cancel ")
timer.cancel() //Terminates this timer,discarding any currently scheduled tasks.
timer.purge() //Removes all cancelled tasks from this timer's task queue.
}
})
It is illegal to nest EL expressions: you should inline them. Using JSTL is perfectly valid in your situation. Correcting the mistake, you'll make the code working:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:c="http://java.sun.com/jstl/core">
<c:if test="#{not empty user or user.userId eq 0}">
<a href="Images/thumb_02.jpg" target="_blank" ></a>
<img src="Images/thumb_02.jpg" />
</c:if>
<c:if test="#{empty user or user.userId eq 0}">
<a href="/DisplayBlobExample?userId=#{user.userId}" target="_blank"></a>
<img src="/DisplayBlobExample?userId=#{user.userId}" />
</c:if>
</html>
Another solution is to specify all the conditions you want inside an EL of one element. Though it could be heavier and less readable, here it is:
<a href="#{not empty user or user.userId eq 0 ? '/Images/thumb_02.jpg' : '/DisplayBlobExample?userId='}#{not empty user or user.userId eq 0 ? '' : user.userId}" target="_blank"></a>
<img src="#{not empty user or user.userId eq 0 ? '/Images/thumb_02.jpg' : '/DisplayBlobExample?userId='}#{not empty user or user.userId eq 0 ? '' : user.userId}" target="_blank"></img>
I know its late to post, but I use the site for my own reference and so I wanted to put an answer here for myself to reference in the future too. I hope you (and others) find it helpful.
Lets pretend a bunch of super Einstein experts designed our database. Our super perfect database has 3 tables, and the following relationships defined between them:
TblA 1:M TblB
TblB 1:M TblC
Notice there is no relationship between TblA and TblC
In most scenarios such a simple database is easy to navigate but in commercial databases it is usually impossible to be able to tell at the design stage all the possible uses and combination of uses for data, tables, and even whole databases, especially as systems get built upon and other systems get integrated or switched around or out. This simple fact has spawned a whole industry built on top of databases called Business Intelligence. But I digress...
In the above case, the structure is so simple to understand that its easy to see you can join from TblA, through to B, and through to C and vice versa to get at what you need. It also very vaguely highlights some of the problems with doing it. Now expand this simple chain to 10 or 20 or 50 relationships long. Now all of a sudden you start to envision a need for exactly your scenario. In simple terms, a join from A to C or vice versa or A to F or B to Z or whatever as our system grows.
There are many ways this can indeed be done. The one mentioned above being the most popular, that is driving through all the links. The major problem is that its very slow. And gets progressively slower the more tables you add to the chain, the more those tables grow, and the further you want to go through it.
Solution 1: Look for a common link. It must be there if you taught of a reason to join A to C. If it is not obvious, create a relationship and then join on it. i.e. To join A through B through C there must be some commonality or your join would either produce zero results or a massive number or results (Cartesian product). If you know this commonality, simply add the needed columns to A and C and link them directly.
The rule for relationships is that they simply must have a reason to exist. Nothing more. If you can find a good reason to link from A to C then do it. But you must ensure your reason is not redundant (i.e. its already handled in some other way).
Now a word of warning. There are some pitfalls. But I don't do a good job of explaining them so I will refer you to my source instead of talking about it here. But remember, this is getting into some heavy stuff, so this video about fan and chasm traps is really only a starting point. You can join without relationships. But I advise watching this video first as this goes beyond what most people learn in college and well into the territory of the BI and SAP guys. These guys, while they can program, their day job is to specialise in exactly this kind of thing. How to get massive amounts of data to talk to each other and make sense.
This video is one of the better videos I have come across on the subject. And it's worth looking over some of his other videos. I learned a lot from him.
echo -n
works and is unlikely to ever disappear due to massive historical usage, however per recent versions of the POSIX standard, new conforming applications are "encouraged to use printf
".
Just adding some more info that solved the problem for me:
Thanks to Pawan Valecha and Abhijeet Sawant for the tips.
I'm not sure exactly what your problem is, because I cannot get your code to work as written. Two things seem evident:
Range
should be assigned to myRange
. Since a Range
type is an object in VBA it needs to be Set
, like this: Set myRange = Range("A:A")
CountA()
should be called with .WorksheetFunction
If you are not doing it already, consider using the Option Explicit option at the top of your module, and typing your variables with Dim
statements, as I have done below.
The following code works for me in 2010. Hopefully it works for you too:
Dim myRange As Range
Dim NumRows As Integer
Set myRange = Range("A:A")
NumRows = Application.WorksheetFunction.CountA(myRange)
Good Luck.
$x = $y ?? 'dev'
is short hand for x = y if y is set, otherwise x = 'dev'
There is also
$x = $y =="SOMETHING" ? 10 : 20
meaning if y equals 'SOMETHING' then x = 10, otherwise x = 20
Try this:
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");
Or alternatively if you have the XML in a string use the LoadXml
method.
Once you have it loaded, you can use SelectNodes
and SelectSingleNode
to query specific values, for example:
XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"
Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:
<Data>
<Employee>
<Name>Test</Name>
<ID>123</ID>
</Employee>
<Company>
<Name>ABC</Name>
<Email>[email protected]</Email>
</Company>
</Data>
I'd like to clarify one small gotcha here. You must use CustomVideoMode1 before CustomVideoMode2, etc. VirtualBox recognizes these modes in order starting from 1 and if you skip a number, it will not recognize anything at or beyond the number you skipped. This caught me by surprise.
This should work.
if (rsData["usr.ursrdaystime"] != System.DBNull.Value))
{
strLevel = rsData["usr.ursrdaystime"].ToString();
}
also need to add using statement, like bellow:
using (var objConn = new SqlConnection(strConnection))
{
objConn.Open();
using (var objCmd = new SqlCommand(strSQL, objConn))
{
using (var rsData = objCmd.ExecuteReader())
{
while (rsData.Read())
{
if (rsData["usr.ursrdaystime"] != System.DBNull.Value)
{
strLevel = rsData["usr.ursrdaystime"].ToString();
}
}
}
}
}
this'll automaticly dispose (close) resources outside of block { .. }.
Enable all these from php.ini configuration file
extension=php_openssl.dll
extension=php_curl.dll
extension=php_xmlrpc.dll
You need to escape the backslash \
:
println yourString.replace("\\", "/")
you may also want to encode and decode to/from base64
function uncompress(str:String):ByteArray {
import mx.utils.Base64Decoder;
var dec:Base64Decoder = new Base64Decoder();
dec.decode(str);
var newByteArr:ByteArray=dec.toByteArray();
return newByteArr;
}
// Compress a ByteArray into a Base64 String.
function compress(bytes:ByteArray):String {
import mx.utils.Base64Decoder; //Transform String in a ByteArray.
import mx.utils.Base64Encoder; //Transform ByteArray in a readable string.
var enc:Base64Encoder = new Base64Encoder();
enc.encodeBytes(bytes);
return enc.drain().split("\n").join("");
}
You may want to tackle this as follows:
CREATE TABLE comments (
comment_id int,
body varchar(100),
PRIMARY KEY (comment_id)
);
CREATE TABLE users (
user_id int,
username varchar(20),
PRIMARY KEY (user_id)
);
CREATE TABLE comments_votes (
comment_id int,
user_id int,
vote_type int,
PRIMARY KEY (comment_id, user_id)
);
The composite primary key (comment_id, user_id)
on the intersection table comments_votes
will prevent users from voting multiple times on the same comments.
Let's insert some data in the above schema:
INSERT INTO comments VALUES (1, 'first comment');
INSERT INTO comments VALUES (2, 'second comment');
INSERT INTO comments VALUES (3, 'third comment');
INSERT INTO users VALUES (1, 'user_a');
INSERT INTO users VALUES (2, 'user_b');
INSERT INTO users VALUES (3, 'user_c');
Now let's add some votes for user 1:
INSERT INTO comments_votes VALUES (1, 1, 1);
INSERT INTO comments_votes VALUES (2, 1, 1);
The above means that user 1 gave a vote of type 1 on comments 1 and 2.
If the same user tries to vote again on one of those comments, the database will reject it:
INSERT INTO comments_votes VALUES (1, 1, 1);
ERROR 1062 (23000): Duplicate entry '1-1' for key 'PRIMARY'
If you will be using the InnoDB storage engine, it will also be wise to use foreign key constraints on the comment_id
and user_id
fields of the intersection table. However note that MyISAM, the default storage engine in MySQL, does not enforce foreign key constraints:
CREATE TABLE comments (
comment_id int,
body varchar(100),
PRIMARY KEY (comment_id)
) ENGINE=INNODB;
CREATE TABLE users (
user_id int,
username varchar(20),
PRIMARY KEY (user_id)
) ENGINE=INNODB;
CREATE TABLE comments_votes (
comment_id int,
user_id int,
vote_type int,
PRIMARY KEY (comment_id, user_id),
FOREIGN KEY (comment_id) REFERENCES comments (comment_id),
FOREIGN KEY (user_id) REFERENCES users (user_id)
) ENGINE=INNODB;
These foreign keys guarantee that a row in comments_votes
will never have a comment_id
or user_id
value that doesn't exist in the comments
and users
tables, respectively. Foreign keys aren't required to have a working relational database, but they are definitely essential to avoid broken relationships and orphan rows (ie. referential integrity).
In fact, referential integrity is something that would have been very difficult to enforce if you were to store serialized arrays into a single database field.
According to the documentation, you can only display the __unicode__
representation of a ForeignKey:
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#list-display
Seems odd that it doesn't support the 'book__author'
style format which is used everywhere else in the DB API.
Turns out there's a ticket for this feature, which is marked as Won't Fix.
if you use 64-bit pc, oracle doesn't compatible with it. Oracle doesn't find oci.dll file in 64-bit.
Therefore, you can try to change oracle home on the top. As a result of that, home path will change.
At least, I solved that error with changing path.
I like the INFORMATION_SCHEMA technique, but another I've used is: exec sp_pkeys 'table'
Just do some error checking, and if everything passes then set window.location
to redirect the user to a different page.
$.ajax({
url: 'mail3.php',
type: 'POST',
data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,
success: function(result) {
//console.log(result);
$('#results,#errors').remove();
$('#contactWrapper').append('<p id="results">' + result + '</p>');
$('#loading').fadeOut(500, function() {
$(this).remove();
});
if ( /*no errors*/ ) {
window.location='thank-you.html'
}
}
});
Other answers have already given you the code you need to iterate though a string using a while
loop (or a for
loop) but I thought it might be useful to explain the difference between the two types of loops.
while
loops repeat some code until a certain condition is met. For example:
import random
sum = 0
while sum < 100:
sum += random.randint(0,100) #add a random number between 0 and 100 to the sum
print sum
This code will keep adding random numbers between 0 and 100 until the total is greater or equal to 100. The important point is that this loop could run exactly once (if the first random number is 100) or it could run forever (if it keeps selecting 0 as the random number). We can't predict how many times the loop will run until after it completes.
for
loops are basically just while loops but we use them when we want a loop to run a preset number of times. Java for
loops usually use some sort of a counter variable (below I use i
), and generally makes the similarity between while
and for
loops much more explicit.
for (int i=0; i < 10; i++) { //starting from 0, until i is 10, adding 1 each iteration
System.out.println(i);
}
This loop will run exactly 10 times. This is just a nicer way to write this:
int i = 0;
while (i < 10) { //until i is 10
System.out.println(i);
i++; //add one to i
}
The most common usage for a for loop is to iterate though a list (or a string), which Python makes very easy:
for item in myList:
print item
or
for character in myString:
print character
However, you didn't want to use a for
loop. In that case, you'll need to look at each character using its index. Like this:
print myString[0] #print the first character
print myString[len(myString) - 1] # print the last character.
Knowing that you can make a for
loop using only a while
loop and a counter and knowing that you can access individual characters by index, it should now be easy to access each character one at a time using a while
loop.
HOWEVER in general you'd use a for
loop in this situation because it's easier to read.
Update: I've succeeded in linking a small test C++ class with Go
If you wrap you C++ code with a C interface you should be able to call your library with cgo (see the example of gmp in $GOROOT/misc/cgo/gmp
).
I'm not sure if the idea of a class in C++ is really expressible in Go, as it doesn't have inheritance.
Here's an example:
I have a C++ class defined as:
// foo.hpp
class cxxFoo {
public:
int a;
cxxFoo(int _a):a(_a){};
~cxxFoo(){};
void Bar();
};
// foo.cpp
#include <iostream>
#include "foo.hpp"
void
cxxFoo::Bar(void){
std::cout<<this->a<<std::endl;
}
which I want to use in Go. I'll use the C interface
// foo.h
#ifdef __cplusplus
extern "C" {
#endif
typedef void* Foo;
Foo FooInit(void);
void FooFree(Foo);
void FooBar(Foo);
#ifdef __cplusplus
}
#endif
(I use a void*
instead of a C struct so the compiler knows the size of Foo)
The implementation is:
//cfoo.cpp
#include "foo.hpp"
#include "foo.h"
Foo FooInit()
{
cxxFoo * ret = new cxxFoo(1);
return (void*)ret;
}
void FooFree(Foo f)
{
cxxFoo * foo = (cxxFoo*)f;
delete foo;
}
void FooBar(Foo f)
{
cxxFoo * foo = (cxxFoo*)f;
foo->Bar();
}
with all that done, the Go file is:
// foo.go
package foo
// #include "foo.h"
import "C"
import "unsafe"
type GoFoo struct {
foo C.Foo;
}
func New()(GoFoo){
var ret GoFoo;
ret.foo = C.FooInit();
return ret;
}
func (f GoFoo)Free(){
C.FooFree(unsafe.Pointer(f.foo));
}
func (f GoFoo)Bar(){
C.FooBar(unsafe.Pointer(f.foo));
}
The makefile I used to compile this was:
// makefile
TARG=foo
CGOFILES=foo.go
include $(GOROOT)/src/Make.$(GOARCH)
include $(GOROOT)/src/Make.pkg
foo.o:foo.cpp
g++ $(_CGO_CFLAGS_$(GOARCH)) -fPIC -O2 -o $@ -c $(CGO_CFLAGS) $<
cfoo.o:cfoo.cpp
g++ $(_CGO_CFLAGS_$(GOARCH)) -fPIC -O2 -o $@ -c $(CGO_CFLAGS) $<
CGO_LDFLAGS+=-lstdc++
$(elem)_foo.so: foo.cgo4.o foo.o cfoo.o
gcc $(_CGO_CFLAGS_$(GOARCH)) $(_CGO_LDFLAGS_$(GOOS)) -o $@ $^ $(CGO_LDFLAGS)
Try testing it with:
// foo_test.go
package foo
import "testing"
func TestFoo(t *testing.T){
foo := New();
foo.Bar();
foo.Free();
}
You'll need to install the shared library with make install, then run make test. Expected output is:
gotest
rm -f _test/foo.a _gotest_.6
6g -o _gotest_.6 foo.cgo1.go foo.cgo2.go foo_test.go
rm -f _test/foo.a
gopack grc _test/foo.a _gotest_.6 foo.cgo3.6
1
PASS
Getting one char from string at specified index
Dim pos As Integer
Dim outStr As String
pos = 2
Dim outStr As String
outStr = Left(Mid("abcdef", pos), 1)
outStr="b"
OpenCV image format supports the numpy array interface. A helper function can be made to support either grayscale or color images. This means the BGR -> RGB conversion can be conveniently done with a numpy slice, not a full copy of image data.
Note: this is a stride trick, so modifying the output array will also change the OpenCV image data. If you want a copy, use .copy()
method on the array!
import numpy as np
def img_as_array(im):
"""OpenCV's native format to a numpy array view"""
w, h, n = im.width, im.height, im.channels
modes = {1: "L", 3: "RGB", 4: "RGBA"}
if n not in modes:
raise Exception('unsupported number of channels: {0}'.format(n))
out = np.asarray(im)
if n != 1:
out = out[:, :, ::-1] # BGR -> RGB conversion
return out
After merging a development branch to master, I usually delete the development branch. However, if I want to cherry pick the commits in the development branch, I have to use the merge commit hash to avoid "bad object" error.
I had a case where the error was thrown by a
$state.go('');
Which is obvious. I guess this can help someone in future.
I just used a snippet of jquery to solve this problem.
$("input[data-val-length-max]").each(function (index, element) {
var length = parseInt($(this).attr("data-val-length-max"));
$(this).prop("maxlength", length);
});
The selector finds all of the elements that have a data-val-length-max attribute set. This is the attribute that the StringLength validation attribute will set.
The each loop loops through these matches and will parse out the value for this attribute and assign it to the mxlength property that should have been set.
Just add this to you document ready function and you are good to go.
You probably need to use a TableModel
(Oracle's tutorial here)
How implements your own TableModel
public class FootballClubTableModel extends AbstractTableModel {
private List<FootballClub> clubs ;
private String[] columns ;
public FootBallClubTableModel(List<FootballClub> aClubList){
super();
clubs = aClubList ;
columns = new String[]{"Pos","Team","P", "W", "L", "D", "MP", "GF", "GA", "GD"};
}
// Number of column of your table
public int getColumnCount() {
return columns.length ;
}
// Number of row of your table
public int getRowsCount() {
return clubs.size();
}
// The object to render in a cell
public Object getValueAt(int row, int col) {
FootballClub club = clubs.get(row);
switch(col) {
case 0: return club.getPosition();
// to complete here...
default: return null;
}
}
// Optional, the name of your column
public String getColumnName(int col) {
return columns[col] ;
}
}
You maybe need to override anothers methods of TableModel
, depends on what you want to do, but here is the essential methods to understand and implements :)
Use it like this
List<FootballClub> clubs = getFootballClub();
TableModel model = new FootballClubTableModel(clubs);
JTable table = new JTable(model);
Hope it help !
As an addition to fuzzyman's reply:
pip won't install binary packages and isn't well tested on Windows.
As Windows doesn't come with a compiler by default pip often can't be used there. easy_install can install binary packages for Windows.
Here is a trick on Windows:
you can use easy_install <package>
to install binary packages to avoid building a binary
you can use pip uninstall <package>
even if you used easy_install.
This is just a work-around that works for me on windows. Actually I always use pip if no binaries are involved.
See the current pip doku: http://www.pip-installer.org/en/latest/other-tools.html#pip-compared-to-easy-install
I will ask on the mailing list what is planned for that.
Here is the latest update:
The new supported way to install binaries is going to be wheel
!
It is not yet in the standard, but almost. Current version is still an alpha: 1.0.0a1
https://pypi.python.org/pypi/wheel
http://wheel.readthedocs.org/en/latest/
I will test wheel
by creating an OS X installer for PySide
using wheel
instead of eggs. Will get back and report about this.
cheers - Chris
The transition to wheel
is almost over. Most packages are supporting wheel
.
I promised to build wheels for PySide
, and I did that last summer. Works great!
HINT:
A few developers failed so far to support the wheel format, simply because they forget to
replace distutils
by setuptools
.
Often, it is easy to convert such packages by replacing this single word in setup.py
.
The following worked pretty well for me:
ping -s my_host_name
I usually prefer to work with deltas in translate animation, since it avoids a lot of confusion.
Try this out, see if it works for you:
TranslateAnimation anim = new TranslateAnimation(0, amountToMoveRight, 0, amountToMoveDown);
anim.setDuration(1000);
anim.setAnimationListener(new TranslateAnimation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) { }
@Override
public void onAnimationRepeat(Animation animation) { }
@Override
public void onAnimationEnd(Animation animation)
{
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)view.getLayoutParams();
params.topMargin += amountToMoveDown;
params.leftMargin += amountToMoveRight;
view.setLayoutParams(params);
}
});
view.startAnimation(anim);
Make sure to make amountToMoveRight
/ amountToMoveDown
final
Hope this helps :)
@bdiamante's answer may only partially help you. If you still get a message after you've suppressed warnings, it's because the pandas
library itself is printing the message. There's not much you can do about it unless you edit the Pandas source code yourself. Maybe there's an option internally to suppress them, or a way to override things, but I couldn't find one.
Suppose that you want to ensure a clean working environment. At the top of your script, you put pd.reset_option('all')
. With Pandas 0.23.4, you get the following:
>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)
C:\projects\stackoverflow\venv\lib\site-packages\pandas\core\config.py:619: FutureWarning: html.bord
er has been deprecated, use display.html.border instead
(currently both are identical)
warnings.warn(d.msg, FutureWarning)
: boolean
use_inf_as_null had been deprecated and will be removed in a future
version. Use `use_inf_as_na` instead.
C:\projects\stackoverflow\venv\lib\site-packages\pandas\core\config.py:619: FutureWarning:
: boolean
use_inf_as_null had been deprecated and will be removed in a future
version. Use `use_inf_as_na` instead.
warnings.warn(d.msg, FutureWarning)
>>>
Following the @bdiamante's advice, you use the warnings
library. Now, true to it's word, the warnings have been removed. However, several pesky messages remain:
>>> import warnings
>>> warnings.simplefilter(action='ignore', category=FutureWarning)
>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)
: boolean
use_inf_as_null had been deprecated and will be removed in a future
version. Use `use_inf_as_na` instead.
>>>
In fact, disabling all warnings produces the same output:
>>> import warnings
>>> warnings.simplefilter(action='ignore', category=Warning)
>>> import pandas as pd
>>> pd.reset_option('all')
html.border has been deprecated, use display.html.border instead
(currently both are identical)
: boolean
use_inf_as_null had been deprecated and will be removed in a future
version. Use `use_inf_as_na` instead.
>>>
In the standard library sense, these aren't true warnings. Pandas implements its own warnings system. Running grep -rn
on the warning messages shows that the pandas
warning system is implemented in core/config_init.py
:
$ grep -rn "html.border has been deprecated"
core/config_init.py:207:html.border has been deprecated, use display.html.border instead
Further chasing shows that I don't have time for this. And you probably don't either. Hopefully this saves you from falling down the rabbit hole or perhaps inspires someone to figure out how to truly suppress these messages!
one way;
var = count("find me", Range("A1:A100"))
function count(find as string, lookin as range) As Long
dim cell As Range
for each cell in lookin
if (cell.Value = find) then count = count + 1 '//case sens
next
end function
Not sure how you want to represent the tree? Anyway here's an example which scans the entire subtree using recursion. Files and directories are treated alike. Note that File.listFiles() returns null for non-directories.
public static void main(String[] args) {
Collection<File> all = new ArrayList<File>();
addTree(new File("."), all);
System.out.println(all);
}
static void addTree(File file, Collection<File> all) {
File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
all.add(child);
addTree(child, all);
}
}
}
Java 7 offers a couple of improvements. For example, DirectoryStream provides one result at a time - the caller no longer has to wait for all I/O operations to complete before acting. This allows incremental GUI updates, early cancellation, etc.
static void addTree(Path directory, Collection<Path> all)
throws IOException {
try (DirectoryStream<Path> ds = Files.newDirectoryStream(directory)) {
for (Path child : ds) {
all.add(child);
if (Files.isDirectory(child)) {
addTree(child, all);
}
}
}
}
Note that the dreaded null return value has been replaced by IOException.
Java 7 also offers a tree walker:
static void addTree(Path directory, final Collection<Path> all)
throws IOException {
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
all.add(file);
return FileVisitResult.CONTINUE;
}
});
}
on OSX, Little Snitch was automatically denying any connection to Eclipse (and the emulator). Allow connections in Little Snitch, you have to go into Little Snitch's rules
You code is correct. replace items with .items as below
<script>
var n = $(".items").css("left");
if(n == -900){
$(".items span").fadeOut("slow");
}
</script>
HREF: Is a REFerence to information for the current page ie css info for the page style or link to another page. Page Parsing is not stopped.
SRC: Is a reSOURCE to be added/loaded to the page as in images or javascript. Page Parsing may stop depending on the coded attribute. That is why it's better to add script just before the ending body tag so that page rendering is not held up.
The solution by PeterVR has the disadvantage that the additional color displays on top of the entire HTML block - meaning that it also shows up on top of div content, not just on top of the background image. This is fine if your div is empty, but if it is not using a linear gradient might be a better solution:
<div class="the-div">Red text</div>
<style type="text/css">
.the-div
{
background-image: url("the-image.png");
color: #f00;
margin: 10px;
width: 200px;
height: 80px;
}
.the-div:hover
{
background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
background-image: -moz-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
background-image: -o-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
background-image: -ms-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
background-image: -webkit-gradient(linear, left top, left bottom, from(rgba(0, 0, 0, 0.1)), to(rgba(0, 0, 0, 0.1))), url("the-image.png");
background-image: -webkit-linear-gradient(top, rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1)), url("the-image.png");
}
</style>
See fiddle. Too bad that gradient specifications are currently a mess. See compatibility table, the code above should work in any browser with a noteworthy market share - with the exception of MSIE 9.0 and older.
Edit (March 2017): The state of the web got far less messy by now. So the linear-gradient
(supported by Firefox and Internet Explorer) and -webkit-linear-gradient
(supported by Chrome, Opera and Safari) lines are sufficient, additional prefixed versions are no longer necessary.
Since Node v11.0.0 fs promises are available natively without promisify
:
const fs = require('fs').promises;
async function loadMonoCounter() {
const data = await fs.readFile("monolitic.txt", "binary");
return new Buffer(data);
}
You just have override the getView
method of ArrayAdapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1, mStringList) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
TextView text = (TextView) view.findViewById(android.R.id.text1);
text.setTextColor(Color.BLACK);
return view;
}
};
I was looking for a solution to quite a related problem: finding the newest records per group which is a specialization of a typical greatest-n-per-group with N = 1.
The solution involves the problem you are dealing with here (i.e., how to build the query in Eloquent) so I am posting it as it might be helpful for others. It demonstrates a cleaner way of sub-query construction using powerful Eloquent fluent interface with multiple join columns and where
condition inside joined sub-select.
In my example I want to fetch the newest DNS scan results (table scan_dns
) per group identified by watch_id
. I build the sub-query separately.
The SQL I want Eloquent to generate:
SELECT * FROM `scan_dns` AS `s`
INNER JOIN (
SELECT x.watch_id, MAX(x.last_scan_at) as last_scan
FROM `scan_dns` AS `x`
WHERE `x`.`watch_id` IN (1,2,3,4,5,42)
GROUP BY `x`.`watch_id`) AS ss
ON `s`.`watch_id` = `ss`.`watch_id` AND `s`.`last_scan_at` = `ss`.`last_scan`
I did it in the following way:
// table name of the model
$dnsTable = (new DnsResult())->getTable();
// groups to select in sub-query
$ids = collect([1,2,3,4,5,42]);
// sub-select to be joined on
$subq = DnsResult::query()
->select('x.watch_id')
->selectRaw('MAX(x.last_scan_at) as last_scan')
->from($dnsTable . ' AS x')
->whereIn('x.watch_id', $ids)
->groupBy('x.watch_id');
$qqSql = $subq->toSql(); // compiles to SQL
// the main query
$q = DnsResult::query()
->from($dnsTable . ' AS s')
->join(
DB::raw('(' . $qqSql. ') AS ss'),
function(JoinClause $join) use ($subq) {
$join->on('s.watch_id', '=', 'ss.watch_id')
->on('s.last_scan_at', '=', 'ss.last_scan')
->addBinding($subq->getBindings());
// bindings for sub-query WHERE added
});
$results = $q->get();
UPDATE:
Since Laravel 5.6.17 the sub-query joins were added so there is a native way to build the query.
$latestPosts = DB::table('posts')
->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
->where('is_published', true)
->groupBy('user_id');
$users = DB::table('users')
->joinSub($latestPosts, 'latest_posts', function ($join) {
$join->on('users.id', '=', 'latest_posts.user_id');
})->get();
I have recently started using 0xED, and like it a lot.
That's not possible. but you can use an Object Mapper like AutoMapper
Example:
class A
{
public int IntProp { get; set; }
}
class B
{
public int IntProp { get; set; }
public string StrProp { get; set; }
}
In global.asax or application startup:
AutoMapper.Mapper.CreateMap<A, B>();
Usage:
var b = AutoMapper.Mapper.Map<B>(a);
It's easily configurable via a fluent API.
Functional requirements are those which are related to the technical functionality of the system.
non-functional requirement is a requirement that specifies criteria that can be used to judge the operation of a system in particular conditions, rather than specific behaviors.
For example if you consider a shopping site, adding items to cart, browsing different items, applying offers and deals and successfully placing orders comes under functional requirements.
Where as performance of the system in peak hours, time taken for the system to retrieve data from DB, security of the user data, ability of the system to handle if large number of users login comes under non functional requirements.
Just to add on to what @Zaph says in the comments.
I have the same problem as you, as to know, the array of String
is not saved. Even though Apple bridges types such as String and NSString, I wasn't able to save an array of [String]
neither of [AnyObject]
.
However an array of [NSString]
works for me.
So your code could look like that :
var key = "keySave"
var array1: [NSString] = [NSString]()
array1.append("value 1")
array1.append("value 2")
//save
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(array1, forKey: key)
defaults.synchronize()
//read
if let testArray : AnyObject? = defaults.objectForKey(key) {
var readArray : [NSString] = testArray! as [NSString]
}
Note that I created an array of NSString and not a dictionary. I didn't check if it works with a dictionary, but probably you will have to define the things as [NSString : NSString]
to have it working.
EDIT
Re-reading your question and your title, you are talking of array of array
. I think that as long as you stay with NSString
, an array of array will work. However, if you think my answer is irrelevant, just let me know in the comments and I will remove it.
You are confusing regular expression with shell globbing. If you want to use regular expression to match file names you could do:
$ ls | egrep '.+\..+'
For me it was an error with my resources, Just changed the resources of my project in resources folder and res folder(i.e. for android) and it worked fine.
Build Successful
Total Time: 1 min 10.034 secs
Check out Hex.encodeHexString from Apache Commons Codec.
import org.apache.commons.codec.binary.Hex;
String hex = Hex.encodeHexString(bytes);
You can do this faster using a nearly optimal trial division sieve in one (long) line like this:
Enumerable.Range(0, Math.Floor(2.52*Math.Sqrt(num)/Math.Log(num))).Aggregate(
Enumerable.Range(2, num-1).ToList(),
(result, index) => {
var bp = result[index]; var sqr = bp * bp;
result.RemoveAll(i => i >= sqr && i % bp == 0);
return result;
}
);
The approximation formula for number of primes used here is p(x) < 1.26 x / ln(x)
. We only need to test by primes not greater than x = sqrt(num)
.
Note that the sieve of Eratosthenes has much better run time complexity than trial division (should run much faster for bigger num
values, when properly implemented).
unit test: testing of individual module or independent component in an application is known to be unit testing , the unit testing will be done by developer.
integration test: combining all the modules and testing the application to verify the communication and the data flow between the modules are working properly or not , this testing also performed by developers.
funcional test checking the individual functionality of an application is mean to be functional testing
acceptance testing this testing is done by end user or customer whether the build application is according to the customer requirement , and customer specification this is known to be acceptance testing