Well there are lot of answeres already provided and lot are making sense too.
Some mentioned it is just warning and some giving a temp way to disable warnings. All that will work but add risk when number of transactions in your DB is high.
I came across similar situation today and here is the query I came up with...
declare
begin
execute immediate '
create table "TBL" ("ID" number not null)';
exception when others then
if SQLCODE = -955 then null; else raise; end if;
end;
/
This is simple, if exception come while running query it will be suppressed. and you can use same for SQL
or Oracle
.
See How to find event listeners on a DOM node.
In a nutshell, assuming at some point an event handler is attached to your element (eg): $('#foo').click(function() { console.log('clicked!') });
You inspect it like so:
jQuery 1.3.x
var clickEvents = $('#foo').data("events").click;
jQuery.each(clickEvents, function(key, value) {
console.log(value) // prints "function() { console.log('clicked!') }"
})
jQuery 1.4.x
var clickEvents = $('#foo').data("events").click;
jQuery.each(clickEvents, function(key, handlerObj) {
console.log(handlerObj.handler) // prints "function() { console.log('clicked!') }"
})
See jQuery.fn.data
(where jQuery stores your handler internally).
jQuery 1.8.x
var clickEvents = $._data($('#foo')[0], "events").click;
jQuery.each(clickEvents, function(key, handlerObj) {
console.log(handlerObj.handler) // prints "function() { console.log('clicked!') }"
})
ListViewItem.IsSelected = true;
ListViewItem.Focus();
I was seeing this unexpected token o
error because my (incomplete) code had run previously (live reload!) and set the particular keyed local storage value to [object Object]
instead of {}
. It wasn't until I changed keys, that things started working as expected. Alternatively, you can follow these instructions to delete the incorrectly set localStorage value.
try checking with any Url like add
in path and start activity if its works than you are adding wrong path
typedef std::string::value_type char_t;
char_t up_char( char_t ch )
{
return std::use_facet< std::ctype< char_t > >( std::locale() ).toupper( ch );
}
std::string toupper( const std::string &src )
{
std::string result;
std::transform( src.begin(), src.end(), std::back_inserter( result ), up_char );
return result;
}
const std::string src = "test test TEST";
std::cout << toupper( src );
Pandas offer a great way to manipulate tables, as you can make binning easy (binning a dataframe in pandas in Python) and calculate statistics. Other thing that is great in pandas is the Panel class that you can join series of layers with different properties and combine it using groupby function.
Is not nice to define textbox width without using CSS, be warned ;-)
<input type="text" name="d" value="4" size="4" />
You can recursively revert like this:
svn revert --recursive .
There is no way (without writing a creative script) to remove things that aren't under source control. I think the closest you could do is to iterate over all of the files, use then grep the result of svn list
, and if the grep fails, then delete it.
EDIT: The solution for the creative script is here: Automatically remove Subversion unversioned files
So you could create a script that combines a revert
with whichever answer in the linked question suits you best.
ES8(2017) try
obj = await (await fetch(url)).json();
async function load() {_x000D_
let url = 'https://my-json-server.typicode.com/typicode/demo/db';_x000D_
let obj = await (await fetch(url)).json();_x000D_
console.log(obj);_x000D_
}_x000D_
_x000D_
load();
_x000D_
you can handle errors by try-catch
async function load() {_x000D_
let url = 'http://query.yahooapis.com/v1/publ...';_x000D_
let obj = null;_x000D_
_x000D_
try {_x000D_
obj = await (await fetch(url)).json();_x000D_
} catch(e) {_x000D_
console.log('error');_x000D_
}_x000D_
_x000D_
console.log(obj);_x000D_
}_x000D_
_x000D_
load();
_x000D_
here you need to skip int 0 like following:
val = s.nextInt();
if ((val < min) && (val!=0)) {
min = val;
}
If loading via pip install mysql-connector
and leads an error Unable to find Protobuf include directory
then this would be useful pip install mysql-connector==2.1.4
mysql-connector
is obsolete, so use pip install mysql-connector-python
. Same here
I would like to suggest to use a single RecyclerView
and populate your list items dynamically. I've added a github project to describe how this can be done. You might have a look. While the other solutions will work just fine, I would like to suggest, this is a much faster and efficient way of showing multiple lists in a RecyclerView
.
The idea is to add logic in your onCreateViewHolder
and onBindViewHolder
method so that you can inflate proper view for the exact positions in your RecyclerView
.
I've added a sample project along with that wiki too. You might clone and check what it does. For convenience, I am posting the adapter that I have used.
public class DynamicListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int FOOTER_VIEW = 1;
private static final int FIRST_LIST_ITEM_VIEW = 2;
private static final int FIRST_LIST_HEADER_VIEW = 3;
private static final int SECOND_LIST_ITEM_VIEW = 4;
private static final int SECOND_LIST_HEADER_VIEW = 5;
private ArrayList<ListObject> firstList = new ArrayList<ListObject>();
private ArrayList<ListObject> secondList = new ArrayList<ListObject>();
public DynamicListAdapter() {
}
public void setFirstList(ArrayList<ListObject> firstList) {
this.firstList = firstList;
}
public void setSecondList(ArrayList<ListObject> secondList) {
this.secondList = secondList;
}
public class ViewHolder extends RecyclerView.ViewHolder {
// List items of first list
private TextView mTextDescription1;
private TextView mListItemTitle1;
// List items of second list
private TextView mTextDescription2;
private TextView mListItemTitle2;
// Element of footer view
private TextView footerTextView;
public ViewHolder(final View itemView) {
super(itemView);
// Get the view of the elements of first list
mTextDescription1 = (TextView) itemView.findViewById(R.id.description1);
mListItemTitle1 = (TextView) itemView.findViewById(R.id.title1);
// Get the view of the elements of second list
mTextDescription2 = (TextView) itemView.findViewById(R.id.description2);
mListItemTitle2 = (TextView) itemView.findViewById(R.id.title2);
// Get the view of the footer elements
footerTextView = (TextView) itemView.findViewById(R.id.footer);
}
public void bindViewSecondList(int pos) {
if (firstList == null) pos = pos - 1;
else {
if (firstList.size() == 0) pos = pos - 1;
else pos = pos - firstList.size() - 2;
}
final String description = secondList.get(pos).getDescription();
final String title = secondList.get(pos).getTitle();
mTextDescription2.setText(description);
mListItemTitle2.setText(title);
}
public void bindViewFirstList(int pos) {
// Decrease pos by 1 as there is a header view now.
pos = pos - 1;
final String description = firstList.get(pos).getDescription();
final String title = firstList.get(pos).getTitle();
mTextDescription1.setText(description);
mListItemTitle1.setText(title);
}
public void bindViewFooter(int pos) {
footerTextView.setText("This is footer");
}
}
public class FooterViewHolder extends ViewHolder {
public FooterViewHolder(View itemView) {
super(itemView);
}
}
private class FirstListHeaderViewHolder extends ViewHolder {
public FirstListHeaderViewHolder(View itemView) {
super(itemView);
}
}
private class FirstListItemViewHolder extends ViewHolder {
public FirstListItemViewHolder(View itemView) {
super(itemView);
}
}
private class SecondListHeaderViewHolder extends ViewHolder {
public SecondListHeaderViewHolder(View itemView) {
super(itemView);
}
}
private class SecondListItemViewHolder extends ViewHolder {
public SecondListItemViewHolder(View itemView) {
super(itemView);
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
if (viewType == FOOTER_VIEW) {
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_footer, parent, false);
FooterViewHolder vh = new FooterViewHolder(v);
return vh;
} else if (viewType == FIRST_LIST_ITEM_VIEW) {
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_first_list, parent, false);
FirstListItemViewHolder vh = new FirstListItemViewHolder(v);
return vh;
} else if (viewType == FIRST_LIST_HEADER_VIEW) {
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_first_list_header, parent, false);
FirstListHeaderViewHolder vh = new FirstListHeaderViewHolder(v);
return vh;
} else if (viewType == SECOND_LIST_HEADER_VIEW) {
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_second_list_header, parent, false);
SecondListHeaderViewHolder vh = new SecondListHeaderViewHolder(v);
return vh;
} else {
// SECOND_LIST_ITEM_VIEW
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_second_list, parent, false);
SecondListItemViewHolder vh = new SecondListItemViewHolder(v);
return vh;
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
try {
if (holder instanceof SecondListItemViewHolder) {
SecondListItemViewHolder vh = (SecondListItemViewHolder) holder;
vh.bindViewSecondList(position);
} else if (holder instanceof FirstListHeaderViewHolder) {
FirstListHeaderViewHolder vh = (FirstListHeaderViewHolder) holder;
} else if (holder instanceof FirstListItemViewHolder) {
FirstListItemViewHolder vh = (FirstListItemViewHolder) holder;
vh.bindViewFirstList(position);
} else if (holder instanceof SecondListHeaderViewHolder) {
SecondListHeaderViewHolder vh = (SecondListHeaderViewHolder) holder;
} else if (holder instanceof FooterViewHolder) {
FooterViewHolder vh = (FooterViewHolder) holder;
vh.bindViewFooter(position);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
int firstListSize = 0;
int secondListSize = 0;
if (secondList == null && firstList == null) return 0;
if (secondList != null)
secondListSize = secondList.size();
if (firstList != null)
firstListSize = firstList.size();
if (secondListSize > 0 && firstListSize > 0)
return 1 + firstListSize + 1 + secondListSize + 1; // first list header, first list size, second list header , second list size, footer
else if (secondListSize > 0 && firstListSize == 0)
return 1 + secondListSize + 1; // second list header, second list size, footer
else if (secondListSize == 0 && firstListSize > 0)
return 1 + firstListSize; // first list header , first list size
else return 0;
}
@Override
public int getItemViewType(int position) {
int firstListSize = 0;
int secondListSize = 0;
if (secondList == null && firstList == null)
return super.getItemViewType(position);
if (secondList != null)
secondListSize = secondList.size();
if (firstList != null)
firstListSize = firstList.size();
if (secondListSize > 0 && firstListSize > 0) {
if (position == 0) return FIRST_LIST_HEADER_VIEW;
else if (position == firstListSize + 1)
return SECOND_LIST_HEADER_VIEW;
else if (position == secondListSize + 1 + firstListSize + 1)
return FOOTER_VIEW;
else if (position > firstListSize + 1)
return SECOND_LIST_ITEM_VIEW;
else return FIRST_LIST_ITEM_VIEW;
} else if (secondListSize > 0 && firstListSize == 0) {
if (position == 0) return SECOND_LIST_HEADER_VIEW;
else if (position == secondListSize + 1) return FOOTER_VIEW;
else return SECOND_LIST_ITEM_VIEW;
} else if (secondListSize == 0 && firstListSize > 0) {
if (position == 0) return FIRST_LIST_HEADER_VIEW;
else return FIRST_LIST_ITEM_VIEW;
}
return super.getItemViewType(position);
}
}
There is another way of keeping your items in a single ArrayList
of objects so that you can set an attribute tagging the items to indicate which item is from first list and which one belongs to second list. Then pass that ArrayList
into your RecyclerView
and then implement the logic inside adapter to populate them dynamically.
Hope that helps.
It means that no rows will be returned if @region
is NULL
, when used in your first example, even if there are rows in the table where Region
is NULL
.
When ANSI_NULLS
is on (which you should always set on anyway, since the option to not have it on is going to be removed in the future), any comparison operation where (at least) one of the operands is NULL
produces the third logic value - UNKNOWN
(as opposed to TRUE
and FALSE
).
UNKNOWN
values propagate through any combining boolean operators if they're not already decided (e.g. AND
with a FALSE
operand or OR
with a TRUE
operand) or negations (NOT
).
The WHERE
clause is used to filter the result set produced by the FROM
clause, such that the overall value of the WHERE
clause must be TRUE
for the row to not be filtered out. So, if an UNKNOWN
is produced by any comparison, it will cause the row to be filtered out.
@user1227804's answer includes this quote:
If both sides of the comparison are columns or compound expressions, the setting does not affect the comparison.
from SET ANSI_NULLS
*
However, I'm not sure what point it's trying to make, since if two NULL
columns are compared (e.g. in a JOIN
), the comparison still fails:
create table #T1 (
ID int not null,
Val1 varchar(10) null
)
insert into #T1(ID,Val1) select 1,null
create table #T2 (
ID int not null,
Val1 varchar(10) null
)
insert into #T2(ID,Val1) select 1,null
select * from #T1 t1 inner join #T2 t2 on t1.ID = t2.ID and t1.Val1 = t2.Val1
The above query returns 0 rows, whereas:
select * from #T1 t1 inner join #T2 t2 on t1.ID = t2.ID and (t1.Val1 = t2.Val1 or t1.Val1 is null and t2.Val1 is null)
Returns one row. So even when both operands are columns, NULL
does not equal NULL
. And the documentation for =
doesn't have anything to say about the operands:
When you compare two
NULL
expressions, the result depends on theANSI_NULLS
setting:If
ANSI_NULLS
is set toON
, the result isNULL
1, following the ANSI convention that aNULL
(or unknown) value is not equal to anotherNULL
or unknown value.If
ANSI_NULLS
is set toOFF
, the result ofNULL
compared toNULL
isTRUE
.Comparing
NULL
to a non-NULL
value always results inFALSE
2.
However, both 1 and 2 are incorrect - the result of both comparisons is UNKNOWN
.
*The cryptic meaning of this text was finally discovered years later. What it actually means is that, for those comparisons, the setting has no effect and it always acts as if the setting were ON. Would have been clearer if it had stated that SET ANSI_NULLS OFF
was the setting that had no affect.
Should't the .htaccess
use add
instead of set
?
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
The return
exits the current function, but the iterations keeps on, so you get the "next" item that skips the if
and alerts the 4...
If you need to stop the looping, you should just use a plain for
loop like so:
$('button').click(function () {
var arr = [1, 2, 3, 4, 5];
for(var i = 0; i < arr.length; i++) {
var n = arr[i];
if (n == 3) {
break;
}
alert(n);
})
})
You can read more about js break & continue here: http://www.w3schools.com/js/js_break.asp
Inspired by AASoft's answer, I went out to improve it a bit more:
$i
and the comparison with 0
in every looptry..finally
block to always close the files in use$p
to reference the current directoryThese changes lead to the following code:
$p = (Get-Location).Path
(Measure-Command {
# Number of lines to skip
$skip = 1
$ins = New-Object System.IO.StreamReader ($p + "\test.log")
$outs = New-Object System.IO.StreamWriter ($p + "\test-1.log")
try {
# Skip the first N lines, but allow for fewer than N, as well
for( $s = 1; $s -le $skip -and !$ins.EndOfStream; $s++ ) {
$ins.ReadLine()
}
while( !$ins.EndOfStream ) {
$outs.WriteLine( $ins.ReadLine() )
}
}
finally {
$outs.Close()
$ins.Close()
}
}).TotalSeconds
The first change brought the processing time for my 60 MB file down from 5.3s
to 4s
. The rest of the changes is more cosmetic.
You should use Impersonation to elevate the state.
WindowsIdentity identity = new WindowsIdentity(accessToken);
WindowsImpersonationContext context = identity.Impersonate();
Don't forget to undo the impersonated context when you are done.
To display a value nicely, you can use the pprint module. The easiest way to dump all variables with it is to do
from pprint import pprint
pprint(globals())
pprint(locals())
If you are running in CGI, a useful debugging feature is the cgitb module, which displays the value of local variables as part of the traceback.
"exec nohup setsid your_command"
the nohup allows your_command to continue even though the process that launched may terminate first. If it does, the the SIGNUP signal will be sent to your_command causing it to terminate (unless it catches that signal and ignores it).
I encountered the same issue after XAMPP v3.2.1 installation. I do not have Skype as most people would believe, however as a Software Developer I assumed port 80 is already in use by my other apps. So I changed it by simply using the XAMPP Control Panel:
Click on the 'Config' button corresponding to the APACHE service and choose the first option 'Apache (httpd.conf)'. In the document that opens (using any text editor - except MS Word!), locate the text:
Listen 12.34.56.78:80
Listen 80
And change this to:
Listen 12.34.56.78:83
Listen 83
This can be any non-used port number. Thanks.
DLL Export Viewer by NirSoft can be used to display exported functions in a DLL.
This utility displays the list of all exported functions and their virtual memory addresses for the specified DLL files. You can easily copy the memory address of the desired function, paste it into your debugger, and set a breakpoint for this memory address. When this function is called, the debugger will stop in the beginning of this function.
High level consumers are registered into Zookeeper, so you can fetch a list from ZK, similarly to the way kafka-topics.sh
fetches the list of topics. I don't think there's a way to collect all consumers; any application sending in a few consume requests is actually a "consumer", and you cannot tell whether they are done already.
On the consumer side, there's a JMX metric exposed to monitor the lag. Also, there is Burrow for lag monitoring.
one fast and simple way is to make the div as
<div runat="server" id="MyDiv"></div>
and on code behind you set MyDiv.Visible=false
Catching Exception
will catch a RuntimeException
import image from './img/one.jpg';
class Icons extends React.Component{
render(){
return(
<img className='profile-image' alt='icon' src={image}/>
);
}
}
export default Icons;
The rules to avoid collision of names are both in the C++ standard (see Stroustrup book) and mentioned by C++ gurus (Sutter, etc.).
Because I did not want to deal with cases, and wanted a simple rule, I have designed a personal one that is both simple and correct:
When naming a symbol, you will avoid collision with compiler/OS/standard libraries if you:
Of course, putting your code in an unique namespace helps to avoid collision, too (but won't protect against evil macros)
(I use macros because they are the more code-polluting of C/C++ symbols, but it could be anything from variable name to class name)
#define _WRONG
#define __WRONG_AGAIN
#define RIGHT_
#define WRONG__WRONG
#define RIGHT_RIGHT
#define RIGHT_x_RIGHT
From the n3242.pdf file (I expect the final standard text to be similar):
17.6.3.3.2 Global names [global.names]
Certain sets of names and function signatures are always reserved to the implementation:
— Each name that contains a double underscore _ _ or begins with an underscore followed by an uppercase letter (2.12) is reserved to the implementation for any use.
— Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.
But also:
17.6.3.3.5 User-defined literal suffixes [usrlit.suffix]
Literal suffix identifiers that do not start with an underscore are reserved for future standardization.
This last clause is confusing, unless you consider that a name starting with one underscore and followed by a lowercase letter would be Ok if not defined in the global namespace...
I created a function that might help. All it does is imitate the alert but put an image instead of text.
function alertImage(imgsrc) {
$('.d').css({
'position': 'absolute',
'top': '0',
'left': '50%',
'-webkit-transform': 'translate(-50%, 0)'
});
$('.d').animate({
opacity: 0
}, 0)
$('.d').animate({
opacity: 1,
top: "10px"
}, 250)
$('.d').append('An embedded page on this page says')
$('.d').append('<br><img src="' + imgsrc + '">')
$('.b').css({
'position':'absolute',
'-webkit-transform': 'translate(-100%, -100%)',
'top':'100%',
'left':'100%',
'display':'inline',
'background-color':'#598cbd',
'border-radius':'4px',
'color':'white',
'border':'none',
'width':'66',
'height':'33'
})
}
<script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>
<div class="d"><button onclick="$('.d').html('')" class="b">OK</button></div>
.d{
font-size: 17px;
font-family: sans-serif;
}
.b{
display: none;
}
public static void writeStringAsFile(final String fileContents, String fileName) {
Context context = App.instance.getApplicationContext();
try {
FileWriter out = new FileWriter(new File(context.getFilesDir(), fileName));
out.write(fileContents);
out.close();
} catch (IOException e) {
Logger.logError(TAG, e);
}
}
public static String readFileAsString(String fileName) {
Context context = App.instance.getApplicationContext();
StringBuilder stringBuilder = new StringBuilder();
String line;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(new File(context.getFilesDir(), fileName)));
while ((line = in.readLine()) != null) stringBuilder.append(line);
} catch (FileNotFoundException e) {
Logger.logError(TAG, e);
} catch (IOException e) {
Logger.logError(TAG, e);
}
return stringBuilder.toString();
}
Although it may seem annoying (coming from C) that Java did not include unsigned byte in the language it really is no big deal since a simple "b & 0xFF" operation yields the unsigned value for (signed) byte b in the (rare) situations that it is actually needed. The bits don't actually change -- just the interpretation (which is important only when doing for example some math operations on the values).
Junit is included by default with Eclipse (at least the Java EE version I'm sure). You may just need to add the view to your perspective.
Run it through a fairly simple regex: [^a-zA-Z]
And then check it's length separately:
if(string.Length > 7)
AFAIK JSON.Net does not provide functionality for reading from a URL. So you need to do this in two steps:
using (var webClient = new System.Net.WebClient()) {
var json = webClient.DownloadString(URL);
// Now parse with JSON.Net
}
You can set the Main-Class attribute in the jar file's manifest to point to which file you want to run automatically.
Here is the code on how to merge two sorted linked lists headA and headB:
Node* MergeLists1(Node *headA, Node* headB)
{
Node *p = headA;
Node *q = headB;
Node *result = NULL;
Node *pp = NULL;
Node *qq = NULL;
Node *head = NULL;
int value1 = 0;
int value2 = 0;
if((headA == NULL) && (headB == NULL))
{
return NULL;
}
if(headA==NULL)
{
return headB;
}
else if(headB==NULL)
{
return headA;
}
else
{
while((p != NULL) || (q != NULL))
{
if((p != NULL) && (q != NULL))
{
int value1 = p->data;
int value2 = q->data;
if(value1 <= value2)
{
pp = p->next;
p->next = NULL;
if(result == NULL)
{
head = result = p;
}
else
{
result->next = p;
result = p;
}
p = pp;
}
else
{
qq = q->next;
q->next = NULL;
if(result == NULL)
{
head = result = q;
}
else
{
result->next = q;
result = q;
}
q = qq;
}
}
else
{
if(p != NULL)
{
pp = p->next;
p->next = NULL;
result->next = p;
result = p;
p = pp;
}
if(q != NULL)
{
qq = q->next;
q->next = NULL;
result->next = q;
result = q;
q = qq;
}
}
}
}
return head;
}
for i in iterator:
try:
# Do something.
pass
except:
# Continue to next iteration.
continue
In $('.editor-container').click(function (){})
, shouldn't var url = "/area/controller/MyEditAction";
be var url = "/area/controller/EditPartData";
?
I know this is an old question but still, I came across a similar problem and i realized that my "not working" css code in my bootstrapOverload.css
file was written after the media queries
. when I moved it above media queries it started working.
Just in case someone else is facing the same problem
...
for(int i=0;i<3;i++){ //Rows
for(int j=0;j<5;j++){ //Cols
printf("%<...>\t",var);
}
printf("\n");
}
...
considering that <...> would be d,e,f,s,c... etc datatype... X)
You just need to keep Program Files in double quote & rest of the command don't need any quote.
C:\"Program Files"\IAR Systems\Embedded Workbench 7.0\430\bin\icc430.exe F:\CP00 .....
I think that, this is the shortest way of addressing this problem. Here I have used ES6 arrow function with .filter to check the existence of newly adding username.
var arr = [{
id: 1,
username: 'fred'
}, {
id: 2,
username: 'bill'
}, {
id: 3,
username: 'ted'
}];
function add(name) {
var id = arr.length + 1;
if (arr.filter(item=> item.username == name).length == 0){
arr.push({ id: id, username: name });
}
}
add('ted');
console.log(arr);
<?php _x000D_
_x000D_
$terms = get_terms( array(_x000D_
'taxonomy' => 'product_cat',_x000D_
'hide_empty' => false,_x000D_
) ); // Get Terms_x000D_
_x000D_
foreach ($terms as $key => $value) _x000D_
{_x000D_
$metaterms = get_term_meta($value->term_id);_x000D_
$thumbnail_id = get_woocommerce_term_meta($value->term_id, 'thumbnail_id', true );_x000D_
$image = wp_get_attachment_url( $thumbnail_id );_x000D_
echo '<img src="'.$image.'" alt="" />';_x000D_
} // Get Images from woocommerce term meta_x000D_
_x000D_
?>
_x000D_
Use dt.days
to obtain the days attribute as integers.
For eg:
In [14]: s = pd.Series(pd.timedelta_range(start='1 days', end='12 days', freq='3000T'))
In [15]: s
Out[15]:
0 1 days 00:00:00
1 3 days 02:00:00
2 5 days 04:00:00
3 7 days 06:00:00
4 9 days 08:00:00
5 11 days 10:00:00
dtype: timedelta64[ns]
In [16]: s.dt.days
Out[16]:
0 1
1 3
2 5
3 7
4 9
5 11
dtype: int64
More generally - You can use the .components
property to access a reduced form of timedelta
.
In [17]: s.dt.components
Out[17]:
days hours minutes seconds milliseconds microseconds nanoseconds
0 1 0 0 0 0 0 0
1 3 2 0 0 0 0 0
2 5 4 0 0 0 0 0
3 7 6 0 0 0 0 0
4 9 8 0 0 0 0 0
5 11 10 0 0 0 0 0
Now, to get the hours
attribute:
In [23]: s.dt.components.hours
Out[23]:
0 0
1 2
2 4
3 6
4 8
5 10
Name: hours, dtype: int64
return
returns a value. It doesn't matter what name you gave to that value. Returning it just "passes it out" so that something else can use it. If you want to use it, you have to grab it from outside:
lst = defineAList()
useTheList(lst)
Returning list
from inside defineAList
doesn't mean "make it so the whole rest of the program can use that variable". It means "pass this variable out and give the rest of the program one chance to grab it and use it". You need to assign that value to something outside the function in order to make use of it. Also, because of this, there is no need to define your list ahead of time with list = []
. Inside defineAList
, you create a new list and return it; this list has no relationship to the one you defined with list = []
at the beginning.
Incidentally, I changed your variable name from list
to lst
. It's not a good idea to use list
as a variable name because that is already the name of a built-in Python type. If you make your own variable called list
, you won't be able to access the builtin one anymore.
One reason is that classes.dex is not found in the root of the .apk-package. Either
Both situations cause the termination because Android supposedly searches only in the root of the apk file. The confusion is because the build run of the .apk file was without an error message.
Core reasons for that error may be:
aapt.exe add ... bin/classes.dex
. Thats would be wrong because classes.dex is in a subfolder /bin of the created .apk file.I had a class in 4.6.1 refering an interface that was in 4.6.2... upgrading the class to 462 fixed it.
There is TKlerx's Android SQLite browser for Eclipse, and it's fully functional alongside Android Studio. I'll recommend it, because it is immensely practical.
To install it on Device Monitor, just place the JAR file in [Path to Android SDK folder]/sdk/tools/lib/monitor-[...]/plugins
.
If you take a look at the sources for django.contrib.auth.views.password_reset you'll see that it uses RequestContext
. The upshot is, you can use Context Processors to modify the context which may allow you to inject the information that you need.
The b-list has a good introduction to context processors.
Edit (I seem to have been confused about what the actual question was):
You'll notice that password_reset
takes a named parameter called template_name
:
def password_reset(request, is_admin_site=False,
template_name='registration/password_reset_form.html',
email_template_name='registration/password_reset_email.html',
password_reset_form=PasswordResetForm,
token_generator=default_token_generator,
post_reset_redirect=None):
Check password_reset for more information.
... thus, with a urls.py like:
from django.conf.urls.defaults import *
from django.contrib.auth.views import password_reset
urlpatterns = patterns('',
(r'^/accounts/password/reset/$', password_reset, {'template_name': 'my_templates/password_reset.html'}),
...
)
django.contrib.auth.views.password_reset
will be called for URLs matching '/accounts/password/reset'
with the keyword argument template_name = 'my_templates/password_reset.html'
.
Otherwise, you don't need to provide any context as the password_reset
view takes care of itself. If you want to see what context you have available, you can trigger a TemplateSyntax
error and look through the stack trace find the frame with a local variable named context
. If you want to modify the context then what I said above about context processors is probably the way to go.
In summary: what do you need to do to use your own template? Provide a template_name
keyword argument to the view when it is called. You can supply keyword arguments to views by including a dictionary as the third member of a URL pattern tuple.
It's possible using multiple handlers.
import logging
import auxiliary_module
# create logger with 'spam_application'
log = logging.getLogger('spam_application')
log.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
log.addHandler(fh)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
ch.setFormatter(formatter)
log.addHandler(ch)
log.info('creating an instance of auxiliary_module.Auxiliary')
a = auxiliary_module.Auxiliary()
log.info('created an instance of auxiliary_module.Auxiliary')
log.info('calling auxiliary_module.Auxiliary.do_something')
a.do_something()
log.info('finished auxiliary_module.Auxiliary.do_something')
log.info('calling auxiliary_module.some_function()')
auxiliary_module.some_function()
log.info('done with auxiliary_module.some_function()')
# remember to close the handlers
for handler in log.handlers:
handler.close()
log.removeFilter(handler)
Please see: https://docs.python.org/2/howto/logging-cookbook.html
Session.Abandon()
will destroy/kill the entire session.
Session.Clear()
removes/clears the session data (i.e. the keys and values from the current session) but the session will be alive.
Compare to Session.Abandon() method, Session.Clear() doesn't create the new session, it just make all variables in the session to NULL.
Session ID will remain same in both the cases, as long as the browser is not closed.
Session.RemoveAll()
It removes all keys and values from the session-state collection.
Session.Remove()
It deletes an item from the session-state collection.
Session.RemoveAt()
It deletes an item at a specified index from the session-state collection.
Session.TimeOut()
This property specifies the time-out period assigned to the Session object for the application. (the time will be specified in minutes).
If the user does not refresh or request a page within the time-out period, then the session ends.
Use the following command on your terminal (Ctrl + Alt + T
):-
$ conda activate
$ anaconda-navigator
If you don't mind using jQuery you can use the code bellow:
<script>
$(document).ready(function(){
$("#department").val("${requestScope.selectedDepartment}").attr('selected', 'selected');
});
</script>
<select id="department" name="department">
<c:forEach var="item" items="${dept}">
<option value="${item.key}">${item.value}</option>
</c:forEach>
</select>
In the your Servlet add the following:
request.setAttribute("selectedDepartment", YOUR_SELECTED_DEPARTMENT );
The command to ignore multiple entries is a little tricky and requires backslashes.
svn propset svn:ignore "cache\
tmp\
null\
and_so_on" .
This command will ignore anything named cache
, tmp
, null
, and and_so_on
in the current directory.
I'm not convinced its a good idea to return image data in a REST service. It ties up your application server's memory and IO bandwidth. Much better to delegate that task to a proper web server that is optimized for this kind of transfer. You can accomplish this by sending a redirect to the image resource (as a HTTP 302 response with the URI of the image). This assumes of course that your images are arranged as web content.
Having said that, if you decide you really need to transfer image data from a web service you can do so with the following (pseudo) code:
@Path("/whatever")
@Produces("image/png")
public Response getFullImage(...) {
BufferedImage image = ...;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
byte[] imageData = baos.toByteArray();
// uncomment line below to send non-streamed
// return Response.ok(imageData).build();
// uncomment line below to send streamed
// return Response.ok(new ByteArrayInputStream(imageData)).build();
}
Add in exception handling, etc etc.
You have to pass the -np
/--no-parent
option to wget
(in addition to -r
/--recursive
, of course), otherwise it will follow the link in the directory index on my site to the parent directory. So the command would look like this:
wget --recursive --no-parent http://example.com/configs/.vim/
To avoid downloading the auto-generated index.html
files, use the -R
/--reject
option:
wget -r -np -R "index.html*" http://example.com/configs/.vim/
In my case, along with Mekanik's suggestions, I was receiving this error in Windows Server 2012 and I had to tick "HTTP Activation" in "Add Role Services".
Merge commits: retains all of the commits in your branch and interleaves them with commits on the base branch
Merge Squash: retains the changes but omits the individual commits from history
Rebase: This moves the entire feature branch to begin on the tip of the master branch, effectively incorporating all of the new commits in master
More on here
well you can do this:
$(function(){
var $header = $('#header');
var $footer = $('#footer');
var $content = $('#content');
var $window = $(window).on('resize', function(){
var height = $(this).height() - $header.height() + $footer.height();
$content.height(height);
}).trigger('resize'); //on page load
});
see fiddle here: http://jsfiddle.net/maniator/JVKbR/
demo: http://jsfiddle.net/maniator/JVKbR/show/
JAXB is part of JDK standard edition version 1.6+. So it is FREE
and no extra libraries to download and manage.
A simple example can be found here
XStream seems to be dead. Last update was on Dec 6 2008.
Simple
seems as easy and simpler as JAXB but I could not find any licensing information to evaluate it for enterprise use.
In Eclipse v4.7 (Oxygen):
Window menu ? Editor ? Toggle Word Wrap (Shift+Alt+Y)
I get this too. I go to the directory (not in Eclipse) where the files are, go into the .svn dir and delete the file called lock.
Flip back to Eclipse and continue.
There is a similar question here Problems committing file to SVN repository
this is the approach that I used:
create pyspark session:
import pyspark
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName('changeColNames').getOrCreate()
create dataframe:
df = spark.createDataFrame(data = [('Bob', 5.62,'juice'), ('Sue',0.85,'milk')], schema = ["Name", "Amount","Item"])
view df with column names:
df.show()
+----+------+-----+
|Name|Amount| Item|
+----+------+-----+
| Bob| 5.62|juice|
| Sue| 0.85| milk|
+----+------+-----+
create a list with new column names:
newcolnames = ['NameNew','AmountNew','ItemNew']
change the column names of the df:
for c,n in zip(df.columns,newcolnames):
df=df.withColumnRenamed(c,n)
view df with new column names:
df.show()
+-------+---------+-------+
|NameNew|AmountNew|ItemNew|
+-------+---------+-------+
| Bob| 5.62| juice|
| Sue| 0.85| milk|
+-------+---------+-------+
Implementation 1 returns the magnitude of the vector that would result from a regular 3D cross product of the input vectors, taking their Z values implicitly as 0 (i.e. treating the 2D space as a plane in the 3D space). The 3D cross product will be perpendicular to that plane, and thus have 0 X & Y components (thus the scalar returned is the Z value of the 3D cross product vector).
Note that the magnitude of the vector resulting from 3D cross product is also equal to the area of the parallelogram between the two vectors, which gives Implementation 1 another purpose. In addition, this area is signed and can be used to determine whether rotating from V1 to V2 moves in an counter clockwise or clockwise direction. It should also be noted that implementation 1 is the determinant of the 2x2 matrix built from these two vectors.
Implementation 2 returns a vector perpendicular to the input vector still in the same 2D plane. Not a cross product in the classical sense but consistent in the "give me a perpendicular vector" sense.
Note that 3D euclidean space is closed under the cross product operation--that is, a cross product of two 3D vectors returns another 3D vector. Both of the above 2D implementations are inconsistent with that in one way or another.
Hope this helps...
This should about cut it (i'll leave the error handling to you):
int slashIndex = url.lastIndexOf('/');
int dotIndex = url.lastIndexOf('.', slashIndex);
String filenameWithoutExtension;
if (dotIndex == -1) {
filenameWithoutExtension = url.substring(slashIndex + 1);
} else {
filenameWithoutExtension = url.substring(slashIndex + 1, dotIndex);
}
A pkg-config file describes all necessary compile-time and link-time flags and dependencies needed to use a library.
pkg-config --static --libs glfw3
shows me that
-L/usr/local/lib -lglfw3 -lrt -lXrandr -lXinerama -lXi -lXcursor -lGL -lm -ldl -lXrender -ldrm -lXdamage -lX11-xcb -lxcb-glx -lxcb-dri2 -lxcb-dri3 -lxcb-present -lxcb-sync -lxshmfence -lXxf86vm -lXfixes -lXext -lX11 -lpthread -lxcb -lXau -lXdmcp
I don't know if all these libs are actually necessary for compiling but for me it works...
Linux/OS X:
Starting from the current directory, recursively find all files ending in .dll or .exe
find . -type f | grep -P "\.dll$|\.exe$"
Starting from the current directory, recursively find all files that DON'T end in .dll or .exe
find . -type f | grep -vP "\.dll$|\.exe$"
Notes:
(1) The P option in grep indicates that we are using the Perl style to write our regular expressions to be used in conjunction with the grep command. For the purpose of excecuting the grep command in conjunction with regular expressions, I find that the Perl style is the most powerful style around.
(2) The v option in grep instructs the shell to exclude any file that satisfies the regular expression
(3) The $ character at the end of say ".dll$" is a delimiter control character that tells the shell that the filename string ends with ".dll"
Here is the command that you are looking for, assuming your sequence for the product table is product_id_seq:
ALTER SEQUENCE product_id_seq RESTART WITH 1453;
Well, this should really be broken into 2 parts:
I'm not sure how you do it in Windows land, but in *nix land there are functions buried in the Bluez stack that let you receive notifications about when a new device appears, and send it the pairing code (clearly there have to be these functions: those are what the user interface use). Given sufficient time and experience I'm sure you could figure out how to write your own version of the Bluetooth Settings app that somehow:
All without having to pop up a user interface.
If you go ahead and write the code I'd LOVE to get my hands on it.
In Python 3.0–3.3 you would use: imp.reload(module)
The BDFL has answered this question.
However, imp
was deprecated in 3.4, in favour of importlib
(thanks @Stefan!).
I think, therefore, you’d now use importlib.reload(module)
, although I’m not sure.
If you want to export your last n amount of records into a file, you can run the following:
mysqldump -u user -p -h localhost --where "1=1 ORDER BY id DESC LIMIT 100" database table > export_file.sql
The above will save the last 100 records into export_file.sql, assuming the table you're exporting from has an auto-incremented id column.
You will need to alter the user, localhost, database and table values. You may optionally alter the id column and export file name.
For me the query that is working, if I want to compare with DrawDate for example is:
CAST(DrawDate AS DATE) = CAST (GETDATE() as DATE)
This is comparing results with today's date.
or the whole query:
SELECT TOP (1000) *
FROM test
where DrawName != 'NULL' and CAST(DrawDate AS DATE) = CAST (GETDATE() as DATE)
order by id desc
If you are on a 64bit build of ubuntu or debian (see e.g. 'cat /proc/version') you should simply use the 64bit cross compilers, if you cloned
git clone https://github.com/raspberrypi/tools
then the 64bit tools are in
tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64
use that directory for the gcc-toolchain. A useful tutorial for compiling that I followed is available here Building and compiling Raspberry PI Kernel (use the -x64 path from above as ${CCPREFIX})
Your code seems to be fine, make sure that key you specify really exists in the array or such key has a value in your array eg:
$array = array(4 => 'Hello There');
print_r(array_keys($array));
// or better
print_r($array);
Output:
Array
(
[0] => 4
)
Now:
$key = 4;
$value = $array[$key];
print $value;
Output:
Hello There
document.ready
is a jQuery event, it runs when the DOM is ready, e.g. all elements are there to be found/used, but not necessarily all content.window.onload
fires later (or at the same time in the worst/failing cases) when images and such are loaded, so if you're using image dimensions for example, you often want to use this instead.For me this was the fact that debug.writeline shows in the Immediate window, not the Output. My installation of VS2013 by default doesn't even show an option to open the Immediate window, so you have to do the following:
Select Tools -> Customize
Commands Tab
View | Other Windows menu bar dropdown
Add Command...
The Immediate option is in the Debug section.
Once you have Ok'd that, you can go to View -> Other Windows and select the Immediate Window and hey presto all of the debug output can be seen.
Unfortunately for me it also showed about 50 errors that I wasn't aware of in my project... maybe I'll just turn it off again :-)
class KeyStatisticCollection(DataDownloadUtilities.DataDownloadCollection):
def GenerateAddressStrings(self):
pass
def worker(self):
pass
def DownloadProc(self):
pass
Try with deleting pod it will try to pull image again.
kubectl delete pod <pod_name> -n <namespace_name>
Stealing from @Lila (couldn't make a comment because of no formatting), this shows the module's /path/, as well:
#!/usr/bin/env python
import sys
from modulefinder import ModuleFinder
finder = ModuleFinder()
# Pass the name of the python file of interest
finder.run_script(sys.argv[1])
# This is what's different from @Lila's script
finder.report()
which produces:
Name File
---- ----
...
m token /opt/rh/rh-python35/root/usr/lib64/python3.5/token.py
m tokenize /opt/rh/rh-python35/root/usr/lib64/python3.5/tokenize.py
m traceback /opt/rh/rh-python35/root/usr/lib64/python3.5/traceback.py
...
.. suitable for grepping or what have you. Be warned, it's long!
//String to Date Convert
var dateString = "2014-01-12"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.dateFromString(dateString)
println(s)
//CONVERT FROM NSDate to String
let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var dateString = dateFormatter.stringFromDate(date)
println(dateString)
Specify a size for the item and warehouse like in the [dbo].[testing1] FUNCTION
@trackingItems1 TABLE (
item nvarchar(25) NULL, -- 25 OR equal size of your item column
warehouse nvarchar(25) NULL, -- same as above
price int NULL
)
Since in MSSQL only saying only nvarchar is equal to nvarchar(1) hence the values of the column from the stock table are truncated
If the double is a Double
with capital D (a boxed primitive value):
Double d = 4.97542;
int i = (int) d.doubleValue();
// or directly:
int i2 = d.intValue();
If the double is already a primitive double
, then you simply cast it:
double d = 4.97542;
int i = (int) d;
Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:
240p 360p 480p 720p 1080p
Resolution 426 x 240 640 x 360 854x480 1280x720 1920x1080
Video Bitrates
Maximum 700 Kbps 1000 Kbps 2000 Kbps 4000 Kbps 6000 Kbps
Recommended 400 Kbps 750 Kbps 1000 Kbps 2500 Kbps 4500 Kbps
Minimum 300 Kbps 400 Kbps 500 Kbps 1500 Kbps 3000 Kbps
It would appear as though this is the case, although the numbers dont sync up to the google table above:
// the bitrates, video width and file names for this clip
bitrates: [
{ url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
{ url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
{ url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
],
I realize this question is old and has been answered to death, but here's my stab at it. I'm trying to reinvent the wheel here because I was using the currently accepted answer and the mishandling of URL fragments recently bit me in a project.
The function is below. It's quite long, but it was made to be as resilient as possible. I would love suggestions for shortening/improving it. I put together a small jsFiddle test suite for it (or other similar functions). If a function can pass every one of the tests there, I say it's probably good to go.
Update: I came across a cool function for using the DOM to parse URLs, so I incorporated that technique here. It makes the function shorter and more reliable. Props to the author of that function.
/**
* Add or update a query string parameter. If no URI is given, we use the current
* window.location.href value for the URI.
*
* Based on the DOM URL parser described here:
* http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
*
* @param (string) uri Optional: The URI to add or update a parameter in
* @param (string) key The key to add or update
* @param (string) value The new value to set for key
*
* Tested on Chrome 34, Firefox 29, IE 7 and 11
*/
function update_query_string( uri, key, value ) {
// Use window URL if no query string is provided
if ( ! uri ) { uri = window.location.href; }
// Create a dummy element to parse the URI with
var a = document.createElement( 'a' ),
// match the key, optional square brackets, an equals sign or end of string, the optional value
reg_ex = new RegExp( key + '((?:\\[[^\\]]*\\])?)(=|$)(.*)' ),
// Setup some additional variables
qs,
qs_len,
key_found = false;
// Use the JS API to parse the URI
a.href = uri;
// If the URI doesn't have a query string, add it and return
if ( ! a.search ) {
a.search = '?' + key + '=' + value;
return a.href;
}
// Split the query string by ampersands
qs = a.search.replace( /^\?/, '' ).split( /&(?:amp;)?/ );
qs_len = qs.length;
// Loop through each query string part
while ( qs_len > 0 ) {
qs_len--;
// Remove empty elements to prevent double ampersands
if ( ! qs[qs_len] ) { qs.splice(qs_len, 1); continue; }
// Check if the current part matches our key
if ( reg_ex.test( qs[qs_len] ) ) {
// Replace the current value
qs[qs_len] = qs[qs_len].replace( reg_ex, key + '$1' ) + '=' + value;
key_found = true;
}
}
// If we haven't replaced any occurrences above, add the new parameter and value
if ( ! key_found ) { qs.push( key + '=' + value ); }
// Set the new query string
a.search = '?' + qs.join( '&' );
return a.href;
}
This will work although when embedding PHP in HTML it is better practice to use the following form:
<table>
<?php foreach($array as $key=>$value): ?>
<tr>
<td><?= $key; ?></td>
</tr>
<?php endforeach; ?>
</table>
You can find the doc for the alternative syntax on PHP.net
If you want to prevent resize by dragging sizegrips and by the maximize button and by maximize by doubleclick on the header text, than insert the following code in the load event of the form:
Me.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle ' Prevent size grips
Me.MaximumSize = Me.Size ' Prevent maximize (also by doubleclick of header text)
Of course all choices of a formborderstyle beginning with Fixed will do.
timeout 5
to delay
timeout 5 >nul
to delay without asking you to press any key to cancel
Try this
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("outfilename"), "UTF-8"));
try {
out.write(aString);
} finally {
out.close();
}
Wrote a glitch workspace that iterates over all the codepoints and emit the character if eval('var ' + String.fromCodePoint(#) + ' = 1')
works.
It just keeps going, and going, and going....
To grab the device's IPv4 addresses, and filter to only grab ones that match your scheme (i.e. Ignore and APIPA addresses or the LocalHost address). You could say to grab the address matching 192.168.200.*
for example.
$IPv4Addr = Get-NetIPAddress -AddressFamily ipV4 | where {$_.IPAddress -like X.X.X.X} | Select IPAddress
Replace the zeros with nan
and then drop the rows with all entries as nan
.
After that replace nan
with zeros.
import numpy as np
df = df.replace(0, np.nan)
df = df.dropna(how='all', axis=0)
df = df.replace(np.nan, 0)
Using Node.js
sync mode:
var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")
async mode:
var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
var textByLine = text.split("\n")
});
UPDATE
As of at least Node 6, readFileSync
returns a Buffer
, so it must first be converted to a string in order for split
to work:
var text = fs.readFileSync("./mytext.txt").toString('utf-8');
Or
var text = fs.readFileSync("./mytext.txt", "utf-8");
Java Web Start is a good technology for installing Java rich clients off the internet direct to the end user's desktop (whether the OS is Windows, Mac or *nix). It comes complete with desktop integration and automatic updates, among many other goodies.
For more information on JWS, see the JWS info page.
I used KUE with socketIO like you described. I stored the socketID with the job and could then retreive it in the Job Complete.. KUE is based on redis and has good examples on github
something like this....
jobs.process('YourQueuedJob',10, function(job, done){ doTheJob(job, done); }); function doTheJob(job, done){ var socket = io.sockets.sockets[job.data.socketId]; try { socket.emit('news', { status : 'completed' , task : job.data.task }); } catch(err){ io.sockets.emit('news', { status : 'fail' , task : job.data.task , socketId: job.data.socketId}); } job.complete(); }
I am using Windows 10 Home edition.
I tried various combination,
netsh wlan show drivers
netsh wlan show hostednetwork
netsh wlan set hostednetwork mode=allow ssid=happy key=12345678
netsh wlan start hostednetwork
and also,
Control Panel\Network and Internet\Network Connections\Ethernet Properties\Sharing\Internet Connection Sharing\Allow other network users to connect through this computer Internet connection...
But still cannot activate WiFi hotspot.
While I have given up, somehow I click on Network icon on the taskbar, suddenly I see the buttons:
[ Wi-Fi ] [ Airplane Mode ] [ Mobile hotspot ]
Just like how our mobile phone can enable Mobile hotspot, Windows 10 has Mobile hotspot build-in. Just click on [ Mobile hotspot ] button and it works.
Bulk inserts in Mongoose can be done with .insert() unless you need to access middleware.
Model.collection.insert(docs, options, callback)
https://github.com/christkv/node-mongodb-native/blob/master/lib/mongodb/collection.js#L71-91
You can easily install update version if you use Anaconda by closing Spyder and then running the following command in a system terminal (Anaconda Prompt on Windows, xterm on Linux or Terminal.app on macOS):
conda install spyder= Your desire version
(For example, Version is 3.1)
conda install spyder=3.1
Or you can use pip with this command in a system terminal (cmd.exe on Windows, xterm on Linux or Terminal.app on macOS):
pip install --pre -U spyder
Note: Do not use this command if you are using Anaconda because it could break your installation.
For finding a simple string, using the indexOf() method and using regex is pretty much the same: http://jsperf.com/substring - so choose which ever one that seems easier to write.
What you could do is, create the "function" as another template file and then include that file passing the parameters to it.
Inside index.html
<h3> Latest Songs </h3>
{% include "song_player_list.html" with songs=latest_songs %}
Inside song_player_list.html
<ul>
{% for song in songs %}
<li>
<div id='songtile'>
<a href='/songs/download/{{song.id}}/'><i class='fa fa-cloud-download'></i> Download</a>
</div>
</li>
{% endfor %}
</ul>
Try to disable SELinux by this command /usr/sbin/setenforce 0
. In my case it solved the problem.
Replace These Headers
#include <iomanip.h>
#include <iomanip>
With These.
#include <iostream>
#include <iomanip>
using namespace std;
Thats it...!!!
No, IIRC there is no getopt() on Windows.
Boost, however, has the program_options library... which works okay. It will seem like overkill at first, but it isn't terrible, especially considering it can handle setting program options in configuration files and environment variables in addition to command line options.
The answer by @chepner will copy all the sub-directories irrespective of the fact if it contains the file or not. If you need to exclude the sub-directories that dont contain the file and still retain the directory structure, use
rsync -zarv --prune-empty-dirs --include "*/" --include="*.sh" --exclude="*" "$from" "$to"
just came across while browsing, might help you javascript-getting-and-setting-caret-position-in-textarea
. You can use it for textbox also.
suggestions of solving this problem is, If you already had installed app in your phone before downloading from google play.(obviously run from your code ) then first uninstal it. and then download and install app from google play . it worked for me .Thanks and regards.
To access properties and methods of a parent class use the base
keyword. So in your child class LoadData()
method you would do this:
public class Child : Parent
{
public void LoadData()
{
base.MyMethod(); // call method of parent class
base.CurrentRow = 1; // set property of parent class
// other stuff...
}
}
Note that you would also have to change the access modifier of your parent MyMethod()
to at least protected
for the child class to access it.
What about:
$('#play').click(function() {_x000D_
const audio = new Audio("https://freesound.org/data/previews/501/501690_1661766-lq.mp3");_x000D_
audio.play();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
ActiveX is only supported by IE - the other browsers use a plugin architecture called NPAPI. However, there's a cross-browser plugin framework called Firebreath that you might find useful.
I wrote this function for both copying (copyFileSync) or moving (renameSync) files recursively between directories:
// Copy files
copyDirectoryRecursiveSync(sourceDir, targetDir);
// Move files
copyDirectoryRecursiveSync(sourceDir, targetDir, true);
function copyDirectoryRecursiveSync(source, target, move) {
if (!fs.lstatSync(source).isDirectory())
return;
var operation = move ? fs.renameSync : fs.copyFileSync;
fs.readdirSync(source).forEach(function (itemName) {
var sourcePath = path.join(source, itemName);
var targetPath = path.join(target, itemName);
if (fs.lstatSync(sourcePath).isDirectory()) {
fs.mkdirSync(targetPath);
copyDirectoryRecursiveSync(sourcePath, targetDir);
}
else {
operation(sourcePath, targetPath);
}
});
}
Configuration Options:
$(document).ready(function () {
$("#companiesTable").dataTable({
"sPaginationType": "full_numbers",
"bJQueryUI": true,
"bAutoWidth": false, // Disable the auto width calculation
"aoColumns": [
{ "sWidth": "30%" }, // 1st column width
{ "sWidth": "30%" }, // 2nd column width
{ "sWidth": "40%" } // 3rd column width and so on
]
});
});
Specify the css for the table:
table.display {
margin: 0 auto;
width: 100%;
clear: both;
border-collapse: collapse;
table-layout: fixed; // add this
word-wrap:break-word; // add this
}
HTML:
<table id="companiesTable" class="display">
<thead>
<tr>
<th>Company name</th>
<th>Address</th>
<th>Town</th>
</tr>
</thead>
<tbody>
<% for(Company c: DataRepository.GetCompanies()){ %>
<tr>
<td><%=c.getName()%></td>
<td><%=c.getAddress()%></td>
<td><%=c.getTown()%></td>
</tr>
<% } %>
</tbody>
</table>
It works for me!
@article = user.articles.build(:title => "MainTitle")
@article.save
This not the best way to manage session in react you can use web tokens to encrypt your data that you want save,you can use various number of services available a popular one is JSON web tokens(JWT) with web-tokens you can logout after some time if there no action from the client And after creating the token you can store it in your local storage for ease of access.
jwt.sign({user}, 'secretkey', { expiresIn: '30s' }, (err, token) => {
res.json({
token
});
user object in here is the user data which you want to keep in the session
localStorage.setItem('session',JSON.stringify(token));
I think MAVEN_OPTS
would be most appropriate for you. See here: http://maven.apache.org/configure.html
In Unix:
Add the
MAVEN_OPTS
environment variable to specify JVM properties, e.g.export MAVEN_OPTS="-Xms256m -Xmx512m"
. This environment variable can be used to supply extra options to Maven.
In Win, you need to set environment variable via the dialogue box
Add ... environment variable by opening up the system properties (
WinKey + Pause
),... In the same dialog, add theMAVEN_OPTS
environment variable in the user variables to specify JVM properties, e.g. the value-Xms256m -Xmx512m
. This environment variable can be used to supply extra options to Maven.
here is my solution:
// Controller_x000D_
$scope.uploadImg = function( files ) {_x000D_
$scope.data.avatar = files[0];_x000D_
}_x000D_
_x000D_
$scope.update = function() {_x000D_
var formData = new FormData();_x000D_
formData.append('desc', data.desc);_x000D_
formData.append('avatar', data.avatar);_x000D_
SomeService.upload( formData );_x000D_
}_x000D_
_x000D_
_x000D_
// Service_x000D_
upload: function( formData ) {_x000D_
var deferred = $q.defer();_x000D_
var url = "/upload" ;_x000D_
_x000D_
var request = {_x000D_
"url": url,_x000D_
"method": "POST",_x000D_
"data": formData,_x000D_
"headers": {_x000D_
'Content-Type' : undefined // important_x000D_
}_x000D_
};_x000D_
_x000D_
console.log(request);_x000D_
_x000D_
$http(request).success(function(data){_x000D_
deferred.resolve(data);_x000D_
}).error(function(error){_x000D_
deferred.reject(error);_x000D_
});_x000D_
return deferred.promise;_x000D_
}_x000D_
_x000D_
_x000D_
// backend use express and multer_x000D_
// a part of the code_x000D_
var multer = require('multer');_x000D_
var storage = multer.diskStorage({_x000D_
destination: function (req, file, cb) {_x000D_
cb(null, '../public/img')_x000D_
},_x000D_
filename: function (req, file, cb) {_x000D_
cb(null, file.fieldname + '-' + Date.now() + '.jpg');_x000D_
}_x000D_
})_x000D_
_x000D_
var upload = multer({ storage: storage })_x000D_
app.post('/upload', upload.single('avatar'), function(req, res, next) {_x000D_
// do something_x000D_
console.log(req.body);_x000D_
res.send(req.body);_x000D_
});
_x000D_
<div>_x000D_
<input type="file" accept="image/*" onchange="angular.element( this ).scope().uploadImg( this.files )">_x000D_
<textarea ng-model="data.desc" />_x000D_
<button type="button" ng-click="update()">Update</button>_x000D_
</div>
_x000D_
This worked for me
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if(tag.equalsIgnoreCase("dashboard")){
DashboardFragment dashboardFragment = (DashboardFragment)
fragmentManager.findFragmentByTag("dashboard");
if(dashboardFragment!=null) ft.show(dashboardFragment);
ShowcaseFragment showcaseFragment = (ShowcaseFragment)
fragmentManager.findFragmentByTag("showcase");
if(showcaseFragment!=null) ft.hide(showcaseFragment);
} else if(tag.equalsIgnoreCase("showcase")){
DashboardFragment dashboardFragment = (DashboardFragment)
fragmentManager.findFragmentByTag("dashboard");
if(dashboardFragment!=null) ft.hide(dashboardFragment);
ShowcaseFragment showcaseFragment = (ShowcaseFragment)
fragmentManager.findFragmentByTag("showcase");
if(showcaseFragment!=null) ft.show(showcaseFragment);
}
ft.commit();
Best explained here.
http://www.w3schools.com/php/func_mysql_real_escape_string.asp
http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php
It generally it helps to avoid SQL injection, for example consider the following code:
<?php
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);
// We didn't check $_POST['password'], it could be anything the user wanted! For example:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";
// This means the query sent to MySQL would be:
echo $query;
?>
and a hacker can send a query like:
SELECT * FROM users WHERE user='aidan' AND password='' OR ''=''
This would allow anyone to log in without a valid password.
You can use ~ (tilde operator) to exclude the rows sampled using df.sample(), letting pandas alone handle sampling and filtering of indexes, to obtain two sets.
train_df = df.sample(frac=0.8, random_state=100)
test_df = df[~df.index.isin(train_df.index)]
As some of my servers are on an old Ubuntu LTS versions, I can't easily upgrade git to the latest version (which supports the -C option as described in some answers).
This trick works well for me, especially because it does not have the side effect of some other answers that leave you in a different directory from where you started.
pushd /X/Y
git pull
popd
Or, doing it as a one-liner:
pushd /X/Y; git pull; popd
Both Linux and Windows have pushd and popd commands.
>/dev/null 2>&1
will mute both stdout
and stderr
yum install nano >/dev/null 2>&1
You can use negated character classes to exclude certain characters: for example [^abcde]
will match anything but a,b,c,d,e characters.
Instead of specifying all the characters literally, you can use shorthands inside character classes: [\w]
(lowercase) will match any "word character" (letter, numbers and underscore), [\W]
(uppercase) will match anything but word characters; similarly, [\d]
will match the 0-9 digits while [\D]
matches anything but the 0-9 digits, and so on.
If you use PHP you can take a look at the regex character classes documentation.
Data Storage:
Specify the utf8mb4
character set on all tables and text columns in your database. This makes MySQL physically store and retrieve values encoded natively in UTF-8. Note that MySQL will implicitly use utf8mb4
encoding if a utf8mb4_*
collation is specified (without any explicit character set).
In older versions of MySQL (< 5.5.3), you'll unfortunately be forced to use simply utf8
, which only supports a subset of Unicode characters. I wish I were kidding.
Data Access:
In your application code (e.g. PHP), in whatever DB access method you use, you'll need to set the connection charset to utf8mb4
. This way, MySQL does no conversion from its native UTF-8 when it hands data off to your application and vice versa.
Some drivers provide their own mechanism for configuring the connection character set, which both updates its own internal state and informs MySQL of the encoding to be used on the connection—this is usually the preferred approach. In PHP:
If you're using the PDO abstraction layer with PHP = 5.3.6, you can specify charset
in the DSN:
$dbh = new PDO('mysql:charset=utf8mb4');
If you're using mysqli, you can call set_charset()
:
$mysqli->set_charset('utf8mb4'); // object oriented style
mysqli_set_charset($link, 'utf8mb4'); // procedural style
If you're stuck with plain mysql but happen to be running PHP = 5.2.3, you can call mysql_set_charset
.
If the driver does not provide its own mechanism for setting the connection character set, you may have to issue a query to tell MySQL how your application expects data on the connection to be encoded: SET NAMES 'utf8mb4'
.
The same consideration regarding utf8mb4
/utf8
applies as above.
Output:
If your application transmits text to other systems, they will also need to be informed of the character encoding. With web applications, the browser must be informed of the encoding in which data is sent (through HTTP response headers or HTML metadata).
In PHP, you can use the default_charset
php.ini option, or manually issue the Content-Type
MIME header yourself, which is just more work but has the same effect.
When encoding the output using json_encode()
, add JSON_UNESCAPED_UNICODE
as a second parameter.
Input:
Unfortunately, you should verify every received string as being valid UTF-8 before you try to store it or use it anywhere. PHP's mb_check_encoding()
does the trick, but you have to use it religiously. There's really no way around this, as malicious clients can submit data in whatever encoding they want, and I haven't found a trick to get PHP to do this for you reliably.
From my reading of the current HTML spec, the following sub-bullets are not necessary or even valid anymore for modern HTML. My understanding is that browsers will work with and submit data in the character set specified for the document. However, if you're targeting older versions of HTML (XHTML, HTML4, etc.), these points may still be useful:
accept-charset
attribute to all your <form>
tags: <form ... accept-charset="UTF-8">
.<form>
tag.Other Code Considerations:
Obviously enough, all files you'll be serving (PHP, HTML, JavaScript, etc.) should be encoded in valid UTF-8.
You need to make sure that every time you process a UTF-8 string, you do so safely. This is, unfortunately, the hard part. You'll probably want to make extensive use of PHP's mbstring
extension.
PHP's built-in string operations are not by default UTF-8 safe. There are some things you can safely do with normal PHP string operations (like concatenation), but for most things you should use the equivalent mbstring
function.
To know what you're doing (read: not mess it up), you really need to know UTF-8 and how it works on the lowest possible level. Check out any of the links from utf8.com for some good resources to learn everything you need to know.
It took me some time to get the conversion working both ways, so here are the two extension methods I came up with:
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Media.Imaging;
public static class BitmapConversion {
public static Bitmap ToWinFormsBitmap(this BitmapSource bitmapsource) {
using (MemoryStream stream = new MemoryStream()) {
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bitmapsource));
enc.Save(stream);
using (var tempBitmap = new Bitmap(stream)) {
// According to MSDN, one "must keep the stream open for the lifetime of the Bitmap."
// So we return a copy of the new bitmap, allowing us to dispose both the bitmap and the stream.
return new Bitmap(tempBitmap);
}
}
}
public static BitmapSource ToWpfBitmap(this Bitmap bitmap) {
using (MemoryStream stream = new MemoryStream()) {
bitmap.Save(stream, ImageFormat.Bmp);
stream.Position = 0;
BitmapImage result = new BitmapImage();
result.BeginInit();
// According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed."
// Force the bitmap to load right now so we can dispose the stream.
result.CacheOption = BitmapCacheOption.OnLoad;
result.StreamSource = stream;
result.EndInit();
result.Freeze();
return result;
}
}
}
You want your change to sit on top of the current state of the remote branch. So probably you want to pull right before you commit yourself. After that, push your changes again.
"Dirty" local files are not an issue as long as there aren't any conflicts with the remote branch. If there are conflicts though, the merge will fail, so there is no risk or danger in pulling before committing local changes.
Space characters may only be encoded as "+" in one context: application/x-www-form-urlencoded key-value pairs.
The RFC-1866 (HTML 2.0 specification), paragraph 8.2.1. subparagraph 1. says: "The form field names and values are escaped: space characters are replaced by `+', and then reserved characters are escaped").
Here is an example of such a string in URL where RFC-1866 allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses (in other cases, spaces should be encoded to %20). This way of encoding form data is also given in later HTML specifications, for example, look for relevant paragraphs about application/x-www-form-urlencoded in HTML 4.01 Specification, and so on.
But, because it's hard to always correctly determine the context, it's the best practice to never encode spaces as "+". It's better to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3. Here is a code example that illustrates what should be encoded. It is given in Delphi (pascal) programming language, but it is very easy to understand how it works for any programmer regardless of the language possessed:
(* percent-encode all unreserved characters as defined in RFC-3986, p.2.3 *)
function UrlEncodeRfcA(const S: AnsiString): AnsiString;
const
HexCharArrA: array [0..15] of AnsiChar = '0123456789ABCDEF';
var
I: Integer;
c: AnsiChar;
begin
// percent-encoding, see RFC-3986, p. 2.1
Result := S;
for I := Length(S) downto 1 do
begin
c := S[I];
case c of
'A' .. 'Z', 'a' .. 'z', // alpha
'0' .. '9', // digit
'-', '.', '_', '~':; // rest of unreserved characters as defined in the RFC-3986, p.2.3
else
begin
Result[I] := '%';
Insert('00', Result, I + 1);
Result[I + 1] := HexCharArrA[(Byte(C) shr 4) and $F)];
Result[I + 2] := HexCharArrA[Byte(C) and $F];
end;
end;
end;
end;
function UrlEncodeRfcW(const S: UnicodeString): AnsiString;
begin
Result := UrlEncodeRfcA(Utf8Encode(S));
end;
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "your api goes here",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer eyJ0eciOiJSUzI1NiJ9.eyJMiIsInNjb3BlcyI6W119.K3lW1STQhMdxfAxn00E4WWFA3uN3iIA"
),
));
$response = curl_exec($curl);
$data = json_decode($response, true);
echo $data;
?>
So I used python3 -m pip install matplotlib' then
import matplotlib.pyplot as plt` and it worked.
This is for the icon in the browser (most of the sites omit the type):
<link rel="icon" type="image/vnd.microsoft.icon"
href="http://example.com/favicon.ico" />
or
<link rel="icon" type="image/png"
href="http://example.com/image.png" />
or
<link rel="apple-touch-icon"
href="http://example.com//apple-touch-icon.png">
for the shortcut icon:
<link rel="shortcut icon"
href="http://example.com/favicon.ico" />
Place them in the <head></head>
section.
Edit may 2019 some additional examples from MDN
Not sure if this matters to anyone else, but I prefer the id for the table to be the first column in the database. The syntax for that is:
ALTER TABLE your_db.your_table ADD COLUMN `id` int(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT FIRST;
Which is just a slight improvement over the first answer. If you wanted it to be in a different position, then
ALTER TABLE unique_address ADD COLUMN `id` int(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT AFTER some_other_column;
HTH, -ft
Java libs makes it almost a one liner to read the public cert, as generated by openssl:
val certificate: X509Certificate = ByteArrayInputStream(
publicKeyCert.toByteArray(Charsets.US_ASCII))
.use {
CertificateFactory.getInstance("X.509")
.generateCertificate(it) as X509Certificate
}
But, o hell, reading the private key was problematic:
RSAPrivateKey
.see this: Final solution in kotlin
http://css-tricks.com/perfect-full-page-background-image/
//HTML
<img src="images/bg.jpg" id="bg" alt="">
//CSS
#bg {
position: fixed;
top: 0;
left: 0;
/* Preserve aspet ratio */
min-width: 100%;
min-height: 100%;
}
OR
img.bg {
/* Set rules to fill background */
min-height: 100%;
min-width: 1024px;
/* Set up proportionate scaling */
width: 100%;
height: auto;
/* Set up positioning */
position: fixed;
top: 0;
left: 0;
}
@media screen and (max-width: 1024px) { /* Specific to this particular image */
img.bg {
left: 50%;
margin-left: -512px; /* 50% */
}
}
OR
//HTML
<img src="images/bg.jpg" id="bg" alt="">
//CSS
#bg { position: fixed; top: 0; left: 0; }
.bgwidth { width: 100%; }
.bgheight { height: 100%; }
//jQuery
$(window).load(function() {
var theWindow = $(window),
$bg = $("#bg"),
aspectRatio = $bg.width() / $bg.height();
function resizeBg() {
if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
$bg
.removeClass()
.addClass('bgheight');
} else {
$bg
.removeClass()
.addClass('bgwidth');
}
}
theWindow.resize(resizeBg).trigger("resize");
});
The concatenation operator '&' is allowed on the right side of the signal assignment operator '<=', only
Jonathan from the ExcelCentral forums suggests:
=WEEKNUM(A1,2)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),2)+1
This formula extracts the week of the year [...] and then subtracts it from the week of the first day in the month to get the week of the month. You can change the day that weeks begin by changing the second argument of both WEEKNUM functions (set to 2 [for Monday] in the above example). For weeks beginning on Sunday, use:
=WEEKNUM(A1,1)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),1)+1
For weeks beginning on Tuesday, use:
=WEEKNUM(A1,12)-WEEKNUM(DATE(YEAR(A1),MONTH(A1),1),12)+1
etc.
I like it better because it's using the built in week calculation functionality of Excel (WEEKNUM).
Slightly modified Danny's solution for easier reading and understanding
from datetime import date
def calculate_age(birth_date):
today = date.today()
age = today.year - birth_date.year
full_year_passed = (today.month, today.day) < (birth_date.month, birth_date.day)
if not full_year_passed:
age -= 1
return age
In Rails 3.0.5, the following approach worked for me:
In config/environments/development.rb
, write
config.custom_config_key = :config_value
The value custom_config_key
can then be referenced from other files using
Rails.application.config.custom_config_key
(Neither IN
nor ANY
is an "operator". A "construct" or "syntax element".)
Logically, quoting the manual:
IN
is equivalent to= ANY
.
But there are two syntax variants of IN
and two variants of ANY
. Details:
IN
taking a set is equivalent to = ANY
taking a set, as demonstrated here:
But the second variant of each is not equivalent to the other. The second variant of the ANY
construct takes an array (must be an actual array type), while the second variant of IN
takes a comma-separated list of values. This leads to different restrictions in passing values and can also lead to different query plans in special cases:
ANY
is more versatileThe ANY
construct is far more versatile, as it can be combined with various operators, not just =
. Example:
SELECT 'foo' LIKE ANY('{FOO,bar,%oo%}');
For a big number of values, providing a set scales better for each:
Related:
"Find rows where id
is in the given array":
SELECT * FROM tbl WHERE id = ANY (ARRAY[1, 2]);
Inversion: "Find rows where id
is not in the array":
SELECT * FROM tbl WHERE id <> ALL (ARRAY[1, 2]);
SELECT * FROM tbl WHERE id <> ALL ('{1, 2}'); -- equivalent array literal
SELECT * FROM tbl WHERE NOT (id = ANY ('{1, 2}'));
All three equivalent. The first with array constructor, the other two with array literal. The data type can be derived from context unambiguously. Else, an explicit cast may be required, like '{1,2}'::int[]
.
Rows with id IS NULL
do not pass either of these expressions. To include NULL
values additionally:
SELECT * FROM tbl WHERE (id = ANY ('{1, 2}')) IS NOT TRUE;
Simple filter something like this (use numeric class on input end filter charchter in []):
<script type="text/javascript">
// Only allow number input
$('.numeric').keyup(function () {
this.value = this.value.replace(/[^0-9+-\.\,\;\:\s()]/g, ''); // this is filter for telefon number !!!
});
To disable a single rule for the rest of the file below:
/* eslint no-undef: "off"*/
const uploadData = new FormData();
I had a similar error but with different context when I uploaded a *.p file to Google Drive. I tried to use it later in a Google Colab session, and got this error:
1 with open("/tmp/train.p", mode='rb') as training_data:
----> 2 train = pickle.load(training_data)
UnpicklingError: invalid load key, '<'.
I solved it by compressing the file, upload it and then unzip on the session. It looks like the pickle file is not saved correctly when you upload/download it so it gets corrupted.
I know that there is already a solution to this question, but I found an alternative to this issue and maybe it could help someone.
I was having trouble with setting the frame of my sub view because certain values were referring to its position within the main view. So if you don't want to update your frame by changing the whole frame via CGRect, you can simply change a value of the frame and then update it.
// keep reference to you frames
var questionView = questionFrame.frame
var answerView = answerFrame.frame
// update the values of the copy
questionView.size.height = CGFloat(screenSize.height * 0.70)
answerView.size.height = CGFloat(screenSize.height * 0.30)
// set the frames to the new frames
questionFrame.frame = questionView
answerFrame.frame = answerView
I think it may be worth mentioning that [ConditionalAttribute]
is in the System.Diagnostics;
namespace. I stumbled a bit when I got:
Error 2 The type or namespace name 'ConditionalAttribute' could not be found (are you missing a using directive or an assembly reference?)
after using it for the first time (I thought it would have been in System
).
In order to trap repeated clicks on the same cell, you need to move the focus to a different cell, so that each time you click, you are in fact moving the selection.
The code below will select the top left cell visible on the screen, when you click on any cell. Obviously, it has the flaw that it won't trap a click on the top left cell, but that can be managed (eg by selecting the top right cell if the activecell is the top left).
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'put your code here to process the selection, then..
ActiveWindow.VisibleRange.Cells(1, 1).Select
End Sub
I had to puzzle my way through self-signed certificates on Windows by combining bits and pieces from the given answers and further resources. Here is my own (and hopefully complete) walk-through. Hope it will spare you some of my own painful learning curve. It also contains infos on related topics that will pop up sooner or later when you create your own certs.
Don't use makecert.exe. It has been deprecated by Microsoft.
The modern way uses a Powershell command.
Windows 10:
Open Powershell with Administrator privileges:
New-SelfSignedCertificate -DnsName "*.dev.local", "dev.local", "localhost" -CertStoreLocation cert:\LocalMachine\My -FriendlyName "Dev Cert *.dev.local, dev.local, localhost" -NotAfter (Get-Date).AddYears(15)
Windows 8, Windows Server 2012 R2:
In Powershell on these systems the parameters -FriendlyName and -NotAfter do not exist. Simply remove them from the above command line.
Open Powershell with Administrator privileges:
New-SelfSignedCertificate -DnsName "*.dev.local", "dev.local", "localhost" -CertStoreLocation cert:\LocalMachine\My
An alternative is to use the method for older Windows version below, which allows you to use all the features of Win 10 for cert creation...
Older Windows versions:
My recommendation for older Windows versions is to create the cert on a Win 10 machine, export it to a .PFX file using an mmc instance (see "Trust the certificate" below) and import it into the cert store on the target machine with the old Windows OS. To import the cert do NOT right-click it. Although there is an "Import certificate" item in the context menu, it failed all my trials to use it on Win Server 2008. Instead open another mmc instance on the target machine, navigate to "Certificates (Local Computer) / Personal / Certificates", right click into the middle pane and select All tasks ? Import.
Both of the above commands create a certificate for the domains localhost
and *.dev.local
.
The Win10 version additionally has a live time of 15 years and a readable display name of "Dev Cert *.dev.local, dev.local, localhost".
Update: If you provide multiple hostname entries in parameter -DnsName
(as shown above) the first of these entries will become the domain's Subject (AKA Common Name). The complete list of all hostname entries will be stored in the field Subject Alternative Name (SAN) of the certificate. (Thanks to @BenSewards for pointing that out.)
After creation the cert will be immediately available in any HTTPS bindings of IIS (instructions below).
The new cert is not part of any chain of trust and is thus not considered trustworthy by any browsers. To change that, we will copy the cert to the certificate store for Trusted Root CAs on your machine:
Open mmc.exe, File ? Add/Remove Snap-In ? choose "Certificates" in left column ? Add ? choose "Computer Account" ? Next ? "Local Computer..." ? Finish ? OK
In the left column choose "Certificates (Local Computer) / Personal / Certificates".
Find the newly created cert (in Win 10 the column "Friendly name" may help).
Select this cert and hit Ctrl-C to copy it to clipboard.
In the left column choose "Certificates (Local Computer) / Trusted Root CAs / Certificates".
Hit Ctrl-V to paste your certificate to this store.
The certificate should appear in the list of Trusted Root Authorities and is now considered trustworthy.
Now you may go to IIS Manager, select the bindings of a local website ? Add ? https ? enter a host name of the form myname.dev.local
(your cert is only valid for *.dev.local
) and select the new certificate ? OK.
Add to hosts
Also add your host name to C:\Windows\System32\drivers\etc\hosts:
127.0.0.1 myname.dev.local
Happy
Now Chrome and IE should treat the certificate as trustworthy and load your website when you open up https://myname.dev.local
.
Firefox maintains its own certificate store. To add your cert here, you must open your website in FF and add it to the exceptions when FF warns you about the certificate.
For Edge browser there may be more action needed (see further down).
To test your certs, Firefox is your best choice. (Believe me, I'm a Chrome fan-boy myself, but FF is better in this case.)
Here are the reasons:
The certificate is not trusted because it is self-signed.
This warning is correct! As noted above, Firefox does not use the Windows certificate store and will only trust this certificate, if you add an exception for it. The button to do this is right below the warnings.
The certificate is not valid for the name ...
This warning shows, that you did something wrong. The (wildcard) domain of your certificate does not match the domain of your website. The problem must be solved by either changing your website's (sub-)domain or by issuing a new certificate that matches. In fact you could add an exception in FF even if the cert does not match, but you would never get a green padlock symbol in Chrome with such a combination.
Firefox can display many other nice and understandable cert warnings at this place, like expired certs, certs with outdated signing algorithms, etc. I found no other browser that gave me that level of feedback to nail down any problems.
In the above New-SelfSignedCertificate command we used the wildcard domain *.dev.local
.
You may think: Why not use *.local
?
Simple reason: It is illegal as a wildcard domain.
Wildcard certificates must contain at least a second level domain name.
So, domains of the form *.local
are nice to develop HTTP websites. But not so much for HTTPS, because you would be forced to issue a new matching certificate for each new project that you start.
Important side notes:
motör_head.dev.local
to your wildcard pattern *.dev.local
. They will comply when you switch to motoer-head.dev.local
.*.dev.local
matches myname.dev.local
but NOT other.myname.dev.local
! *.*.dev.local
) are NOT possible in certificates.
So other.myname.dev.local
can only be covered by a wildcard of the form *.myname.dev.local
. As a result, it is best not to use a forth level domain part. Put all your variations into the third level part. This way you will get along with a single certificate for all your dev sites.This is not really about self-signed certificates, but still related to the whole process:
After following the above steps, Edge may not show any content when you open up myname.dev.local
.
The reason is a characteristic feature of the network management of Windows 10 for Modern Apps, called "Network Isolation".
To solve that problem, open a command prompt with Administrator privileges and enter the following command once:
CheckNetIsolation LoopbackExempt -a -n=Microsoft.MicrosoftEdge_8wekyb3d8bbwe
More infos about Edge and Network Isolation can be found here: https://blogs.msdn.microsoft.com/msgulfcommunity/2015/07/01/how-to-debug-localhost-on-microsoft-edge/
You have to check if you have the folder with name manager
inside the folder webapps
in your tomcat.
Rubens-MacBook-Pro:tomcat rfanjul$ ls -la webapps/
total 16
drwxr-xr-x 8 rfanjul staff 272 21 May 12:20 .
drwxr-xr-x 14 rfanjul staff 476 21 May 12:22 ..
-rw-r--r--@ 1 rfanjul staff 6148 21 May 12:20 .DS_Store
drwxr-xr-x 19 rfanjul staff 646 17 Feb 15:13 ROOT
drwxr-xr-x 51 rfanjul staff 1734 17 Feb 15:13 docs
drwxr-xr-x 6 rfanjul staff 204 17 Feb 15:13 examples
drwxr-xr-x 7 rfanjul staff 238 17 Feb 15:13 host-manager
drwxr-xr-x 8 rfanjul staff 272 17 Feb 15:13 manager
After that you will be sure that you have this permmint for you user in the file conf/tomcat-users.xml
:
<role rolename="admin-gui"/>
<role rolename="manager-gui"/>
<user username="test" password="test" roles="admin-gui,manager-gui"/>
restart tomcat and stat tomcat again.
sh bin/shutdown.sh
sh bin/startup.sh
I hope that will works fine for you.
You can use zip
:
>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> for x, y in zip(a, b):
... print x, y
...
1 a
2 b
3 c
I really wanted to respond to @Sev's answer.
Sev is right, there is a bug inside the window.history.replaceState
To fix this simply rewrite the constructor to set the title manually.
var replaceState_tmp = window.history.replaceState.constructor;
window.history.replaceState.constructor = function(obj, title, url){
var title_ = document.getElementsByTagName('title')[0];
if(title_ != undefined){
title_.innerHTML = title;
}else{
var title__ = document.createElement('title');
title__.innerHTML = title;
var head_ = document.getElementsByTagName('head')[0];
if(head_ != undefined){
head_.appendChild(title__);
}else{
var head__ = document.createElement('head');
document.documentElement.appendChild(head__);
head__.appendChild(title__);
}
}
replaceState_tmp(obj,title, url);
}
Have you tried setting the spacing to zero?
/*alternating row*/
table, tr, td, th {margin:0;border:0;padding:0;spacing:0;}
tr.rowhighlight {background-color:#f0f8ff;margin:0;border:0;padding:0;spacing:0;}
You have:
foreach (var category in Model.Categories)
and then
@foreach (var product in Model)
Based on that view and model it seems that Model
is of type Product
if yes then the second foreach
is not valid. Actually the first one could be the one that is invalid if you return a collection of Product
.
UPDATE:
You are right, I am returning the model of type Product. Also, I do understand what is wrong now that you've pointed it out. How am I supposed to do what I'm trying to do then if I can't do it this way?
I'm surprised your code compiles when you said you are returning a model of Product
type. Here's how you can do it:
@foreach (var category in Model)
{
<h3><u>@category.Name</u></h3>
<div>
<ul>
@foreach (var product in category.Products)
{
<li>
put the rest of your code
</li>
}
</ul>
</div>
}
That suggest that instead of returning a Product
, you return a collection of Category
with Products. Something like this in EF:
// I am typing it here directly
// so I'm not sure if this is the correct syntax.
// I assume you know how to do this,
// anyway this should give you an idea.
context.Categories.Include(o=>o.Product)
Another approach (more words, less code) that may help:
The locations of local maxima and minima are also the locations of the zero crossings of the first derivative. It is generally much easier to find zero crossings than it is to directly find local maxima and minima.
Unfortunately, the first derivative tends to "amplify" noise, so when significant noise is present in the original data, the first derivative is best used only after the original data has had some degree of smoothing applied.
Since smoothing is, in the simplest sense, a low pass filter, the smoothing is often best (well, most easily) done by using a convolution kernel, and "shaping" that kernel can provide a surprising amount of feature-preserving/enhancing capability. The process of finding an optimal kernel can be automated using a variety of means, but the best may be simple brute force (plenty fast for finding small kernels). A good kernel will (as intended) massively distort the original data, but it will NOT affect the location of the peaks/valleys of interest.
Fortunately, quite often a suitable kernel can be created via a simple SWAG ("educated guess"). The width of the smoothing kernel should be a little wider than the widest expected "interesting" peak in the original data, and its shape will resemble that peak (a single-scaled wavelet). For mean-preserving kernels (what any good smoothing filter should be) the sum of the kernel elements should be precisely equal to 1.00, and the kernel should be symmetric about its center (meaning it will have an odd number of elements.
Given an optimal smoothing kernel (or a small number of kernels optimized for different data content), the degree of smoothing becomes a scaling factor for (the "gain" of) the convolution kernel.
Determining the "correct" (optimal) degree of smoothing (convolution kernel gain) can even be automated: Compare the standard deviation of the first derivative data with the standard deviation of the smoothed data. How the ratio of the two standard deviations changes with changes in the degree of smoothing cam be used to predict effective smoothing values. A few manual data runs (that are truly representative) should be all that's needed.
All the prior solutions posted above compute the first derivative, but they don't treat it as a statistical measure, nor do the above solutions attempt to performing feature preserving/enhancing smoothing (to help subtle peaks "leap above" the noise).
Finally, the bad news: Finding "real" peaks becomes a royal pain when the noise also has features that look like real peaks (overlapping bandwidth). The next more-complex solution is generally to use a longer convolution kernel (a "wider kernel aperture") that takes into account the relationship between adjacent "real" peaks (such as minimum or maximum rates for peak occurrence), or to use multiple convolution passes using kernels having different widths (but only if it is faster: it is a fundamental mathematical truth that linear convolutions performed in sequence can always be convolved together into a single convolution). But it is often far easier to first find a sequence of useful kernels (of varying widths) and convolve them together than it is to directly find the final kernel in a single step.
Hopefully this provides enough info to let Google (and perhaps a good stats text) fill in the gaps. I really wish I had the time to provide a worked example, or a link to one. If anyone comes across one online, please post it here!
If you want to reset the selected options
$('select option:selected').removeAttr('selected');
If you actually want to remove the options (although I don't think you mean this).
$('select').empty();
Substitute select
for the most appropriate selector in your case (this may be by id or by CSS class). Using as is will reset all <select>
elements on the page
Facebook uses og:tags
and the Open Graph Protocol to decipher what information to display when previewing your URL in a share dialog
or in a news feed on facebook.
The og:tags
contain information such as :
Here is an example ( taken from the facebook documentation ) of some og:tags
<meta property="og:title" content="The Rock"/>
<meta property="og:type" content="movie"/>
<meta property="og:url" content="http://www.imdb.com/title/tt0117500/"/>
<meta property="og:image" content="http://ia.media-imdb.com/rock.jpg"/>
Once you have implemented the correct markup of the og:tags
and set their values, you can test how facebook will view your URL by using the Facebook Debugger. The debugger tool will also highlight any problems it finds with the og:tags
on the page or lack there-of.
One thing to keep in mind is that facebook does do some caching with regard to this information, so in order for changes to take effect your page will have t be scraped as stated in the documentation :
Editing Meta Tags
You can update the attributes of your page by updating your page's tags. Note that og:title and og:type are only editable initially - after your page receives 50 likes the title becomes fixed, and after your page receives 10,000 likes the type becomes fixed. These properties are fixed to avoid surprising users who have liked the page already. Changing the title or type tags after these limits are reached does nothing, your page retains the original title and type.
For the changes to be reflected on Facebook, you must force your page to be scraped. The page is scraped when an admin for the page clicks the Like button or when the URL is entered into the
Facebook URL LinterFacebook Debugger...
These can be helpful.
If you're finding by Contains then it'll be like this
$("input[id*='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you're finding by Starts With then it'll be like this
$("input[id^='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you're finding by Ends With then it'll be like this
$("input[id$='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you want to select elements which id is not a given string
$("input[id!='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you want to select elements which name contains a given word, delimited by spaces
$("input[name~='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
If you want to select elements which id is equal to a given string or starting with that string followed by a hyphen
$("input[id|='DiscountType']").each(function (i, el) {
//It'll be an array of elements
});
I had this problem with 2.7 and 3.5 installed on my system trying to test a telegram bot with Python-Telegram-Bot.
I couldn't get it to work after installing with pip and pip3, with sudo or without. I always got:
Traceback (most recent call last):
File "telegram.py", line 2, in <module>
from telegram.ext import Updater
File "$USER/telegram.py", line 2, in <module>
from telegram.ext import Updater
ImportError: No module named 'telegram.ext'; 'telegram' is not a package
Reading the error message correctly tells me that python is looking in the current directory for a telegram.py
. And right, I had a script lying there called telegram.py and this was loaded by python when I called import
.
Conclusion, make sure you don't have any package.py
in your current working dir when trying to import. (And read error message thoroughly).
I have an open source library that does this very well. It's a four gesture library that comes with an out-of-the-box pan zoom setting. You can find it here: https://bitbucket.org/warwick/hacergestov3 Or you can download the demo app here: https://play.google.com/store/apps/details?id=com.WarwickWestonWright.HacerGestoV3Demo This is a pure canvas library so it can be used in pretty any scenario. Hope this helps.
Applications' schema may evolve in time; if you have several installations, which may be at different versions, you should have some way to ensure that your application, some kind of tool or script is capable of migrating schema and data from one version stepwise to any following one.
Having all your persistence in Hibernate mappings (or annotations) is a very good way for keeping schema evolution under control.
You should consider that schema evolution has several aspects to be considered:
evolution of the database schema in adding more columns and tables
dropping of old columns, tables and relations
filling new columns with defaults
Hibernate tools are important in particular in case (like in my experience) you have different versions of the same application on many different kinds of databases.
Point 3 is very sensitive in case you are using Hibernate, as in case you introduce a new boolean valued property or numeric one, if Hibernate will find any null value in such columns, if will raise an exception.
So what I would do is: do indeed use the Hibernate tools capacity of schema update, but you must add alongside of it some data and schema maintenance callback, like for filling defaults, dropping no longer used columns, and similar. In this way you get the advantages (database independent schema update scripts and avoiding duplicated coding of the updates, in peristence and in scripts) but you also cover all the aspects of the operation.
So for example if a version update consists simply in adding a varchar valued property (hence column), which may default to null, with auto update you'll be done. Where more complexity is necessary, more work will be necessary.
This is assuming that the application when updated is capable of updating its schema (it can be done), which also means that it must have the user rights to do so on the schema. If the policy of the customer prevents this (likely Lizard Brain case), you will have to provide the database - specific scripts.
I think that replacing:
List<String> list = Arrays.asList(split);
with
List<String> list = new ArrayList<String>(Arrays.asList(split));
resolves the problem.
Correct syntax for background-image
is:
background-image: url("path_to_image");
Correct syntax for ng-style is:
ng-style="{'background-image':'url(https://www.google.com/images/srpr/logo4w.png)'}">
I can't comment because my reputation is not high enough. @Franklin Rivero if you are using Laravel 5.2 you can set the bindings on the main query instead of the join using the setBindings method.
So the main query in @ph4r05's answer would look something like this:
$q = DnsResult::query()
->from($dnsTable . ' AS s')
->join(
DB::raw('(' . $qqSql. ') AS ss'),
function(JoinClause $join) {
$join->on('s.watch_id', '=', 'ss.watch_id')
->on('s.last_scan_at', '=', 'ss.last_scan');
})
->setBindings($subq->getBindings());
After years, I want to add another approach by using a view engine in Express.js
var fs = require('fs');
app.get('/test', function(req, res, next) {
var html = fs.readFileSync('./html/test.html', 'utf8')
res.render('test', { html: html })
// or res.send(html)
})
Then, do that in your views/test
if you choose res.render
method at the above code (I'm writing in EJS format):
<%- locals.html %>
That's all.
In this way, you don't need to break your View Engine arrangements.
Actually,
var var1 = 1, var2 = 1, var3 = 1;
is not equivalent to:
var var1 = var2 = var3 = 1;
The difference is in scoping:
function good() {_x000D_
var var1 = 1, var2 = 1, var3 = 1;_x000D_
}_x000D_
_x000D_
function bad() {_x000D_
var var1 = var2 = var3 = 1;_x000D_
}_x000D_
_x000D_
good();_x000D_
console.log(window.var2); // undefined_x000D_
_x000D_
bad();_x000D_
console.log(window.var2); // 1. Aggh!
_x000D_
Actually this shows that assignment are right associative. The bad
example is equivalent to:
var var1 = (window.var2 = (window.var3 = 1));
You should use event.target.value
prop with onChange handler if not you could see :
index.js:1437 Warning: Failed prop type: You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.
Or If you want to use other handler than onChange, use event.currentTarget.value
TEMPLATE_DIR=os.path.join(BASE_DIR,'templates')
STATIC_DIR=os.path.join(BASE_DIR,'static')
STATICFILES_DIRS=[STATIC_DIR]
private func convertDictToJson(dict : NSDictionary) -> NSDictionary?
{
var jsonDict : NSDictionary!
do {
let jsonData = try JSONSerialization.data(withJSONObject:dict, options:[])
let jsonDataString = String(data: jsonData, encoding: String.Encoding.utf8)!
print("Post Request Params : \(jsonDataString)")
jsonDict = [ParameterKey : jsonDataString]
return jsonDict
} catch {
print("JSON serialization failed: \(error)")
jsonDict = nil
}
return jsonDict
}
On Mac:
?+CTRL+g
However, you can reset any key any way you'd like using "Customize your Sublime Text 2 configuration for awesome coding." for Mac.
On Windows/Linux:
Alt+F3
If anyone has how-tos or articles on this, I'd be more than happy to update.
The main (very interesting) difference for me is that:
"string" & Null
-> "string"
while
"string" + Null
-> Null
But that's probably more useful in database apps like Access.
I had to do this in that order:
Install-Module MSOnline
Install-Module AzureAD
Import-Module AzureAD
import java.util.*;
public class String_char
{
public static void main(String arg[]){
Scanner in = new Scanner(System.in);
System.out.println("Enter the value");
String data;
data = in.next();
int len = data.length();
for (int i = 0 ; i < len ; i++){
char ch = data.charAt(i);
if ((ch >= '0' && ch <= '9')){
System.out.println("Number ");
}
else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
System.out.println("Character");
}
else{
System.out.println("Symbol");
}
}
}
}
From WebReference:
throw {
name: "System Error",
level: "Show Stopper",
message: "Error detected. Please contact the system administrator.",
htmlMessage: "Error detected. Please contact the <a href=\"mailto:[email protected]\">system administrator</a>.",
toString: function(){return this.name + ": " + this.message;}
};
create php-file with:
<?php
print shell_exec( 'whoami' );
?>
or
<?php echo exec('whoami'); ?>
try the output in your web-browser. if the output is not your user example: www-data then proceed to next step
open as root:
/etc/apache2/envvars
look for these lines:
export APACHE_RUN_USER=user-name
export APACHE_RUN_GROUP=group-name
example:
export APACHE_RUN_USER=www-data
export APACHE_RUN_GROUP=www-data
where:
username = your username that has access to the folder you are using group = group you've given read+write+execute access
change it to:
export APACHE_RUN_USER="username"
export APACHE_RUN_GROUP="group"
if your user have no access yet:
sudo chmod 775 -R "directory of folder you want to give r/w/x access"
You have to select and send the form data as well:
$("#post-btn").click(function(){
$.post("process.php", $("#reg-form").serialize(), function(data) {
alert(data);
});
});
Take a look at the documentation for the jQuery serialize
method, which encodes the data from the form fields into a data-string to be sent to the server.
NikolaB explained it very well, However example would be helpful to understand, So here is one simple example...
import java.util.concurrent.*;
public class CountDownLatchExample {
public static class ProcessThread implements Runnable {
CountDownLatch latch;
long workDuration;
String name;
public ProcessThread(String name, CountDownLatch latch, long duration){
this.name= name;
this.latch = latch;
this.workDuration = duration;
}
public void run() {
try {
System.out.println(name +" Processing Something for "+ workDuration/1000 + " Seconds");
Thread.sleep(workDuration);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name+ "completed its works");
//when task finished.. count down the latch count...
// basically this is same as calling lock object notify(), and object here is latch
latch.countDown();
}
}
public static void main(String[] args) {
// Parent thread creating a latch object
CountDownLatch latch = new CountDownLatch(3);
new Thread(new ProcessThread("Worker1",latch, 2000)).start(); // time in millis.. 2 secs
new Thread(new ProcessThread("Worker2",latch, 6000)).start();//6 secs
new Thread(new ProcessThread("Worker3",latch, 4000)).start();//4 secs
System.out.println("waiting for Children processes to complete....");
try {
//current thread will get notified if all chidren's are done
// and thread will resume from wait() mode.
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("All Process Completed....");
System.out.println("Parent Thread Resuming work....");
}
}
Firstly, double quote character is nothing special in regex - it's just another character, so it doesn't need escaping from the perspective of regex.
However, because java uses double quotes to delimit String constants, if you want to create a string in java with a double quote in it, you must escape them.
This code will test if your String matches:
if (str.matches("\".*\"")) {
// this string starts and end with a double quote
}
Note that you don't need to add start and end of input markers (^
and $
) in the regex, because matches()
requires that the whole input be matched to return true - ^
and $
are implied.
These are equivalent
char buf[10] = "";
char buf[10] = {0};
char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
These are equivalent
char buf[10] = " ";
char buf[10] = {' '};
char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0};
These are equivalent
char buf[10] = "a";
char buf[10] = {'a'};
char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0};
I think curl --verbose/-v
is the easiest. It will spit out the request headers (lines prefixed with '>') without having to write to a file:
$ curl -v -I -H "Testing: Test header so you see this works" http://stackoverflow.com/
* About to connect() to stackoverflow.com port 80 (#0)
* Trying 69.59.196.211... connected
* Connected to stackoverflow.com (69.59.196.211) port 80 (#0)
> HEAD / HTTP/1.1
> User-Agent: curl/7.16.3 (i686-pc-cygwin) libcurl/7.16.3 OpenSSL/0.9.8h zlib/1.2.3 libssh2/0.15-CVS
> Host: stackoverflow.com
> Accept: */*
> Testing: Test header so you see this works
>
< HTTP/1.0 200 OK
...
Sending raw POST requests can be sometimes more convenient. Below you can see post.js original example from PhantomJS
// Example using HTTP POST operation
var page = require('webpage').create(),
server = 'http://posttestserver.com/post.php?dump',
data = 'universe=expanding&answer=42';
page.open(server, 'post', data, function (status) {
if (status !== 'success') {
console.log('Unable to post!');
} else {
console.log(page.content);
}
phantom.exit();
});
Logcat has a little icon to the right of logcat. You can use the icon to turn logcat on and off. I can usually make logcat active by clicking the icon (maybe several times).
If you are using AutoMapper with Entity Framework on the same class, you might hit this problem. For instance if your class is
class A
{
public ClassB ClassB { get; set; }
public int ClassBId { get; set; }
}
AutoMapper.Map<A, A>(input, destination);
This will try to copy both properties. In this case, ClassBId is non Nullable. Since AutoMapper will copy destination.ClassB = input.ClassB;
this will cause a problem.
Set your AutoMapper to Ignore ClassB
property.
cfg.CreateMap<A, A>()
.ForMember(m => m.ClassB, opt => opt.Ignore()); // We use the ClassBId
A void*
does not mean anything. It is a pointer, but the type that it points to is not known.
It's not that it can return "anything". A function that returns a void*
generally is doing one of the following:
operator new
and malloc
return: a pointer to a block of memory of a certain size. Since the memory does not have a type (because it does not have a properly constructed object in it yet), it is typeless. IE: void
.This construct is nothing like dynamic
or object
in C#. Those tools actually know what the original type is; void*
does not. This makes it far more dangerous than any of those, because it is very easy to get it wrong, and there's no way to ask if a particular usage is the right one.
And on a personal note, if you see code that uses void*
's "often", you should rethink what code you're looking at. void*
usage, especially in C++, should be rare, used primary for dealing in raw memory.
mkdir -p "$d" && cp file "$d"
(there's no such option for cp
).
standalone one cell solution based on VLOOKUP
=IFERROR(ARRAYFORMULA(IF(LEN(A2:A),
IF(A2:A>2000, "More than 2000",VLOOKUP(A2:A,
{{(TRANSPOSE({{{0; "Less than 500"},
{500; "Between 500 and 1000"}},
{{1000; "Between 1000 and 1500"},
{1500; "Between 1500 and 2000"}}}))}}, 2)),)), )
=IFERROR(ARRAYFORMULA(IF(LEN(A2:A);
IF(A2:A>2000; "More than 2000";VLOOKUP(A2:A;
{{(TRANSPOSE({{{0; "Less than 500"}\
{500; "Between 500 and 1000"}}\
{{1000; "Between 1000 and 1500"}\
{1500; "Between 1500 and 2000"}}}))}}; 2));)); )
This can also happen if you've been working on your scripts and functions and have been moving them around (i.e. changed the location of the definition) which could have accidentally created a looping reference.
You may find that the situation is solved if you just reset the iPython kernal to clear any old assignments:
%reset
or menu->restart terminal
If is a package then you can get the source for that with:
select text from all_source where name = 'PADCAMPAIGN'
and type = 'PACKAGE BODY'
order by line;
Oracle doesn't store the source for a sub-program separately, so you need to look through the package source for it.
Note: I've assumed you didn't use double-quotes when creating that package, but if you did , then use
select text from all_source where name = 'pAdCampaign'
and type = 'PACKAGE BODY'
order by line;
Have you tried:
eval $cmd
For the follow-on question of how to escape *
since it has special meaning when it's naked or in double quoted strings: use single quotes.
MYSQL='mysql AMORE -u username -ppassword -h localhost -e'
QUERY="SELECT "'*'" FROM amoreconfig" ;# <-- "double"'single'"double"
eval $MYSQL "'$QUERY'"
Bonus: It also reads nice: eval mysql query ;-)
add remote as:
git remote add https://username:[email protected]/repodir/myrepo.git
You need to set the actual page to margin:0 and padding: 0 to the actual html, not just the body.
use this in your css stylesheet.
*, html {
margin:0;
padding:0;
}
that will set the whole page to 0, for a fresh clean start with no margin or paddings.
A "little" late to the party but the real answer to this - if you use Oracle.ManagedDataAccess
ODP.NET provider, you should forget about things like network\admin
, Oracle client
, Oracle_Home
, etc.
Here is what you need
C:\Program Files (x86)
. With full dev tools, under 60MbAt this point you have 2 options to connect.
a) In the connection string set datasource
in the following format
DataSource=ServerName:Port/SID . . .
or DataSource=IP:Port/SID . . .
b) Create tnsnames.ora
file (only it is going to be different from previous experiences). Have entry in it:
AAA = (DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = ServerNameOrIP)(PORT = 1521))
(CONNECT_DATA = (SERVER = DEDICATED) (SERVICE_NAME = SIDNAME)))
And place this file into your bin folder, where your application is running from.
Now you can connect using your connection name - DataSource=AAA . . .
So, even though you have tnsnames.ora, with ODP.net managed it works a bit different - you create local TNS file. And now, it is easy to manage it.
To summarize - with managed, no need for heavy Oracle Client, Oracle_home
or knowing depths of oracle installation folders. Everything can be done within your .net application structures.
I have used the statement below on debian 10
apt-get install iputils-ping
In Ubuntu
Step 1:
sudo vi /etc/mysql/mysql.conf.d/mysqld.cnf
Step 2: Go to last line and add the following
sql_mode = ""
Step 3: Save
Step 4: Restart mysql server.
I use a handy app called Karabiner to do this, and many other things. It's free and open source.
It's a keyboard remapper, with a lot of handy presets for many common remaps that people may want to do.
As you can see from the screenshot, this remap is included as a preset in Karabiner.
Hope this helps. Happy remapping!
Service workers have access to header informations, including the Content-Length
header.
Service workers are a bit complicated to understand, so I've built a small library called sw-get-headers.
Than you need to:
response
eventContent-Length
header!Note that your website needs to be on HTTPS to use Service Workers, the browser needs to be compatible with Service Workers and the images must be on the same origin as your page.
One more way -
select * from <table> where id=(select max(id) from <table>)
Also you can check on this link -
Solution with .Where and .Contains has complexity of O(N square). Simple .Join should have a lot better performance (close to O(N) due to hashing). So the correct code is:
_dataContext.UserProfile.Join(idList, up => up.ID, id => id, (up, id) => up);
And now result of my measurement. I generated 100 000 UserProfiles and 100 000 ids. Join took 32ms and .Where with .Contains took 2 minutes and 19 seconds! I used pure IEnumerable for this testing to prove my statement. If you use List instead of IEnumerable, .Where and .Contains will be faster. Anyway the difference is significant. The fastest .Where .Contains is with Set<>. All it depends on complexity of underlying coletions for .Contains. Look at this post to learn about linq complexity.Look at my test sample below:
private static void Main(string[] args)
{
var userProfiles = GenerateUserProfiles();
var idList = GenerateIds();
var stopWatch = new Stopwatch();
stopWatch.Start();
userProfiles.Join(idList, up => up.ID, id => id, (up, id) => up).ToArray();
Console.WriteLine("Elapsed .Join time: {0}", stopWatch.Elapsed);
stopWatch.Restart();
userProfiles.Where(up => idList.Contains(up.ID)).ToArray();
Console.WriteLine("Elapsed .Where .Contains time: {0}", stopWatch.Elapsed);
Console.ReadLine();
}
private static IEnumerable<int> GenerateIds()
{
// var result = new List<int>();
for (int i = 100000; i > 0; i--)
{
yield return i;
}
}
private static IEnumerable<UserProfile> GenerateUserProfiles()
{
for (int i = 0; i < 100000; i++)
{
yield return new UserProfile {ID = i};
}
}
Console output:
Elapsed .Join time: 00:00:00.0322546
Elapsed .Where .Contains time: 00:02:19.4072107
Using the DISTINCT flag will remove duplicate rows.
SELECT DISTINCT
C.Content_ID,
C.Content_Title,
M.Media_Id
FROM tbl_Contents C
LEFT JOIN tbl_Media M ON M.Content_Id = C.Content_Id
ORDER BY C.Content_DatePublished ASC
In my case index.aspx file was not created by default and after adding another web form i did not set the form as start page ...After setting the page as start page my issue get resolved . So right click a web form and set the form as start page :)
on Windows F9 to run single line
Select the lines which you want to run on console and press F9 button for multi line
It's an old question. I would like to answer it using new tools.
Works with python 3 (should work with python 2, but I haven't test it) and PyQt5.
Minimal working example. Copy it to the python shell and get the result.
from PyQt5.QtWidgets import QApplication
app = QApplication([])
screen = app.primaryScreen()
screenshot = screen.grabWindow(QApplication.desktop().winId())
screenshot.save('/tmp/screenshot.png')
The Powershell Version of git branch --merged master | grep -v '^[ *]*master$' | xargs git branch -d
git branch --merged master | %{ if($_ -notmatch '\*.*master'){ git branch -d "$($_.Trim())" }}
This will remove any local branches that have been merged into master, while you are on the master branch.
git checkout master
to switch.
I've done this on a regular (local) TextView
, and it should work on the remote variety since the docs list the method as equivalent between the two:
remote_text_view.setText(Html.fromHtml("This is <del>crossed off</del>."));
Here is an input function which is compatible with both Python 2.7 and Python 3+:
(Slightly modified answer by @Hardian) to avoid UnboundLocalError: local variable 'input' referenced before assignment
error
def input_compatible(prompt=None):
try:
input_func = raw_input
except NameError:
input_func = input
return input_func(prompt)
Identifiers (including column names) that are not double-quoted are folded to lower case in PostgreSQL. Column names that were created with double-quotes and thereby retained upper-case letters (and/or other syntax violations) have to be double-quoted for the rest of their life:
"first_Name"
Values (string literals / constants) are enclosed in single quotes:
'xyz'
So, yes, PostgreSQL column names are case-sensitive (when double-quoted):
SELECT * FROM persons WHERE "first_Name" = 'xyz';
Read the manual on identifiers here.
My standing advice is to use legal, lower-case names exclusively so double-quoting is not needed.