When you return something from a then()
callback, it's a bit magic. If you return a value, the next then()
is called with that value. However, if you return something promise-like, the next then()
waits on it, and is only called when that promise settles (succeeds/fails).
Source: https://web.dev/promises/#queuing-asynchronous-actions
//function a(callback){_x000D_
setTimeout(function() {_x000D_
console.log('Hi I am order 1');_x000D_
}, 3000);_x000D_
// callback();_x000D_
//}_x000D_
_x000D_
//function b(callback){_x000D_
setTimeout(function() {_x000D_
console.log('Hi I am order 2');_x000D_
}, 2000);_x000D_
// callback();_x000D_
//}_x000D_
_x000D_
_x000D_
_x000D_
//function c(callback){_x000D_
setTimeout(function() {_x000D_
console.log('Hi I am order 3');_x000D_
}, 1000);_x000D_
// callback();_x000D_
_x000D_
//}_x000D_
_x000D_
_x000D_
/*function d(callback){_x000D_
a(function(){_x000D_
b(function(){_x000D_
_x000D_
c(callback);_x000D_
_x000D_
});_x000D_
_x000D_
});_x000D_
_x000D_
_x000D_
}_x000D_
d();*/_x000D_
_x000D_
_x000D_
async function funa(){_x000D_
_x000D_
var pr1=new Promise((res,rej)=>{_x000D_
_x000D_
setTimeout(()=>res("Hi4 I am order 1"),3000)_x000D_
_x000D_
})_x000D_
_x000D_
_x000D_
var pr2=new Promise((res,rej)=>{_x000D_
_x000D_
setTimeout(()=>res("Hi4 I am order 2"),2000)_x000D_
_x000D_
})_x000D_
_x000D_
var pr3=new Promise((res,rej)=>{_x000D_
_x000D_
setTimeout(()=>res("Hi4 I am order 3"),1000)_x000D_
_x000D_
})_x000D_
_x000D_
_x000D_
var res1 = await pr1;_x000D_
var res2 = await pr2;_x000D_
var res3 = await pr3;_x000D_
console.log(res1,res2,res3);_x000D_
console.log(res1);_x000D_
console.log(res2);_x000D_
console.log(res3);_x000D_
_x000D_
} _x000D_
funa();_x000D_
_x000D_
_x000D_
_x000D_
async function f1(){_x000D_
_x000D_
await new Promise(r=>setTimeout(r,3000))_x000D_
.then(()=>console.log('Hi3 I am order 1'))_x000D_
return 1; _x000D_
_x000D_
}_x000D_
_x000D_
async function f2(){_x000D_
_x000D_
await new Promise(r=>setTimeout(r,2000))_x000D_
.then(()=>console.log('Hi3 I am order 2'))_x000D_
return 2; _x000D_
_x000D_
}_x000D_
_x000D_
async function f3(){_x000D_
_x000D_
await new Promise(r=>setTimeout(r,1000))_x000D_
.then(()=>console.log('Hi3 I am order 3'))_x000D_
return 3; _x000D_
_x000D_
}_x000D_
_x000D_
async function finaloutput2(arr){_x000D_
_x000D_
return await Promise.all([f3(),f2(),f1()]);_x000D_
}_x000D_
_x000D_
//f1().then(f2().then(f3()));_x000D_
//f3().then(f2().then(f1()));_x000D_
_x000D_
//finaloutput2();_x000D_
_x000D_
//var pr1=new Promise(f3)_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
async function f(){_x000D_
console.log("makesure");_x000D_
var pr=new Promise((res,rej)=>{_x000D_
setTimeout(function() {_x000D_
console.log('Hi2 I am order 1');_x000D_
}, 3000);_x000D_
});_x000D_
_x000D_
_x000D_
var result=await pr;_x000D_
console.log(result);_x000D_
}_x000D_
_x000D_
// f(); _x000D_
_x000D_
async function g(){_x000D_
console.log("makesure");_x000D_
var pr=new Promise((res,rej)=>{_x000D_
setTimeout(function() {_x000D_
console.log('Hi2 I am order 2');_x000D_
}, 2000);_x000D_
});_x000D_
_x000D_
_x000D_
var result=await pr;_x000D_
console.log(result);_x000D_
}_x000D_
_x000D_
// g(); _x000D_
_x000D_
async function h(){_x000D_
console.log("makesure");_x000D_
var pr=new Promise((res,rej)=>{_x000D_
setTimeout(function() {_x000D_
console.log('Hi2 I am order 3');_x000D_
}, 1000);_x000D_
});_x000D_
_x000D_
_x000D_
var result=await pr;_x000D_
console.log(result);_x000D_
}_x000D_
_x000D_
async function finaloutput(arr){_x000D_
_x000D_
return await Promise.all([f(),g(),h()]);_x000D_
}_x000D_
_x000D_
//finaloutput();_x000D_
_x000D_
//h(); _x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
Here is an example ...
select * from tablename where to_char(added_time, 'YYYY-MM-DD') = to_char( now(), 'YYYY-MM-DD' )
added_time is a column name which I converted to char for match
Aside from getting decode
and encode
backwards, I think part of the answer here is actually don't use the ascii
encoding. It's probably not what you want.
To begin with, think of str
like you would a plain text file. It's just a bunch of bytes with no encoding actually attached to it. How it's interpreted is up to whatever piece of code is reading it. If you don't know what this paragraph is talking about, go read Joel's The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets right now before you go any further.
Naturally, we're all aware of the mess that created. The answer is to, at least within memory, have a standard encoding for all strings. That's where unicode
comes in. I'm having trouble tracking down exactly what encoding Python uses internally for sure, but it doesn't really matter just for this. The point is that you know it's a sequence of bytes that are interpreted a certain way. So you only need to think about the characters themselves, and not the bytes.
The problem is that in practice, you run into both. Some libraries give you a str
, and some expect a str
. Certainly that makes sense whenever you're streaming a series of bytes (such as to or from disk or over a web request). So you need to be able to translate back and forth.
Enter codecs
: it's the translation library between these two data types. You use encode
to generate a sequence of bytes (str
) from a text string (unicode
), and you use decode
to get a text string (unicode
) from a sequence of bytes (str
).
For example:
>>> s = "I look like a string, but I'm actually a sequence of bytes. \xe2\x9d\xa4"
>>> codecs.decode(s, 'utf-8')
u"I look like a string, but I'm actually a sequence of bytes. \u2764"
What happened here? I gave Python a sequence of bytes, and then I told it, "Give me the unicode
version of this, given that this sequence of bytes is in 'utf-8'
." It did as I asked, and those bytes (a heart character) are now treated as a whole, represented by their Unicode codepoint.
Let's go the other way around:
>>> u = u"I'm a string! Really! \u2764"
>>> codecs.encode(u, 'utf-8')
"I'm a string! Really! \xe2\x9d\xa4"
I gave Python a Unicode string, and I asked it to translate the string into a sequence of bytes using the 'utf-8'
encoding. So it did, and now the heart is just a bunch of bytes it can't print as ASCII; so it shows me the hexadecimal instead.
We can work with other encodings, too, of course:
>>> s = "I have a section \xa7"
>>> codecs.decode(s, 'latin1')
u'I have a section \xa7'
>>> codecs.decode(s, 'latin1')[-1] == u'\u00A7'
True
>>> u = u"I have a section \u00a7"
>>> u
u'I have a section \xa7'
>>> codecs.encode(u, 'latin1')
'I have a section \xa7'
('\xa7'
is the section character, in both
Unicode and Latin-1.)
So for your question, you first need to figure out what encoding your str
is in.
Did it come from a file? From a web request? From your database? Then the source determines the encoding. Find out the encoding of the source and use that to translate it into a unicode
.
s = [get from external source]
u = codecs.decode(s, 'utf-8') # Replace utf-8 with the actual input encoding
Or maybe you're trying to write it out somewhere. What encoding does the destination expect? Use that to translate it into a str
. UTF-8 is a good choice for plain text documents; most things can read it.
u = u'My string'
s = codecs.encode(u, 'utf-8') # Replace utf-8 with the actual output encoding
[Write s out somewhere]
Are you just translating back and forth in memory for interoperability or something? Then just pick an encoding and stick with it; 'utf-8'
is probably the best choice for that:
u = u'My string'
s = codecs.encode(u, 'utf-8')
newu = codecs.decode(s, 'utf-8')
In modern programming, you probably never want to use the 'ascii'
encoding for any of this. It's an extremely small subset of all possible characters, and no system I know of uses it by default or anything.
Python 3 does its best to make this immensely clearer simply by changing the names. In Python 3, str
was replaced with bytes
, and unicode
was replaced with str
.
Absolute positioning positions an element relative to its nearest positioned ancestor. So put position: relative
on the container, then for child elements, top
and left
will be relative to the top-left of the container so long as the child elements have position: absolute
. More information is available in the CSS 2.1 specification.
I also ran into this error when I was using Dapper and forgot to input a parameterized value.
To fix I had to ensure that the object passed in as a parameter had properties matching the parameterised values in the SQL string.
Press F2 and then rename it (or right click on the project and select Rename
). It changes wherever that package is declared in your project. It's automatically renamed all over.
public class MyAdapter extends Adapter {
private Context context;
public MyAdapter(Context context) {
this.context = context;
}
public View getView(...){
View v;
v.setOnClickListener(new OnClickListener() {
void onClick() {
Intent intent= new Intent(context, ToActivity.class);
intent.putExtra("your_extra","your_class_value");
context.startActivity(intent);
}
});
}
}
For me this happened because i merged a branch dev into master using web interface and then tried to sync/pull using VSCode which was open on dev branch.(its weird that i could not change to master without getting this error.)
git pull
Your configuration specifies to merge with the ref 'refs/heads/dev'
from the remote, but no such ref was fetched.'
It makes sense that is not finding it refs/heads/dev - for me it was easier to just delete the local folder and clone again.
Write bytes and Create the file if not exists:
f = open('./put/your/path/here.png', 'wb')
f.write(data)
f.close()
wb
means open the file in write binary
mode.
From wikipedia:
In computer science, an array data structure or simply array is a data structure consisting of a collection of elements (values or variables), each identified by one or more integer indices, stored so that the address of each element can be computed from its index tuple by a simple mathematical formula.
So when you say byte array, you're referring to an array of some defined length (e.g. number of elements) that contains a collection of byte (8 bits) sized elements.
In C# a byte array could look like:
byte[] bytes = { 3, 10, 8, 25 };
The sample above defines an array of 4 elements, where each element can be up to a Byte in length.
I think i'am late for the party but when you use a wildfly, you can add an default-encoding to the standalone.xml. Just search in the standalone.xml for
<servlet-container name="default">
and add encoding like this:
<servlet-container name="default" default-encoding="UTF-8">
I struggled with this issue for a long time. Finally an elegant external library suggested here helped me out.
From the fine manual:
ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;
There's no need to specify the type when you're just changing the nullability.
prop.table is a nice friendly way of obtaining proportions of tables.
m <- matrix(1:4,2)
m
[,1] [,2]
[1,] 1 3
[2,] 2 4
Leaving margin blank gives you proportions of the whole table
prop.table(m, margin=NULL)
[,1] [,2]
[1,] 0.1 0.3
[2,] 0.2 0.4
Giving it 1 gives you row proportions
prop.table(m, 1)
[,1] [,2]
[1,] 0.2500000 0.7500000
[2,] 0.3333333 0.6666667
And 2 is column proportions
prop.table(m, 2)
[,1] [,2]
[1,] 0.3333333 0.4285714
[2,] 0.6666667 0.5714286
I use WebKit's developer menu/console (Safari 4). It is almost identical to Firebug.
console.log()
is the new black -- far better than alert()
.
I like to used this method the most, it will auto select the first column to the last column being used. However, if the last cell in the first row or the last cell in the first column are empty, this code will not calculate properly. Check the link for other methods to dynamically select cell range.
Sub DynamicRange()
'Best used when first column has value on last row and first row has a value in the last column
Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range
Set sht = Worksheets("Sheet1")
Set StartCell = Range("A1")
'Find Last Row and Column
LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column
'Select Range
sht.Range(StartCell, sht.Cells(LastRow, LastColumn)).Select
End Sub
I solve it just by changing 'http://webname...'
to "http://webname..."
Notice the quote. It should be double ("
) instead of single ('
).
driver.get()
is used to navigate particular URL(website) and wait till page load.
driver.navigate()
is used to navigate to particular URL and does not wait to page load. It maintains browser history or cookies to navigate back or forward.
Font myFont = new Font ("Courier New", 1, 17);
The 17 represents the font size. Once you have that, you can put:
g.setFont (myFont);
g.drawString ("Hello World", 10, 10);
For buttons created with .Button() in jQuery........
Whilst the other answers will change the text they will mess up the styling of the button, it turns out that when a jQuery button is rendered the text of the button is nested within a span e.g.
<button id="thebutton">
<span class="ui-button-text">My Text</span>
</button>
If you remove the span and replace it with text (as in the other examples) - you'll loose the span and associated formatting.
So you actually need to change the text within the SPAN tag and NOT the BUTTON!
$("#thebutton span").text("My NEW Text");
or (if like me it's being done on a click event)
$("span", this).text("My NEW Text");
For windows OS users (It worked for me) in XAMPP.
step 1: Go to C:\xampp\php\php.ini
edit this file php.ini
find curl- you will see a line ;extension=php_curl.dll.
remove semicolon (;)extension=php_curl.dll. so this line looks like
;extension=php_curl.dll
to
extension=php_curl.dll
step 2: copy ssleay32.dll, libeay32.dll from php folder. paste it in C:\Windows\System32\
step 3: Restart the system . Curl will run successfully.
Unfortunately, setTimeout()
is the only reliable way (not the only way, but the only reliable way) to pause the execution of the script without blocking the UI.
It's not that hard to use actually, instead of writing this:
var x = 1;
// Place mysterious code that blocks the thread for 100 ms.
x = x * 3 + 2;
var y = x / 2;
you use setTimeout()
to rewrite it this way:
var x = 1;
var y = null; // To keep under proper scope
setTimeout(function() {
x = x * 3 + 2;
y = x / 2;
}, 100);
I understand that using setTimeout()
involves more thought than a desirable sleep()
function, but unfortunately the later doesn't exist. Many workarounds are there to try to implement such functions. Some using busy loops:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
Unfortunately, those are workarounds and are likely to cause other problems (such as freezing browsers). It is recommended to simply stick with the recommended way, which is setTimeout()
).
In my case the data directory was automatically initialized with the --initialize-insecure
option. So /var/log/mysql/error.log
does not contain a temporary password but:
[Warning] root@localhost is created with an empty password ! Please consider switching off the --initialize-insecure option.
What worked was:
shell> mysql -u root --skip-password
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';
Details: MySQL 5.7 Reference Manual > 2.10.4 Securing the Initial MySQL Account
Try placing $PATH at the end.
export PATH=/usr/local/git/bin:/usr/local/bin:$PATH
Edit: atp's answer below is better. Please use that one!
You might have an easier time, if you're looking for a specific list of files, putting them directly on the command line instead:
# rsync -avP -e ssh `cat deploy/rsync_include.txt` [email protected]:/var/www/
This is assuming, however, that your list isn't so long that the command line length will be a problem and that the rsync_include.txt
file contains just real paths (i.e. no comments, and no regexps).
I had same problem with 'parallax' plugin.
I changed jQuery librery version to *jquery-1.6.4*
from *jquery-1.10.2*.
And error cleared.
It's not built in, but if you want unusual length numbers then you could use the bitstring module.
>>> from bitstring import Bits
>>> a = Bits(bin='111111111111')
>>> a.int
-1
The same object can equivalently be created in several ways, including
>>> b = Bits(int=-1, length=12)
It just behaves like a string of bits of arbitrary length, and uses properties to get different interpretations:
>>> print a.int, a.uint, a.bin, a.hex, a.oct
-1 4095 111111111111 fff 7777
If your file is really big try to use following formula: =A1 / 86400 + 25569
A1 should be replaced to what your need. Should work faster than =(((COLUMN_ID_HERE/60)/60)/24)+DATE(1970,1,1) cause of less number of calculations needed.
Maybe a simpler solution is to set an overlay in front of your map using FrameLayout
or RelativeLayout
and treating them as regular buttons in your activity. You should declare your layers in back to front order, e.g., map before buttons. I modified your layout, simplified it a little bit. Try the following layout and see if it works for you:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapActivity" >
<fragment xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:scrollbars="vertical"
class="com.google.android.gms.maps.SupportMapFragment"/>
<RadioGroup
android:id="@+id/radio_group_list_selector"
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="horizontal"
android:background="#80000000"
android:padding="4dp" >
<RadioButton
android:id="@+id/radioPopular"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="@string/Popular"
android:gravity="center_horizontal|center_vertical"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton"
android:textColor="@color/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioAZ"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/AZ"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton2"
android:textColor="@color/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioCategory"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/Category"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton2"
android:textColor="@color/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioNearBy"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/NearBy"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton3"
android:textColor="@color/textcolor_radiobutton" />
</RadioGroup>
</FrameLayout>
Open Anaconda Prompt (base):
conda update -n base -c defaults conda
conda create -n python38 python=3.8
conda activate python38
python
I solved the issue removing gulp and installing gulp-cli again:
rm /usr/local/bin/gulp
npm install -g gulp-cli
In my case, boolean values in my Python dict were the problem. JSON boolean values are in lowercase ("true", "false") whereas in Python they are in Uppercase ("True", "False"). Couldn't find this solution anywhere online but hope it helps.
Floating div's will help what your trying to achieve.
HTML
<div class="container">
<div class="content1 content">
</div>
<div class="content2 content">
</div>
</div>
CSS
.container{
width:100%;
height:200px;
background-color:grey;
}
.content{
float:left;
height:30px;
}
.content1{
background-color:blue;
width:300px;
}
.content2{
width:200px;
background-color:green;
}
Zoom in the page to see the effects.
Hope it helps.
The Content-Security-Policy
meta-tag allows you to reduce the risk of XSS attacks by allowing you to define where resources can be loaded from, preventing browsers from loading data from any other locations. This makes it harder for an attacker to inject malicious code into your site.
I banged my head against a brick wall trying to figure out why I was getting CSP errors one after another, and there didn't seem to be any concise, clear instructions on just how does it work. So here's my attempt at explaining some points of CSP briefly, mostly concentrating on the things I found hard to solve.
For brevity I won’t write the full tag in each sample. Instead I'll only show the content
property, so a sample that says content="default-src 'self'"
means this:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">
1. How can I allow multiple sources?
You can simply list your sources after a directive as a space-separated list:
content="default-src 'self' https://example.com/js/"
Note that there are no quotes around parameters other than the special ones, like 'self'
. Also, there's no colon (:
) after the directive. Just the directive, then a space-separated list of parameters.
Everything below the specified parameters is implicitly allowed. That means that in the example above these would be valid sources:
https://example.com/js/file.js
https://example.com/js/subdir/anotherfile.js
These, however, would not be valid:
http://example.com/js/file.js
^^^^ wrong protocol
https://example.com/file.js
^^ above the specified path
2. How can I use different directives? What do they each do?
The most common directives are:
default-src
the default policy for loading javascript, images, CSS, fonts, AJAX requests, etcscript-src
defines valid sources for javascript filesstyle-src
defines valid sources for css filesimg-src
defines valid sources for imagesconnect-src
defines valid targets for to XMLHttpRequest (AJAX), WebSockets or EventSource. If a connection attempt is made to a host that's not allowed here, the browser will emulate a 400
errorThere are others, but these are the ones you're most likely to need.
3. How can I use multiple directives?
You define all your directives inside one meta-tag by terminating them with a semicolon (;
):
content="default-src 'self' https://example.com/js/; style-src 'self'"
4. How can I handle ports?
Everything but the default ports needs to be allowed explicitly by adding the port number or an asterisk after the allowed domain:
content="default-src 'self' https://ajax.googleapis.com http://example.com:123/free/stuff/"
The above would result in:
https://ajax.googleapis.com:123
^^^^ Not ok, wrong port
https://ajax.googleapis.com - OK
http://example.com/free/stuff/file.js
^^ Not ok, only the port 123 is allowed
http://example.com:123/free/stuff/file.js - OK
As I mentioned, you can also use an asterisk to explicitly allow all ports:
content="default-src example.com:*"
5. How can I handle different protocols?
By default, only standard protocols are allowed. For example to allow WebSockets ws://
you will have to allow it explicitly:
content="default-src 'self'; connect-src ws:; style-src 'self'"
^^^ web Sockets are now allowed on all domains and ports.
6. How can I allow the file protocol file://
?
If you'll try to define it as such it won’t work. Instead, you'll allow it with the filesystem
parameter:
content="default-src filesystem"
7. How can I use inline scripts and style definitions?
Unless explicitly allowed, you can't use inline style definitions, code inside <script>
tags or in tag properties like onclick
. You allow them like so:
content="script-src 'unsafe-inline'; style-src 'unsafe-inline'"
You'll also have to explicitly allow inline, base64 encoded images:
content="img-src data:"
8. How can I allow eval()
?
I'm sure many people would say that you don't, since 'eval is evil' and the most likely cause for the impending end of the world. Those people would be wrong. Sure, you can definitely punch major holes into your site's security with eval, but it has perfectly valid use cases. You just have to be smart about using it. You allow it like so:
content="script-src 'unsafe-eval'"
9. What exactly does 'self'
mean?
You might take 'self'
to mean localhost, local filesystem, or anything on the same host. It doesn't mean any of those. It means sources that have the same scheme (protocol), same host, and same port as the file the content policy is defined in. Serving your site over HTTP? No https for you then, unless you define it explicitly.
I've used 'self'
in most examples as it usually makes sense to include it, but it's by no means mandatory. Leave it out if you don't need it.
But hang on a minute! Can't I just use content="default-src *"
and be done with it?
No. In addition to the obvious security vulnerabilities, this also won’t work as you'd expect. Even though some docs claim it allows anything, that's not true. It doesn't allow inlining or evals, so to really, really make your site extra vulnerable, you would use this:
content="default-src * 'unsafe-inline' 'unsafe-eval'"
... but I trust you won’t.
Further reading:
or you could just write the power function, with recursion as a added bonus
int power(int x, int y){
if(y == 0)
return 1;
return (x * power(x,y-1) );
}
yes,yes i know this is less effecient space and time complexity but recursion is just more fun!!
The JDK 1.6 I'm currently using on OSX Mountain Lion did not come with a src.zip
either, and as far as i can tell there is no supported OSX JDK for 1.6 available anymore.
So I downloaded the OpenJDK source (using the links from the accepted answer (+1)) then ran:
cd ~/Downloads
mkdir jdk6src
cd jdk6src
tar xf ../openjdk-6-src-b27-26_oct_2012.tar.gz
cd jdk/src/share/classes
jar cf /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/src.jar *
(your file names and paths may vary...)
Associate that src.jar
with the appropriate Java platform in your IDE and you should be good to go.
There are some discrepancies between the OpenJDK source and the JDK I'm currently running (line numbers don't match up in the debugger, for one), but if all you want is a zip/jar to point your IDE to for the relatively few cases you need to peek at some code to understand how something works, then this should do the trick.
This:
STR_TO_DATE(t.datestring, '%d/%m/%Y')
...will convert the string into a datetime datatype. To be sure that it comes out in the format you desire, use DATE_FORMAT:
DATE_FORMAT(STR_TO_DATE(t.datestring, '%d/%m/%Y'), '%Y-%m-%d')
If you can't change the datatype on the original column, I suggest creating a view that uses the STR_TO_DATE
call to convert the string to a DateTime data type.
Try double-clicking on the bottom right hand corner of the cell (ie on the box that you would otherwise drag).
I do this:
git rm --cached `git ls-files -i --exclude-from=.gitignore`
git commit -m 'Removed all files that are in the .gitignore'
git push origin master
Which will remove all the files/folders that are in your git ignore, saving you have to pick each one manually
This seems to have stopped working for me, I now do:
git rm -r --cached .
git add .
git commit -m 'Removed all files that are in the .gitignore'
git push origin master
Try this...
<div class="row">
<div class="col-xs-3">
Menu
</div>
<div class="col-xs-9">
<div class="row">
<div class="col-sm-4 col-sm-push-8">
Right content
</div>
<div class="col-sm-8 col-sm-pull-4">
Content
</div>
</div>
</div>
</div>
If at all possible, its always a good idea to create your XML using the XML classes rather than string manipulation - one of the benefits being that the classes will automatically escape characters as needed.
Also, if you need to format telephone number on output only, you can use a custom filter like this one:
angular.module('ng').filter('tel', function () {
return function (tel) {
if (!tel) { return ''; }
var value = tel.toString().trim().replace(/^\+/, '');
if (value.match(/[^0-9]/)) {
return tel;
}
var country, city, number;
switch (value.length) {
case 10: // +1PPP####### -> C (PPP) ###-####
country = 1;
city = value.slice(0, 3);
number = value.slice(3);
break;
case 11: // +CPPP####### -> CCC (PP) ###-####
country = value[0];
city = value.slice(1, 4);
number = value.slice(4);
break;
case 12: // +CCCPP####### -> CCC (PP) ###-####
country = value.slice(0, 3);
city = value.slice(3, 5);
number = value.slice(5);
break;
default:
return tel;
}
if (country == 1) {
country = "";
}
number = number.slice(0, 3) + '-' + number.slice(3);
return (country + " (" + city + ") " + number).trim();
};
});
Then you can use this filter in your template:
{{ phoneNumber | tel }}
<span ng-bind="phoneNumber | tel"></span>
Start with this link to the wiki, explains what they are and gives links to the sdk. Here is some information regarding the deve
How to compile a plugin - For making VST plugins in C++Builder, first you need the VST sdk by Steinberg. It's available from the Yvan Grabit's site (the link is at the top of the page).
The next thing you need to do is create a .def file (for example : myplugin.def). This needs to contain at least the following lines:
EXPORTS main=_main
Borland compilers add an underscore to function names, and this exports the main()
function the way a VST host expects it. For more information about .def files, see the C++Builder help files.
This is not enough, though. If you're going to use any VCL element (anything to do with forms or components), you have to take care your plugin doesn't crash Cubase (or another VST host, for that matter). Here's how:
In the constructor of your effect class, write
_control87(PC_64|MCW_EM,MCW_PC|MCW_EM);
That should do the trick.
Here are some more useful sites:
http://www.steinberg.net/en/company/developer.html
how to write a vst plugin (pdf) via http://www.asktoby.com/#vsttutorial
Use a setter for the ViewChild:
private contentPlaceholder: ElementRef;
@ViewChild('contentPlaceholder') set content(content: ElementRef) {
if(content) { // initially setter gets called with undefined
this.contentPlaceholder = content;
}
}
The setter is called with an element reference once *ngIf
becomes true
.
Note, for Angular 8 you have to make sure to set { static: false }
, which is a default setting in other Angular versions:
@ViewChild('contentPlaceholder', { static: false })
Note: if contentPlaceholder is a component you can change ElementRef to your component Class:
private contentPlaceholder: MyCustomComponent;
@ViewChild('contentPlaceholder') set content(content: MyCustomComponent) {
if(content) { // initially setter gets called with undefined
this.contentPlaceholder = content;
}
}
Another way to cope with it is to use Cygwin, depending on what do you want to do with the files (i.e. if Cygwin commands suit your needs)
For example it allows to copy, move or rename files that even Windows Explorer can't. Or of course deal with the contents of them like md5sum, grep, gzip, etc.
Also for programs that you are coding, you could link them to the Cygwin DLL and it would enable them to use long paths (I haven't tested this though)
CMake 3.X offers a 'clean' target.
cmake --build C:/foo/build/ --target clean
From the CMake docs for 3.0.2:
--clean-first = Build target 'clean' first, then build.
(To clean only, use --target 'clean'.)
There is no cmake clean
in CMake version 2.X
I usually build the project in a single folder like "build". So if I want to make clean
, I can just rm -rf build
.
The "build" folder in the same directory as the root "CMakeLists.txt" is usually a good choice. To build your project, you simply give cmake the location of the CMakeLists.txt as an argument. For example: cd <location-of-cmakelists>/build && cmake ..
. (From @ComicSansMS)
The functionality to name returned aggregate columns has been reintroduced in the master branch and is targeted for pandas 0.25. The new syntax is .agg(new_col_name=('col_name', 'agg_func')
. Detailed example from the PR linked above:
In [2]: df = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
...: 'height': [9.1, 6.0, 9.5, 34.0],
...: 'weight': [7.9, 7.5, 9.9, 198.0]})
...:
In [3]: df
Out[3]:
kind height weight
0 cat 9.1 7.9
1 dog 6.0 7.5
2 cat 9.5 9.9
3 dog 34.0 198.0
In [4]: df.groupby('kind').agg(min_height=('height', 'min'),
max_weight=('weight', 'max'))
Out[4]:
min_height max_weight
kind
cat 9.1 9.9
dog 6.0 198.0
It will also be possible to use multiple lambda expressions with this syntax and the two-step rename syntax I suggested earlier (below) as per this PR. Again, copying from the example in the PR:
In [2]: df = pd.DataFrame({"A": ['a', 'a'], 'B': [1, 2], 'C': [3, 4]})
In [3]: df.groupby("A").agg({'B': [lambda x: 0, lambda x: 1]})
Out[3]:
B
<lambda> <lambda 1>
A
a 0 1
and then .rename()
, or in one go:
In [4]: df.groupby("A").agg(b=('B', lambda x: 0), c=('B', lambda x: 1))
Out[4]:
b c
A
a 0 0
The currently accepted answer by unutbu describes are great way of doing this in pandas versions <= 0.20. However, as of pandas 0.20, using this method raises a warning indicating that the syntax will not be available in future versions of pandas.
Series:
FutureWarning: using a dict on a Series for aggregation is deprecated and will be removed in a future version
DataFrames:
FutureWarning: using a dict with renaming is deprecated and will be removed in a future version
According to the pandas 0.20 changelog, the recommended way of renaming columns while aggregating is as follows.
# Create a sample data frame
df = pd.DataFrame({'A': [1, 1, 1, 2, 2],
'B': range(5),
'C': range(5)})
# ==== SINGLE COLUMN (SERIES) ====
# Syntax soon to be deprecated
df.groupby('A').B.agg({'foo': 'count'})
# Recommended replacement syntax
df.groupby('A').B.agg(['count']).rename(columns={'count': 'foo'})
# ==== MULTI COLUMN ====
# Syntax soon to be deprecated
df.groupby('A').agg({'B': {'foo': 'sum'}, 'C': {'bar': 'min'}})
# Recommended replacement syntax
df.groupby('A').agg({'B': 'sum', 'C': 'min'}).rename(columns={'B': 'foo', 'C': 'bar'})
# As the recommended syntax is more verbose, parentheses can
# be used to introduce line breaks and increase readability
(df.groupby('A')
.agg({'B': 'sum', 'C': 'min'})
.rename(columns={'B': 'foo', 'C': 'bar'})
)
Please see the 0.20 changelog for additional details.
With the old style dictionary syntax, it was possible to pass multiple lambda
functions to .agg
, since these would be renamed with the key in the passed dictionary:
>>> df.groupby('A').agg({'B': {'min': lambda x: x.min(), 'max': lambda x: x.max()}})
B
max min
A
1 2 0
2 4 3
Multiple functions can also be passed to a single column as a list:
>>> df.groupby('A').agg({'B': [np.min, np.max]})
B
amin amax
A
1 0 2
2 3 4
However, this does not work with lambda functions, since they are anonymous and all return <lambda>
, which causes a name collision:
>>> df.groupby('A').agg({'B': [lambda x: x.min(), lambda x: x.max]})
SpecificationError: Function names must be unique, found multiple named <lambda>
To avoid the SpecificationError
, named functions can be defined a priori instead of using lambda
. Suitable function names also avoid calling .rename
on the data frame afterwards. These functions can be passed with the same list syntax as above:
>>> def my_min(x):
>>> return x.min()
>>> def my_max(x):
>>> return x.max()
>>> df.groupby('A').agg({'B': [my_min, my_max]})
B
my_min my_max
A
1 0 2
2 3 4
If you will be checking the existence of attributes frequently, I would suggest creating a hasAttr
function, to use as you hypothesized in your question:
$.fn.hasAttr = function(name) {
return this.attr(name) !== undefined;
};
$(document).ready(function() {
if($('.edit').hasAttr('id')) {
alert('true');
} else {
alert('false');
}
});
<div class="edit" id="div_1">Test field</div>
Use this One
((Excel.Range)oSheet.Cells[1, 1]).EntireColumn.ColumnWidth = 10;
It might be possible to delete the Zone Record entirely, then recreate it exactly as you want it. Perhaps this will force a full propagation. If I'm wrong, somebody tell me and I'll delete this suggestion. Also, I don't know how to save a Zone Record and recreate it using WHM or any other tool.
I do know that when I deleted a hosting account today and recreated it, the original Zone Record seemed to be propagated instantly to a DNS resolver up the line from my computer. That is good evidence it works.
I had a similar problem. My data is provided by a remote server. I want some value to be entered in the selectize box, but it is not sure in advance whether this value is a valid one on the server.
So I want the value to be entered in the box, and I want selectize to show the possible options just if like the user had entered the value.
I ended up using this hack (which it is probably unsupported):
var $selectize = $("#my_input").selectize(/* settings with load*/);
var selectize = $select[0].selectize;
// get the search from the remote server
selectize.onSearchChange('my value');
// enter the input in the input field
$selectize.parent().find('input').val('my value');
// focus on the input field, to make the options visible
$selectize.parent().find('input').focus();
Starting Xampp as a console application (simply by doubleclicking xampp_start.exe in the Xampp root folder) was the only thing that worked for me on Windows 10 (no Skype, no Word Wide Web Publishing Service). WampServer and UwAmp also didn't work.
A better alternative is to use weakref.finalize. See the examples at Finalizer Objects and Comparing finalizers with __del__() methods.
This is one of the points in C that can be confusing at first, but the C standard only specifies a minimum range for integer types that is guaranteed to be supported. int
is guaranteed to be able to hold -32767 to 32767, which requires 16 bits. In that case, int
, is 2 bytes. However, implementations are free to go beyond that minimum, as you will see that many modern compilers make int
32-bit (which also means 4 bytes pretty ubiquitously).
The reason your book says 2 bytes is most probably because it's old. At one time, this was the norm. In general, you should always use the sizeof
operator if you need to find out how many bytes it is on the platform you're using.
To address this, C99 added new types where you can explicitly ask for a certain sized integer, for example int16_t
or int32_t
. Prior to that, there was no universal way to get an integer of a specific width (although most platforms provided similar types on a per-platform basis).
You could just use the bound ng-model
(answers[item.questID]
) value itself in your ng-change method to detect if it has been checked or not.
Example:-
<input type="checkbox" ng-model="answers[item.questID]"
ng-change="stateChanged(item.questID)" /> <!-- Pass the specific id -->
and
$scope.stateChanged = function (qId) {
if($scope.answers[qId]){ //If it is checked
alert('test');
}
}
MongoDB needs data directory to store data.
Default path is /data/db
When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx
permission to user.
If you want to change the path of your data directory then you should specify it while starting mongod server like,
mongod --dbpath /data/<path> --port <port no>
This should help you start your mongod server with custom path and port.
What you are asking for is called multiple dispatch. See Julia language examples which demonstrates different types of dispatches.
However, before looking at that, we'll first tackle why overloading is not really what you want in Python.
First, one needs to understand the concept of overloading and why it's not applicable to Python.
When working with languages that can discriminate data types at compile-time, selecting among the alternatives can occur at compile-time. The act of creating such alternative functions for compile-time selection is usually referred to as overloading a function. (Wikipedia)
Python is a dynamically typed language, so the concept of overloading simply does not apply to it. However, all is not lost, since we can create such alternative functions at run-time:
In programming languages that defer data type identification until run-time the selection among alternative functions must occur at run-time, based on the dynamically determined types of function arguments. Functions whose alternative implementations are selected in this manner are referred to most generally as multimethods. (Wikipedia)
So we should be able to do multimethods in Python—or, as it is alternatively called: multiple dispatch.
The multimethods are also called multiple dispatch:
Multiple dispatch or multimethods is the feature of some object-oriented programming languages in which a function or method can be dynamically dispatched based on the run time (dynamic) type of more than one of its arguments. (Wikipedia)
Python does not support this out of the box1, but, as it happens, there is an excellent Python package called multipledispatch that does exactly that.
Here is how we might use multipledispatch2 package to implement your methods:
>>> from multipledispatch import dispatch
>>> from collections import namedtuple
>>> from types import * # we can test for lambda type, e.g.:
>>> type(lambda a: 1) == LambdaType
True
>>> Sprite = namedtuple('Sprite', ['name'])
>>> Point = namedtuple('Point', ['x', 'y'])
>>> Curve = namedtuple('Curve', ['x', 'y', 'z'])
>>> Vector = namedtuple('Vector', ['x','y','z'])
>>> @dispatch(Sprite, Point, Vector, int)
... def add_bullet(sprite, start, direction, speed):
... print("Called Version 1")
...
>>> @dispatch(Sprite, Point, Point, int, float)
... def add_bullet(sprite, start, headto, speed, acceleration):
... print("Called version 2")
...
>>> @dispatch(Sprite, LambdaType)
... def add_bullet(sprite, script):
... print("Called version 3")
...
>>> @dispatch(Sprite, Curve, int)
... def add_bullet(sprite, curve, speed):
... print("Called version 4")
...
>>> sprite = Sprite('Turtle')
>>> start = Point(1,2)
>>> direction = Vector(1,1,1)
>>> speed = 100 #km/h
>>> acceleration = 5.0 #m/s
>>> script = lambda sprite: sprite.x * 2
>>> curve = Curve(3, 1, 4)
>>> headto = Point(100, 100) # somewhere far away
>>> add_bullet(sprite, start, direction, speed)
Called Version 1
>>> add_bullet(sprite, start, headto, speed, acceleration)
Called version 2
>>> add_bullet(sprite, script)
Called version 3
>>> add_bullet(sprite, curve, speed)
Called version 4
1. Python 3 currently supports single dispatch 2. Take care not to use multipledispatch in a multi-threaded environment or you will get weird behavior.
Probably one of the indexes is wrong, either the inner one or the outer one.
I suspect you mean to say [0]
where you say [1]
and [1]
where you say [2]
. Indexes are 0-based in Python.
This is the correct way to perform the check as-per Microsoft's knowledgebase reference ( http://support.microsoft.com/kb/556009 ) that I have re-edited into just a single line of code.
It doesn't rely on any environment variables or folder names and instead checks directly in the registry.
As shown in a full batch file below it sets an environment variable OS equal to either 32BIT or 64BIT that you can use as desired.
@echo OFF
reg Query "HKLM\Hardware\Description\System\CentralProcessor\0" | find /i "x86" > NUL && set OS=32BIT || set OS=64BIT
if %OS%==32BIT echo This is a 32bit operating system
if %OS%==64BIT echo This is a 64bit operating system
This search engine was made to solve exactly the kind of problem you're having: http://symbolhound.com/
I am the developer of SymbolHound.
I was struggling with the same problem and stumbled upon this page. Another solution I came up with would be this :
In your html, echo the session variable (mine here is $_SESSION['origin']
) to any element of your choosing :
<p id="sessionOrigin"><?=$_SESSION['origin'];?></p>
In your js, using jQuery you can access it like so :
$("#sessionOrigin").text();
EDIT: or even better, put it in a hidden input
<input type="hidden" name="theOrigin" value="<?=$_SESSION['origin'];?>"></input>
I had the same problem today. I needed to set a flag in a nmake Makefile if the cl compiler version is 15. Here is the hack I came up with:
!IF ([cl /? 2>&1 | findstr /C:"Version 15" > nul] == 0)
FLAG = "cl version 15"
!ENDIF
Note that cl /?
prints the version information to the standard error stream and the help text to the standard output. To be able to check the version with the findstr
command one must first redirect stderr to stdout using 2>&1
.
The above idea can be used to write a Windows batch file that checks if the cl compiler version is <=
a given number. Here is the code of cl_version_LE.bat
:
@echo off
FOR /L %%G IN (10,1,%1) DO cl /? 2>&1 | findstr /C:"Version %%G" > nul && goto FOUND
EXIT /B 0
:FOUND
EXIT /B 1
Now if you want to set a flag in your nmake Makefile if the cl version <=
15, you can use:
!IF [cl_version_LE.bat 15]
FLAG = "cl version <= 15"
!ENDIF
This is @Jason's answer but with simplified output
SELECT name, CASE WHEN value = 1 THEN 'YES' ELSE 'NO' END AS 'Enabled'
FROM sys.configurations WHERE name = 'clr enabled'
The above returns the following:
| name | Enabled |
-------------------------
| clr enabled | YES |
Tested on SQL Server 2017
Based on quick inspection of google web, this would be CSS path to links in page list
ol[id="rso"] h3[class="r"] a
So you should do something like
String path = "ol[id='rso'] h3[class='r'] a";
driver.findElements(By.cssSelector(path)).get(2).click();
However you could also use xpath
which is not really recommended as a best practice and also JQuery locators but I am not sure if you can use them aynywhere else except inArquillian Graphene
https://facebook.github.io/react/tips/inline-styles.html
You don't need the quotes.
<a style={{backgroundColor: bgColors.Yellow}}>yellow</a>
In my situation I needed to answer some questions without Y or N but with text or blank. I found the best way to do this in my situation was to create a shellscript file. In my case I called it autocomplete.sh
I was needing to answer some questions for a doctrine schema exporter so my file looked like this.
-- This is an example only --
php vendor/bin/mysql-workbench-schema-export mysqlworkbenchfile.mwb ./doctrine << EOF
`#Export to Doctrine Annotation Format` 1
`#Would you like to change the setup configuration before exporting` y
`#Log to console` y
`#Log file` testing.log
`#Filename [%entity%.%extension%]`
`#Indentation [4]`
`#Use tabs [no]`
`#Eol delimeter (win, unix) [win]`
`#Backup existing file [yes]`
`#Add generator info as comment [yes]`
`#Skip plural name checking [no]`
`#Use logged storage [no]`
`#Sort tables and views [yes]`
`#Export only table categorized []`
`#Enhance many to many detection [yes]`
`#Skip many to many tables [yes]`
`#Bundle namespace []`
`#Entity namespace []`
`#Repository namespace []`
`#Use automatic repository [yes]`
`#Skip column with relation [no]`
`#Related var name format [%name%%related%]`
`#Nullable attribute (auto, always) [auto]`
`#Generated value strategy (auto, identity, sequence, table, none) [auto]`
`#Default cascade (persist, remove, detach, merge, all, refresh, ) [no]`
`#Use annotation prefix [ORM\]`
`#Skip getter and setter [no]`
`#Generate entity serialization [yes]`
`#Generate extendable entity [no]` y
`#Quote identifier strategy (auto, always, none) [auto]`
`#Extends class []`
`#Property typehint [no]`
EOF
The thing I like about this strategy is you can comment what your answers are and using EOF a blank line is just that (the default answer). Turns out by the way this exporter tool has its own JSON counterpart for answering these questions, but I figured that out after I did this =).
to run the script simply be in the directory you want and run 'sh autocomplete.sh'
in terminal.
In short by using << EOL & EOF in combination with Return Lines you can answer each question of the prompt as necessary. Each new line is a new answer.
My example just shows how this can be done with comments also using the ` character so you remember what each step is.
Note the other advantage of this method is you can answer with more then just Y or N ... in fact you can answer with blanks!
Hope this helps someone out.
First, Identify the user you are logged in as:
select user();
select current_user();
The result for the first command is what you attempted to login as, the second is what you actually connected as. Confirm that you are logged in as root@localhost
in mysql.
Grant_priv
to root@localhost
. Here is how you can check.
mysql> SELECT host,user,password,Grant_priv,Super_priv FROM mysql.user;
+-----------+------------------+-------------------------------------------+------------+------------+
| host | user | password | Grant_priv | Super_priv |
+-----------+------------------+-------------------------------------------+------------+------------+
| localhost | root | ***************************************** | N | Y |
| localhost | debian-sys-maint | ***************************************** | Y | Y |
| localhost | staging | ***************************************** | N | N |
+-----------+------------------+-------------------------------------------+------------+------------+
You can see that the Grant_priv is set to N for root@localhost. This needs to be Y. Below is how to fixed this:
UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';
FLUSH PRIVILEGES;
GRANT ALL ON *.* TO 'root'@'localhost';
I logged back in, it was fine.
The postgresql port is defined in your postgresql.conf
file.
For me in Ubuntu 14.04 it is: /etc/postgresql/9.3/main/postgresql.conf
Inside there is a line:
port = 5432
Changing the number there requires restart of postgresql for it to take effect.
The problem here is the line 292 (Using Python 3.4.3 here) in $python_install_prefix/Lib/distutils/msvc9compiler.py
which says:
VERSION = get_build_version()
This only checks for the MSVC version that your python was built with. Just replacing this line with your actual Visual Studio version, eg. 12.0
for MSVC2013
VERSION = 12.0
will fix the issue.
UPDATE: Turns out that there is a good reason why this version is hardcoded. MSVC C runtime is not required to be compatible between major versions. Hence when you use a different VS version you might run into runtime problems. So I advise to use VS 2008 (for Python 2.6 up to 3.2) and VS2010 for (Python 3.3 and later) until this issue is sorted out.
Binary compatibility will arrive with VS 2015 (see here) along with Python 3.5 .
For Python 2.7 users Microsoft released a special Microsoft Visual C++ Compiler for Python 2.7 which can be used without installing the whole VS 2008.
If you are using a framework like express, you need to put the package.json file into the folder you are using and don't forget change main name.
You can simply add another join like this:
SELECT dashboard_data.headline, dashboard_data.message, dashboard_messages.image_id, images.filename
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
INNER JOIN images
ON dashboard_messages.image_id = images.image_id
However be aware that, because it is an INNER JOIN
, if you have a message without an image, the entire row will be skipped. If this is a possibility, you may want to do a LEFT OUTER JOIN
which will return all your dashboard messages and an image_filename only if one exists (otherwise you'll get a null)
SELECT dashboard_data.headline, dashboard_data.message, dashboard_messages.image_id, images.filename
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
LEFT OUTER JOIN images
ON dashboard_messages.image_id = images.image_id
In my case the error was "caused" by my Homestead / Vagrant configuration about which I forgot :) trying to run the migration just from command line.
In case of using Homestead Vagrant Box environment you should run your migration from within your Homestead machine (after connecting to it using ssh: [email protected]:22
) then the access rights will be OK and will allow the migration to run.
One way you do this is set a counter and if number exceeds the certain number return false. easy as this.
var mybutton_counter=0;
$("#mybutton").on('click', function(e){
if (mybutton_counter>0){return false;} //you can set the number to any
//your call
mybutton_counter++; //incremental
});
make sure, if statement is on top of your call.
I would like to emphasize an answer that was in the comments that is working well for me. As mikey has said, this will work if you want to have variables in the included file in scope in the caller of 'include', just insert it as normal python. It works like an include statement in PHP. Works in Python 3.8.5. Happy coding!
Alternative #1
import textwrap
from pathlib import Path
exec(textwrap.dedent(Path('myfile.py').read_text()))
Alternative #2
with open('myfile.py') as f: exec(f.read())
Simple solution:
<iframe onload="this.style.height=this.contentWindow.document.body.scrollHeight + 'px';" ...></iframe>
This works when the iframe and parent window are in the same domain. It does not work when the two are in different domains.
We can also use
return $this->db->count_all('table_name');
or
$this->db->from('table_name');
return $this->db->count_all_result();
or
return $this->db->count_all_result('table_name');
or
$query = $this->db->query('select * from tab');
return $query->num_rows();
What you need to do is divide it into two divs. One with overflow set to scroll, and an inner one to hold the text so you can get it's outersize.
<div id="chatdiv">
<div id="textdiv"/>
</div>
textdiv.html("");
$.each(chatMessages, function (i, e) {
textdiv.append("<span>" + e + "</span><br/>");
});
chatdiv.scrollTop(textdiv.outerHeight());
You can check out a jsfiddle here: http://jsfiddle.net/xj5c3jcn/1/
Obviously you don't want to rebuild the whole text div each time, so take that with a grain of salt - just an example.
In my opinion this is the simplest solution
$orderby = 'name';
$order = 'asc';
$hide_empty = false ;
$cat_args = array(
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
);
$product_categories = get_terms( 'product_cat', $cat_args );
if( !empty($product_categories) ){
echo '
<ul>';
foreach ($product_categories as $key => $category) {
echo '
<li>';
echo '<a href="'.get_term_link($category).'" >';
echo $category->name;
echo '</a>';
echo '</li>';
}
echo '</ul>
';
}
From my experience the default location is /var/lib/mongodb
after I do
sudo apt-get install -y mongodb-org
A more generic solution, which works for non-numeric values as well:
a = {'a': 'foo', 'b':'bar', 'c': 'baz'}
b = {'a': 'spam', 'c':'ham', 'x': 'blah'}
r = dict(a.items() + b.items() +
[(k, a[k] + b[k]) for k in set(b) & set(a)])
or even more generic:
def combine_dicts(a, b, op=operator.add):
return dict(a.items() + b.items() +
[(k, op(a[k], b[k])) for k in set(b) & set(a)])
For example:
>>> a = {'a': 2, 'b':3, 'c':4}
>>> b = {'a': 5, 'c':6, 'x':7}
>>> import operator
>>> print combine_dicts(a, b, operator.mul)
{'a': 10, 'x': 7, 'c': 24, 'b': 3}
Instead of Googling for %02d
you should have been searching for sprintf()
function.
%02d
means "format the integer with 2 digits, left padding it with zeroes", so:
Format Data Result %02d 1 01 %02d 11 11
I suspect you need to use ClientID
rather than the literal ID string in your JavaScript code, since you've marked the field as runat="server"
.
E.g., if your JavaScript code is in an aspx file (not a separate JavaScript file):
var val = document.getElementById('<%=hdntxtbxTaksit.ClientID%>').value;
If it's in a separate JavaScript file that isn't rendered by the ASP.Net stuff, you'll have to find it another way, such as by class.
Save your sorting order in a ViewState.
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection) ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void GridView_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
private void SortGridView(string sortExpression,string direction)
{
// You can cache the DataTable for improving performance
DataTable dt = GetData().Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}
Why you don't want to use existing sorting functionality? You can always customize it.
Sorting Data in a GridView Web Server Control at MSDN
Here is an example with customization:
You can also use %
as follows:
source = "#{ROOT_DIR}/%s/App.config" % project
This approach works with '
(single) quotation mark as well.
For one thing, MVVM is a progression of the MVC pattern which uses XAML to handle the display. This article outlines some of the facets of the two.
The main thrust of the Model/View/ViewModel architecture seems to be that on top of the data (”the Model”), there’s another layer of non-visual components (”the ViewModel”) that map the concepts of the data more closely to the concepts of the view of the data (”the View”). It’s the ViewModel that the View binds to, not the Model directly.
I always go for the second method (using the GString template), though when there are more than a couple of parameters like you have, I tend to wrap them in ${X}
as I find it makes it more readable.
Running some benchmarks (using Nagai Masato's excellent GBench module) on these methods also shows templating is faster than the other methods:
@Grab( 'com.googlecode.gbench:gbench:0.3.0-groovy-2.0' )
import gbench.*
def (foo,bar,baz) = [ 'foo', 'bar', 'baz' ]
new BenchmarkBuilder().run( measureCpuTime:false ) {
// Just add the strings
'String adder' {
foo + bar + baz
}
// Templating
'GString template' {
"$foo$bar$baz"
}
// I find this more readable
'Readable GString template' {
"${foo}${bar}${baz}"
}
// StringBuilder
'StringBuilder' {
new StringBuilder().append( foo )
.append( bar )
.append( baz )
.toString()
}
'StringBuffer' {
new StringBuffer().append( foo )
.append( bar )
.append( baz )
.toString()
}
}.prettyPrint()
That gives me the following output on my machine:
Environment
===========
* Groovy: 2.0.0
* JVM: Java HotSpot(TM) 64-Bit Server VM (20.6-b01-415, Apple Inc.)
* JRE: 1.6.0_31
* Total Memory: 81.0625 MB
* Maximum Memory: 123.9375 MB
* OS: Mac OS X (10.6.8, x86_64)
Options
=======
* Warm Up: Auto
* CPU Time Measurement: Off
String adder 539
GString template 245
Readable GString template 244
StringBuilder 318
StringBuffer 370
So with readability and speed in it's favour, I'd recommend templating ;-)
NB: If you add toString()
to the end of the GString methods to make the output type the same as the other metrics, and make it a fairer test, StringBuilder
and StringBuffer
beat the GString methods for speed. However as GString can be used in place of String for most things (you just need to exercise caution with Map keys and SQL statements), it can mostly be left without this final conversion
Adding these tests (as it has been asked in the comments)
'GString template toString' {
"$foo$bar$baz".toString()
}
'Readable GString template toString' {
"${foo}${bar}${baz}".toString()
}
Now we get the results:
String adder 514
GString template 267
Readable GString template 269
GString template toString 478
Readable GString template toString 480
StringBuilder 321
StringBuffer 369
So as you can see (as I said), it is slower than StringBuilder or StringBuffer, but still a bit faster than adding Strings...
But still lots more readable.
Updated to latest gbench, larger strings for concatenation and a test with a StringBuilder initialised to a good size:
@Grab( 'org.gperfutils:gbench:0.4.2-groovy-2.1' )
def (foo,bar,baz) = [ 'foo' * 50, 'bar' * 50, 'baz' * 50 ]
benchmark {
// Just add the strings
'String adder' {
foo + bar + baz
}
// Templating
'GString template' {
"$foo$bar$baz"
}
// I find this more readable
'Readable GString template' {
"${foo}${bar}${baz}"
}
'GString template toString' {
"$foo$bar$baz".toString()
}
'Readable GString template toString' {
"${foo}${bar}${baz}".toString()
}
// StringBuilder
'StringBuilder' {
new StringBuilder().append( foo )
.append( bar )
.append( baz )
.toString()
}
'StringBuffer' {
new StringBuffer().append( foo )
.append( bar )
.append( baz )
.toString()
}
'StringBuffer with Allocation' {
new StringBuffer( 512 ).append( foo )
.append( bar )
.append( baz )
.toString()
}
}.prettyPrint()
gives
Environment
===========
* Groovy: 2.1.6
* JVM: Java HotSpot(TM) 64-Bit Server VM (23.21-b01, Oracle Corporation)
* JRE: 1.7.0_21
* Total Memory: 467.375 MB
* Maximum Memory: 1077.375 MB
* OS: Mac OS X (10.8.4, x86_64)
Options
=======
* Warm Up: Auto (- 60 sec)
* CPU Time Measurement: On
user system cpu real
String adder 630 0 630 647
GString template 29 0 29 31
Readable GString template 32 0 32 33
GString template toString 429 0 429 443
Readable GString template toString 428 1 429 441
StringBuilder 383 1 384 396
StringBuffer 395 1 396 409
StringBuffer with Allocation 277 0 277 286
IISReset restarts the entire webserver (including all associated sites). If you're just looking to reset a single ASP.NET website, you should just recycle that Application Domain.
Using name on a select option is not valid.
Other have suggested the data- attribute, an alternative is a lookup table
Here the "this" refers to the select so no need to "find" the option
var names = ["", "acoustic", "jazz", "acoustic_jazz", "party", "acoustic_party", "jazz_party", "acoustic_jazz_party"];_x000D_
_x000D_
$(function() {_x000D_
$('#band_type_choices').on('change', function() {_x000D_
$('.checkboxlist').hide();_x000D_
var idx = this.selectedIndex;_x000D_
if (idx > 0) $('#checkboxlist_' + names[idx]).show();_x000D_
});_x000D_
});
_x000D_
.checkboxlist { display:none }
_x000D_
Choose acoustic to see the corresponding div_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select id="band_type_choices">_x000D_
<option vlaue="0"></option>_x000D_
<option value="100" name="acoustic">Acoustic</option>_x000D_
<option value="0" name="jazz">Jazz/Easy Listening</option>_x000D_
<option value="0" name="acoustic_jazz">Acoustic + Jazz/Easy Listening</option>_x000D_
<option value="0" name="party">Party</option>_x000D_
<option value="0" name="acoustic_party">Acoustic + Party</option>_x000D_
<option value="0" name="jazz_party">Jazz/Easy Listening + Party</option>_x000D_
<option value="0" name="acoustic_jazz_party">Acoustic + Jazz/Easy Listening + Party</option>_x000D_
</select>_x000D_
<div class="checkboxlist" id="checkboxlist_acoustic">_x000D_
<input type="checkbox" class="checkbox keys" name="keys" value="100" />Keys<br>_x000D_
<input type="checkbox" class="checkbox acou_guit" name="acou_guit" value="100" />Acoustic Guitar<br>_x000D_
<input type="checkbox" class="checkbox drums" name="drums" value="100" />Drums<br>_x000D_
<input type="checkbox" class="checkbox alt_sax" name="alt_sax" value="100" />Alto Sax<br>_x000D_
<input type="checkbox" class="checkbox ten_sax" name="ten_sax" value="100" />Tenor Sax<br>_x000D_
<input type="checkbox" class="checkbox clarinet" name="clarinet" value="100" />Clarinet<br>_x000D_
<input type="checkbox" class="checkbox trombone" name="trombone" value="100" />Trombone<br>_x000D_
<input type="checkbox" class="checkbox trumpet" name="trumpet" value="100" />Trumpet<br>_x000D_
<input type="checkbox" class="checkbox flute" name="flute" value="100" />Flute<br>_x000D_
<input type="checkbox" class="checkbox cello" name="cello" value="100" />Cello<br>_x000D_
<input type="checkbox" class="checkbox violin" name="violin" value="100" />Violin<br>_x000D_
</div>
_x000D_
By adb shell input keyevent
, either an event_code
or a string
will be sent to the device.
usage: input [text|keyevent]
input text <string>
input keyevent <event_code>
Some possible values for event_code
are:
0 --> "KEYCODE_UNKNOWN"
1 --> "KEYCODE_MENU"
2 --> "KEYCODE_SOFT_RIGHT"
3 --> "KEYCODE_HOME"
4 --> "KEYCODE_BACK"
5 --> "KEYCODE_CALL"
6 --> "KEYCODE_ENDCALL"
7 --> "KEYCODE_0"
8 --> "KEYCODE_1"
9 --> "KEYCODE_2"
10 --> "KEYCODE_3"
11 --> "KEYCODE_4"
12 --> "KEYCODE_5"
13 --> "KEYCODE_6"
14 --> "KEYCODE_7"
15 --> "KEYCODE_8"
16 --> "KEYCODE_9"
17 --> "KEYCODE_STAR"
18 --> "KEYCODE_POUND"
19 --> "KEYCODE_DPAD_UP"
20 --> "KEYCODE_DPAD_DOWN"
21 --> "KEYCODE_DPAD_LEFT"
22 --> "KEYCODE_DPAD_RIGHT"
23 --> "KEYCODE_DPAD_CENTER"
24 --> "KEYCODE_VOLUME_UP"
25 --> "KEYCODE_VOLUME_DOWN"
26 --> "KEYCODE_POWER"
27 --> "KEYCODE_CAMERA"
28 --> "KEYCODE_CLEAR"
29 --> "KEYCODE_A"
30 --> "KEYCODE_B"
31 --> "KEYCODE_C"
32 --> "KEYCODE_D"
33 --> "KEYCODE_E"
34 --> "KEYCODE_F"
35 --> "KEYCODE_G"
36 --> "KEYCODE_H"
37 --> "KEYCODE_I"
38 --> "KEYCODE_J"
39 --> "KEYCODE_K"
40 --> "KEYCODE_L"
41 --> "KEYCODE_M"
42 --> "KEYCODE_N"
43 --> "KEYCODE_O"
44 --> "KEYCODE_P"
45 --> "KEYCODE_Q"
46 --> "KEYCODE_R"
47 --> "KEYCODE_S"
48 --> "KEYCODE_T"
49 --> "KEYCODE_U"
50 --> "KEYCODE_V"
51 --> "KEYCODE_W"
52 --> "KEYCODE_X"
53 --> "KEYCODE_Y"
54 --> "KEYCODE_Z"
55 --> "KEYCODE_COMMA"
56 --> "KEYCODE_PERIOD"
57 --> "KEYCODE_ALT_LEFT"
58 --> "KEYCODE_ALT_RIGHT"
59 --> "KEYCODE_SHIFT_LEFT"
60 --> "KEYCODE_SHIFT_RIGHT"
61 --> "KEYCODE_TAB"
62 --> "KEYCODE_SPACE"
63 --> "KEYCODE_SYM"
64 --> "KEYCODE_EXPLORER"
65 --> "KEYCODE_ENVELOPE"
66 --> "KEYCODE_ENTER"
67 --> "KEYCODE_DEL"
68 --> "KEYCODE_GRAVE"
69 --> "KEYCODE_MINUS"
70 --> "KEYCODE_EQUALS"
71 --> "KEYCODE_LEFT_BRACKET"
72 --> "KEYCODE_RIGHT_BRACKET"
73 --> "KEYCODE_BACKSLASH"
74 --> "KEYCODE_SEMICOLON"
75 --> "KEYCODE_APOSTROPHE"
76 --> "KEYCODE_SLASH"
77 --> "KEYCODE_AT"
78 --> "KEYCODE_NUM"
79 --> "KEYCODE_HEADSETHOOK"
80 --> "KEYCODE_FOCUS"
81 --> "KEYCODE_PLUS"
82 --> "KEYCODE_MENU"
83 --> "KEYCODE_NOTIFICATION"
84 --> "KEYCODE_SEARCH"
85 --> "TAG_LAST_KEYCODE"
The sendevent
utility sends touch or keyboard events, as well as other events for simulating the hardware events. Refer to this article for details: Android, low level shell click on screen.
In my case, i got wifi problem. make sure you have valid internet connection
I completely agree with pythoneer's answer here. But I have stumbled on some code that was flawed with circular imports and caused issues when trying to add unit tests. So to quickly patch it without changing everything you can resolve the issue by doing a dynamic import.
# Hack to import something without circular import issue
def load_module(name):
"""Load module using imp.find_module"""
names = name.split(".")
path = None
for name in names:
f, path, info = imp.find_module(name, path)
path = [path]
return imp.load_module(name, f, path[0], info)
constants = load_module("app.constants")
Again, this isn't a permanent fix but may help someone that wants to fix an import error without changing too much of the code.
Cheers!
I was pretty sure that you need to specify the NOLOCK
for each JOIN
in the query. But my experience was limited to SQL Server 2005.
When I looked up MSDN just to confirm, I couldn't find anything definite. The below statements do seem to make me think, that for 2008, your two statements above are equivalent though for 2005 it is not the case:
[SQL Server 2008 R2]
All lock hints are propagated to all the tables and views that are accessed by the query plan, including tables and views referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.
[SQL Server 2005]
In SQL Server 2005, all lock hints are propagated to all the tables and views that are referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.
Additionally, point to note - and this applies to both 2005 and 2008:
The table hints are ignored if the table is not accessed by the query plan. This may be caused by the optimizer choosing not to access the table at all, or because an indexed view is accessed instead. In the latter case, accessing an indexed view can be prevented by using the
OPTION (EXPAND VIEWS)
query hint.
by installing AspNetMVC4Setup.exe ( Here is the link :https://www.microsoft.com/en-us/download/details.aspx?id=30683) solves the issue.
by restart/reinstalling Microsoft.AspNet.Mvc Package doesn't help me.
open the CMD and use this command :
**
pip uninstall django
**
it will easy uninstalled .
b1 = (Button) findViewById(R.id.click_me);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivity(i);
}
});
Some Kotlin code to use supportFragmentManager inside a Fragment.
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
super.onCreateView(inflater, container, savedInstanceState)
val rootView = inflater.inflate(R.layout.fragment_home, container, false)
// ....
if (rootView.home_play_btn != null) {
rootView.home_play_btn.setOnClickListener {
val fragment: BaseFragment = ListFragment.newInstance()
val fragManager: FragmentManager = (activity as AppCompatActivity).supportFragmentManager
fragManager.beginTransaction()
.replace(R.id.content_home_frame, fragment, TAG).commit()
}
Below are the 3 different ways provided by HTML to insert empty space
to add a single space.  
to add 2 spaces. 
to add 4 spaces.This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.
In standard SQL one would write:
SELECT t0.foo, t1.bar
FROM FIRST_TABLE t0
RIGHT OUTER JOIN SECOND_TABLE t1;
Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :
Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]
git add B # Add it to the index
git reset A # Remove it from the index
git commit # Commit the index
As Cheese Bread suggested, use getActiveNetworkInfo()
getActiveNetworkInfo
Added in API level 1
NetworkInfo getActiveNetworkInfo ()
Returns details about the currently active default data network. When connected, this network is the default route for outgoing connections. You should always check isConnected() before initiating network traffic. This may return null when there is no default network. This method requires the caller to hold the permission ACCESS_NETWORK_STATE. Returns NetworkInfo a NetworkInfo object for the current default network or null if no default network is currently active.
Reference : Android Studio
public final boolean isInternetOn() {
// get Connectivity Manager object to check connection
ConnectivityManager connec =
(ConnectivityManager)getSystemService(getBaseContext().CONNECTIVITY_SERVICE);
// Check for network connections
if ( connec.getActiveNetworkInfo().getState() == android.net.NetworkInfo.State.CONNECTED ||
connec.getActiveNetworkInfo().getState() == android.net.NetworkInfo.State.CONNECTING ) {
// if connected with internet
Toast.makeText(this, connec.getActiveNetworkInfo().getTypeName(), Toast.LENGTH_LONG).show();
return true;
} else if (
connec.getActiveNetworkInfo().getState() == android.net.NetworkInfo.State.DISCONNECTED ||
connec.getActiveNetworkInfo().getState() == android.net.NetworkInfo.State.DISCONNECTED ) {
Toast.makeText(this, " Not Connected ", Toast.LENGTH_LONG).show();
return false;
}
return false;
}
now call the method , for safe use try catch
try {
if (isInternetOn()) { /* connected actions */ }
else { /* not connected actions */ }
} catch (Exception e){
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
And do not forget to add:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
I also tried using pymysql (on my Win7 x64 machine, Python 3.3), without too much luck. I downloaded the .tar.gz, extract, ran "setup.py install", and everything seemed fine. Until I tried connecting to a database, and got "KeyError [56]". An error which I was unable to find documented anywhere.
So I gave up on pymysql, and I settled on the Oracle MySQL connector.
It comes as a setup package, and works out of the box. And it also seems decently documented.
How about calling the .NET Framework methods?
You can do ANYTHING with them... :
[System.IO.File]::Copy($src, $dest, $true);
The $true
argument makes it overwrite.
Try the read
shell builtin:
read -p "Continue (y/n)?" CONT
if [ "$CONT" = "y" ]; then
echo "yaaa";
else
echo "booo";
fi
I have write a bash helper to write a nice bash tool
project home: https://gitlab.mbedsys.org/mbedsys/bashopts
example:
#!/bin/bash -ei
# load the library
. bashopts.sh
# Enable backtrace dusplay on error
trap 'bashopts_exit_handle' ERR
# Initialize the library
bashopts_setup -n "$0" -d "This is myapp tool description displayed on help message" -s "$HOME/.config/myapprc"
# Declare the options
bashopts_declare -n first_name -l first -o f -d "First name" -t string -i -s -r
bashopts_declare -n last_name -l last -o l -d "Last name" -t string -i -s -r
bashopts_declare -n display_name -l display-name -t string -d "Display name" -e "\$first_name \$last_name"
bashopts_declare -n age -l number -d "Age" -t number
bashopts_declare -n email_list -t string -m add -l email -d "Email adress"
# Parse arguments
bashopts_parse_args "$@"
# Process argument
bashopts_process_args
will give help:
NAME:
./example.sh - This is myapp tool description displayed on help message
USAGE:
[options and commands] [-- [extra args]]
OPTIONS:
-h,--help Display this help
-n,--non-interactive true Non interactive mode - [$bashopts_non_interactive] (type:boolean, default:false)
-f,--first "John" First name - [$first_name] (type:string, default:"")
-l,--last "Smith" Last name - [$last_name] (type:string, default:"")
--display-name "John Smith" Display name - [$display_name] (type:string, default:"$first_name $last_name")
--number 0 Age - [$age] (type:number, default:0)
--email Email adress - [$email_list] (type:string, default:"")
enjoy :)
You could also come up with something like this!
def get_logger(name=None):
default = "__app__"
formatter = logging.Formatter('%(levelname)s: %(asctime)s %(funcName)s(%(lineno)d) -- %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
log_map = {"__app__": "app.log", "__basic_log__": "file1.log", "__advance_log__": "file2.log"}
if name:
logger = logging.getLogger(name)
else:
logger = logging.getLogger(default)
fh = logging.FileHandler(log_map[name])
fh.setFormatter(formatter)
logger.addHandler(fh)
logger.setLevel(logging.DEBUG)
return logger
Now you could use multiple loggers in same module and across whole project if the above is defined in a separate module and imported in other modules were logging is required.
a=get_logger("__app___")
b=get_logger("__basic_log__")
a.info("Starting logging!")
b.debug("Debug Mode")
IF your Device is running Android v.4.1.2 or before,
the menu is not displayed in the action-bar.
But it can be accessed through the Menu-(hardware)-Button.
You should call this function from the controller.
angular.module('App', [])
.controller('CinemaCtrl', ['$scope', function($scope) {
myFunction();
}]);
Even with normal javascript/html your function won't run on page load as all your are doing is defining the function, you never call it. This is really nothing to do with angular, but since you're using angular the above would be the "angular way" to invoke the function.
Obviously better still declare the function in the controller too.
Edit: Actually I see your "onload" - that won't get called as angular injects the HTML into the DOM. The html is never "loaded" (or the page is only loaded once).
For your iphone You could use in your head balise :
"width=device-width"
It doesn't make a lot of sense, the original GAC was already quite capable of storing different versions of assemblies. And there's little reason to assume a program will ever accidentally reference the wrong assembly, all the .NET 4 assemblies got the [AssemblyVersion] bumped up to 4.0.0.0. The new in-process side-by-side feature should not change this.
My guess: there were already too many .NET projects out there that broke the "never reference anything in the GAC directly" rule. I've seen it done on this site several times.
Only one way to avoid breaking those projects: move the GAC. Back-compat is sacred at Microsoft.
Yes.
I use uncompyle6 decompile (even support latest Python 3.8.0):
uncompyle6 utils.cpython-38.pyc > utils.py
and the origin python and decompiled python comparing look like this:
so you can see, ALMOST same, decompile effect is VERY GOOD.
Copy the downloaded DLL file in a custom folder on your dev drive, then add the reference to your project using the Browse button in the Add Reference
dialog.
Be sure that the new reference has the Copy Local = True
.
The Add Reference
dialog could be opened right-clicking on the References item in your project in Solution Explorer
UPDATE AFTER SOME YEARS
At the present time the best way to resolve all those problems is through the
Manage NuGet packages menu command of Visual Studio 2017/2019.
You can right click on the References node of your project and select that command. From the Browse tab search for the library you want to use in the NuGet repository, click on the item if found and then Install it. (Of course you need to have a package for that DLL and this is not guaranteed to exist)
Add the following line in your .profile
file in your home directory (using vi ~/.profile
):
PATH=$PATH:/home/me/play
export PATH
Then, for the change to take effect, simply type in your terminal:
$ . ~/.profile
That should work:
>>> df = pd.DataFrame()
>>> data = pd.DataFrame({"A": range(3)})
>>> df.append(data)
A
0 0
1 1
2 2
But the append
doesn't happen in-place, so you'll have to store the output if you want it:
>>> df
Empty DataFrame
Columns: []
Index: []
>>> df = df.append(data)
>>> df
A
0 0
1 1
2 2
If you are encountering this issue with an application installed via conda, the solution (as stated in this bug report) is simply to install setup-tools with:
conda install setuptools
To handle the situation in which there is no wiring, beans are available with @Autowired
required
attribute set to false
.
But when using @Inject
, the Provider interface works with the bean which means that the bean is not injected directly but with the Provider.
This worked for me . In my case 2 tables foo and boo have to be joined based on 3 different columns.Please note in my case ,in boo the 3 common columns are not primary key
i.e., one to one mapping based on 3 different columns
@Entity
@Table(name = "foo")
public class foo implements Serializable
{
@Column(name="foocol1")
private String foocol1;
//add getter setter
@Column(name="foocol2")
private String foocol2;
//add getter setter
@Column(name="foocol3")
private String foocol3;
//add getter setter
private Boo boo;
private int id;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "brsitem_id", updatable = false)
public int getId()
{
return this.id;
}
public void setId(int id)
{
this.id = id;
}
@OneToOne
@JoinColumns(
{
@JoinColumn(updatable=false,insertable=false, name="foocol1", referencedColumnName="boocol1"),
@JoinColumn(updatable=false,insertable=false, name="foocol2", referencedColumnName="boocol2"),
@JoinColumn(updatable=false,insertable=false, name="foocol3", referencedColumnName="boocol3")
}
)
public Boo getBoo()
{
return boo;
}
public void setBoo(Boo boo)
{
this.boo = boo;
}
}
@Entity
@Table(name = "boo")
public class Boo implements Serializable
{
private int id;
@Column(name="boocol1")
private String boocol1;
//add getter setter
@Column(name="boocol2")
private String boocol2;
//add getter setter
@Column(name="boocol3")
private String boocol3;
//add getter setter
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "item_id", updatable = false)
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
}
There are a few existing resources you might check:
For what it's worth, my own personal guidelines that I tend to use are as follows:
A couple of other points:
Use htmlspecialchars(). Then quote and less / greater than symbols don't break your HTML tags~
Use smaller h
// 24 hrs
H:i
// output 14:20
// 12 hrs
h:i
// output 2:20
There is the accept attribute for the input tag. However, it is not reliable in any way. Browsers most likely treat it as a "suggestion", meaning the user will, depending on the file manager as well, have a pre-selection that only displays the desired types. They can still choose "all files" and upload any file they want.
For example:
<form>_x000D_
<input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />_x000D_
</form>
_x000D_
Read more in the HTML5 spec
Keep in mind that it is only to be used as a "help" for the user to find the right files. Every user can send any request he/she wants to your server. You always have to validated everything server-side.
So the answer is: no you cannot restrict, but you can set a pre-selection but you cannot rely on it.
Alternatively or additionally you can do something similar by checking the filename (value of the input field) with JavaScript, but this is nonsense because it provides no protection and also does not ease the selection for the user. It only potentially tricks a webmaster into thinking he/she is protected and opens a security hole. It can be a pain in the ass for users that have alternative file extensions (for example jpeg instead of jpg), uppercase, or no file extensions whatsoever (as is common on Linux systems).
Wrap the Parallel.Foreach
into a Task.Run()
and instead of the await
keyword use [yourasyncmethod].Result
(you need to do the Task.Run thing to not block the UI thread)
Something like this:
var yourForeachTask = Task.Run(() =>
{
Parallel.ForEach(ids, i =>
{
ICustomerRepo repo = new CustomerRepo();
var cust = repo.GetCustomer(i).Result;
customers.Add(cust);
});
});
await yourForeachTask;
In PostgreSQL 9.1, the idle connections with following query. It helped me to ward off the situation which warranted in restarting the database. This happens mostly with JDBC connections opened and not closed properly.
SELECT
pg_terminate_backend(procpid)
FROM
pg_stat_activity
WHERE
current_query = '<IDLE>'
AND
now() - query_start > '00:10:00';
static String toCamelCase(String s){
String[] parts = s.split(" ");
String camelCaseString = "";
for (String part : parts){
if(part!=null && part.trim().length()>0)
camelCaseString = camelCaseString + toProperCase(part);
else
camelCaseString=camelCaseString+part+" ";
}
return camelCaseString;
}
static String toProperCase(String s) {
String temp=s.trim();
String spaces="";
if(temp.length()!=s.length())
{
int startCharIndex=s.charAt(temp.indexOf(0));
spaces=s.substring(0,startCharIndex);
}
temp=temp.substring(0, 1).toUpperCase() +
spaces+temp.substring(1).toLowerCase()+" ";
return temp;
}
public static void main(String[] args) {
String string="HI tHiS is SomE Statement";
System.out.println(toCamelCase(string));
}
Below is the structure of SQL that you may write. You can do multiple joins by using "AND" or "OR".
Select TableA.Col1, TableA.Col2, TableB.Val
FROM TableA,
INNER JOIN TableB
ON TableA.Col1 = TableB.Col1 OR TableA.Col2 = TableB.Col2
Just incase anyone else stumbles across this, I use the fs-extra library in node and write javascript objects to a file like this:
const fse = require('fs-extra');
fse.outputJsonSync('path/to/output/file.json', objectToWriteToFile);
An adaption to @Mrchief's / @amit's answer, but for people using VB
Dim JSONOut As String = JsonConvert.SerializeObject(
myContainerObject,
New JsonSerializerSettings With {
.NullValueHandling = NullValueHandling.Ignore
}
)
See: "Object Initializers: Named and Anonymous Types (Visual Basic)"
Based on your comment, moddify this:
$( '.bgHeaderH2' ).html (); // will return whatever is inside the DIV
to:
$( '.bgHeaderH2', $( this ) ).html (); // will return whatever is inside the DIV
More about selectors: https://api.jquery.com/category/selectors/
If you're using ASP.NET 2.0 or greater, you can turn it on in the Web.config file. In the <system.web> section, add the following line:
<httpCookies httpOnlyCookies="true"/>
Keeping the element's size relative to its content can also be done with display: inline-flex
and display: table
The centering can be done with..
text-align: center;
on the parent (or above, it's inherited)
display: flex;
and justify-content: center;
on the parent
position: absolute;
left: 50%;
transform: translateX(-50%);
on
the element with position: relative; (at least) on the parent.
Here's a flexbox guide from CSS Tricks
Here's an article on centering from CSS Tricks.
Keeping an element only as wide as its content..
Can use display: table;
Or inline-anything including inline-flex
as used in my snippet
example below.
Keep in mind that when centering with flexbox's justify-content: center;
when the text wraps the text will align left. So you will still need text-align: center;
if your site is responsive and you expect lines to wrap.
body {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
height: 100vh;_x000D_
padding: 20px;_x000D_
}_x000D_
.container {_x000D_
display: flex;_x000D_
justify-content: center; /* center horizontally */_x000D_
align-items: center; /* center vertically */_x000D_
height: 50%;_x000D_
}_x000D_
.container.c1 {_x000D_
text-align: center; /* needed if the text wraps */_x000D_
/* text-align is inherited, it can be put on the parent or the target element */_x000D_
}_x000D_
.container.c2 {_x000D_
/* without text-align: center; */_x000D_
}_x000D_
.button {_x000D_
padding: 5px 10px;_x000D_
font-size: 30px;_x000D_
text-decoration: none;_x000D_
color: hsla(0, 0%, 90%, 1);_x000D_
background: linear-gradient(hsla(21, 85%, 51%, 1), hsla(21, 85%, 61%, 1));_x000D_
border-radius: 10px;_x000D_
box-shadow: 2px 2px 15px -5px hsla(0, 0%, 0%, 1);_x000D_
}_x000D_
.button:hover {_x000D_
background: linear-gradient(hsl(207.5, 84.8%, 51%), hsla(207, 84%, 62%, 1));_x000D_
transition: all 0.2s linear;_x000D_
}_x000D_
.button.b1 {_x000D_
display: inline-flex; /* element only as wide as content */_x000D_
}_x000D_
.button.b2 {_x000D_
display: table; /* element only as wide as content */_x000D_
}
_x000D_
<div class="container c1">_x000D_
<a class="button b1" href="https://stackoverflow.com/questions/27722872/">This Text Is Centered Before And After Wrap</a>_x000D_
</div>_x000D_
<div class="container c2">_x000D_
<a class="button b2" href="https://stackoverflow.com/questions/27722872/">This Text Is Centered Only Before Wrap</a>_x000D_
</div>
_x000D_
Fiddle
To show how much fun it is to create some functions that are fail fast I've written the following 3 functions.
One creates an AES key, one encodes it and one decodes it back. These three methods can be used with Java 8 (without dependence of internal classes or outside dependencies):
public static SecretKey generateAESKey(int keysize)
throws InvalidParameterException {
try {
if (Cipher.getMaxAllowedKeyLength("AES") < keysize) {
// this may be an issue if unlimited crypto is not installed
throw new InvalidParameterException("Key size of " + keysize
+ " not supported in this runtime");
}
final KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(keysize);
return keyGen.generateKey();
} catch (final NoSuchAlgorithmException e) {
// AES functionality is a requirement for any Java SE runtime
throw new IllegalStateException(
"AES should always be present in a Java SE runtime", e);
}
}
public static SecretKey decodeBase64ToAESKey(final String encodedKey)
throws IllegalArgumentException {
try {
// throws IllegalArgumentException - if src is not in valid Base64
// scheme
final byte[] keyData = Base64.getDecoder().decode(encodedKey);
final int keysize = keyData.length * Byte.SIZE;
// this should be checked by a SecretKeyFactory, but that doesn't exist for AES
switch (keysize) {
case 128:
case 192:
case 256:
break;
default:
throw new IllegalArgumentException("Invalid key size for AES: " + keysize);
}
if (Cipher.getMaxAllowedKeyLength("AES") < keysize) {
// this may be an issue if unlimited crypto is not installed
throw new IllegalArgumentException("Key size of " + keysize
+ " not supported in this runtime");
}
// throws IllegalArgumentException - if key is empty
final SecretKeySpec aesKey = new SecretKeySpec(keyData, "AES");
return aesKey;
} catch (final NoSuchAlgorithmException e) {
// AES functionality is a requirement for any Java SE runtime
throw new IllegalStateException(
"AES should always be present in a Java SE runtime", e);
}
}
public static String encodeAESKeyToBase64(final SecretKey aesKey)
throws IllegalArgumentException {
if (!aesKey.getAlgorithm().equalsIgnoreCase("AES")) {
throw new IllegalArgumentException("Not an AES key");
}
final byte[] keyData = aesKey.getEncoded();
final String encodedKey = Base64.getEncoder().encodeToString(keyData);
return encodedKey;
}
NPM has created a node_modules directory at '/home/jasonshark/' path.
From your question it looks like you wanted node_modules to be created in the current directory.
For that,
mkdir <project-name>
cd <project-name>
npm init
This will create package.json file at current pathOpen package.json & fill it something like below
{
"name": "project-name",
"version": "project-version",
"dependencies": {
"mongodb": "*"
}
}
Now do : npm install
OR npm update
Now it will create node_modules directory under folder 'project-name' you created.
If you want to get Syntax Error with line number, use this
error: function(xhr, status, error) {
alert(error);
}
You are just supposed to read the file and exec the code yourself. 2to3 current replaces
execfile("somefile.py", global_vars, local_vars)
as
with open("somefile.py") as f:
code = compile(f.read(), "somefile.py", 'exec')
exec(code, global_vars, local_vars)
(The compile call isn't strictly needed, but it associates the filename with the code object making debugging a little easier.)
See:
This is just because the application is built in non unicode language fonts and you are running the system on unicode fonts. change your default non unicode fonts to arabic by going in regional settings advanced tab in control panel. That will solve your problem.
The simplest way would be to convert your hexadecimal string to a byte array and use the File.WriteAllBytes
method.
Using the StringToByteArray()
method from this question, you'd do something like this:
string hexString = "0CFE9E69271557822FE715A8B3E564BE";
File.WriteAllBytes("output.dat", StringToByteArray(hexString));
The StringToByteArray
method is included below:
public static byte[] StringToByteArray(string hex) {
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
The function that it returns has a call signature, but you told Typescript to completely ignore that by adding : any
in its signature.
I believe that you will have to drop the foreign key constraints first. Then update all of the appropriate tables and remap them as they were.
ALTER TABLE [dbo.Details_tbl] DROP CONSTRAINT [FK_Details_tbl_User_tbl];
-- Perform more appropriate alters
ALTER TABLE [dbo.Details_tbl] ADD FOREIGN KEY (FK_Details_tbl_User_tbl)
REFERENCES User_tbl(appId);
-- Perform all appropriate alters to bring the key constraints back
However, unless memory is a really big issue, I would keep the identity as an INT. Unless you are 100% positive that your keys will never grow past the TINYINT restraints. Just a word of caution :)
In Bootstrap 4 (beta), use align-middle
. Refer to Bootstrap 4 Documentation on Vertical alignment:
Change the alignment of elements with the vertical-alignment utilities. Please note that vertical-align only affects inline, inline-block, inline-table, and table cell elements.
Choose from
.align-baseline
,.align-top
,.align-middle
,.align-bottom
,.align-text-bottom
, and.align-text-top
as needed.
I came across the same error after updating to the latest version of JQuery. Therefore I updated the jquery file I was working on, as stated in a previous answer, so it said .on("load")
instead of .load()
.
This fix isn't very stable and sometimes it didn't work for me. Therefore to fix this issue you should update your code from:
.load();
to
.trigger("load");
I got this fix from the following source: https://github.com/stevenwanderski/bxslider-4/pull/1024
using ClosedXML.Excel;
public ActionResult Downloadexcel()
{
var Emplist = JsonConvert.SerializeObject(dbcontext.Employees.ToList());
DataTable dt11 = (DataTable)JsonConvert.DeserializeObject(Emplist, (typeof(DataTable)));
dt11.TableName = "Emptbl";
FileContentResult robj;
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt11);
using (MemoryStream stream = new MemoryStream())
{
wb.SaveAs(stream);
var bytesdata = File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "myFileName.xlsx");
robj = bytesdata;
}
}
return Json(robj, JsonRequestBehavior.AllowGet);
}
Use this - "require command here" > log_file_name 2>&1
Detail description of redirection operator in Unix/Linux.
The > operator redirects the output usually to a file but it can be to a device. You can also use >> to append.
If you don't specify a number then the standard output stream is assumed but you can also redirect errors
> file redirects stdout to file
1> file redirects stdout to file
2> file redirects stderr to file
&> file redirects stdout and stderr to file
/dev/null is the null device it takes any input you want and throws it away. It can be used to suppress any output.
If you're using ZLib in your project, then you need to find :
#if 1
in zconf.h and replace(uncomment) it with :
#if HAVE_UNISTD_H /* ...the rest of the line
If it isn't ZLib I guess you should find some alternative way to do this. GL.
The Core KTX module provides extensions for common libraries that are part of the Android framework, androidx.core.view
among them.
dependencies {
implementation "androidx.core:core-ktx:{latest-version}"
}
The following extension functions are handy to deal with margins:
Note: they are all extension functions of
MarginLayoutParams
, so first you need to get and cast thelayoutParams
of your view:val params = (myView.layoutParams as ViewGroup.MarginLayoutParams)
setMargins()
extension function:Sets the margins of all axes in the ViewGroup
's MarginLayoutParams
. (The dimension has to be provided in pixels, see the last section if you want to work with dp)
inline fun MarginLayoutParams.setMargins(@Px size: Int): Unit
// E.g. 16px margins
params.setMargins(16)
updateMargins()
extension function:Updates the margins in the ViewGroup
's ViewGroup.MarginLayoutParams
.
inline fun MarginLayoutParams.updateMargins(
@Px left: Int = leftMargin,
@Px top: Int = topMargin,
@Px right: Int = rightMargin,
@Px bottom: Int = bottomMargin
): Unit
// Example: 8px left margin
params.updateMargins(left = 8)
updateMarginsRelative()
extension function:Updates the relative margins in the ViewGroup
's MarginLayoutParams
(start/end instead of left/right).
inline fun MarginLayoutParams.updateMarginsRelative(
@Px start: Int = marginStart,
@Px top: Int = topMargin,
@Px end: Int = marginEnd,
@Px bottom: Int = bottomMargin
): Unit
// E.g: 8px start margin
params.updateMargins(start = 8)
The following extension properties are handy to get the current margins:
inline val View.marginBottom: Int
inline val View.marginEnd: Int
inline val View.marginLeft: Int
inline val View.marginRight: Int
inline val View.marginStart: Int
inline val View.marginTop: Int
// E.g: get margin bottom
val bottomPx = myView1.marginBottom
dp
instead of px
:If you want to work with dp
(density-independent pixels) instead of px
, you will need to convert them first. You can easily do that with the following extension property:
val Int.px: Int
get() = (this * Resources.getSystem().displayMetrics.density).toInt()
Then you can call the previous extension functions like:
params.updateMargins(start = 16.px, end = 16.px, top = 8.px, bottom = 8.px)
val bottomDp = myView1.marginBottom.dp
Old answer:
In Kotlin you can declare an extension function like:
fun View.setMargins(
leftMarginDp: Int? = null,
topMarginDp: Int? = null,
rightMarginDp: Int? = null,
bottomMarginDp: Int? = null
) {
if (layoutParams is ViewGroup.MarginLayoutParams) {
val params = layoutParams as ViewGroup.MarginLayoutParams
leftMarginDp?.run { params.leftMargin = this.dpToPx(context) }
topMarginDp?.run { params.topMargin = this.dpToPx(context) }
rightMarginDp?.run { params.rightMargin = this.dpToPx(context) }
bottomMarginDp?.run { params.bottomMargin = this.dpToPx(context) }
requestLayout()
}
}
fun Int.dpToPx(context: Context): Int {
val metrics = context.resources.displayMetrics
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), metrics).toInt()
}
Then you can call it like:
myView1.setMargins(8, 16, 34, 42)
Or:
myView2.setMargins(topMarginDp = 8)
You can accomplish this (if I understand what you are trying to do) using dynamic SQL.
The trick is that you need to create a string containing the SQL statement. That's because the tablename has to specified in the actual SQL text, when you execute the statement. The table references and column references can't be supplied as parameters, those have to appear in the SQL text.
So you can use something like this approach:
SET @stmt = 'INSERT INTO @tmpTbl1 SELECT ' + @KeyValue
+ ' AS fld1 FROM tbl' + @KeyValue
EXEC (@stmt)
First, we create a SQL statement as a string. Given a @KeyValue of 'Foo', that would create a string containing:
'INSERT INTO @tmpTbl1 SELECT Foo AS fld1 FROM tblFoo'
At this point, it's just a string. But we can execute the contents of the string, as a dynamic SQL statement, using EXECUTE
(or EXEC
for short).
The old-school sp_executesql
procedure is an alternative to EXEC, another way to execute dymamic SQL, which also allows you to pass parameters, rather than specifying all values as literals in the text of the statement.
FOLLOWUP
EBarr points out (correctly and importantly) that this approach is susceptible to SQL Injection.
Consider what would happen if @KeyValue
contained the string:
'1 AS foo; DROP TABLE students; -- '
The string we would produce as a SQL statement would be:
'INSERT INTO @tmpTbl1 SELECT 1 AS foo; DROP TABLE students; -- AS fld1 ...'
When we EXECUTE that string as a SQL statement:
INSERT INTO @tmpTbl1 SELECT 1 AS foo;
DROP TABLE students;
-- AS fld1 FROM tbl1 AS foo; DROP ...
And it's not just a DROP TABLE that could be injected. Any SQL could be injected, and it might be much more subtle and even more nefarious. (The first attacks can be attempts to retreive information about tables and columns, followed by attempts to retrieve data (email addresses, account numbers, etc.)
One way to address this vulnerability is to validate the contents of @KeyValue, say it should contain only alphabetic and numeric characters (e.g. check for any characters not in those ranges using LIKE '%[^A-Za-z0-9]%'
. If an illegal character is found, then reject the value, and exit without executing any SQL.
I have a very well working solution for tables of max-width: 100%
.
Just use word-break: break-all;
for the table cells (except heading cells) to break all long text into several lines:
<!DOCTYPE html>
<html>
<head>
<style>
table {
max-width: 100%;
}
table td {
word-break: break-all;
}
</style>
</head>
<body>
<table border="1">
<tr>
<th><strong>Input</strong></th>
<th><strong>Output</strong></th>
</tr>
<tr>
<td>some text</td>
<td>12b6459fc6b4cabb4b1990be1a78e4dc5fa79c3a0fe9aa9f0386d673cfb762171a4aaa363b8dac4c33e0ad23e4830888</td>
</tr>
</table>
</body>
</html>
This will render like this (when the screen width is limited):
It's been a few years, and Chrome at least makes use of this attribute. This attribute is very useful from a usability standpoint as it will filter out the unnecessary files for the user, making their experience smoother. However, the user can still select "all files" from the type (or otherwise bypass the filter), thus you should always validate the file where it is actually used; If you're using it on the server, validate it there before using it. The user can always bypass any client-side scripting.
SELECT tab.*,
row_number() OVER () as rnum
FROM tab;
Here's the relevant section in the docs.
P.S. This, in fact, fully matches the answer in the referenced question.
I was brought here by a different problem. Whenever I tried to login, i got that message because instead of authenticating correctly I logged in as anonymous user. The solution to my problem was:
To see which user you are, and whose permissions you have:
select user(), current_user();
To delete the pesky anonymous user:
drop user ''@'localhost';
Just a Typing Error,
<script>
$("#intro").owlCarousel({
// Most important owl features
//Autoplay
autoPlay : 5000,
stopOnHover : false
)} ----- TYPO
</script>
It should be-
<script>
$("#intro").owlCarousel({
// Most important owl features
//Autoplay
autoPlay : 5000,
stopOnHover : false
}) ----- Correct
</script>
To create a proper, mysql, varchar 32 GUID
SecureRandom.uuid.gsub('-','').upcase
Add your button:
JButton close = new JButton("Close");
Add an ActionListener:
close.addActionListner(new CloseListener());
Add a class for the Listener implementing the ActionListener interface and override its main function:
private class CloseListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
//DO SOMETHING
System.exit(0);
}
}
This might be not the best way, but its a point to start. The class for example can be made public and not as a private class inside another one.
By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.
In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.
The client code must set the withCredentials
property on the XMLHttpRequest
to true
in order to give permission.
However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials
header. Responding with this header to true
means that the server allows cookies (or other user credentials) to be included on cross-origin requests.
You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.
Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).
I had the same error. To fix the error:
Gallery Menu
and select API Manager
.Credentials
and then click New Credentials
.Create Credentials
.API KEY
.Navigator Key
(there are more options; It depends on when consumed).You must use this new API Navigator Key
, generated by the system.
Lombok
supports var but it's still classified as experimental:
import lombok.experimental.var;
var number = 1; // Inferred type: int
number = 2; // Legal reassign since var is not final
number = "Hi"; // Compilation error since a string cannot be assigned to an int variable
System.out.println(number);
Here is a pitfall to avoid when trying to use it in IntelliJ IDEA
. It appears to work as expected though including auto completion and everything. Until there is a "non-hacky" solution (e.g. due to JEP 286: Local-Variable Type Inference), this might be your best bet right now.
Note that val
is support by Lombok
as well without modifying or creating a lombok.config
.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(didChangeTextViewText:)
name:UITextFieldTextDidChangeNotification object:nil];
- (void) didChangeTextViewText {
//do something
}
Deny from all
is an .htaccess command(the actual content of that file you are trying to view). Not a denial of being able to edit the file. Just reopen the .htaccess file in the text viewer of choice and make the alterations as you so desire, save it, then reupload it to your folder of choice.
Though I think inadvertently you are blocking even yourself from viewing said application once uploaded.
I would do something like:
order deny,allow
deny from all
allow from 127.0.0.1
which will deny everyone but the IP in the allow from
line, which you would change the IP to match your IP which you can obtain from http://www.whatismyip.com/ or similar site.
There may be a problem with Maven path configuration, if you used unix-like Operator System.
step 1: create new file in path ~/.bash_profile
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home
CLASSPAHT=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
PATH=$JAVA_HOME/bin:$PATH:
export JAVA_HOME
export CLASSPATH
export PATH
step 2: shell run source ~/.bash_profile
OR modify zsh config file(add new line: source ~/.bash_profile
)
You can use this:
NumberFormat formatter = new DecimalFormat("00");
String s = formatter.format(1); // ----> 01
I can give an example commonly seen in project.
Here, option --no-ff
(i.e. true merge) creates a new commit with multiple parents, and provides a better history tracking. Otherwise, --ff
(i.e. fast-forward merge) is by default.
$ git checkout master
$ git checkout -b newFeature
$ ...
$ git commit -m 'work from day 1'
$ ...
$ git commit -m 'work from day 2'
$ ...
$ git commit -m 'finish the feature'
$ git checkout master
$ git merge --no-ff newFeature -m 'add new feature'
$ git log
// something like below
commit 'add new feature' // => commit created at merge with proper message
commit 'finish the feature'
commit 'work from day 2'
commit 'work from day 1'
$ gitk // => see details with graph
$ git checkout -b anotherFeature // => create a new branch (*)
$ ...
$ git commit -m 'work from day 3'
$ ...
$ git commit -m 'work from day 4'
$ ...
$ git commit -m 'finish another feature'
$ git checkout master
$ git merge anotherFeature // --ff is by default, message will be ignored
$ git log
// something like below
commit 'work from day 4'
commit 'work from day 3'
commit 'add new feature'
commit 'finish the feature'
commit ...
$ gitk // => see details with graph
(*) Note that here if the newFeature
branch is re-used, instead of creating a new branch, git will have to do a --no-ff
merge anyway. This means fast forward merge is not always eligible.
Others worked for me, but this did:
Tag.find().sort('name', 1).run(onComplete);
You should be aware that in evaluating an expression containing integers, the temporary results from each stage of evaluation are also rounded to be integers. In your assignment to float m
, the value is only converted to the real-number capable float
type after the integer arithmetic. This means that, for example, 3 / 4 would already be a "0" value before becoming 0.0. You need to force the conversion to float to happen earlier. You can do this by using the syntax float(value)
on any of a.y
, b.y
, a.x
, b.x
, a.y - b.y
, or a.x - b.x
: it doesn't matter when it's done as long as one of the terms is a float before the division happens, e.g.
float m = float(a.y - b.y) / (a.x - b.x);
float m = (float(a.y) - b.y) / (a.x - b.x);
...etc...
You map your dispatcher on *.do:
<servlet-mapping>
<servlet-name>Dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
but your controller is mapped on an url without .do:
@RequestMapping("/editPresPage")
Try changing this to:
@RequestMapping("/editPresPage.do")
Specifically for boolean is*()
getters:
I've spend a lot of time on why neither below
@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
nor this
setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE);
setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE);
setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
worked for my Boolean Getter/Setter.
Solution is simple:
@JsonAutoDetect(isGetterVisibility = Visibility.NONE, ...
setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE);
UPDATE: spring-boot allowed configure it:
jackson:
visibility.field: any
visibility.getter: none
visibility.setter: none
visibility.is-getter: none
import datetime
def print_time():
parser = datetime.datetime.now()
return parser.strftime("%d-%m-%Y %H:%M:%S")
print(print_time())
# Output>
# 03-02-2021 22:39:28
Sometimes it's better to think like a parser, like T-SQL parser. While executing the statement, parser does not have any value in Pivot section and you can't have any check expression in that section. By the way, you can simply use this:
SELECT CLASS
, IsNull([AZ], 0)
, IsNull([CA], 0)
, IsNull([TX], 0)
FROM #TEMP
PIVOT (
SUM(DATA)
FOR STATE IN (
[AZ]
, [CA]
, [TX]
)
) AS PVT
ORDER BY CLASS
If you're attempting to start a SERVICE rather than activity, this worked for me:
Intent intent = new Intent();
intent.setClassName("com.example.otherapplication", "com.example.otherapplication.ServiceName");
context.startService(intent);
If you use the intent.setComponent(...) method as mentioned in other answers, you may get an "Implicit intents with startService are not safe" warning.
Just installed MongoDB via Homebrew. At the end of the installation console, you can see an output as follows:
To start mongodb:
brew services start mongodb
Or, if you don't want/need a background service you can just run:
mongod --config /usr/local/etc/mongod.conf
So, brew services start mongodb, managed to run MongoDB as a service for me.
One option is just to use the regex |
character to try to match each of the substrings in the words in your Series s
(still using str.contains
).
You can construct the regex by joining the words in searchfor
with |
:
>>> searchfor = ['og', 'at']
>>> s[s.str.contains('|'.join(searchfor))]
0 cat
1 hat
2 dog
3 fog
dtype: object
As @AndyHayden noted in the comments below, take care if your substrings have special characters such as $
and ^
which you want to match literally. These characters have specific meanings in the context of regular expressions and will affect the matching.
You can make your list of substrings safer by escaping non-alphanumeric characters with re.escape
:
>>> import re
>>> matches = ['$money', 'x^y']
>>> safe_matches = [re.escape(m) for m in matches]
>>> safe_matches
['\\$money', 'x\\^y']
The strings with in this new list will match each character literally when used with str.contains
.
System.getProperties()
can be overridden by calls to System.setProperty(String key, String value)
or with command line parameters -Dfile.separator=/
File.separator
gets the separator for the default filesystem.
FileSystems.getDefault()
gets you the default filesystem.
FileSystem.getSeparator()
gets you the separator character for the filesystem. Note that as an instance method you can use this to pass different filesystems to your code other than the default, in cases where you need your code to operate on multiple filesystems in the one JVM.
Unique ID with count information
import java.util.concurrent.atomic.AtomicLong;
public class RandomIdUtils {
private static AtomicLong atomicCounter = new AtomicLong();
public static String createId() {
String currentCounter = String.valueOf(atomicCounter.getAndIncrement());
String uniqueId = UUID.randomUUID().toString();
return uniqueId + "-" + currentCounter;
}
}
Dir has also shorter syntax to get an array of all files from directory:
Dir['dir/to/files/*'].each do |fname|
# do something with fname
end
I answered a very similar question:
https://stackoverflow.com/a/15982217/1467082
You simply need to iterate over the series' .Points
collection, and then you can assign the points' .Format.Fill.ForeColor.RGB
value based on whatever criteria you need.
UPDATED
The code below will color the chart per the screenshot. This only assumes three colors are used. You can add additional case statements for other color values, and update the assignment of myColor
to the appropriate RGB values for each.
Option Explicit
Sub ColorScatterPoints()
Dim cht As Chart
Dim srs As Series
Dim pt As Point
Dim p As Long
Dim Vals$, lTrim#, rTrim#
Dim valRange As Range, cl As Range
Dim myColor As Long
Set cht = ActiveSheet.ChartObjects(1).Chart
Set srs = cht.SeriesCollection(1)
'## Get the series Y-Values range address:
lTrim = InStrRev(srs.Formula, ",", InStrRev(srs.Formula, ",") - 1, vbBinaryCompare) + 1
rTrim = InStrRev(srs.Formula, ",")
Vals = Mid(srs.Formula, lTrim, rTrim - lTrim)
Set valRange = Range(Vals)
For p = 1 To srs.Points.Count
Set pt = srs.Points(p)
Set cl = valRange(p).Offset(0, 1) '## assume color is in the next column.
With pt.Format.Fill
.Visible = msoTrue
'.Solid 'I commented this out, but you can un-comment and it should still work
'## Assign Long color value based on the cell value
'## Add additional cases as needed.
Select Case LCase(cl)
Case "red"
myColor = RGB(255, 0, 0)
Case "orange"
myColor = RGB(255, 192, 0)
Case "green"
myColor = RGB(0, 255, 0)
End Select
.ForeColor.RGB = myColor
End With
Next
End Sub
Seems like the general query log is the file that you need. A good introduction to this is at http://dev.mysql.com/doc/refman/5.1/en/query-log.html
<?php
$xml = $argv[1];
$dom = new DOMDocument();
// Initial block (must before load xml string)
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
// End initial block
$dom->loadXML($xml);
$out = $dom->saveXML();
print_R($out);
I've had this exact same problem a few days ago. I eventually managed to solve it. I'm not quite sure how, but I'll tell you what I did anyway. Maybe it'll help you.
I started by downloading RVM. If you aren't using it yet, I highly recommend doing so. It basically creates a sandbox for a new separate installation of Ruby, RoR and RubyGems. In fact, you can have multiple installations simultaneously and instantly switch to one other. It works like a charm.
Why is this useful? Because you shouldn't mess with the default Ruby installation in OS X. The system depends on it. It's best to just leave the default Ruby and RoR installation alone and create a new one using RVM that you can use for your own development.
Once I created my separate Ruby installation, I just installed RoR, RubyGems and mysql, and it worked. For the exact steps I took, see my question: Installing Rails, MySQL, etc. everything goes wrong
Again: I don't know for certain this will solve your problem. But it certainly did the trick for me, and in any case using RVM is highly recommendable.
This variant looks more simple and elegant.
CollectionType typeReference =
TypeFactory.defaultInstance().constructCollectionType(List.class, Dto.class);
List<Dto> resultDto = objectMapper.readValue(content, typeReference);
If you want to insert a raw HTML string no matter how complex, you can use:
insertAdjacentHTML
, with appropriate first argument:
'beforebegin' Before the element itself. 'afterbegin' Just inside the element, before its first child. 'beforeend' Just inside the element, after its last child. 'afterend' After the element itself.
Hint: you can always call Element.outerHTML
to get the HTML string representing the element to be inserted.
An example of usage:
document.getElementById("foo").insertAdjacentHTML("beforeBegin",
"<div><h1>I</h1><h2>was</h2><h3>inserted</h3></div>");
Caution: insertAdjacentHTML
does not preserve listeners that where attached with .addEventLisntener
.
Note:drawRect
and fillRect
are different.
Draws the outline of the specified rectangle:
public void drawRect(int x,
int y,
int width,
int height)
Fills the specified rectangle. The rectangle is filled using the graphics context's current color:
public abstract void fillRect(int x,
int y,
int width,
int height)
This method is the simplest way for beginners to control Layouts rendering in your ASP.NET MVC application. We can identify the controller and render the Layouts as par controller, to do this we can write our code in _ViewStart file in the root directory of the Views folder. Following is an example shows how it can be done.
@{
var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
string cLayout = "";
if (controller == "Webmaster")
cLayout = "~/Views/Shared/_WebmasterLayout.cshtml";
else
cLayout = "~/Views/Shared/_Layout.cshtml";
Layout = cLayout;
}
Read Complete Article here "How to Render different Layout in ASP.NET MVC"
#mybox:hover { display: none; }
#mybox:hover { visibility: hidden; }
#mybox:hover { background: none; }
#mybox:hover { color: green; }
though it should be noted that IE6 and below wont listen to the hover when it's not on an A tag. For that you have to incorporate JavaScript to add a class to the div during the hover.
An even simpler solution to the above:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<color android:color="@color/semitransparent_white" />
</item>
<item>
<color android:color="@color/transparent" />
</item>
</selector>
Save that in the drawable folder and you're good to go.
Use SHOW VARIABLES
:
One-liner using TestRestTemplate.exchange function with parameters map.
restTemplate.exchange("/someUrl?id={id}", HttpMethod.GET, reqEntity, respType, ["id": id])
The params map initialized like this is a groovy initializer*
For anyone coming to this question wondering how to do this in Eclipse, You can remove the displayed text from the logCat using the button provided (often has a red X on the icon)
Hope this helps;
df1 = data.frame(CustomerId=c(1:10),
Hobby = c(rep("sing", 4), rep("pingpong", 3), rep("hiking", 3)),
Product=c(rep("Toaster",3),rep("Phone", 2), rep("Radio",3), rep("Stereo", 2)))
df2 = data.frame(CustomerId=c(2,4,6, 8, 10),State=c(rep("Alabama",2),rep("Ohio",1), rep("Cal", 2)),
like=c("sing", 'hiking', "pingpong", 'hiking', "sing"))
df3 = merge(df1, df2, by.x=c("CustomerId", "Hobby"), by.y=c("CustomerId", "like"))
Assuming df1$Hobby
and df2$like
mean the same thing.
Use nc command,
nc -zv <hostname/ip> <port/port range>
For example,
nc -zv localhost 27017-27019
or
nc -zv localhost 27017
You can also use telnet command
telnet <ip/host> port
you can just map like that
select * from tableA a
join tableB b on isnull(a.colID,'') = isnull(b.colId,'')
You can use the setsockopt function to set a timeout on receive operations:
SO_RCVTIMEO
Sets the timeout value that specifies the maximum amount of time an input function waits until it completes. It accepts a timeval structure with the number of seconds and microseconds specifying the limit on how long to wait for an input operation to complete. If a receive operation has blocked for this much time without receiving additional data, it shall return with a partial count or errno set to [EAGAIN] or [EWOULDBLOCK] if no data is received. The default for this option is zero, which indicates that a receive operation shall not time out. This option takes a timeval structure. Note that not all implementations allow this option to be set.
// LINUX
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
// WINDOWS
DWORD timeout = timeout_in_seconds * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);
// MAC OS X (identical to Linux)
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
Reportedly on Windows this should be done before calling bind
. I have verified by experiment that it can be done either before or after bind
on Linux and OS X.
Assuming i understand your question.
You can get the selected row using the DataGridView.SelectedRows
Collection. If your DataGridView allows only one selected, have a look at my sample.
DataGridView.SelectedRows Gets the collection of rows selected by the user.
if (dataGridView1.SelectedRows.Count != 0)
{
DataGridViewRow row = this.dataGridView1.SelectedRows[0];
row.Cells["ColumnName"].Value
}
use JavaScript setInterval
method:
setInterval(function(){ location.reload(); }, 3000);
Flex layout modes are not (fully) natively supported in IE yet. IE10 implements the "tween" version of the spec which is not fully recent, but still works.
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes
This CSS-Tricks article has some advice on cross-browser use of flexbox (including IE): http://css-tricks.com/using-flexbox/
edit: after a bit more research, IE10 flexbox layout mode implemented current to the March 2012 W3C draft spec: http://www.w3.org/TR/2012/WD-css3-flexbox-20120322/
The most current draft is a year or so more recent: http://dev.w3.org/csswg/css-flexbox/
I have tried to make note about these and have collected and written examples from a java perspective.
Putting it here for any java developer who is looking into the same subject.
if you have more than one element having a class name 'example', to remove classes of 'color-'in all of them you can do this:[using jquery]
var objs = $('html').find('.example');
for(index=0 ; index < obj1s.length ; index++){
objs[index].className = objs[index].className.replace(/col-[a-z1-9\-]*/,'');
}
if you don't put [a-z1-9-]* in your regex it won't remove the classes which have a number or some '-' in their names.
The problem you're running into is that you're trying to replace an entire row object. That is not allowed by the DataTable API. Instead you have to update the values in the columns of a row object. Or add a new row to the collection.
To update the column of a particular row you can access it by name or index. For instance you could write the following code to update the column "Foo" to be the value strVerse
dtResult.Rows(i)("Foo") = strVerse
All of the answers above break expected browser behavior. What most people want is something that will scroll to the top if it's a "new" page, but return to the previous position if you're getting there through the Back (or Forward) button.
If you assume HTML5 mode, this turns out to be easy (although I'm sure some bright folks out there can figure out how to make this more elegant!):
// Called when browser back/forward used
window.onpopstate = function() {
$timeout.cancel(doc_scrolling);
};
// Called after ui-router changes state (but sadly before onpopstate)
$scope.$on('$stateChangeSuccess', function() {
doc_scrolling = $timeout( scroll_top, 50 );
// Moves entire browser window to top
scroll_top = function() {
document.body.scrollTop = document.documentElement.scrollTop = 0;
}
The way it works is that the router assumes it is going to scroll to the top, but delays a bit to give the browser a chance to finish up. If the browser then notifies us that the change was due to a Back/Forward navigation, it cancels the timeout, and the scroll never occurs.
I used raw document
commands to scroll because I want to move to the entire top of the window. If you just want your ui-view
to scroll, then set autoscroll="my_var"
where you control my_var
using the techniques above. But I think most people will want to scroll the entire page if you are going to the page as "new".
The above uses ui-router, though you could use ng-route instead by swapping $routeChangeSuccess
for$stateChangeSuccess
.