Here is a variation of @zhigang's answer which does without AWK, relying only on Bash's native parsing possibilities:
function killtree {
kill -STOP "$1"
ps -e -o pid= -o ppid= | while read -r pid ppid
do
[[ $ppid = $1 ]] || continue
killtree "$pid" || true # Skip over failures
done
kill -CONT "$1"
kill -TERM "$1"
}
It seems to work fine on both Macs and Linux. In situations where you can't rely on being able to manage process groups -- like when writing scripts for testing a piece of software which must be built in multiple environments -- this tree-walking technique is definitely helpful.
The error seems clear: model objects do not support item assignment.
MyModel.objects.latest('id')['foo'] = 'bar'
will throw this same error.
It's a little confusing that your model instance is called projectForm
...
To reproduce your first block of code in a loop, you need to use setattr
for k,v in session_results.iteritems():
setattr(projectForm, k, v)
Character.isSpaceChar(c) || Character.isWhitespace(c)
worked for me.
Consider making your route:
_files_manage:
pattern: /files/management/{project}/{user}
defaults: { _controller: AcmeTestBundle:File:manage }
since they are required fields. It will make your url's prettier, and be a bit easier to manage.
Your Controller would then look like
public function projectAction($project, $user)
One solution is to run manually a shell function that sets my environment to work or personal, but I am pretty sure that I will often forget to switch to the correct identity resulting in committing under the wrong identity.
That was exactly my problem. I have written a hook script which warns you if you have any github remote and not defined a local username.
Here's how you set it up:
Create a directory to hold the global hook
mkdir -p ~/.git-templates/hooks
Tell git to copy everything in ~/.git-templates
to your per-project .git
directory when you run git init or clone
git config --global init.templatedir '~/.git-templates'
And now copy the following lines to ~/.git-templates/hooks/pre-commit
and make the file executable (don't forget this otherwise git won't execute it!)
#!/bin/bash
RED='\033[0;31m' # red color
NC='\033[0m' # no color
GITHUB_REMOTE=$(git remote -v | grep github.com)
LOCAL_USERNAME=$(git config --local user.name)
if [ -n "$GITHUB_REMOTE" ] && [ -z "$LOCAL_USERNAME" ]; then
printf "\n${RED}ATTENTION: At least one Github remote repository is configured, but no local username. "
printf "Please define a local username that matches your Github account.${NC} [pre-commit hook]\n\n"
exit 1
fi
If you use other hosts for your private repositories you have to replace github.com
according to your needs.
Now every time you do a git init
or git clone
git will copy this script to the repository and executes it before any commit is done. If you have not set a local username it will output a warning and won't let you commit.
Since Django 2.x, on_delete
is required.
Deprecated since version 1.9: on_delete will become a required argument in Django 2.0. In older versions it defaults to CASCADE.
void addToSpecific()
{
int n;
int f=0; //flag
Node *temp=H; //H-Head, T-Tail
if(NULL!=H)
{
cout<<"Enter the Number"<<endl;
cin>>n;
while(NULL!=(temp->getNext()))
{
if(n==(temp->getInfo()))
{
f=1;
break;
}
temp=temp->getNext();
}
}
if(NULL==H)
{
Node *nn=new Node();
nn->setInfo();
nn->setNext(NULL);
T=H=nn;
}
else if(0==f)
{
Node *nn=new Node();
nn->setInfo();
nn->setNext(NULL);
T->setNext(nn);
T=nn;
}
else if(1==f)
{
Node *nn=new Node();
nn->setInfo();
nn->setNext(NULL);
nn->setNext((temp->getNext()));
temp->setNext(nn);
}
}
Hmmm I bet that in some previous lines you have something like:
list = set(something)
Am I wrong ?
Not sure what isn't working in your case, but the following code will put a formula into cell A1 that will retrieve the value in the cell G2.
strProjectName = "Sheet1"
Cells(1, 1).Formula = "=" & strProjectName & "!" & Cells(2, 7).Address
The workbook and worksheet that strProjectName
references must exist at the time that this formula is placed. Excel will immediately try to evaluate the formula. You might be able to stop that from happening by turning off automatic recalculation until the workbook does exist.
I was not able to install cv2 on Anaconda-Jupyter notebook running on Ubuntu on Google Cloud Platform. But I found a way to do it as follows:
Run the following command from the ssh terminal and follow the instruction:
sudo apt-get install libsm6 libxrender1 libfontconfig1
Once its installed Open the Jupyter notebook and run following command:
!pip install opencv-contrib-python
Note: I tried to run this command: "sudo python3 -m pip install opencv-contrib-python"but it was showing an error. But above command worked for me.
Now refresh the notebook page and check whether it's installed or not by running import cv2
in the notebook.
Add XAttribute
in the constructor of the XElement
, like
new XElement("Conn", new XAttribute("Server", comboBox1.Text));
You can also add multiple attributes or elements via the constructor
new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));
or you can use the Add-Method of the XElement
to add attributes
XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);
You can create one:
class myDict(dict):
def __init__(self):
self = dict()
def add(self, key, value):
self[key] = value
## example
myd = myDict()
myd.add('apples',6)
myd.add('bananas',3)
print(myd)
Gives:
>>>
{'apples': 6, 'bananas': 3}
final ListView lv = (ListView) findViewById(R.id.ListView01);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));
}
});
I hope this fixes your problem.
In the root directory of the project there is a hidden .git
directory that contains configuration, the repository etc.
You need to put the arguments to pass ("/select etc") in the second parameter of the Start method.
Run the below commands as admin to install NuGet
using Powershell:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Install-PackageProvider -Name NuGet
TL;DR: You should add a JProperty to a JObject. Simple. The index query returns a JValue, so figure out how to get the JProperty instead :)
The accepted answer is not answering the question as it seems. What if I want to specifically add a JProperty after a specific one? First, lets start with terminologies which really had my head worked up.
"name":"value"
.Now, when you query Json item using the index [], you are getting the JToken without the identifier, which might be a JContainer or a JValue (requires casting), but you cannot add anything after it, because it is only a value. You can change it itself, query more deep values, but you cannot add anything after it for example.
What you actually want to get is the property as whole, and then add another property after it as desired. For this, you use JOjbect.Property("name")
, and then create another JProperty of your desire and then add it after this using AddAfterSelf
method. You are done then.
For more info: http://www.newtonsoft.com/json/help/html/ModifyJson.htm
This is the code I modified.
public class Program
{
public static void Main()
{
try
{
string jsonText = @"
{
""food"": {
""fruit"": {
""apple"": {
""colour"": ""red"",
""size"": ""small""
},
""orange"": {
""colour"": ""orange"",
""size"": ""large""
}
}
}
}";
var foodJsonObj = JObject.Parse(jsonText);
var bananaJson = JObject.Parse(@"{ ""banana"" : { ""colour"": ""yellow"", ""size"": ""medium""}}");
var fruitJObject = foodJsonObj["food"]["fruit"] as JObject;
fruitJObject.Property("orange").AddAfterSelf(new JProperty("banana", fruitJObject));
Console.WriteLine(foodJsonObj.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.GetType().Name + ": " + ex.Message);
}
}
}
Try this:
(add-hook 'text-mode-hook
(function
(lambda ()
(setq tab-width 4)
(define-key text-mode-map "\C-i" 'self-insert-command)
)))
That will make TAB always insert a literal TAB character with tab stops every 4 characters (but only in Text mode). If that's not what you're asking for, please describe the behavior you'd like to see.
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
To set for x minutes we need to set x minutes in the 1st argument and then the path of your script
For 15 mins
*/15 * * * * /usr/bin/php /mydomain.in/cromail.php > /dev/null 2>&1
Your HTML:
<div class="img-with-text">
<img src="yourimage.jpg" alt="sometext" />
<p>Some text</p>
</div>
If you know the width of your image, your CSS:
.img-with-text {
text-align: justify;
width: [width of img];
}
.img-with-text img {
display: block;
margin: 0 auto;
}
Otherwise your text below the image will free-flow. To prevent this, just set a width to your container.
Short and easy-to-understand one-liners without regular expressions.
startsWith() is straight forward.
function startsWith($haystack, $needle) {
return (strpos($haystack, $needle) === 0);
}
endsWith() uses the slightly fancy and slow strrev():
function endsWith($haystack, $needle) {
return (strpos(strrev($haystack), strrev($needle)) === 0);
}
As mscdex said NPM comes with the nodejs msi installed file. I happened to just install the node js installer (standalone). To separately add NPM I followed following step
Few tips that may help:
I came across this article in CSS optimization yesterday:
CSS profiling for ... optimization
A lot of useful info on CSS and what CSS causes the most performance drains.
I saw the following presentation on jQueryUK on "hidden secrets" in Googe Chrome (Canary) Dev Tools: DevTools Can do that. Check out the sections on Time to First Paint, repaints and costly CSS.
Also, if you are using a loader like requireJS you could have a look at one of the CSS loader plugins, called require-CSS, which uses CSSO - a optimzer that also does structural optimization, eg. merging blocks with identical properties. I used it a few times and it can save quite a lot of CSS from case to case.
Off the question: I second @Enzino in creating a sprite for all the small icons you are loading. The file sizes are so small it does not really warrant a server roundtrip for each icon. Also keep in mind the total number of concurrent http requests are browser can do. So requests for a larger number of small icons are "render-blocking" as well. Although an empty page compare to yours, I like how duckduckgo loads for example.
Not sure if it is still relevant but I came across this problem, my situation i just needed to return a dictionary of the changes for all nested dictionaries etc etc. Could not find a good solution out there but I did end up writing a simple function to do this. Hope this helps,
Alternative Swift solution:
static func topMostController() -> UIViewController {
var topController = UIApplication.sharedApplication().keyWindow?.rootViewController
while (topController?.presentedViewController != nil) {
topController = topController?.presentedViewController
}
return topController!
}
I normally only disable foreign key constraints when I want to truncate a table, and since I keep coming back to this answer this is for future me:
SET FOREIGN_KEY_CHECKS=0;
TRUNCATE TABLE table;
SET FOREIGN_KEY_CHECKS=1;
After a long research and different experiments the easiest way "FOR MAC USERS" is to create a script:
open -a "Visual Studio" \
"path to first sln" \
"path to second sln" \
...
:D
I would go with netcat too , but since you can't use it , here is an alternative : netcat :). You can find netcat implemented in three languages ( python/ruby/perl ) . All you need to do is install the interpreters for the language you choose . Surely , that won't be viewed as a hacking tool .
Here are the links :
Escape the quotes with backslashes:
printf("She said \"time flies like an arrow, but fruit flies like a banana\".");
There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.
If you want to add time to LongDateString Date, you can format it this way:
DateTime date = DateTime.Now;
string formattedDate = date.ToLongDateString();
string formattedTime = date.ToShortTimeString();
Label1.Text = "New Formatted Date: " + formattedDate + " " + formattedTime;
Output:
New Formatted Date: Monday, January 1, 1900 8:53 PM
All title
nodes with zipcode
or book
node as parent:
Version 1:
//title[parent::zipcode|parent::book]
Version 2:
//bookstore/book/title|//bookstore/city/zipcode/title
Version 3: (results are sorted based on source data rather than the order of book then zipcode)
//title[../../../*[book or magazine] or ../../../../*[city/zipcode]]
or - used within true/false - a Boolean operator in xpath
| - a Union operator in xpath that appends the query to the right of the operator to the result set from the left query.
You can use
if("/quit".equals(s))
...
or
if("/quit".compareTo(s) == 0)
...
The latter makes a lexicographic comparison, and will return 0 if the two strings are the same.
You can also do the following,to import datetime
from datetime import datetime as dt
dt.strptime(date, '%Y-%m-%d')
This is a copy/paste of another answer of mine for question SQL 'like' vs '=' performance:
A personal example using mysql 5.5: I had an inner join between 2 tables, one of 3 million rows and one of 10 thousand rows.
When using a like on an index as below(no wildcards), it took about 30 seconds:
where login like '12345678'
using 'explain' I get:
When using an '=' on the same query, it took about 0.1 seconds:
where login ='12345678'
Using 'explain' I get:
As you can see, the like
completely cancelled the index seek, so query took 300 times more time.
The difference is that raw_input()
does not exist in Python 3.x, while input()
does. Actually, the old raw_input()
has been renamed to input()
, and the old input()
is gone, but can easily be simulated by using eval(input())
. (Remember that eval()
is evil. Try to use safer ways of parsing your input if possible.)
I understand this is an old post. But it is programmable. Otherwise make sure your fill is set to "No Fill" and your boarders are set to "No Boarder" via the user interface shown in the previous posts.
Sub clear()
Range("A4:G1000").Borders.LineStyle = xlNone
Range("A4:G1000").Interior.ColorIndex = xlNone
End Sub()
You can build DFA using simple modular arithmetics.
We can interpret w
which is a string of k-ary numbers using a following rule
V[0] = 0
V[i] = (S[i-1] * k) + to_number(str[i])
V[|w|]
is a number that w
is representing. If modify this rule to find w mod N
, the rule becomes this.
V[0] = 0
V[i] = ((S[i-1] * k) + to_number(str[i])) mod N
and each V[i]
is one of a number from 0 to N-1, which corresponds to each state in DFA. We can use this as the state transition.
See an example.
k = 2, N = 5
| V | (V*2 + 0) mod 5 | (V*2 + 1) mod 5 |
+---+---------------------+---------------------+
| 0 | (0*2 + 0) mod 5 = 0 | (0*2 + 1) mod 5 = 1 |
| 1 | (1*2 + 0) mod 5 = 2 | (1*2 + 1) mod 5 = 3 |
| 2 | (2*2 + 0) mod 5 = 4 | (2*2 + 1) mod 5 = 0 |
| 3 | (3*2 + 0) mod 5 = 1 | (3*2 + 1) mod 5 = 2 |
| 4 | (4*2 + 0) mod 5 = 3 | (4*2 + 1) mod 5 = 4 |
k = 3, N = 5
| V | 0 | 1 | 2 |
+---+---+---+---+
| 0 | 0 | 1 | 2 |
| 1 | 3 | 4 | 0 |
| 2 | 1 | 2 | 3 |
| 3 | 4 | 0 | 1 |
| 4 | 2 | 3 | 4 |
Now you can see a very simple pattern. You can actually build a DFA transition just write repeating numbers from left to right, from top to bottom, from 0 to N-1.
For me i started getting this problem when I upgraded to java 8, and then reverted back to java 7. Upgraded again to java 8 and the problem got resolved.
Your code looks pretty good.
Be careful, however, for your call to Range("H5")
is a shortcut command to Application.Range("H5")
, which is equivalent to Application.ActiveSheet.Range("H5")
. This could be fine, if the only changes are user-changes -- which is the most typical -- but it is possible for the worksheet's cell values to change when it is not the active sheet via programmatic changes, e.g. VBA.
With this in mind, I would utilize Target.Worksheet.Range("H5")
:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Target.Worksheet.Range("H5")) Is Nothing Then Macro
End Sub
Or you can use Me.Range("H5")
, if the event handler is on the code page for the worksheet in question (it usually is):
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Me.Range("H5")) Is Nothing Then Macro
End Sub
Hope this helps...
The models.CharField is a CharField representation of one of the choices. What you want is a set of choices. This doesn't seem to be implemented in django (yet).
You could use a many to many field for it, but that has the disadvantage that the choices have to be put in a database. If you want to use hard coded choices, this is probably not what you want.
There is a django snippet at http://djangosnippets.org/snippets/1200/ that does seem to solve your problem, by implementing a ModelField MultipleChoiceField
.
In my IE11, works normally. Version: 11.306.10586.0
We can test if ActiveX works at IE, in this site: http://www.pcpitstop.com/testax.asp
public boolean isInternetWorking() {
boolean success = false;
try {
URL url = new URL("https://google.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(10000);
connection.connect();
success = connection.getResponseCode() == 200;
} catch (IOException e) {
e.printStackTrace();
}
return success;
}
return true if internet is actually available
Make sure you have these two permission
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
if http does not work its because of the new android security they donot allow plain text communication now. for now just to by pass it.
android:usesCleartextTraffic="true"
try this
<div class="container">
<!-- Header-->
</div>
</div>
<div class="row-fluid">
<div class="span3 well">
<ul class="nav nav-list">
<li class="nav-header">Our Services</li>
<!-- Navigation -->
<li class="active"><a href="#">Overview</a></li>
<li><a href="#">Android Applications</a></li>
<li class="divider"></li>
</ul>
</div>
<div class="span7 offset1">
<!-- Content -->
</div>
</div>
Visit http://www.sitepoint.com/building-responsive-websites-using-twitter-bootstrap/
Thanks to Syed
When this problem comes up with multiprocessing
a simple solution is to switch from Pool
to ThreadPool
. This can be done with no change of code other than the import-
from multiprocessing.pool import ThreadPool as Pool
This works because ThreadPool shares memory with the main thread, rather than creating a new process- this means that pickling is not required.
The downside to this method is that python isn't the greatest language with handling threads- it uses something called the Global Interpreter Lock to stay thread safe, which can slow down some use cases here. However, if you're primarily interacting with other systems (running HTTP commands, talking with a database, writing to filesystems) then your code is likely not bound by CPU and won't take much of a hit. In fact I've found when writing HTTP/HTTPS benchmarks that the threaded model used here has less overhead and delays, as the overhead from creating new processes is much higher than the overhead for creating new threads.
So if you're processing a ton of stuff in python userspace this might not be the best method.
This is function with inverted option
It will return:
function getPercentageChange( $oldNumber , $newNumber , $format = true , $invert = false ){
$value = $newNumber - $oldNumber;
$change = '';
$sign = '';
$result = 0.00;
if ( $invert ) {
if ( $value > 0 ) {
// going UP
$change = 'up';
$sign = '+';
if ( $oldNumber > 0 ) {
$result = ($newNumber / $oldNumber) * 100;
} else {
$result = 100.00;
}
}elseif ( $value < 0 ) {
// going DOWN
$change = 'down';
//$value = abs($value);
$result = ($oldNumber / $newNumber) * 100;
$result = abs($result);
$sign = '-';
}else {
// no changes
}
}else{
if ( $newNumber > $oldNumber ) {
// increase
$change = 'up';
if ( $oldNumber > 0 ) {
$result = ( ( $newNumber / $oldNumber ) - 1 )* 100;
}else{
$result = 100.00;
}
$sign = '+';
}elseif ( $oldNumber > $newNumber ) {
// decrease
$change = 'down';
if ( $oldNumber > 0 ) {
$result = ( ( $newNumber / $oldNumber ) - 1 )* 100;
} else {
$result = 100.00;
}
$sign = '-';
}else{
// no change
}
$result = abs($result);
}
$result_formatted = number_format($result, 2);
if ( $invert ) {
if ( $change == 'up' ) {
$change = 'down';
}elseif ( $change == 'down' ) {
$change = 'up';
}else{
//
}
if ( $sign == '+' ) {
$sign = '-';
}elseif ( $sign == '-' ) {
$sign = '+';
}else{
//
}
}
if ( $format ) {
$formatted = '<span class="going '.$change.'">'.$sign.''.$result_formatted.' %</span>';
} else{
$formatted = $result_formatted;
}
return array( 'change' => $change , 'result' => $result , 'formatted' => $formatted );
}
In my case I had this error, /var/run/postgresql/.s.PGSQL.5433
(note, one number up from the file it was looking for, .s.PGSQL.5432
) was present. Tried the instructions at the top of this page but nothing worked.
Turns out there was an old directory for PostGreSQL 12 config files in /etc/postgresql/12
, which I deleted, which solved the issue.
((frmMain)this.Owner).MyListControl.Items.Add("abc");
Make sure to provide access level you want at Modifiers properties other than Private for MyListControl
at frmMain
try calling a function on the onload method of your body tag and in that function change the style of body like this document.body.style.overflow = 'scroll'; also you might need to set the width of your html as this will show horizontal scroll bars as well
your html file will look something like this
<script language="javascript">
function showscroll() {
document.body.style.overflow = 'scroll';
}
</script>
</head>
<body onload="showscroll()">
It's actually Document Object Model. HTML is used to build the DOM which is an in-memory representation of the page (while closely related to HTML, they are not exactly the same thing). Things like CSS and Javascript interact with the DOM.
Try this:
#myelement {
background-position: 100% 50%;
margin-right: 5px;
}
Note though that the code above will move the whole element (not the background image only) 5px from the right. This might be ok for your case.
Well, std::string
is a class, const char *
is a pointer. Those are two different things. It's easy to get from string
to a pointer (since it typically contains one that it can just return), but for the other way, you need to create an object of type std::string
.
My recommendation: Functions that take constant strings and don't modify them should always take const char *
as an argument. That way, they will always work - with string literals as well as with std::string
(via an implicit c_str()
).
If you have Apache2.4 check 000-default.conf
- remove DocumentRoot
and add
Redirect permanent / https://[your-domain]/
Try to use it
$(document).ready(function() {
// If the browser type if Mozilla Firefox
if ($.browser.mozilla && $.browser.version >= "1.8" ){
// some code
}
// If the browser type is Opera
if( $.browser.opera)
{
// some code
}
// If the web browser type is Safari
if( $.browser.safari )
{
// some code
}
// If the web browser type is Chrome
if( $.browser.chrome)
{
// some code
}
// If the web browser type is Internet Explorer
if ($.browser.msie && $.browser.version <= 6 )
{
// some code
}
//If the web browser type is Internet Explorer 6 and above
if ($.browser.msie && $.browser.version > 6)
{
// some code
}
});
This should work
<option *ngFor="let title of titleArray"
[value]="title.Value"
[attr.selected]="passenger.Title==title.Text ? true : null">
{{title.Text}}
</option>
I'm not sure the attr.
part is necessary.
The Console output is not appearing is because the backend code is not running in the context of the test.
You're probably better off using Trace.WriteLine
(In System.Diagnostics) and then adding a trace listener which writes to a file.
This topic from MSDN shows a way of doing this.
According to Marty Neal's and Dave Anderson's comments:
using System; using System.Diagnostics; ... Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); // or Trace.Listeners.Add(new ConsoleTraceListener()); Trace.WriteLine("Hello World");
The server should respond with the correct MIME Type for JSONP application/javascript
and your request should tell jQuery you are loading JSONP dataType: 'jsonp'
Please see this answer for further details !
You can also have a look a this one as it explains why loading .js
file with text/plain
won't work.
After going through all the solutions here, the easiest way to find the loaded php.ini
file is to go into phpinfo
on the loaded MAMP webpage, which will show you the loaded php.ini file.
This will also confirm if the parameters you change, like max_file_size, have updated correctly.
Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..
FROM TABLE A
The other way is
FROM (SELECT col as name1, col2 as name2 FROM ...) B
Notice that the select clause and the parentheses around it are a table, a virtual table.
So, using your second code example (I am guessing at the columns you are hoping to retrieve here):
SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
Notice that your real table attribute
is the first table in this join, and that this virtual table I've called b
is the second table.
This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.
SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
SELECT count(*) AS langcount, at.attribute
FROM attributeTranslation at
GROUP BY at.attribute
) c ON (a.id = c.attribute)
See how that goes? You've generated a virtual table c
containing two columns, joined it to the other two, used one of the columns for the ON
clause, and returned the other as a column in your result set.
You could wrap your VLOOKUP() in an IFERROR()
Edit: before Excel 2007, use =IF(ISERROR()...)
I had multiple projects in the solution, but I had the correct Default Project set, so I thought it should work.
In the end, I had to add the -StartupProject MyProjectName
option to the command
Another short one (and easier to understand imo):
def int_to_str(n, b, symbols='0123456789abcdefghijklmnopqrstuvwxyz'):
return (int_to_str(n/b, b, symbols) if n >= b else "") + symbols[n%b]
And with proper exception handling:
def int_to_str(n, b, symbols='0123456789abcdefghijklmnopqrstuvwxyz'):
try:
return (int_to_str(n/b, b) if n >= b else "") + symbols[n%b]
except IndexError:
raise ValueError(
"The symbols provided are not enough to represent this number in "
"this base")
One way which I'm currently using measures the spread of edges in the image. Look for this paper:
@ARTICLE{Marziliano04perceptualblur,
author = {Pina Marziliano and Frederic Dufaux and Stefan Winkler and Touradj Ebrahimi},
title = {Perceptual blur and ringing metrics: Application to JPEG2000,” Signal Process},
journal = {Image Commun},
year = {2004},
pages = {163--172} }
It's usually behind a paywall but I've seen some free copies around. Basically, they locate vertical edges in an image, and then measure how wide those edges are. Averaging the width gives the final blur estimation result for the image. Wider edges correspond to blurry images, and vice versa.
This problem belongs to the field of no-reference image quality estimation. If you look it up on Google Scholar, you'll get plenty of useful references.
EDIT
Here's a plot of the blur estimates obtained for the 5 images in nikie's post. Higher values correspond to greater blur. I used a fixed-size 11x11 Gaussian filter and varied the standard deviation (using imagemagick's convert
command to obtain the blurred images).
If you compare images of different sizes, don't forget to normalize by the image width, since larger images will have wider edges.
Finally, a significant problem is distinguishing between artistic blur and undesired blur (caused by focus miss, compression, relative motion of the subject to the camera), but that is beyond simple approaches like this one. For an example of artistic blur, have a look at the Lenna image: Lenna's reflection in the mirror is blurry, but her face is perfectly in focus. This contributes to a higher blur estimate for the Lenna image.
a = [0,4,8,2,5,0,2,6]
sum = 0
a.each { |b| sum += b }
average = sum / a.length
This code (example) :
Chronology ch1 = GregorianChronology.getInstance(); Chronology ch2 = ISOChronology.getInstance(); DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1); DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2); System.out.println(dt); System.out.println(dt2); boolean b = dt.equals(dt2); System.out.println(b);
Will print :
2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false
You are probably comparing two DateTimes with same date but different Chronology.
if inside own custom view : val editText = TextInputEditText(context, attrs, defStyleAttr)
You can import the whole module as follows:
import * as FriendCard from './../pages/FriendCard';
For more details please refer the modules section of Typescript official docs.
Here is production code which may help you.
Package.json
{
"name": "node-mysql",
"version": "0.0.1",
"dependencies": {
"express": "^4.10.6",
"mysql": "^2.5.4"
}
}
Here is Server file.
var express = require("express");
var mysql = require('mysql');
var app = express();
var pool = mysql.createPool({
connectionLimit : 100, //important
host : 'localhost',
user : 'root',
password : '',
database : 'address_book',
debug : false
});
function handle_database(req,res) {
pool.getConnection(function(err,connection){
if (err) {
connection.release();
res.json({"code" : 100, "status" : "Error in connection database"});
return;
}
console.log('connected as id ' + connection.threadId);
connection.query("select * from user",function(err,rows){
connection.release();
if(!err) {
res.json(rows);
}
});
connection.on('error', function(err) {
res.json({"code" : 100, "status" : "Error in connection database"});
return;
});
});
}
app.get("/",function(req,res){-
handle_database(req,res);
});
app.listen(3000);
Reference : https://codeforgeek.com/2015/01/nodejs-mysql-tutorial/
You should be able to set these via the attr()
or prop()
functions in jQuery as shown below:
jQuery (< 1.7):
// This will disable just the div
$("#dcacl").attr('disabled','disabled');
or
// This will disable everything contained in the div
$("#dcacl").children().attr("disabled","disabled");
jQuery (>= 1.7):
// This will disable just the div
$("#dcacl").prop('disabled',true);
or
// This will disable everything contained in the div
$("#dcacl").children().prop('disabled',true);
or
// disable ALL descendants of the DIV
$("#dcacl *").prop('disabled',true);
Javascript:
// This will disable just the div
document.getElementById("dcalc").disabled = true;
or
// This will disable all the children of the div
var nodes = document.getElementById("dcalc").getElementsByTagName('*');
for(var i = 0; i < nodes.length; i++){
nodes[i].disabled = true;
}
In addition to cookies and localStorage
, there's at least one other place you can store "semi-persistent" client data: window.name
. Any string value you assign to window.name
will stay there until the window is closed.
To test it out, just open the console and type window.name = "foo"
, then refresh the page and type window.name
; it should respond with foo
.
This is a bit of a hack, but if you don't want cookies filled with unnecessary data being sent to the server with every request, and if you can't use localStorage
for whatever reason (legacy clients), it may be an option to consider.
window.name
has another interesting property: it's visible to windows served from other domains; it's not subject to the same-origin policy like nearly every other property of window
. So, in addition to storing "semi-persistent" data there while the user navigates or refreshes the page, you can also use it for CORS-free cross-domain communication.
Note that window.name
can only store strings, but with the wide availability of JSON
, this shouldn't be much of an issue even for complex data.
The browser support status is this:
IE8, Firefox, Opera: $("html")
Chrome, Safari: $("body")
So this works:
bodyelem = $.browser.safari ? $("body") : $("html") ;
bodyelem.animate( {scrollTop: 0}, 500 );
jQuery is just a library which enhances the capabilities of the DOM within a web browser; the underlying language is JavaScript, which has, as you might hope to expect from a programming language, the ability to perform conditional logic, i.e.
if( condition ) {
// do something
}
Testing two conditions is straightforward, too:
if( A && B ) {
// do something
}
Dear God, I hope this isn't a troll...
Eclipse Collections has Pair
and all combinations of primitive/object Pairs (for all eight primitives).
The Tuples
factory can create instances of Pair
, and the PrimitiveTuples
factory can be used to create all combinations of primitive/object pairs.
We added these before Java 8 was released. They were useful to implement key/value Iterators for our primitive maps, which we also support in all primitive/object combinations.
If you're willing to add the extra library overhead, you can use Stuart's accepted solution and collect the results into a primitive IntList
to avoid boxing. We added new methods in Eclipse Collections 9.0 to allow for Int/Long/Double
collections to be created from Int/Long/Double
Streams.
IntList list = IntLists.mutable.withAll(intStream);
Note: I am a committer for Eclipse Collections.
a,b=[],[]
n=int(input("Provide me size of squre matrix row==column : "))
for i in range(n):
for j in range(n):
b.append(int(input()))
a.append(b)
print("Here your {} column {}".format(i+1,a))
b=[]
for m in range(n):
print(a[m])
works perfectly
You cannot (should not?) define anything as undefined, as the variable would no longer be undefined – you just defined it to something.
You cannot (should not?) pass undefined
to a function. If you want to pass an empty value, use null
instead.
The statement if(!testvar)
checks for boolean true/false values, this particular one tests whether testvar
evaluates to false
. By definition, null
and undefined
shouldn't be evaluated neither as true
or false
, but JavaScript evaluates null
as false
, and gives an error if you try to evaluate an undefined variable.
To properly test for undefined
or null
, use these:
if(typeof(testvar) === "undefined") { ... }
if(testvar === null) { ... }
I created this simple one a while back. The main challenge I had was to create a good build environment - a makefile that would compile and link/deploy everything without having to use the GUI. For the code, here is the header:
class AMLed
{
private:
uint8_t _ledPin;
long _turnOffTime;
public:
AMLed(uint8_t pin);
void setOn();
void setOff();
// Turn the led on for a given amount of time (relies
// on a call to check() in the main loop()).
void setOnForTime(int millis);
void check();
};
And here is the main source
AMLed::AMLed(uint8_t ledPin) : _ledPin(ledPin), _turnOffTime(0)
{
pinMode(_ledPin, OUTPUT);
}
void AMLed::setOn()
{
digitalWrite(_ledPin, HIGH);
}
void AMLed::setOff()
{
digitalWrite(_ledPin, LOW);
}
void AMLed::setOnForTime(int p_millis)
{
_turnOffTime = millis() + p_millis;
setOn();
}
void AMLed::check()
{
if (_turnOffTime != 0 && (millis() > _turnOffTime))
{
_turnOffTime = 0;
setOff();
}
}
It's more prettily formatted here: http://amkimian.blogspot.com/2009/07/trivial-led-class.html
To use, I simply do something like this in the .pde file:
#include "AM_Led.h"
#define TIME_LED 12 // The port for the LED
AMLed test(TIME_LED);
Here a little program in Python that uses the angle between vectors to determine if a point is inside or outside a certain polygon
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from shapely.geometry import Point, Polygon
from pprint import pprint
# Plot variables
x_min, x_max = -6, 12
y_min, y_max = -3, 8
tick_interval = 1
FIG_SIZE = (10, 10)
DELTA_ERROR = 0.00001
IN_BOX_COLOR = 'yellow'
OUT_BOX_COLOR = 'black'
def angle_between(v1, v2):
""" Returns the angle in radians between vectors 'v1' and 'v2'
The sign of the angle is dependent on the order of v1 and v2
so acos(norm(dot(v1, v2))) does not work and atan2 has to be used, see:
https://stackoverflow.com/questions/21483999/using-atan2-to-find-angle-between-two-vectors
"""
arg1 = np.cross(v1, v2)
arg2 = np.dot(v1, v2)
angle = np.arctan2(arg1, arg2)
return angle
def point_inside(point, border):
""" Returns True if point is inside border polygon and False if not
Arguments:
:point: x, y in shapely.geometry.Point type
:border: [x1 y1, x2 y2, ... , xn yn] in shapely.geomettry.Polygon type
"""
assert len(border.exterior.coords) > 2,\
'number of points in the polygon must be > 2'
point = np.array(point)
side1 = np.array(border.exterior.coords[0]) - point
sum_angles = 0
for border_point in border.exterior.coords[1:]:
side2 = np.array(border_point) - point
angle = angle_between(side1, side2)
sum_angles += angle
side1 = side2
# if wn is 1 then the point is inside
wn = sum_angles / 2 / np.pi
if abs(wn - 1) < DELTA_ERROR:
return True
else:
return False
class MainMap():
@classmethod
def settings(cls, fig_size):
# set the plot outline, including axes going through the origin
cls.fig, cls.ax = plt.subplots(figsize=fig_size)
cls.ax.set_xlim(-x_min, x_max)
cls.ax.set_ylim(-y_min, y_max)
cls.ax.set_aspect(1)
tick_range_x = np.arange(round(x_min + (10*(x_max - x_min) % tick_interval)/10, 1),
x_max + 0.1, step=tick_interval)
tick_range_y = np.arange(round(y_min + (10*(y_max - y_min) % tick_interval)/10, 1),
y_max + 0.1, step=tick_interval)
cls.ax.set_xticks(tick_range_x)
cls.ax.set_yticks(tick_range_y)
cls.ax.tick_params(axis='both', which='major', labelsize=6)
cls.ax.spines['left'].set_position('zero')
cls.ax.spines['right'].set_color('none')
cls.ax.spines['bottom'].set_position('zero')
cls.ax.spines['top'].set_color('none')
@classmethod
def get_ax(cls):
return cls.ax
@staticmethod
def plot():
plt.tight_layout()
plt.show()
class PlotPointandRectangle(MainMap):
def __init__(self, start_point, rectangle_polygon, tolerance=0):
self.current_object = None
self.currently_dragging = False
self.fig.canvas.mpl_connect('key_press_event', self.on_key)
self.plot_types = ['o', 'o-']
self.plot_type = 1
self.rectangle = rectangle_polygon
# define a point that can be moved around
self.point = patches.Circle((start_point.x, start_point.y), 0.10,
alpha=1)
if point_inside(start_point, self.rectangle):
_color = IN_BOX_COLOR
else:
_color = OUT_BOX_COLOR
self.point.set_color(_color)
self.ax.add_patch(self.point)
self.point.set_picker(tolerance)
cv_point = self.point.figure.canvas
cv_point.mpl_connect('button_release_event', self.on_release)
cv_point.mpl_connect('pick_event', self.on_pick)
cv_point.mpl_connect('motion_notify_event', self.on_motion)
self.plot_rectangle()
def plot_rectangle(self):
x = [point[0] for point in self.rectangle.exterior.coords]
y = [point[1] for point in self.rectangle.exterior.coords]
# y = self.rectangle.y
self.rectangle_plot, = self.ax.plot(x, y,
self.plot_types[self.plot_type], color='r', lw=0.4, markersize=2)
def on_release(self, event):
self.current_object = None
self.currently_dragging = False
def on_pick(self, event):
self.currently_dragging = True
self.current_object = event.artist
def on_motion(self, event):
if not self.currently_dragging:
return
if self.current_object == None:
return
point = Point(event.xdata, event.ydata)
self.current_object.center = point.x, point.y
if point_inside(point, self.rectangle):
_color = IN_BOX_COLOR
else:
_color = OUT_BOX_COLOR
self.current_object.set_color(_color)
self.point.figure.canvas.draw()
def remove_rectangle_from_plot(self):
try:
self.rectangle_plot.remove()
except ValueError:
pass
def on_key(self, event):
# with 'space' toggle between just points or points connected with
# lines
if event.key == ' ':
self.plot_type = (self.plot_type + 1) % 2
self.remove_rectangle_from_plot()
self.plot_rectangle()
self.point.figure.canvas.draw()
def main(start_point, rectangle):
MainMap.settings(FIG_SIZE)
plt_me = PlotPointandRectangle(start_point, rectangle) #pylint: disable=unused-variable
MainMap.plot()
if __name__ == "__main__":
try:
start_point = Point([float(val) for val in sys.argv[1].split()])
except IndexError:
start_point= Point(0, 0)
border_points = [(-2, -2),
(1, 1),
(3, -1),
(3, 3.5),
(4, 1),
(5, 1),
(4, 3.5),
(5, 6),
(3, 4),
(3, 5),
(-0.5, 1),
(-3, 1),
(-1, -0.5),
]
border_points_polygon = Polygon(border_points)
main(start_point, border_points_polygon)
There is a pseudocolumn called %%physloc%% that shows the physical address of the row.
Care must be taken that i
is an integer type of variable. In javaScript we don't specify the datatype during declaration of variables, but our initialisation can guarantee that our variable is of a specific datatype.
It is a good practice to initialize variables of declaration:
var num = 0;
var str = "";
Even if your i
variable is integer, +
operator can perform concatenation instead of addition.
In your problem's case, you have supposed that i = 1
, in order to get 2
in addition with 1
try using (i-1+2)
. Use of ()
-parenthesis will not be necessary.
-
(minus operator) cannot be misunderstood and you will not get unexpected result/s.
Here is the way I use to find the external card. Use mount cmd return then parse the vfat part.
String s = "";
try {
Process process = new ProcessBuilder().command("mount")
.redirectErrorStream(true).start();
process.waitFor();
InputStream is = process.getInputStream();
byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
s = s + new String(buffer);
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
//????mount??
String[] lines = s.split("\n");
for(int i=0; i<lines.length; i++) {
//???????????vfat??,???????????sd????
if(-1 != lines[i].indexOf(path[0]) && -1 != lines[i].indexOf("vfat")) {
//??????
String[] blocks = lines[i].split("\\s");
for(int j=0; j<blocks.length; j++) {
//????????vfat??
if(-1 != blocks[j].indexOf(path[0])) {
//Test if it is the external sd card.
}
}
}
}
For a .NET 4.0 console application, none of these worked for me. So I used the following below and it worked:
private static void UpdateSetting(string key, string value)
{
Configuration configuration = ConfigurationManager.
OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
configuration.AppSettings.Settings[key].Value = value;
configuration.Save();
ConfigurationManager.RefreshSection("appSettings");
}
Or you can just run the following command and you will see all databases of the Redis instance without firing up redis-cli
:
$ redis-cli INFO | grep ^db
db0:keys=1500,expires=2
db1:keys=200000,expires=1
db2:keys=350003,expires=1
If you're using Bootstrap it's also possible that Bootstrap's jQuery, if included below your jQuery script tag, is overwriting your jQuery script tag with another version. Including jQuery's own CDN and deleting the jQuery script tag that Bootstrap provides was the only thing that worked for me.
"However I want to share alot of variables and some might be rather large so I don't want to be creating copies of them like above."
That doesn't make a copy (especially with String, but even objects are pass by value of the reference, not the object itself, and getter's like that are fine to use -- arguably better to use than other means because they are common and well understood). The older "performance myths," such as not using getters and setters, still have some value, but have also been updated in the docs.
But if you don't want to do that, you could also just make the variables public or protected in GlobalState and access them directly. And, you can make a static singleton as the Application object JavaDoc indicates:
There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.
Using Intent data, as other answers here note is another way to pass data, but it's usually used for smaller data and simple types. You can pass larger/more complex data, but it's more involved than just using a static singleon. The Application object is still my personal favorite for sharing larger/more complex non persistent data between Android application components though (because it has a well defined lifecycle in an Android app).
Also, as others have noted, if the data gets very complex and needs to be persistent then you can use SQLite or the filesystem too.
The error MethodNotAllowedHttpException means the route exists, but the HTTP method (GET) is wrong. You have to change it to POST:
Route::post('test/register', array('uses'=>'TestController@create'));
Also, you need to hash your passwords:
public function create()
{
$user = new User;
$user->username = Input::get('username');
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->save();
return Redirect::back();
}
And I removed the line:
$user= Input::all();
Because in the next command you replace its contents with
$user = new User;
To debug your Input, you can, in the first line of your controller:
dd( Input::all() );
It will display all fields in the input.
The thing to watch out for when writing C++ dlls is name mangling. If you want interoperability between C and C++, you'd be better off by exporting non-mangled C-style functions from within the dll.
You have two options to use a dll
LoadLibrary()
or some suitable function to load the library, retrieve a function pointer (GetProcAddress
) and call it -- runtime dynamic linkingExporting classes will not work if you follow the second method though.
Use:
from datetime import datetime
current_month = datetime.now().strftime('%m') // 02 //This is 0 padded
current_month_text = datetime.now().strftime('%h') // Feb
current_month_text = datetime.now().strftime('%B') // February
current_day = datetime.now().strftime('%d') // 23 //This is also padded
current_day_text = datetime.now().strftime('%a') // Fri
current_day_full_text = datetime.now().strftime('%A') // Friday
current_weekday_day_of_today = datetime.now().strftime('%w') //5 Where 0 is Sunday and 6 is Saturday.
current_year_full = datetime.now().strftime('%Y') // 2018
current_year_short = datetime.now().strftime('%y') // 18 without century
current_second= datetime.now().strftime('%S') //53
current_minute = datetime.now().strftime('%M') //38
current_hour = datetime.now().strftime('%H') //16 like 4pm
current_hour = datetime.now().strftime('%I') // 04 pm
current_hour_am_pm = datetime.now().strftime('%p') // 4 pm
current_microseconds = datetime.now().strftime('%f') // 623596 Rarely we need.
current_timzone = datetime.now().strftime('%Z') // UTC, EST, CST etc. (empty string if the object is naive).
Reference: 8.1.7. strftime() and strptime() Behavior
Reference: strftime() and strptime() Behavior
The above things are useful for any date parsing, not only now or today. It can be useful for any date parsing.
e.g.
my_date = "23-02-2018 00:00:00"
datetime.strptime(str(my_date),'%d-%m-%Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S+00:00')
datetime.strptime(str(my_date),'%d-%m-%Y %H:%M:%S').strftime('%m')
And so on...
I used this FileSaver.js. In my case with csv files, i did this (in coffescript):
$.ajax
url: "url-to-server"
data: "data-to-send"
success: (csvData)->
blob = new Blob([csvData], { type: 'text/csv' })
saveAs(blob, "filename.csv")
I think for most complicated case, the data must be processed properly. Under the hood FileSaver.js implement the same approach of the answer of Jonathan Amend.
I think Call SOAP Web Service from Android application will help you a lot.
The correct way to apply a filter to a JTable is through the RowFilter interface added to a TableRowSorter. Using this interface, the view of a model can be changed without changing the underlying model. This strategy preserves the Model-View-Controller paradigm, whereas removing the rows you wish hidden from the model itself breaks the paradigm by confusing your separation of concerns.
If you are running postgresql on mac os, try these:
Edit the pg_hba.conf file
sudo vi /Library/PostgreSQL/9.2/data/pg_hba.conf
Change the "md5" method for all users to "trust" near the bottom of the file
Find the name of the service
ls /Library/LaunchDaemons
Look for postgresql
Stop the postgresql service
sudo launchctl stop com.edb.launchd.postgresql-9.2
Start the postgresql service
sudo launchctl start com.edb.launchd.postgresql-9.2
Start psql session as postgres
psql -U postgres
(shouldn't ask for password because of 'trust' setting)
Reset password in psql session by typing
ALTER USER postgres with password 'secure-new-password';
enter
Edit the pg_hba.conf file
Switch it back to 'md5'
Restart services again
this
is a HTML element.
$(this)
is a jQuery object that encapsulates the HTML element.
Use $(this).text()
to retrieve the element's inner text.
I suggest you refer to the jQuery API documentation for further information.
Thats because DataGridView looks for properties of containing objects. For string there is just one property - length. So, you need a wrapper for a string like this
public class StringValue
{
public StringValue(string s)
{
_value = s;
}
public string Value { get { return _value; } set { _value = value; } }
string _value;
}
Then bind List<StringValue>
object to your grid. It works
Just to help new readers, I've created an example to better understand @bluefeet's answer about UNPIVOT.
SELECT id
,entityId
,indicatorname
,indicatorvalue
FROM (VALUES
(1, 1, 'Value of Indicator 1 for entity 1', 'Value of Indicator 2 for entity 1', 'Value of Indicator 3 for entity 1'),
(2, 1, 'Value of Indicator 1 for entity 2', 'Value of Indicator 2 for entity 2', 'Value of Indicator 3 for entity 2'),
(3, 1, 'Value of Indicator 1 for entity 3', 'Value of Indicator 2 for entity 3', 'Value of Indicator 3 for entity 3'),
(4, 2, 'Value of Indicator 1 for entity 4', 'Value of Indicator 2 for entity 4', 'Value of Indicator 3 for entity 4')
) AS Category(ID, EntityId, Indicator1, Indicator2, Indicator3)
UNPIVOT
(
indicatorvalue
FOR indicatorname IN (Indicator1, Indicator2, Indicator3)
) UNPIV;
Use the appropriate methods in Scripting.FileSystemObject. Then your code will be more portable to VBScript and VB.net. To get you started, you'll need to include:
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
Then you could use
Call fso.CopyFile(source, destination[, overwrite] )
where source and destination are the full names (including paths) of the file.
See https://docs.microsoft.com/en-us/office/vba/Language/Reference/user-interface-help/copyfile-method
The fact that std::map insert()
function doesn't overwrite value associated with the key allows us to write object enumeration code like this:
string word;
map<string, size_t> dict;
while(getline(cin, word)) {
dict.insert(make_pair(word, dict.size()));
}
It's a pretty common problem when we need to map different non-unique objects to some id's in range 0..N. Those id's can be later used, for example, in graph algorithms. Alternative with operator[]
would look less readable in my opinion:
string word;
map<string, size_t> dict;
while(getline(cin, word)) {
size_t sz = dict.size();
if (!dict.count(word))
dict[word] = sz;
}
Why not fix a <video>
and use z-index:-1
to put it behind all other elements?
html, body { width:100%; height:100%; margin:0; padding:0; }
<div style="position: fixed; top: 0; width: 100%; height: 100%; z-index: -1;">
<video id="video" style="width:100%; height:100%">
....
</video>
</div>
<div class='content'>
....
If you want it within a container you have to add a container element and a little more CSS
/* HTML */
<div class='vidContain'>
<div class='vid'>
<video> ... </video>
</div>
<div class='content'> ... The rest of your content ... </div>
</div>
/* CSS */
.vidContain {
width:300px; height:200px;
position:relative;
display:inline-block;
margin:10px;
}
.vid {
position: absolute;
top: 0; left:0;
width: 100%; height: 100%;
z-index: -1;
}
.content {
position:absolute;
top:0; left:0;
background: black;
color:white;
}
First download the JavaMail API and make sure the relevant jar files are in your classpath.
Here's a full working example using GMail.
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Main {
private static String USER_NAME = "*****"; // GMail user name (just the part before "@gmail.com")
private static String PASSWORD = "********"; // GMail password
private static String RECIPIENT = "[email protected]";
public static void main(String[] args) {
String from = USER_NAME;
String pass = PASSWORD;
String[] to = { RECIPIENT }; // list of recipient email addresses
String subject = "Java send mail example";
String body = "Welcome to JavaMail!";
sendFromGMail(from, pass, to, subject, body);
}
private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for( int i = 0; i < to.length; i++ ) {
toAddress[i] = new InternetAddress(to[i]);
}
for( int i = 0; i < toAddress.length; i++) {
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae) {
ae.printStackTrace();
}
catch (MessagingException me) {
me.printStackTrace();
}
}
}
Naturally, you'll want to do more in the catch
blocks than print the stack trace as I did in the example code above. (Remove the catch
blocks to see which method calls from the JavaMail API throw exceptions so you can better see how to properly handle them.)
Thanks to @jodonnel and everyone else who answered. I'm giving him a bounty because his answer led me about 95% of the way to a complete answer.
You could check each bit on the byte then append either 0 or 1 to a string. Here is a little helper method I wrote for testing:
public static String byteToString(byte b) {
byte[] masks = { -128, 64, 32, 16, 8, 4, 2, 1 };
StringBuilder builder = new StringBuilder();
for (byte m : masks) {
if ((b & m) == m) {
builder.append('1');
} else {
builder.append('0');
}
}
return builder.toString();
}
In case you have a.my-company.com
and b.my-company.com
instead of just a.com
and b.com
you can issue a cookie for .my-company.com
domain - it will be accepted and sent to both of the domains.
This answer may have to be modified depending on what you were trying to achieve with position: fixed;
. If all you want is two columns side by side then do the following:
I floated both columns to the left.
Note: I added min-height
to each column for illustrative purposes and I simplified your CSS.
body {_x000D_
background-color: #444;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
width: 1005px;_x000D_
margin: 0 auto;_x000D_
}_x000D_
_x000D_
#leftcolumn,_x000D_
#rightcolumn {_x000D_
border: 1px solid white;_x000D_
float: left;_x000D_
min-height: 450px;_x000D_
color: white;_x000D_
}_x000D_
_x000D_
#leftcolumn {_x000D_
width: 250px;_x000D_
background-color: #111;_x000D_
}_x000D_
_x000D_
#rightcolumn {_x000D_
width: 750px;_x000D_
background-color: #777;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<div id="leftcolumn">_x000D_
Left_x000D_
</div>_x000D_
<div id="rightcolumn">_x000D_
Right_x000D_
</div>_x000D_
</div>
_x000D_
If you would like the left column to stay in place as you scroll do the following:
Here we float the right column to the right while adding position: relative;
to #wrapper
and position: fixed;
to #leftcolumn
.
Note: I again used min-height
for illustrative purposes and can be removed for your needs.
body {_x000D_
background-color: #444;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
width: 1005px;_x000D_
margin: 0 auto;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
#leftcolumn,_x000D_
#rightcolumn {_x000D_
border: 1px solid white;_x000D_
min-height: 750px;_x000D_
color: white;_x000D_
}_x000D_
_x000D_
#leftcolumn {_x000D_
width: 250px;_x000D_
background-color: #111;_x000D_
min-height: 100px;_x000D_
position: fixed;_x000D_
}_x000D_
_x000D_
#rightcolumn {_x000D_
width: 750px;_x000D_
background-color: #777;_x000D_
float: right;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<div id="leftcolumn">_x000D_
Left_x000D_
</div>_x000D_
<div id="rightcolumn">_x000D_
Right_x000D_
</div>_x000D_
</div>
_x000D_
Information from the Official Adobe site about this issue
The issue is when you embed a youtube link:
https://www.youtube.com/embed/kRvL6K8SEgY
in an iFrame, the default wmode is windowed which essentially gives it a z-index greater then everything else and it will overlay over anything.
Try appending this GET parameter to your URL:
wmode=opaque
like so:
https://www.youtube.com/embed/kRvL6K8SEgY?wmode=opaque
Make sure its the first parameter in the URL. Other parameters must go after
In the iframe tag:
Example:
<iframe class="youtube-player" type="text/html" width="520" height="330" src="http://www.youtube.com/embed/NWHfY_lvKIQ?wmode=opaque" frameborder="0"></iframe>
I'm not sure what structure you want your resulting array in, but the following code will do what I think you're asking for:
int sum = 0;
int[] results = new int[100];
for (int i = 0; i < 100; i++) {
sum += (i+1);
results[i] = sum;
}
Gives you an array of the sum at each point in the loop [1, 3, 6, 10...]
This may happen if you are using Android+Lambdas. Sometimes I can use Lambdas without any issues but in other situations the project won't compile and gives the exception in the compiler (When I try to pass a Lambda or a method reference to ScheduledExecutorService.scheduleAtFixedRate).
There is a discussion in this link (https://bugs.openjdk.java.net/browse/JDK-8169759) where they explain why this happen. In the mean time I'm just using lambdas in my Android project when the compiler allows me.
Sometimes it is very convenient to use stringstream to convert between strings and other numerical types. The usage of stringstream
is similar to the usage of iostream
, so it is not a burden to learn.
Stringstreams can be used to both read strings and write data into strings. It mainly functions with a string buffer, but without a real I/O channel.
The basic member functions of stringstream class are
str()
, which returns the contents of its buffer in string type.
str(string)
, which set the contents of the buffer to the string argument.
Here is an example of how to use string streams.
ostringstream os;
os << "dec: " << 15 << " hex: " << std::hex << 15 << endl;
cout << os.str() << endl;
The result is dec: 15 hex: f
.
istringstream
is of more or less the same usage.
To summarize, stringstream is a convenient way to manipulate strings like an independent I/O device.
FYI, the inheritance relationships between the classes are:
userIdeaUC = userIdea.substring(0, 1).toUpperCase() + userIdea.length() > 1 ? userIdea.substring(1) : "";
or
userIdeaUC = userIdea.substring(0, 1).toUpperCase();
if(userIdea.length() > 1)
userIdeaUC += userIdea.substring(1);
that depends on what kind of information are you passing to the conditional..
sometimes your result will be null
or undefined
or ''
or 0
, for my simple validation i use this if.
( $('#id').val() == '0' || $('#id').val() == '' || $('#id').val() == 'undefined' || $('#id').val() == null )
NOTE: null
!= 'null'
assume series s
s = pd.Series(np.arange(100))
Get quantiles for [.1, .2, .3, .4, .5, .6, .7, .8, .9]
s.quantile(np.linspace(.1, 1, 9, 0))
0.1 9.9
0.2 19.8
0.3 29.7
0.4 39.6
0.5 49.5
0.6 59.4
0.7 69.3
0.8 79.2
0.9 89.1
dtype: float64
OR
s.quantile(np.linspace(.1, 1, 9, 0), 'lower')
0.1 9
0.2 19
0.3 29
0.4 39
0.5 49
0.6 59
0.7 69
0.8 79
0.9 89
dtype: int32
The isinstance
built-in is the preferred way if you really must, but even better is to remember Python's motto: "it's easier to ask forgiveness than permission"!-) (It was actually Grace Murray Hopper's favorite motto;-). I.e.:
def my_print(text, begin, end):
"Print 'text' in UPPER between 'begin' and 'end' in lower"
try:
print begin.lower() + text.upper() + end.lower()
except (AttributeError, TypeError):
raise AssertionError('Input variables should be strings')
This, BTW, lets the function work just fine on Unicode strings -- without any extra effort!-)
If multiple criteria use countifs
=countifs(A1:A10,">""",B1:B10,">""")
The " >"" "
looks at the greater than being empty. This formula looks for two criteria and neither column can be empty on the same row for it to count. If just counting one column do this with the one criteria (i.e. Use everything before B1:B10
not including the comma)
If you mean all columns whose email is unique:
SELECT * FROM table WHERE email in
(SELECT email FROM table GROUP BY email HAVING COUNT(email)=1);
This is an example of checking a file for changes. One that may not be the best way of doing it, but it sure is a short way.
Handy tool for restarting application when changes have been made to the source. I made this when playing with pygame so I can see effects take place immediately after file save.
When used in pygame make sure the stuff in the 'while' loop is placed in your game loop aka update or whatever. Otherwise your application will get stuck in an infinite loop and you will not see your game updating.
file_size_stored = os.stat('neuron.py').st_size
while True:
try:
file_size_current = os.stat('neuron.py').st_size
if file_size_stored != file_size_current:
restart_program()
except:
pass
In case you wanted the restart code which I found on the web. Here it is. (Not relevant to the question, though it could come in handy)
def restart_program(): #restart application
python = sys.executable
os.execl(python, python, * sys.argv)
Have fun making electrons do what you want them to do.
AutoPostBack property:
Asp.net controls which cannot submit the Form (PostBack) on their own and hence ASP.Net has provided a feature using
AutoPostBack = "true"
: which controls like DropDownList, CheckBoxList, RadioButtonList, etc. can perform PostBack(when clicked on it).
And
AutoPostBack = "false"
It is the by default state of controls which can perform Postback on button submit.
I had some dealings with the select \ multi-select this is what did the trick for me
<select name="mySelect" multiple="multiple">
<option>Foo</option>
<option>Bar</option>
<option>Foo Bar</option>
<option>Bar Foo</option>
</select>
I looked at most the solutions posted, but came across a different one that I prefer. It's simple, doesn't use threads, and works for what I want it to.
http://weblogs.asp.net/kennykerr/archive/2004/11/26/where-is-form-s-loaded-event.aspx
I added to the solution in the article and moved the code into a base class that all my forms inherit from. Now I just call one function: ShowWaitForm() during the frm_load() event of any form that needs a wait dialogue box while the form is loading. Here's the code:
public class MyFormBase : System.Windows.Forms.Form
{
private MyWaitForm _waitForm;
protected void ShowWaitForm(string message)
{
// don't display more than one wait form at a time
if (_waitForm != null && !_waitForm.IsDisposed)
{
return;
}
_waitForm = new MyWaitForm();
_waitForm.SetMessage(message); // "Loading data. Please wait..."
_waitForm.TopMost = true;
_waitForm.StartPosition = FormStartPosition.CenterScreen;
_waitForm.Show();
_waitForm.Refresh();
// force the wait window to display for at least 700ms so it doesn't just flash on the screen
System.Threading.Thread.Sleep(700);
Application.Idle += OnLoaded;
}
private void OnLoaded(object sender, EventArgs e)
{
Application.Idle -= OnLoaded;
_waitForm.Close();
}
}
MyWaitForm is the name of a form you create to look like a wait dialogue. I added a SetMessage() function to customize the text on the wait form.
Unless you write your own Homescreen launcher or use an existing one from Goolge Play, there's "no way" to resize icons.
Well, "no way" does not mean its impossible:
You can use case-sensitive or case-insensitive comparison, depending what you need. Case-sensitive is like this:
if ([category isEqualToString:@"Some String"])
{
// Both strings are equal without respect to their case.
}
Case-insensitive is like this:
if ([category compare:@"Some String" options:NSCaseInsensitiveSearch] == NSOrderedSame)
{
// Both strings are equal with respect to their case.
}
You can try this lightweight small plugin.
It will allow you customize it as per your requirement. It will have Expand/Collapse functionality.
There is a way to get count of runes without any packages by converting string to []rune as len([]rune(YOUR_STRING))
:
package main
import "fmt"
func main() {
russian := "??????? ? ??????"
english := "Sputnik & pogrom"
fmt.Println("count of bytes:",
len(russian),
len(english))
fmt.Println("count of runes:",
len([]rune(russian)),
len([]rune(english)))
}
count of bytes 30 16
count of runes 16 16
Eclipse by default does not know about your external Maven installation and uses the embedded one. Therefore in order for Eclipse to use your global settings you need to set it in menu Settings ? Maven ? Installations.
It depends on a server configuration. If you're working with PHP under Linux or similar, you can control it using .htaccess configuration file, like so:
#set max post size
php_value post_max_size 20M
And, yes, I can personally attest to the fact that this works :)
If you're using IIS, I don't have any idea how you'd set this particular value.
Take a look at this :
var event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(event.toLocaleDateString('de-DE', options));
// expected output: Donnerstag, 20. Dezember 2012
console.log(event.toLocaleDateString('ar-EG', options));
// expected output: ??????? ?? ??????? ????
console.log(event.toLocaleDateString('ko-KR', options));
// expected output: 2012? 12? 20? ???
Source : Mozilla Doc
I currently am working on a codebase where two of the people working on it blindly subscribe to the "single point of exit" theory and I can tell you that from experience, it's a horrible horrible practice. It makes code extremely difficult to maintain and I'll show you why.
With the "single point of exit" theory, you inevitably wind up with code that looks like this:
function()
{
HRESULT error = S_OK;
if(SUCCEEDED(Operation1()))
{
if(SUCCEEDED(Operation2()))
{
if(SUCCEEDED(Operation3()))
{
if(SUCCEEDED(Operation4()))
{
}
else
{
error = OPERATION4FAILED;
}
}
else
{
error = OPERATION3FAILED;
}
}
else
{
error = OPERATION2FAILED;
}
}
else
{
error = OPERATION1FAILED;
}
return error;
}
Not only does this make the code very hard to follow, but now say later on you need to go back and add an operation in between 1 and 2. You have to indent just about the entire freaking function, and good luck making sure all of your if/else conditions and braces are matched up properly.
This method makes code maintenance extremely difficult and error prone.
You can append to a csv by opening the file in append mode:
with open('my_csv.csv', 'a') as f:
df.to_csv(f, header=False)
If this was your csv, foo.csv
:
,A,B,C
0,1,2,3
1,4,5,6
If you read that and then append, for example, df + 6
:
In [1]: df = pd.read_csv('foo.csv', index_col=0)
In [2]: df
Out[2]:
A B C
0 1 2 3
1 4 5 6
In [3]: df + 6
Out[3]:
A B C
0 7 8 9
1 10 11 12
In [4]: with open('foo.csv', 'a') as f:
(df + 6).to_csv(f, header=False)
foo.csv
becomes:
,A,B,C
0,1,2,3
1,4,5,6
0,7,8,9
1,10,11,12
This can be done quite easily using javascript XMLHttpRequest() class (AJAX):
function FileHelper()
{
FileHelper.readStringFromFileAtPath = function(pathOfFileToReadFrom)
{
var request = new XMLHttpRequest();
request.open("GET", pathOfFileToReadFrom, false);
request.send(null);
var returnValue = request.responseText;
return returnValue;
}
}
...
var text = FileHelper.readStringFromFileAtPath ( "mytext.txt" );
Use the if __name__ == '__main__'
idiom -- __name__
is a special variable whose value is '__main__'
if the module is being run as a script, and the module name if it's imported. So you'd do something like
# imports
# class/function definitions
if __name__ == '__main__':
# code here will only run when you invoke 'python main.py'
Here is a way to easily escape & char in oracle DB
set escape '\\'
and within query write like
'ERRORS &\\\ PERFORMANCE';
Combine Dynamic SQL with OpenQuery. (This goes to a Teradata server)
DECLARE
@dayOfWk TINYINT = DATEPART(DW, GETDATE()),
@qSQL NVARCHAR(MAX) = '';
SET @qSQL = '
SELECT
*
FROM
OPENQUERY(TERASERVER,''
SELECT DISTINCT
CASE
WHEN ' + CAST(@dayOfWk AS NCHAR(1)) + ' = 2
THEN ''''Monday''''
ELSE ''''Not Monday''''
END
'');';
EXEC sp_executesql @qSQL;
When taking Distinct we have to cast into IEnumerable too. If list is model means, need to write code like this
IEnumerable<T> ids = list.Select(x => x).Distinct();
After trying a lot of things I find a way that works. I share it here if it is useful to anyone. You can see it here working: http://jsbin.com/iquviq/30/edit
.content {
width: 200px;
height: 600px;
background-color: blue;
position: absolute; /*Can also be `fixed`*/
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
/*Solves a problem in which the content is being cut when the div is smaller than its' wrapper:*/
max-width: 100%;
max-height: 100%;
overflow: auto;
}
This happens when Maven tries to run your test cases while building the jar. You can simply skip running the test cases by adding -DskipTests
at the end of your maven command.
Ex: mvn clean install -DskipTests
or
mvn clean package -DskipTests
You probably have a mixture of spaces and tabs in your original source file. Replace all the tabs with four spaces (or vice versa) and you should see the problem straight away.
Your code as pasted into your question doesn't have this problem, but I guess your editor (or your web browser, or Stack Overflow itself...) could have done the tabs-to-spaces conversion without your knowledge.
Python 3.5 recursive folder size using os.scandir
def folder_size(path='.'):
total = 0
for entry in os.scandir(path):
if entry.is_file():
total += entry.stat().st_size
elif entry.is_dir():
total += folder_size(entry.path)
return total
Best way to do what you want is to add another server block:
server {
#implemented by default, change if you need different ip or port
#listen *:80 | *:8000;
server_name test.com;
return 301 $scheme://www.test.com$request_uri;
}
And edit your main server block server_name variable as following:
server_name www.test.com;
Important: New server
block is the right way to do this, if
is evil. You must use locations and servers instead of if
if it's possible. Rewrite
is sometimes evil too, so replaced it with return
.
I had a the same error and solved it after moving initialization of formBuilder
from ngOnInit
to constructor.
public class GPSService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
private LocationRequest mLocationRequest;
private GoogleApiClient mGoogleApiClient;
private static final String LOGSERVICE = "#######";
@Override
public void onCreate() {
super.onCreate();
buildGoogleApiClient();
Log.i(LOGSERVICE, "onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(LOGSERVICE, "onStartCommand");
if (!mGoogleApiClient.isConnected())
mGoogleApiClient.connect();
return START_STICKY;
}
@Override
public void onConnected(Bundle bundle) {
Log.i(LOGSERVICE, "onConnected" + bundle);
Location l = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (l != null) {
Log.i(LOGSERVICE, "lat " + l.getLatitude());
Log.i(LOGSERVICE, "lng " + l.getLongitude());
}
startLocationUpdate();
}
@Override
public void onConnectionSuspended(int i) {
Log.i(LOGSERVICE, "onConnectionSuspended " + i);
}
@Override
public void onLocationChanged(Location location) {
Log.i(LOGSERVICE, "lat " + location.getLatitude());
Log.i(LOGSERVICE, "lng " + location.getLongitude());
LatLng mLocation = (new LatLng(location.getLatitude(), location.getLongitude()));
EventBus.getDefault().post(mLocation);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(LOGSERVICE, "onDestroy - Estou sendo destruido ");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(LOGSERVICE, "onConnectionFailed ");
}
private void initLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(2000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
private void startLocationUpdate() {
initLocationRequest();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
private void stopLocationUpdate() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addOnConnectionFailedListener(this)
.addConnectionCallbacks(this)
.addApi(LocationServices.API)
.build();
}
}
Straight from the API Specifications for the ClassCastException
:
Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.
So, for example, when one tries to cast an Integer
to a String
, String
is not an subclass of Integer
, so a ClassCastException
will be thrown.
Object i = Integer.valueOf(42);
String s = (String)i; // ClassCastException thrown here.
For future readers, "Still Reachable" might mean you forgot to close something like a file. While it doesn't seem that way in the original question, you should always make sure you've done that.
It's possible with a lot of work.
Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.
But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.
Plus, you'll need to ask user to log into your app and ask them the publish_action
permission.
All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.
Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.
If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it
I know I told babay in 2012 that I thought it was unlikely that someone wouldn't realize that they weren't on a branch and commit. This just happened to me, so I guess I have to admit that I was wrong, but considering that it took until 2016 for this to happen to me, you could argue that it is in fact unlikely.
Anyway, creating a new branch is overkill in my opinion. All you have to do is:
git checkout some-branch
git merge commit-sha
If you didn't copy the commit-sha before checking out the other branch, you can easily find it by running:
git reflog
@RequestMapping(value = "/testonly", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter,
@RequestParam(required = false) String parameter1,
@RequestParam(required = false) String parameter2,
BindingResult result, HttpServletRequest request)
throws ParseException {
LONG CODE and SAME LONG CODE with a minor difference
}
if @RequestParam(required = true)
then you must pass parameter1,parameter2
Use BindingResult and request them based on your conditions.
The Other way
@RequestMapping(value = "/books", method = RequestMethod.GET)
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,
two @RequestParam parameters, HttpServletRequest request) throws ParseException {
myMethod();
}
@RequestMapping(value = "/books", method = RequestMethod.POST)
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter,
BindingResult result) throws ParseException {
myMethod();
do here your minor difference
}
private returntype myMethod(){
LONG CODE
}
Inside ViewDidLoad
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped(tapGestureRecognizer:)))
self.imgMainAdView.isUserInteractionEnabled = true
self.imgMainAdView.addGestureRecognizer(tapGestureRecognizer)
//MARK: - Image Tap Method -
@objc func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
print("Tapped")
if let url = URL(string: self.strMAinAdvLink)
{
UIApplication.shared.open(url, options: [:])
}
}
Calling Purpose
@IBAction func btnCall1Action(_ sender: Any)
{
let text = self.strPhoneNumber1!
let test = String(text.filter { !" -()".contains($0) })
UIApplication.shared.openURL(NSURL(string: "tel://\(test)")! as URL)
}
Mail Purpose
MFMailComposeViewControllerDelegate
@IBAction func btnMailAction(_ sender: Any)
{
let strEmail = SAFESTRING(str: (self.dictEventDetails?.value(forKeyPath: "Email.value_text.email") as! String))
if !MFMailComposeViewController.canSendMail()
{
AppDelegate.sharedInstance().showAlertAction(strTitle: "OK", strMessage: "Mail services are not available") { (success) in
}
return
}
let composeVC = MFMailComposeViewController()
composeVC.mailComposeDelegate = self
composeVC.setToRecipients([strEmail])
composeVC.setSubject("")
composeVC.setMessageBody("", isHTML: false)
self.present(composeVC, animated: true, completion: nil)
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?)
{
controller.dismiss(animated: true, completion: nil)
}
in widget use 'value' attr. Example:
username = forms.CharField(
required=False,
widget=forms.TextInput(attrs={'readonly': True, 'value': 'CONSTANT_VALUE'}),
)
Complete example for using template functions in RazorEngine (for email generation, for example):
@model SomeModel
@{
Func<PropertyChangeInfo, object> PropInfo =
@<tr class="property">
<td>
@item.PropertyName
</td>
<td class="value">
<small class="old">@item.OldValue</small>
<small class="new">@item.CurrentValue</small>
</td>
</tr>;
}
<body>
@{ WriteLiteral(PropInfo(new PropertyChangeInfo("p1", @Model.Id, 2)).ToString()); }
</body>
1) Verify your database path, check in your settings.py
DATABASES = {
'default': {
'CONN_MAX_AGE': 0,
'ENGINE': 'django.db.backends.sqlite3',
'HOST': 'localhost',
'NAME': os.path.join(BASE_DIR, 'project.db'),
'PASSWORD': '',
'PORT': '',
'USER':''
some times there wont be NAME': os.path.join(BASE_DIR, 'project.db'),
2)Be sure for the permission and ownership to destination folder
it worked for me,
If you looking for vertical LinearLayout Manager you can achieve smooth scrolling using a custom LinearSmoothScroller
:
import android.content.Context;
import android.graphics.PointF;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;
public class SnappingLinearLayoutManager extends LinearLayoutManager {
public SnappingLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
int position) {
RecyclerView.SmoothScroller smoothScroller = new TopSnappedSmoothScroller(recyclerView.getContext());
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
private class TopSnappedSmoothScroller extends LinearSmoothScroller {
public TopSnappedSmoothScroller(Context context) {
super(context);
}
@Override
public PointF computeScrollVectorForPosition(int targetPosition) {
return SnappingLinearLayoutManager.this
.computeScrollVectorForPosition(targetPosition);
}
@Override
protected int getVerticalSnapPreference() {
return SNAP_TO_START;
}
}
}
use an instance of the layoutmanager in recycle view and then calling recyclerView.smoothScrollToPosition(pos);
will smooth scroll to selected position to top of the recycler view
Since I didn't like some of the code in the other answers, here's my simple solution. This solution is meant to be usable in an Activity or Service to track the location. It makes sure that it never returns data that's too stale unless you explicitly request stale data. It can be run in either a callback mode to get updates as we receive them, or in poll mode to poll for the most recent info.
Generic LocationTracker interface. Allows us to have multiple types of location trackers and plug the appropriate one in easily:
package com.gabesechan.android.reusable.location;
import android.location.Location;
public interface LocationTracker {
public interface LocationUpdateListener{
public void onUpdate(Location oldLoc, long oldTime, Location newLoc, long newTime);
}
public void start();
public void start(LocationUpdateListener update);
public void stop();
public boolean hasLocation();
public boolean hasPossiblyStaleLocation();
public Location getLocation();
public Location getPossiblyStaleLocation();
}
ProviderLocationTracker- this class will track the location for either GPS or NETWORK.
package com.gabesechan.android.reusable.location;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class ProviderLocationTracker implements LocationListener, LocationTracker {
// The minimum distance to change Updates in meters
private static final long MIN_UPDATE_DISTANCE = 10;
// The minimum time between updates in milliseconds
private static final long MIN_UPDATE_TIME = 1000 * 60;
private LocationManager lm;
public enum ProviderType{
NETWORK,
GPS
};
private String provider;
private Location lastLocation;
private long lastTime;
private boolean isRunning;
private LocationUpdateListener listener;
public ProviderLocationTracker(Context context, ProviderType type) {
lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
if(type == ProviderType.NETWORK){
provider = LocationManager.NETWORK_PROVIDER;
}
else{
provider = LocationManager.GPS_PROVIDER;
}
}
public void start(){
if(isRunning){
//Already running, do nothing
return;
}
//The provider is on, so start getting updates. Update current location
isRunning = true;
lm.requestLocationUpdates(provider, MIN_UPDATE_TIME, MIN_UPDATE_DISTANCE, this);
lastLocation = null;
lastTime = 0;
return;
}
public void start(LocationUpdateListener update) {
start();
listener = update;
}
public void stop(){
if(isRunning){
lm.removeUpdates(this);
isRunning = false;
listener = null;
}
}
public boolean hasLocation(){
if(lastLocation == null){
return false;
}
if(System.currentTimeMillis() - lastTime > 5 * MIN_UPDATE_TIME){
return false; //stale
}
return true;
}
public boolean hasPossiblyStaleLocation(){
if(lastLocation != null){
return true;
}
return lm.getLastKnownLocation(provider)!= null;
}
public Location getLocation(){
if(lastLocation == null){
return null;
}
if(System.currentTimeMillis() - lastTime > 5 * MIN_UPDATE_TIME){
return null; //stale
}
return lastLocation;
}
public Location getPossiblyStaleLocation(){
if(lastLocation != null){
return lastLocation;
}
return lm.getLastKnownLocation(provider);
}
public void onLocationChanged(Location newLoc) {
long now = System.currentTimeMillis();
if(listener != null){
listener.onUpdate(lastLocation, lastTime, newLoc, now);
}
lastLocation = newLoc;
lastTime = now;
}
public void onProviderDisabled(String arg0) {
}
public void onProviderEnabled(String arg0) {
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}
The is the FallbackLocationTracker, which will track by both GPS and NETWORK, and use whatever location is more accurate.
package com.gabesechan.android.reusable.location;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
public class FallbackLocationTracker implements LocationTracker, LocationTracker.LocationUpdateListener {
private boolean isRunning;
private ProviderLocationTracker gps;
private ProviderLocationTracker net;
private LocationUpdateListener listener;
Location lastLoc;
long lastTime;
public FallbackLocationTracker(Context context) {
gps = new ProviderLocationTracker(context, ProviderLocationTracker.ProviderType.GPS);
net = new ProviderLocationTracker(context, ProviderLocationTracker.ProviderType.NETWORK);
}
public void start(){
if(isRunning){
//Already running, do nothing
return;
}
//Start both
gps.start(this);
net.start(this);
isRunning = true;
}
public void start(LocationUpdateListener update) {
start();
listener = update;
}
public void stop(){
if(isRunning){
gps.stop();
net.stop();
isRunning = false;
listener = null;
}
}
public boolean hasLocation(){
//If either has a location, use it
return gps.hasLocation() || net.hasLocation();
}
public boolean hasPossiblyStaleLocation(){
//If either has a location, use it
return gps.hasPossiblyStaleLocation() || net.hasPossiblyStaleLocation();
}
public Location getLocation(){
Location ret = gps.getLocation();
if(ret == null){
ret = net.getLocation();
}
return ret;
}
public Location getPossiblyStaleLocation(){
Location ret = gps.getPossiblyStaleLocation();
if(ret == null){
ret = net.getPossiblyStaleLocation();
}
return ret;
}
public void onUpdate(Location oldLoc, long oldTime, Location newLoc, long newTime) {
boolean update = false;
//We should update only if there is no last location, the provider is the same, or the provider is more accurate, or the old location is stale
if(lastLoc == null){
update = true;
}
else if(lastLoc != null && lastLoc.getProvider().equals(newLoc.getProvider())){
update = true;
}
else if(newLoc.getProvider().equals(LocationManager.GPS_PROVIDER)){
update = true;
}
else if (newTime - lastTime > 5 * 60 * 1000){
update = true;
}
if(update){
if(listener != null){
listener.onUpdate(lastLoc, lastTime, newLoc, newTime);
}
lastLoc = newLoc;
lastTime = newTime;
}
}
}
Since both implement the LocationTracker interface, you can easily change your mind about which one to use. To run the class in poll mode, just call start(). To run it in update mode, call start(Listener).
Also take a look at my blog post on the code
Well, base on your code, you would put onkeyup=sum() in each text box txt1 and txt2
A negative look ahead is a correct answer, but it can be written more cleanly like:
(\\)(?!.*\\)
This looks for an occurrence of \ and then in a check that does not get matched, it looks for any number of characters followed by the character you don't want to see after it. Because it's negative, it only matches if it does not find a match.
SELECT TOP 10 *
FROM Users
Note that if you don't specify an ORDER BY
clause then any 10 rows could be returned, because "first 10 rows" doesn't really mean anything until you tell the database what ordering to use.
Hmmm ... the closest I saw to a convenient answer was using the command line to try the import. But I prefer to even avoid that.
How about 'pip freeze | grep pkgname'? I tried it and it works well. It also shows you the version it has and whether it is installed under version control (install) or editable (develop).
Use static method valueOf(String)
defined for each enum
.
For example if you have enum MyEnum
you can say MyEnum.valueOf("foo")
I have the same error and it fixed it including in the file the following
#include <stdint.h>
at the beginning of your file.
To affect ONLY text type input boxes use the attribute selector
input[type="text"]
This way it will not affect other inputs and just text inputs.
https://www.w3schools.com/css/css_attribute_selectors.asp
example, use a div and give it an idea to refer to:
#divEntry input[type="text"] {
text-align: right;}
Looks like you have a typo -- "trustStrore" should be "trustStore", i.e.
System.setProperty("javax.net.ssl.trustStrore", "cacerts.jks");
should be:
System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");
closest()
selects the first element that matches the selector, up from the DOM tree. Begins from the current element and travels up.
parent()
selects one element up (single level up) the DOM tree.
parents()
method is similar toparent()
but selects all the matching elements up the DOM tree. Begins from the parent element and travels up.
So many answers that return a value that LOOKS empty but is not actually an empty as cell as requested...
As requested, if you actually want a formula that returns an empty cell. It IS possible through VBA. So, here is the code to do just exactly that. Start by writing a formula to return the #N/A error wherever you want the cells to be empty. Then my solution automatically clears all the cells which contain that #N/A error. Of course you can modify the code to automatically delete the contents of cells based on anything you like.
Open the "visual basic viewer" (Alt + F11) Find the workbook of interest in the project explorer and double click it (or right click and select view code). This will open the "view code" window. Select "Workbook" in the (General) dropdown menu and "SheetCalculate" in the (Declarations) dropdown menu.
Paste the following code (based on the answer by J.T. Grimes) inside the Workbook_SheetCalculate function
For Each cell In Sh.UsedRange.Cells
If IsError(cell.Value) Then
If (cell.Value = CVErr(xlErrNA)) Then cell.ClearContents
End If
Next
Save your file as a macro enabled workbook
NB: This process is like a scalpel. It will remove the entire contents of any cells that evaluate to the #N/A error so be aware. They will go and you cant get them back without reentering the formula they used to contain.
NB2: Obviously you need to enable macros when you open the file else it won't work and #N/A errors will remain undeleted
Just add a .htaccess
file in your root project path with the following code to redirect to the public folder:
.HTACCESS
## Redirect to public folder
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^$ public/ [L]
RewriteRule (.*) public/$1 [L]
</IfModule>
Very simple but work for me in my server.
Regards!
$fname = "database.php";
$fhandle = fopen($fname,"r");
$content = fread($fhandle,filesize($fname));
$content = str_replace("192.168.1.198", "localhost", $content);
$fhandle = fopen($fname,"w");
fwrite($fhandle,$content);
fclose($fhandle);
I just save token to users table, when user login I will update new token, and when auth equal to the user current jwt.
I think this is not the best solution but that work for me.
In your scenario, converting a string to a boolean can be done via something like someString === 'true'
(as was already answered).
However, let me try to address your main issue: dealing with the local storage.
The local storage only supports strings as values; a good way of using it would thus be to always serialise your data as a string before storing it in the storage, and reversing the process when fetching it.
A possibly decent format for serialising your data in is JSON, since it is very easy to deal with in JavaScript.
The following functions could thus be used to interact with local storage, provided that your data can be serialised into JSON.
function setItemInStorage(key, item) {
localStorage.setItem(key, JSON.stringify(item));
}
function getItemFromStorage(key) {
return JSON.parse(localStorage.getItem(key));
}
Your example could then be rewritten as:
setItemInStorage('CheckOutPageReload', [this.btnLoginNumOne, this.btnLoginEdit]);
And:
if (getItemFromStorage('CheckOutPageReload')) {
const pageLoadParams = getItemFromStorage('CheckOutPageReload');
this.btnLoginNumOne = pageLoadParams[0];
this.btnLoginEdit = pageLoadParams[1];
}
I'm not a 100% sure, but won't
$(data)
produce a jquery object with a DOM for that data, not connected anywhere? Or if it's already parsed as a DOM, you could just go $("#myImg", data), or whatever selector suits your needs.
EDIT
Rereading your question it appears your 'data' is already a DOM, which means you could just go (assuming there's only an img in your DOM, otherwise you'll need a more precise selector)
$("img", data).attr ("src")
if you want to access the src-attribute. If your data is just text, it would probably work to do
$("img", $(data)).attr ("src")
CSS has a feature: Conditional Rules. This feature of CSS is applied based on a specific condition. Conditional Rules are:
Syntax:
@supports ("condition") {
/* your css style */
}
Example code snippet:
<!DOCTYPE html>
<html>
<head>
<title>Supports Rule</title>
<style>
@supports (display: block) {
section h1 {
background-color: pink;
color: white;
}
section h2 {
background-color: pink;
color: black;
}
}
</style>
</head>
<body>
<section>
<h1>Stackoverflow</h1>
<h2>Stackoverflow</h2>
</section>
</body>
</html>
_x000D_
Welcome to C++11 and rvalue references:
#include <cassert>
#include <string>
using std::string;
void myfunc(string*&& val)
{
assert(&val);
assert(val);
assert(val->c_str());
// Do stuff to the string pointer
}
// sometime later
int main () {
// ...
string s;
myfunc(&s);
// ...
}
Now you have access to the value of the pointer (referred to by val
), which is the address of the string.
You can modify the pointer, and no one will care. That is one aspect of what an rvalue is in the first place.
Be careful: The value of the pointer is only valid until myfunc()
returns. At last, its a temporary.
There are two uses. These are specially used more often in embedded development.
Compiler will not optimise the functions that uses variables that are defined with volatile keyword
Volatile is used to access exact memory locations in RAM, ROM, etc... This is used more often to control memory-mapped devices, access CPU registers and locate specific memory locations.
See examples with assembly listing. Re: Usage of C "volatile" Keyword in Embedded Development
From your description I suspect the most likely explanation is that you have some error in your memory management. You said you've been working on iPhone development for a few weeks, but not whether you are experienced with Objective C in general. If you've come from another background it can take a little while before you really internalise the memory management rules - unless you make a big point of it.
Remember, anything you get from an allocation function (usually the static alloc method, but there are a few others), or a copy method, you own the memory too and must release it when you are done.
But if you get something back from just about anything else including factory methods (e.g. [NSString stringWithFormat]
) then you'll have an autorelease reference, which means it could be released at some time in the future by other code - so it is vital that if you need to keep it around beyond the immediate function that you retain it. If you don't, the memory may remain allocated while you are using it, or be released but coincidentally still valid, during your emulator testing, but is more likely to be released and show up as bad access errors when running on the device.
The best way to track these things down, and a good idea anyway (even if there are no apparent problems) is to run the app in the Instruments tool, especially with the Leaks option.
The SQL WITH clause was introduced by Oracle in the Oracle 9i release 2 database. The SQL WITH clause allows you to give a sub-query block a name (a process also called sub-query refactoring), which can be referenced in several places within the main SQL query. The name assigned to the sub-query is treated as though it was an inline view or table. The SQL WITH clause is basically a drop-in replacement to the normal sub-query.
Syntax For The SQL WITH Clause
The following is the syntax of the SQL WITH clause when using a single sub-query alias.
WITH <alias_name> AS (sql_subquery_statement)
SELECT column_list FROM <alias_name>[,table_name]
[WHERE <join_condition>]
When using multiple sub-query aliases, the syntax is as follows.
WITH <alias_name_A> AS (sql_subquery_statement),
<alias_name_B> AS(sql_subquery_statement_from_alias_name_A
or sql_subquery_statement )
SELECT <column_list>
FROM <alias_name_A>, <alias_name_B> [,table_names]
[WHERE <join_condition>]
In the syntax documentation above, the occurrences of alias_name
is a meaningful name you would give to the sub-query after the AS clause. Each sub-query should be separated with a comma Example for WITH statement. The rest of the queries follow the standard formats for simple and complex SQL SELECT queries.
For more information: http://www.brighthub.com/internet/web-development/articles/91893.aspx
This code snippet can be used for displaying time in seconds,milliseconds and microseconds:
#include <sys/time.h>
struct timeval start, stop;
double secs = 0;
gettimeofday(&start, NULL);
// Do stuff here
gettimeofday(&stop, NULL);
secs = (double)(stop.tv_usec - start.tv_usec) / 1000000 + (double)(stop.tv_sec - start.tv_sec);
printf("time taken %f\n",secs);
Works for every browser.
<button type="button" onClick="Refresh()">Close</button>
<script>
function Refresh() {
window.parent.location = window.parent.location.href;
}
</script>
This is a follow up to the discussion with @RocketRoy regarding his answer, but it might be useful to anyone who wants to compare these results.
tl;dr From what I've seen, Roy's approach ((0xFFFFFFFF == (x | 0xFFFFFFFE)
) is not completely optimized to x & 1
as the mod
approach, but in practice running times should turn out equal in all cases.
So, first I compared the compiled output using Compiler Explorer:
Functions tested:
int isOdd_mod(unsigned x) {
return (x % 2);
}
int isOdd_and(unsigned x) {
return (x & 1);
}
int isOdd_or(unsigned x) {
return (0xFFFFFFFF == (x | 0xFFFFFFFE));
}
CLang 3.9.0 with -O3:
isOdd_mod(unsigned int): # @isOdd_mod(unsigned int)
and edi, 1
mov eax, edi
ret
isOdd_and(unsigned int): # @isOdd_and(unsigned int)
and edi, 1
mov eax, edi
ret
isOdd_or(unsigned int): # @isOdd_or(unsigned int)
and edi, 1
mov eax, edi
ret
GCC 6.2 with -O3:
isOdd_mod(unsigned int):
mov eax, edi
and eax, 1
ret
isOdd_and(unsigned int):
mov eax, edi
and eax, 1
ret
isOdd_or(unsigned int):
or edi, -2
xor eax, eax
cmp edi, -1
sete al
ret
Hats down to CLang, it realized that all three cases are functionally equal. However, Roy's approach isn't optimized in GCC, so YMMV.
It's similar with Visual Studio; inspecting the disassembly Release x64 (VS2015) for these three functions, I could see that the comparison part is equal for "mod" and "and" cases, and slightly larger for the Roy's "or" case:
// x % 2
test bl,1
je (some address)
// x & 1
test bl,1
je (some address)
// Roy's bitwise or
mov eax,ebx
or eax,0FFFFFFFEh
cmp eax,0FFFFFFFFh
jne (some address)
However, after running an actual benchmark for comparing these three options (plain mod, bitwise or, bitwise and), results were completely equal (again, Visual Studio 2005 x86/x64, Release build, no debugger attached).
Release assembly uses the test
instruction for and
and mod
cases, while Roy's case uses the cmp eax,0FFFFFFFFh
approach, but it's heavily unrolled and optimized so there is no difference in practice.
My results after 20 runs (i7 3610QM, Windows 10 power plan set to High Performance):
[Test: Plain mod 2 ] AVERAGE TIME: 689.29 ms (Relative diff.: +0.000%) [Test: Bitwise or ] AVERAGE TIME: 689.63 ms (Relative diff.: +0.048%) [Test: Bitwise and ] AVERAGE TIME: 687.80 ms (Relative diff.: -0.217%)
The difference between these options is less than 0.3%, so it's rather obvious the assembly is equal in all cases.
Here is the code if anyone wants to try, with a caveat that I only tested it on Windows (check the #if LINUX
conditional for the get_time
definition and implement it if needed, taken from this answer).
#include <stdio.h>
#if LINUX
#include <sys/time.h>
#include <sys/resource.h>
double get_time()
{
struct timeval t;
struct timezone tzp;
gettimeofday(&t, &tzp);
return t.tv_sec + t.tv_usec*1e-6;
}
#else
#include <windows.h>
double get_time()
{
LARGE_INTEGER t, f;
QueryPerformanceCounter(&t);
QueryPerformanceFrequency(&f);
return (double)t.QuadPart / (double)f.QuadPart * 1000.0;
}
#endif
#define NUM_ITERATIONS (1000 * 1000 * 1000)
// using a macro to avoid function call overhead
#define Benchmark(accumulator, name, operation) { \
double startTime = get_time(); \
double dummySum = 0.0, elapsed; \
int x; \
for (x = 0; x < NUM_ITERATIONS; x++) { \
if (operation) dummySum += x; \
} \
elapsed = get_time() - startTime; \
accumulator += elapsed; \
if (dummySum > 2000) \
printf("[Test: %-12s] %0.2f ms\r\n", name, elapsed); \
}
void DumpAverage(char *test, double totalTime, double reference)
{
printf("[Test: %-12s] AVERAGE TIME: %0.2f ms (Relative diff.: %+6.3f%%)\r\n",
test, totalTime, (totalTime - reference) / reference * 100.0);
}
int main(void)
{
int repeats = 20;
double runningTimes[3] = { 0 };
int k;
for (k = 0; k < repeats; k++) {
printf("Run %d of %d...\r\n", k + 1, repeats);
Benchmark(runningTimes[0], "Plain mod 2", (x % 2));
Benchmark(runningTimes[1], "Bitwise or", (0xFFFFFFFF == (x | 0xFFFFFFFE)));
Benchmark(runningTimes[2], "Bitwise and", (x & 1));
}
{
double reference = runningTimes[0] / repeats;
printf("\r\n");
DumpAverage("Plain mod 2", runningTimes[0] / repeats, reference);
DumpAverage("Bitwise or", runningTimes[1] / repeats, reference);
DumpAverage("Bitwise and", runningTimes[2] / repeats, reference);
}
getchar();
return 0;
}
Something like this should do it for you.
Sub CombineColumns1()
Dim xRng As Range
Dim i As Long, j As Integer
Dim xNextRow As Long
Dim xTxt As String
On Error Resume Next
With ActiveSheet
xTxt = .RangeSelection.Address
Set xRng = Application.InputBox("please select the data range", "Kutools for Excel", xTxt, , , , , 8)
If xRng Is Nothing Then Exit Sub
j = xRng.Columns(1).Column
For i = 4 To xRng.Columns.Count Step 3
'Need to recalculate the last row, as some of the final columns may not have data in all rows
xNextRow = .Cells(.Rows.Count, j).End(xlUp).Row + 1
.Range(xRng.Cells(1, i), xRng.Cells(xRng.Rows.Count, i + 2)).Copy .Cells(xNextRow, j)
.Range(xRng.Cells(1, i), xRng.Cells(xRng.Rows.Count, i + 2)).Clear
Next
End With
End Sub
You could do this too.
Sub TransposeFormulas()
Dim vFormulas As Variant
Dim oSel As Range
If TypeName(Selection) <> "Range" Then
MsgBox "Please select a range of cells first.", _
vbOKOnly + vbInformation, "Transpose formulas"
Exit Sub
End If
Set oSel = Selection
vFormulas = oSel.Formula
vFormulas = Application.WorksheetFunction.Transpose(vFormulas)
oSel.Offset(oSel.Rows.Count + 2).Resize(oSel.Columns.Count, oSel.Rows.Count).Formula = vFormulas
End Sub
See this for more info.
There's a native and less intrusive alternative, which works only for your call.
URL url = new URL(“location address”);
URLConnection uc = url.openConnection();
String userpass = username + ":" + password;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();
In Bootstrap 3, columns are specified using percentages. (In Bootstrap 2, this was only the case if a column/span was within a .row-fluid
element, but that's no longer necessary and that class no longer exists.) If you use a .container
, then @Michael is absolutely right that you'll be stuck with a fixed-width layout. However, you should be in good shape if you just avoid using a .container element.
<body>
<div class="row">
<div class="col-lg-4">...</div>
<div class="col-lg-8">...</div>
</div>
</body>
The margin for the body is already 0, so you should be able to get up right to the edge. (Columns still have a 15px padding on both sides, so you may have to account for that in your design, but this shouldn't stop you, and you can always customize this when you download Bootstrap.)
In the case of your fictional getattr
function, if the requested attribute always should be available but isn't then throw an error. If the attribute is optional then return None
.
I would suggest using the strip_tags
method.
For Windows users only:
Install tesseract using:
pip install tesseract
and then add this line to your code, mind the "\"
pytesseract.pytesseract.tesseract_cmd = "C:\Program Files (x86)\Tesseract-OCR\\tesseract.exe"
The identifing relaionship means the child entity is totally depend on the existance of the parent entity. Example account table person table and personaccount.The person account table is identified by the existance of account and person table only.
The non identifing relationship means the child table does not identified by the existance of the parent table example there is table as accounttype and account.accounttype table is not identified with the existance of account table.
Functions dealing with text like label
, title
, etc. accept parameters same as matplotlib.text.Text
. For the font size you can use size/fontsize
:
from matplotlib import pyplot as plt
fig = plt.figure()
plt.plot(data)
fig.suptitle('test title', fontsize=20)
plt.xlabel('xlabel', fontsize=18)
plt.ylabel('ylabel', fontsize=16)
fig.savefig('test.jpg')
For globally setting title
and label
sizes, mpl.rcParams
contains axes.titlesize
and axes.labelsize
. (From the page):
axes.titlesize : large # fontsize of the axes title
axes.labelsize : medium # fontsize of the x any y labels
(As far as I can see, there is no way to set x
and y
label sizes separately.)
And I see that axes.titlesize
does not affect suptitle
. I guess, you need to set that manually.
You can use the @RequestHeader
annotation with HttpHeaders
method parameter to gain access to all request headers:
@RequestMapping(value = "/restURL")
public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers) {
// Use headers to get the information about all the request headers
long contentLength = headers.getContentLength();
// ...
StreamSource source = new StreamSource(new StringReader(body));
YourObject obj = (YourObject) jaxb2Mashaller.unmarshal(source);
// ...
}
The "Issue 2" answer given by @Sagar works for the majority of git servers such as gitorious.
However, there will be a name clash in a system like gitolite where the public ssh keys are checked in as files named with the username, ie keydir/jenkins.pub
. What if there are multiple jenkins servers that need to access the same gitolite server?
(Note: this is about running the Jenkins daemon not running a build job as a user (addressed by @Sagar's "Issue 1").)
So in this case you do need to run the Jenkins daemon as a different user.
There are two steps:
The main thing is to update the JENKINS_USER
environment variable. Here's a patch showing how to change the user to ptran
.
--- etc/default/jenkins.old 2011-10-28 17:46:54.410305099 -0700
+++ etc/default/jenkins 2011-10-28 17:47:01.670369300 -0700
@@ -13,7 +13,7 @@
PIDFILE=/var/run/jenkins/jenkins.pid
# user id to be invoked as (otherwise will run as root; not wise!)
-JENKINS_USER=jenkins
+JENKINS_USER=ptran
# location of the jenkins war file
JENKINS_WAR=/usr/share/jenkins/jenkins.war
--- etc/init.d/jenkins.old 2011-10-28 17:47:20.878539172 -0700
+++ etc/init.d/jenkins 2011-10-28 17:47:47.510774714 -0700
@@ -23,7 +23,7 @@
#DAEMON=$JENKINS_SH
DAEMON=/usr/bin/daemon
-DAEMON_ARGS="--name=$NAME --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG - -pidfile=$PIDFILE"
+DAEMON_ARGS="--name=$JENKINS_USER --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG --pidfile=$PIDFILE"
SU=/bin/su
END PATCH
Update ownership of jenkins directories:
chown -R ptran /var/log/jenkins
chown -R ptran /var/lib/jenkins
chown -R ptran /var/run/jenkins
chown -R ptran /var/cache/jenkins
Restart jenkins
sudo service jenkins restart
For compiling the java file having dependency on a jar
javac -cp path_of_the_jar/jarName.jar className.java
For executing the class file
java -cp .;path_of_the_jar/jarName.jar className
For Python 2.7 (See Raymond's answer, for Python 3 equivalent):
Wanting to know whether something "is not None" is so common in python (and other OO languages), that in my Common.py (which I import to each module with "from Common import *"), I include these lines:
def exists(it):
return (it is not None)
Then to remove None elements from a list, simply do:
filter(exists, L)
I find this easier to read, than the corresponding list comprehension (which Raymond shows, as his Python 2 version).
None of that solved my problem. but what I did was if click on the pom.xml, there is a tab at the bottom named dependencies. in this tab it is split into 2 section, one called dependencies and one called dependency management. select every thing in the dependency section and click add to be under the dependency management control. close and reopen your project.
This was the best solution I found after more time than I care to admit. Basically, add target="_self" to each link that you need to insure a page reload.
http://blog.panjiesw.com/posts/2013/09/angularjs-normal-links-with-html5mode/
Depends on what your are doing.
If you have SPA (Single-Page Application) the you can use:
<input id="txtName" type="text" />
Otherwise using Html helpers is recommended, to get your controls bound with your model.
SELECT *
FROM table1
INNER JOIN table2
ON table1.primaryKey=table2.table1Id
INNER JOIN table3
ON table1.primaryKey=table3.table1Id
Using Java7 and try-with-resources, comes with a simplified and readable version.
try(InputStream inputStream = new FileInputStream("C:\\mov.mp4");
OutputStream outputStream = new FileOutputStream("D:\\mov.mp4")) {
byte[] buffer = new byte[10*1024];
for (int length; (length = inputStream.read(buffer)) != -1; ) {
outputStream.write(buffer, 0, length);
}
} catch (FileNotFoundException exception) {
exception.printStackTrace();
} catch (IOException ioException) {
ioException.printStackTrace();
}
The best way is the clearest, most robust way: *
Thread.currentThread().equals( Looper.getMainLooper().getThread() )
Or, if the runtime platform is API level 23 (Marshmallow 6.0) or higher:
Looper.getMainLooper().isCurrentThread()
See the Looper API. Note that calling Looper.getMainLooper()
involves synchronization (see the source). You might want to avoid the overhead by storing the return value and reusing it.
* credit greg7gkb and 2cupsOfTech
I have solved a similar problem using external native lib dependencies that are packaged inside of jar files. Sometimes these architecture dependend libraries are packaged alltogether inside one jar, sometimes they are split up into several jar files. so i wrote some buildscript to scan the jar dependencies for native libs and sort them into the correct android lib folders. Additionally this also provides a way to download dependencies that not found in maven repos which is currently usefull to get JNA working on android because not all native jars are published in public maven repos.
android {
compileSdkVersion 23
buildToolsVersion '24.0.0'
lintOptions {
abortOnError false
}
defaultConfig {
applicationId "myappid"
minSdkVersion 17
targetSdkVersion 23
versionCode 1
versionName "1.0.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets {
main {
jniLibs.srcDirs = ["src/main/jniLibs", "$buildDir/native-libs"]
}
}
}
def urlFile = { url, name ->
File file = new File("$buildDir/download/${name}.jar")
file.parentFile.mkdirs()
if (!file.exists()) {
new URL(url).withInputStream { downloadStream ->
file.withOutputStream { fileOut ->
fileOut << downloadStream
}
}
}
files(file.absolutePath)
}
dependencies {
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.android.support:design:23.3.0'
compile 'net.java.dev.jna:jna:4.2.0'
compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-arm.jar?raw=true', 'jna-android-arm')
compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-armv7.jar?raw=true', 'jna-android-armv7')
compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-aarch64.jar?raw=true', 'jna-android-aarch64')
compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-x86.jar?raw=true', 'jna-android-x86')
compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-x86-64.jar?raw=true', 'jna-android-x86_64')
compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-mips.jar?raw=true', 'jna-android-mips')
compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-mips64.jar?raw=true', 'jna-android-mips64')
}
def safeCopy = { src, dst ->
File fdst = new File(dst)
fdst.parentFile.mkdirs()
fdst.bytes = new File(src).bytes
}
def archFromName = { name ->
switch (name) {
case ~/.*android-(x86-64|x86_64|amd64).*/:
return "x86_64"
case ~/.*android-(i386|i686|x86).*/:
return "x86"
case ~/.*android-(arm64|aarch64).*/:
return "arm64-v8a"
case ~/.*android-(armhf|armv7|arm-v7|armeabi-v7).*/:
return "armeabi-v7a"
case ~/.*android-(arm).*/:
return "armeabi"
case ~/.*android-(mips).*/:
return "mips"
case ~/.*android-(mips64).*/:
return "mips64"
default:
return null
}
}
task extractNatives << {
project.configurations.compile.each { dep ->
println "Scanning ${dep.name} for native libs"
if (!dep.name.endsWith(".jar"))
return
zipTree(dep).visit { zDetail ->
if (!zDetail.name.endsWith(".so"))
return
print "\tFound ${zDetail.name}"
String arch = archFromName(zDetail.toString())
if(arch != null){
println " -> $arch"
safeCopy(zDetail.file.absolutePath,
"$buildDir/native-libs/$arch/${zDetail.file.name}")
} else {
println " -> No valid arch"
}
}
}
}
preBuild.dependsOn(['extractNatives'])
First convert your image to Base64 (encode to Base64). You can do it online or with a PHP script.
After converting you will get the result as
iVBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoV2luZG93cykiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6MEVBMTczNDg3QzA5MTFFNjk3ODM5NjQyRjE2RjA3QTkiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6MEVBMTczNDk3QzA5MTFFNjk3ODM5NjQyRjE2RjA3QTkiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDowRUExNzM0NjdDMDkxMUU2OTc4Mzk2NDJGMTZGMDdBOSIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDowRUExNzM0NzdDMDkxMUU2OTc4Mzk2NDJGMTZGMDdBOSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PjjUmssAAAGASURBVHjatJaxTsMwEIbpIzDA6FaMMPYJkDKzVYU+QFeEGPIKfYU8AETkCYI6wANkZQwIKRNDB1hA0Jrf0rk6WXZ8BvWkb4kv99vn89kDrfVexBSYgVNwDA7AN+jAK3gEd+AlGMGIBFDgFvzouK3JV/lihQTOwLtOtw9wIRG5pJn91Tbgqk9kSk7GViADrTD4HCyZ0NQnomi51sb0fUyCMQEbp2WpU67IjfNjwcYyoUDhjJVcZBjYBy40j4wXgaobWoe8Z6Y80CJBwFpunepIzt2AUgFjtXXshNXjVmMh+K+zzp/CMs0CqeuzrxSRpbOKfdCkiMTS1VBQ41uxMyQR2qbrXiiwYN3ACh1FDmsdK2Eu4J6Tlo31dYVtCY88h5ELZIJJ+IRMzBHfyJINrigNkt5VsRiub9nXICdsYyVd2NcVvA3ScE5t2rb5JuEeyZnAhmLt9NK63vX1O5Pe8XaPSuGq1uTrfUgMEp9EJ+CQvr+BJ/AAKvAcCiAR+bf9CjAAluzmdX4AEIIAAAAASUVORK5CYII=
Now it's simple to use.
You have to just put it in the src
of the image and define there as it is in base64 encoded form.
Example:
<img src="data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMy1jMDExIDY2LjE0NTY2MSwgMjAxMi8wMi8wNi0xNDo1NjoyNyAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNiAoV2luZG93cykiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6MEVBMTczNDg3QzA5MTFFNjk3ODM5NjQyRjE2RjA3QTkiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6MEVBMTczNDk3QzA5MTFFNjk3ODM5NjQyRjE2RjA3QTkiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDowRUExNzM0NjdDMDkxMUU2OTc4Mzk2NDJGMTZGMDdBOSIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDowRUExNzM0NzdDMDkxMUU2OTc4Mzk2NDJGMTZGMDdBOSIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PjjUmssAAAGASURBVHjatJaxTsMwEIbpIzDA6FaMMPYJkDKzVYU+QFeEGPIKfYU8AETkCYI6wANkZQwIKRNDB1hA0Jrf0rk6WXZ8BvWkb4kv99vn89kDrfVexBSYgVNwDA7AN+jAK3gEd+AlGMGIBFDgFvzouK3JV/lihQTOwLtOtw9wIRG5pJn91Tbgqk9kSk7GViADrTD4HCyZ0NQnomi51sb0fUyCMQEbp2WpU67IjfNjwcYyoUDhjJVcZBjYBy40j4wXgaobWoe8Z6Y80CJBwFpunepIzt2AUgFjtXXshNXjVmMh+K+zzp/CMs0CqeuzrxSRpbOKfdCkiMTS1VBQ41uxMyQR2qbrXiiwYN3ACh1FDmsdK2Eu4J6Tlo31dYVtCY88h5ELZIJJ+IRMzBHfyJINrigNkt5VsRiub9nXICdsYyVd2NcVvA3ScE5t2rb5JuEeyZnAhmLt9NK63vX1O5Pe8XaPSuGq1uTrfUgMEp9EJ+CQvr+BJ/AAKvAcCiAR+bf9CjAAluzmdX4AEIIAAAAASUVORK5CYII=">
Deleting the bin folder was not enough, I also deleted the gen folder. Then after two rebuilds the dex error message was gone.
You can use the GetStringAsync
method:
var uri = new Uri("http://yoururlhere");
var response = await client.GetStringAsync(uri);
try if install lampp
sudo chown www-data:www-data -R /opt/lampp/phpmyadmin/*
sudo chown www-data:www-data -R /opt/lampp/phpmyadmin
or if install phpmyadmin
sudo chown www-data:www-data -R /etc/phpmyadmin/*
sudo chown www-data:www-data -R /etc/phpmyadmin
Try this:
String output = response.getEntity(String.class);
EDIT
Thanks to @Martin Spamer to mention that it will work for Jersey 1.x jars only. For Jersey 2.x use
String output = response.readEntity(String.class);
I've encountered a similar scenario. I solved it by adding in this following code just before find_library()
:
set(CMAKE_PREFIX_PATH /the/custom/path/to/your/lib/)
then it can find the library location.
Yes. In fact, all instance methods in Java are virtual by default. Only certain methods are not virtual:
Here are some examples:
"Normal" virtual functions
The following example is from an old version of the wikipedia page mentioned in another answer.
import java.util.*;
public class Animal
{
public void eat()
{
System.out.println("I eat like a generic Animal.");
}
public static void main(String[] args)
{
List<Animal> animals = new LinkedList<Animal>();
animals.add(new Animal());
animals.add(new Fish());
animals.add(new Goldfish());
animals.add(new OtherAnimal());
for (Animal currentAnimal : animals)
{
currentAnimal.eat();
}
}
}
class Fish extends Animal
{
@Override
public void eat()
{
System.out.println("I eat like a fish!");
}
}
class Goldfish extends Fish
{
@Override
public void eat()
{
System.out.println("I eat like a goldfish!");
}
}
class OtherAnimal extends Animal {}
Output:
I eat like a generic Animal. I eat like a fish! I eat like a goldfish! I eat like a generic Animal.
Example with virtual functions with interfaces
Java interface methods are all virtual. They must be virtual because they rely on the implementing classes to provide the method implementations. The code to execute will only be selected at run time.
For example:
interface Bicycle { //the function applyBrakes() is virtual because
void applyBrakes(); //functions in interfaces are designed to be
} //overridden.
class ACMEBicycle implements Bicycle {
public void applyBrakes(){ //Here we implement applyBrakes()
System.out.println("Brakes applied"); //function
}
}
Example with virtual functions with abstract classes.
Similar to interfaces Abstract classes must contain virtual methods because they rely on the extending classes' implementation. For Example:
abstract class Dog {
final void bark() { //bark() is not virtual because it is
System.out.println("woof"); //final and if you tried to override it
} //you would get a compile time error.
abstract void jump(); //jump() is a "pure" virtual function
}
class MyDog extends Dog{
void jump(){
System.out.println("boing"); //here jump() is being overridden
}
}
public class Runner {
public static void main(String[] args) {
Dog dog = new MyDog(); // Create a MyDog and assign to plain Dog variable
dog.jump(); // calling the virtual function.
// MyDog.jump() will be executed
// although the variable is just a plain Dog.
}
}