You might just have to install the packages.
yum install php-pdo php-mysqli
After they're installed, restart Apache.
httpd restart
or
apachectl restart
Check you have <meta charset="utf-8">
inside head block.
The error indicates that the DLL is either not a COM DLL or it's corrupt. If it's not a COM DLL and not being used as a COM DLL by an application then there is no need to register it.
From what you say in your question (the service is not registered)
it seems that we are talking about a service not correctly installed. I will try to reinstall the application.
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = <sql server name>;
builder.UserID = <user id>; //User id used to login into SQL
builder.Password = <password>; //password used to login into SQL
builder.InitialCatalog = <database name>; //Name of Database
DataTable orderTable = new DataTable();
//<sp name> stored procedute name which you want to exceute
using (var con = new SqlConnection(builder.ConnectionString))
using (SqlCommand cmd = new SqlCommand(<sp name>, con))
using (var da = new SqlDataAdapter(cmd))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
//Data adapter(da) fills the data retuned from stored procedure
//into orderTable
da.Fill(orderTable);
}
Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order. you are selecting
t1.ID, t2.ReceivedDate from Table t1
union
t2.ID from Table t2
which is incorrect.
so you have to write
t1.ID, t1.ReceivedDate from Table t1 union t2.ID, t2.ReceivedDate from Table t1
you can use sub query here
SELECT tbl1.ID, tbl1.ReceivedDate FROM
(select top 2 t1.ID, t1.ReceivedDate
from tbl1 t1
where t1.ItemType = 'TYPE_1'
order by ReceivedDate desc
) tbl1
union
SELECT tbl2.ID, tbl2.ReceivedDate FROM
(select top 2 t2.ID, t2.ReceivedDate
from tbl2 t2
where t2.ItemType = 'TYPE_2'
order by t2.ReceivedDate desc
) tbl2
so it will return only distinct values by default from both table.
Note: I'm aware this is slightly different than the requested solution, but I think many will find it useful.
If you want to find each "x" intervals (days, months, years, etc...) between two dates, moment.js and the moment-range extension packages enable this functionality.
For example, to find each 30th day between two dates:
window['moment-range'].extendMoment(moment);
var dateString = "2018-05-12 17:32:34.874-08";
var start = new Date(dateString);
var end = new Date();
var range1 = moment.range(start, end);
var arrayOfIntervalDates = Array.from(range1.by('day', { step: 30 }));
arrayOfIntervalDates.map(function(intervalDate){
console.log(intervalDate.format('YY-M-DD'))
});
You can use the pexpect module
child = pexpect.spawn ('/usr/bin/sftp ' + [email protected] )
child.expect ('.* password:')
child.sendline (your_password)
child.expect ('sftp> ')
child.sendline ('dir')
child.expect ('sftp> ')
file_list = child.before
child.sendline ('bye')
I haven't tested this but it should work
The following constructor, JLabel(String, int)
, allow you to specify the horizontal alignment of the label.
JLabel label = new JLabel("The Label", SwingConstants.CENTER);
The duplicate values in any column can be deleted with a simple for loop.
Sub remove()
Dim a As Long
For a = Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
If WorksheetFunction.CountIf(Range("A1:A" & a), Cells(a, 1)) > 1 Then Rows(a).Delete
Next
End Sub
Apache StringUtils
has several methods: leftPad
, rightPad
, center
and repeat
.
But please note that — as others have mentioned and demonstrated in this answer — String.format()
and the Formatter
classes in the JDK are better options. Use them over the commons code.
<p:commandXxx process>
<p:ajax process>
<f:ajax execute>
The process
attribute is server side and can only affect UIComponent
s implementing EditableValueHolder
(input fields) or ActionSource
(command fields). The process
attribute tells JSF, using a space-separated list of client IDs, which components exactly must be processed through the entire JSF lifecycle upon (partial) form submit.
JSF will then apply the request values (finding HTTP request parameter based on component's own client ID and then either setting it as submitted value in case of EditableValueHolder
components or queueing a new ActionEvent
in case of ActionSource
components), perform conversion, validation and updating the model values (EditableValueHolder
components only) and finally invoke the queued ActionEvent
(ActionSource
components only). JSF will skip processing of all other components which are not covered by process
attribute. Also, components whose rendered
attribute evaluates to false
during apply request values phase will also be skipped as part of safeguard against tampered requests.
Note that it's in case of ActionSource
components (such as <p:commandButton>
) very important that you also include the component itself in the process
attribute, particularly if you intend to invoke the action associated with the component. So the below example which intends to process only certain input component(s) when a certain command component is invoked ain't gonna work:
<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="foo" action="#{bean.action}" />
It would only process the #{bean.foo}
and not the #{bean.action}
. You'd need to include the command component itself as well:
<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="@this foo" action="#{bean.action}" />
Or, as you apparently found out, using @parent
if they happen to be the only components having a common parent:
<p:panel><!-- Type doesn't matter, as long as it's a common parent. -->
<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="@parent" action="#{bean.action}" />
</p:panel>
Or, if they both happen to be the only components of the parent UIForm
component, then you can also use @form
:
<h:form>
<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="@form" action="#{bean.action}" />
</h:form>
This is sometimes undesirable if the form contains more input components which you'd like to skip in processing, more than often in cases when you'd like to update another input component(s) or some UI section based on the current input component in an ajax listener method. You namely don't want that validation errors on other input components are preventing the ajax listener method from being executed.
Then there's the @all
. This has no special effect in process
attribute, but only in update
attribute. A process="@all"
behaves exactly the same as process="@form"
. HTML doesn't support submitting multiple forms at once anyway.
There's by the way also a @none
which may be useful in case you absolutely don't need to process anything, but only want to update some specific parts via update
, particularly those sections whose content doesn't depend on submitted values or action listeners.
Noted should be that the process
attribute has no influence on the HTTP request payload (the amount of request parameters). Meaning, the default HTML behavior of sending "everything" contained within the HTML representation of the <h:form>
will be not be affected. In case you have a large form, and want to reduce the HTTP request payload to only these absolutely necessary in processing, i.e. only these covered by process
attribute, then you can set the partialSubmit
attribute in PrimeFaces Ajax components as in <p:commandXxx ... partialSubmit="true">
or <p:ajax ... partialSubmit="true">
. You can also configure this 'globally' by editing web.xml
and add
<context-param>
<param-name>primefaces.SUBMIT</param-name>
<param-value>partial</param-value>
</context-param>
Alternatively, you can also use <o:form>
of OmniFaces 3.0+ which defaults to this behavior.
The standard JSF equivalent to the PrimeFaces specific process
is execute
from <f:ajax execute>
. It behaves exactly the same except that it doesn't support a comma-separated string while the PrimeFaces one does (although I personally recommend to just stick to space-separated convention), nor the @parent
keyword. Also, it may be useful to know that <p:commandXxx process>
defaults to @form
while <p:ajax process>
and <f:ajax execute>
defaults to @this
. Finally, it's also useful to know that process
supports the so-called "PrimeFaces Selectors", see also How do PrimeFaces Selectors as in update="@(.myClass)" work?
<p:commandXxx update>
<p:ajax update>
<f:ajax render>
The update
attribute is client side and can affect the HTML representation of all UIComponent
s. The update
attribute tells JavaScript (the one responsible for handling the ajax request/response), using a space-separated list of client IDs, which parts in the HTML DOM tree need to be updated as response to the form submit.
JSF will then prepare the right ajax response for that, containing only the requested parts to update. JSF will skip all other components which are not covered by update
attribute in the ajax response, hereby keeping the response payload small. Also, components whose rendered
attribute evaluates to false
during render response phase will be skipped. Note that even though it would return true
, JavaScript cannot update it in the HTML DOM tree if it was initially false
. You'd need to wrap it or update its parent instead. See also Ajax update/render does not work on a component which has rendered attribute.
Usually, you'd like to update only the components which really need to be "refreshed" in the client side upon (partial) form submit. The example below updates the entire parent form via @form
:
<h:form>
<p:inputText id="foo" value="#{bean.foo}" required="true" />
<p:message id="foo_m" for="foo" />
<p:inputText id="bar" value="#{bean.bar}" required="true" />
<p:message id="bar_m" for="bar" />
<p:commandButton action="#{bean.action}" update="@form" />
</h:form>
(note that process
attribute is omitted as that defaults to @form
already)
Whilst that may work fine, the update of input and command components is in this particular example unnecessary. Unless you change the model values foo
and bar
inside action
method (which would in turn be unintuitive in UX perspective), there's no point of updating them. The message components are the only which really need to be updated:
<h:form>
<p:inputText id="foo" value="#{bean.foo}" required="true" />
<p:message id="foo_m" for="foo" />
<p:inputText id="bar" value="#{bean.bar}" required="true" />
<p:message id="bar_m" for="bar" />
<p:commandButton action="#{bean.action}" update="foo_m bar_m" />
</h:form>
However, that gets tedious when you have many of them. That's one of the reasons why PrimeFaces Selectors exist. Those message components have in the generated HTML output a common style class of ui-message
, so the following should also do:
<h:form>
<p:inputText id="foo" value="#{bean.foo}" required="true" />
<p:message id="foo_m" for="foo" />
<p:inputText id="bar" value="#{bean.bar}" required="true" />
<p:message id="bar_m" for="bar" />
<p:commandButton action="#{bean.action}" update="@(.ui-message)" />
</h:form>
(note that you should keep the IDs on message components, otherwise @(...)
won't work! Again, see How do PrimeFaces Selectors as in update="@(.myClass)" work? for detail)
The @parent
updates only the parent component, which thus covers the current component and all siblings and their children. This is more useful if you have separated the form in sane groups with each its own responsibility. The @this
updates, obviously, only the current component. Normally, this is only necessary when you need to change one of the component's own HTML attributes in the action method. E.g.
<p:commandButton action="#{bean.action}" update="@this"
oncomplete="doSomething('#{bean.value}')" />
Imagine that the oncomplete
needs to work with the value
which is changed in action
, then this construct wouldn't have worked if the component isn't updated, for the simple reason that oncomplete
is part of generated HTML output (and thus all EL expressions in there are evaluated during render response).
The @all
updates the entire document, which should be used with care. Normally, you'd like to use a true GET request for this instead by either a plain link (<a>
or <h:link>
) or a redirect-after-POST by ?faces-redirect=true
or ExternalContext#redirect()
. In effects, process="@form" update="@all"
has exactly the same effect as a non-ajax (non-partial) submit. In my entire JSF career, the only sensible use case I encountered for @all
is to display an error page in its entirety in case an exception occurs during an ajax request. See also What is the correct way to deal with JSF 2.0 exceptions for AJAXified components?
The standard JSF equivalent to the PrimeFaces specific update
is render
from <f:ajax render>
. It behaves exactly the same except that it doesn't support a comma-separated string while the PrimeFaces one does (although I personally recommend to just stick to space-separated convention), nor the @parent
keyword. Both update
and render
defaults to @none
(which is, "nothing").
See also:
The document.location
is an object that contains properties for the current location.
The href
property is one of these properties, containing the complete URL, i.e. all the other properties put together.
Some browsers allow you to assign an URL to the location
object and acts as if you assigned it to the href
property. Some other browsers are more picky, and requires you to use the href
property. Thus, to make the code work in all browsers, you have to use the href
property.
Both the window
and document
objects has a location
object. You can set the URL using either window.location.href
or document.location.href
. However, logically the document.location
object should be read-only (as you can't change the URL of a document; changing the URL loads a new document), so to be on the safe side you should rather use window.location.href
when you want to set the URL.
VIDEO_ID with actual ID of your YouTube video.
<div data-video="VIDEO_ID"
data-autoplay="0"
data-loop="1"
id="youtube-audio">
</div>
<script src="https://www.youtube.com/iframe_api"></script>
<script src="https://cdn.rawgit.com/labnol/files/master/yt.js"></script>
Try the CURRENT_USER()
function. This returns the username that MySQL used to authenticate your client connection. It is this username that determines your privileges.
This may be different from the username that was sent to MySQL by the client (for example, MySQL might use an anonymous account to authenticate your client, even though you sent a username). If you want the username the client sent to MySQL when connecting use the USER()
function instead.
The value indicates the user name you specified when connecting to the server, and the client host from which you connected. The value can be different from that of CURRENT_USER().
http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_current-user
You can read a group of txt files in a folder and echo the contents like this.
<?php
$directory = "folder/";
$dir = opendir($directory);
$filenames = [];
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if($type !== 'file') continue;
$filenames[] = $filename;
}
closedir($dir);
?>
This image explains normal script tag, async and defer
Async scripts are executed as soon as the script is loaded, so it doesn't guarantee the order of execution (a script you included at the end may execute before the first script file )
Defer scripts guarantees the order of execution in which they appear in the page.
Ref this link : http://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html
You can use Named Sections.
_Layout.cshtml
<head>
<script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
@RenderSection("JavaScript", required: false)
</head>
_SomeView.cshtml
@section JavaScript
{
<script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
<script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}
I use runjs
like:
runjs example.js
The package is called just run
npm install -g run
dec = int(input("Enter a number below 256: "))
hex1 = dec // 16
if hex1 >= 10:
hex1 = hex(dec)
hex2 = dec % 16
if hex2 >= 10:
hex2 = hex(hex2)
print(hex1.strip("0x"))
Works well.
You have 4 columns A,B,C,D
Here is a better way to select the columns you need for the new dataframe:-
df2 = df1[['A','D']]
if you wish to use column numbers instead, use:-
df2 = df1[[0,3]]
Download the Processing application from http://www.processing.org/download/. The zip file contains a folder called java. It includes the JDK 1.6.0_32 (version checked on 19/02/2013).
SELECT DATABASEPROPERTYEX('DBName', 'Collation') SQLCollation;
Where DBName is your database name.
Provide at least an 512px X 512px image and use this tool: https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html
It will generate all icons for you in the correct size, inclusive the web image for the play store.
Be careful that this will create an "alternate reality" for people who have already fetch/pulled/cloned from the remote repository. But in fact, it's quite simple:
git reset HEAD^ # remove commit locally
git push origin +HEAD # force-push the new HEAD commit
If you want to still have it in your local repository and only remove it from the remote, then you can use:
git push origin +HEAD^:<name of your branch, most likely 'master'>
See the documentation:
list.append(x)
- Add an item to the end of the list; equivalent to a[len(a):] = [x].
list.extend(L) - Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.
c.append(c)
"appends" c to itself as an element. Since a list is a reference type, this creates a recursive data structure.
c += c
is equivalent to extend(c)
, which appends the elements of c to c.
Bill Horst's - Converting SQL to LINQ is a very good resource for this task (as well as LINQPad).
LINQ Tools has a decent list of tools as well but I do not believe there is anything else out there that can do what Linqer did.
Generally speaking, LINQ is a higher-level querying language than SQL which can cause translation loss when trying to convert SQL to LINQ. For one, LINQ emits shaped results and SQL flat result sets. The issue here is that an automatic translation from SQL to LINQ will often have to perform more transliteration than translation - generating examples of how NOT to write LINQ queries. For this reason, there are few (if any) tools that will be able to reliably convert SQL to LINQ. Analogous to learning C# 4 by first converting VB6 to C# 4 and then studying the resulting conversion.
I can think of the following possible causes:
For 1.) you can try runas /user:Administrator
in order to get higher privileges or start the batch file as administrator via context menu. If that doesn't help, maybe even the administrator doesn't have the rights. Then you need to take over the ownership of the directory.
For 2.) download Process Explorer, click Find/Find handle or DLL...
or press Ctrl+F, type the name of the directory and find out who uses it. Close the application which uses the directory, if possible.
sh prog1;sh prog2
I think this works..
<span style="color:#ffffff; font-size:18px; line-height:35px; font-family: Calibri;">Our Activities </span>
This works for me well:) As it has been already mentioned above "The font tag has been deprecated, at least in XHTML. It always safe to use span tag. font may not give you desire results, at least in my case it didn't.
DECLARE @str AS VARCHAR(50)
SET @str = 'PONIES!!...pon1es!!...p0n1es!!'
IF PATINDEX('%[0-9]%', @str) > 0
PRINT 'YES, The string has numbers'
ELSE
PRINT 'NO, The string does not have numbers'
It´s eaiser to implement an random function on the enum.
public enum Via {
A, B;
public static Via viaAleatoria(){
Via[] vias = Via.values();
Random generator = new Random();
return vias[generator.nextInt(vias.length)];
}
}
and then you call it from the class you need it like this
public class Guardia{
private Via viaActiva;
public Guardia(){
viaActiva = Via.viaAleatoria();
}
This is an error that I faced. I had saved .csv file in MAC OSX.
While saving, save it as "Windows Comma Separated Values (.csv)" which resolved the issue.
Here's one way to do it:
mkdir -p `dirname /path/to/copy/file/to/is/very/deep/there` \
&& cp -r file /path/to/copy/file/to/is/very/deep/there
dirname
will give you the parent of the destination directory or file. mkdir -p `dirname ...` will then create that directory ensuring that when you call cp -r the correct base directory is in place.
The advantage of this over --parents is that it works for the case where the last element in the destination path is a filename.
And it'll work on OS X.
Update: using .indexOf()
to detect if stat
value is one of arr
elements
Pure JavaScript
var arr = [20,30,40,50,60,70,80,90,100];_x000D_
//or detect equal to all_x000D_
//var arr = [10,10,10,10,10,10,10];_x000D_
var stat = 10;_x000D_
_x000D_
if(arr.indexOf(stat)==-1)alert("stat is not equal to one more elements of array");
_x000D_
I wanted to add this to @marczking's answer (Option 1) as a comment, but my lowly status on StackOverflow is preventing that.
I did a port of @marczking's answer to Objective C. Works like charm, thanks @marczking!
UIView+Border.h:
#import <UIKit/UIKit.h>
IB_DESIGNABLE
@interface UIView (Border)
-(void)setBorderColor:(UIColor *)color;
-(void)setBorderWidth:(CGFloat)width;
-(void)setCornerRadius:(CGFloat)radius;
@end
UIView+Border.m:
#import "UIView+Border.h"
@implementation UIView (Border)
// Note: cannot use synthesize in a Category
-(void)setBorderColor:(UIColor *)color
{
self.layer.borderColor = color.CGColor;
}
-(void)setBorderWidth:(CGFloat)width
{
self.layer.borderWidth = width;
}
-(void)setCornerRadius:(CGFloat)radius
{
self.layer.cornerRadius = radius;
self.layer.masksToBounds = radius > 0;
}
@end
Normal rounding will work with a small tweak:
Math.round(price * 10)/10
and if you want to keep a currency format, you can use the Number method .toFixed()
(Math.round(price * 10)/10).toFixed(2)
Though this will make it a String =)
You can find elements by available methods and check response array length if the length of an array equal the 0 element not exist.
element_exist = False if len(driver.find_elements_by_css_selector('div.eiCW-')) > 0 else True
Like this: .
The .
means any character except newline (which sometimes is but often isn't included, check your regex flavour).
You can rewrite your expression as ^.{1,35}$
, which should match any line of length 1-35.
You can use an iframe to display a preview of the page on mouseover:
.box{_x000D_
display: none;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
a:hover + .box,.box:hover{_x000D_
display: block;_x000D_
position: relative;_x000D_
z-index: 100;_x000D_
}
_x000D_
This live preview for <a href="https://en.wikipedia.org/">Wikipedia</a>_x000D_
<div class="box">_x000D_
<iframe src="https://en.wikipedia.org/" width = "500px" height = "500px">_x000D_
</iframe>_x000D_
</div> _x000D_
remains open on mouseover.
_x000D_
Here's an example with multiple live previews:
.box{_x000D_
display: none;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
a:hover + .box,.box:hover{_x000D_
display: block;_x000D_
position: relative;_x000D_
z-index: 100;_x000D_
}
_x000D_
Live previews for <a href="https://en.wikipedia.org/">Wikipedia</a>_x000D_
<div class="box">_x000D_
<iframe src="https://en.wikipedia.org/" width = "500px" height = "500px">_x000D_
</iframe>_x000D_
</div> _x000D_
and <a href="https://www.jquery.com/">JQuery</a>_x000D_
<div class="box">_x000D_
<iframe src="https://www.jquery.com/" width = "500px" height = "500px">_x000D_
</iframe>_x000D_
</div> _x000D_
will appear when these links are moused over.
_x000D_
If you are using Angular 6.1 or later, the most convenient way is to use KeyValuePipe
@Component({
selector: 'keyvalue-pipe',
template: `<span>
<p>Object</p>
<div *ngFor="let item of object | keyvalue">
{{item.key}}:{{item.value}}
</div>
<p>Map</p>
<div *ngFor="let item of map | keyvalue">
{{item.key}}:{{item.value}}
</div>
</span>`
})
export class KeyValuePipeComponent {
object: Record<number, string> = {2: 'foo', 1: 'bar'};
map = new Map([[2, 'foo'], [1, 'bar']]);
}
To create a model that references another, use the Ruby on Rails model generator:
$ rails g model wheel car:references
That produces app/models/wheel.rb:
class Wheel < ActiveRecord::Base
belongs_to :car
end
And adds the following migration:
class CreateWheels < ActiveRecord::Migration
def self.up
create_table :wheels do |t|
t.references :car
t.timestamps
end
end
def self.down
drop_table :wheels
end
end
When you run the migration, the following will end up in your db/schema.rb:
$ rake db:migrate
create_table "wheels", :force => true do |t|
t.integer "car_id"
t.datetime "created_at"
t.datetime "updated_at"
end
As for documentation, a starting point for rails generators is Ruby on Rails: A Guide to The Rails Command Line which points you to API Documentation for more about available field types.
Same issues as others reported - using Excel 2016. Found that when applying conditional formulas against tables; AND, multiplying the conditions, and adding the conditions failed. Had to create the TRUE/FALSE logic myself:
=IF($C2="SomeText",0,1)+IF(INT($D2)>1000,0,1)=0
Use this
<div *ngFor="let talk of talks>
{{talk.title}}
{{talk.speaker}}
<p>{{talk.description}}
</div>
You need to specify variable to iterate over an array of an object
You'll need to create an instance of the class and invoke the method on it.
public class Foo
{
public void Data1()
{
}
public static void Data2()
{
Foo foo = new Foo();
foo.Data1();
}
}
TreeMap will automatically sort in ascending order. If you want to sort in descending order, use the following code:
Copy the below code within your class and outside of the main execute method:
static class DescOrder implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
}
Then in your logic:
TreeMap<String, String> map = new TreeMap<String, String>(new DescOrder());
map.put("A", "test1");
map.put("C", "test3");
map.put("E", "test5");
map.put("B", "test2");
map.put("D", "test4");
Well as we all know that it gets erased. But it can be known under some circumstances where the type is explicitly mentioned in the class hierarchy:
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
public abstract class CaptureType<T> {
/**
* {@link java.lang.reflect.Type} object of the corresponding generic type. This method is useful to obtain every kind of information (including annotations) of the generic type.
*
* @return Type object. null if type could not be obtained (This happens in case of generic type whose information cant be obtained using Reflection). Please refer documentation of {@link com.types.CaptureType}
*/
public Type getTypeParam() {
Class<?> bottom = getClass();
Map<TypeVariable<?>, Type> reifyMap = new LinkedHashMap<>();
for (; ; ) {
Type genericSuper = bottom.getGenericSuperclass();
if (!(genericSuper instanceof Class)) {
ParameterizedType generic = (ParameterizedType) genericSuper;
Class<?> actualClaz = (Class<?>) generic.getRawType();
TypeVariable<? extends Class<?>>[] typeParameters = actualClaz.getTypeParameters();
Type[] reified = generic.getActualTypeArguments();
assert (typeParameters.length != 0);
for (int i = 0; i < typeParameters.length; i++) {
reifyMap.put(typeParameters[i], reified[i]);
}
}
if (bottom.getSuperclass().equals(CaptureType.class)) {
bottom = bottom.getSuperclass();
break;
}
bottom = bottom.getSuperclass();
}
TypeVariable<?> var = bottom.getTypeParameters()[0];
while (true) {
Type type = reifyMap.get(var);
if (type instanceof TypeVariable) {
var = (TypeVariable<?>) type;
} else {
return type;
}
}
}
/**
* Returns the raw type of the generic type.
* <p>For example in case of {@code CaptureType<String>}, it would return {@code Class<String>}</p>
* For more comprehensive examples, go through javadocs of {@link com.types.CaptureType}
*
* @return Class object
* @throws java.lang.RuntimeException If the type information cant be obtained. Refer documentation of {@link com.types.CaptureType}
* @see com.types.CaptureType
*/
public Class<T> getRawType() {
Type typeParam = getTypeParam();
if (typeParam != null)
return getClass(typeParam);
else throw new RuntimeException("Could not obtain type information");
}
/**
* Gets the {@link java.lang.Class} object of the argument type.
* <p>If the type is an {@link java.lang.reflect.ParameterizedType}, then it returns its {@link java.lang.reflect.ParameterizedType#getRawType()}</p>
*
* @param type The type
* @param <A> type of class object expected
* @return The Class<A> object of the type
* @throws java.lang.RuntimeException If the type is a {@link java.lang.reflect.TypeVariable}. In such cases, it is impossible to obtain the Class object
*/
public static <A> Class<A> getClass(Type type) {
if (type instanceof GenericArrayType) {
Type componentType = ((GenericArrayType) type).getGenericComponentType();
Class<?> componentClass = getClass(componentType);
if (componentClass != null) {
return (Class<A>) Array.newInstance(componentClass, 0).getClass();
} else throw new UnsupportedOperationException("Unknown class: " + type.getClass());
} else if (type instanceof Class) {
Class claz = (Class) type;
return claz;
} else if (type instanceof ParameterizedType) {
return getClass(((ParameterizedType) type).getRawType());
} else if (type instanceof TypeVariable) {
throw new RuntimeException("The type signature is erased. The type class cant be known by using reflection");
} else throw new UnsupportedOperationException("Unknown class: " + type.getClass());
}
/**
* This method is the preferred method of usage in case of complex generic types.
* <p>It returns {@link com.types.TypeADT} object which contains nested information of the type parameters</p>
*
* @return TypeADT object
* @throws java.lang.RuntimeException If the type information cant be obtained. Refer documentation of {@link com.types.CaptureType}
*/
public TypeADT getParamADT() {
return recursiveADT(getTypeParam());
}
private TypeADT recursiveADT(Type type) {
if (type instanceof Class) {
return new TypeADT((Class<?>) type, null);
} else if (type instanceof ParameterizedType) {
ArrayList<TypeADT> generic = new ArrayList<>();
ParameterizedType type1 = (ParameterizedType) type;
return new TypeADT((Class<?>) type1.getRawType(),
Arrays.stream(type1.getActualTypeArguments()).map(x -> recursiveADT(x)).collect(Collectors.toList()));
} else throw new UnsupportedOperationException();
}
}
public class TypeADT {
private final Class<?> reify;
private final List<TypeADT> parametrized;
TypeADT(Class<?> reify, List<TypeADT> parametrized) {
this.reify = reify;
this.parametrized = parametrized;
}
public Class<?> getRawType() {
return reify;
}
public List<TypeADT> getParameters() {
return parametrized;
}
}
And now you can do things like:
static void test1() {
CaptureType<String> t1 = new CaptureType<String>() {
};
equals(t1.getRawType(), String.class);
}
static void test2() {
CaptureType<List<String>> t1 = new CaptureType<List<String>>() {
};
equals(t1.getRawType(), List.class);
equals(t1.getParamADT().getParameters().get(0).getRawType(), String.class);
}
private static void test3() {
CaptureType<List<List<String>>> t1 = new CaptureType<List<List<String>>>() {
};
equals(t1.getParamADT().getRawType(), List.class);
equals(t1.getParamADT().getParameters().get(0).getRawType(), List.class);
}
static class Test4 extends CaptureType<List<String>> {
}
static void test4() {
Test4 test4 = new Test4();
equals(test4.getParamADT().getRawType(), List.class);
}
static class PreTest5<S> extends CaptureType<Integer> {
}
static class Test5 extends PreTest5<Integer> {
}
static void test5() {
Test5 test5 = new Test5();
equals(test5.getTypeParam(), Integer.class);
}
static class PreTest6<S> extends CaptureType<S> {
}
static class Test6 extends PreTest6<Integer> {
}
static void test6() {
Test6 test6 = new Test6();
equals(test6.getTypeParam(), Integer.class);
}
class X<T> extends CaptureType<T> {
}
class Y<A, B> extends X<B> {
}
class Z<Q> extends Y<Q, Map<Integer, List<List<List<Integer>>>>> {
}
void test7(){
Z<String> z = new Z<>();
TypeADT param = z.getParamADT();
equals(param.getRawType(), Map.class);
List<TypeADT> parameters = param.getParameters();
equals(parameters.get(0).getRawType(), Integer.class);
equals(parameters.get(1).getRawType(), List.class);
equals(parameters.get(1).getParameters().get(0).getRawType(), List.class);
equals(parameters.get(1).getParameters().get(0).getParameters().get(0).getRawType(), List.class);
equals(parameters.get(1).getParameters().get(0).getParameters().get(0).getParameters().get(0).getRawType(), Integer.class);
}
static void test8() throws IllegalAccessException, InstantiationException {
CaptureType<int[]> type = new CaptureType<int[]>() {
};
equals(type.getRawType(), int[].class);
}
static void test9(){
CaptureType<String[]> type = new CaptureType<String[]>() {
};
equals(type.getRawType(), String[].class);
}
static class SomeClass<T> extends CaptureType<T>{}
static void test10(){
SomeClass<String> claz = new SomeClass<>();
try{
claz.getRawType();
throw new RuntimeException("Shouldnt come here");
}catch (RuntimeException ex){
}
}
static void equals(Object a, Object b) {
if (!a.equals(b)) {
throw new RuntimeException("Test failed. " + a + " != " + b);
}
}
More info here. But again, it is almost impossible to retrieve for:
class SomeClass<T> extends CaptureType<T>{}
SomeClass<String> claz = new SomeClass<>();
where it gets erased.
You are using
$ curl -s -XPOST localhost:9200/_bulk --data-binary @requests
If 'requests' is a json file then you have to change this to
$ curl -s -XPOST localhost:9200/_bulk --data-binary @requests.json
Now before this, if your json file is not indexed, you have to insert an index line before each line inside the json file. You can do this with JQ. Refer below link: http://kevinmarsh.com/2014/10/23/using-jq-to-import-json-into-elasticsearch.html
Go to elasticsearch tutorials (example the shakespeare tutorial) and download the json file sample used and have a look at it. In front of each json object (each individual line) there is an index line. This is what you are looking for after using the jq command. This format is mandatory to use the bulk API, plain json files wont work.
Useful differences:
Use notify() if all your waiting threads are interchangeable (the order they wake up doesn't matter), or if you only ever have one waiting thread. A common example is a thread pool used to execute jobs from a queue--when a job is added, one of threads is notified to wake up, execute the next job and go back to sleep.
Use notifyAll() for other cases where the waiting threads may have different purposes and should be able to run concurrently. An example is a maintenance operation on a shared resource, where multiple threads are waiting for the operation to complete before accessing the resource.
Most likely your sushosin updated, which changed the default of suhosin.memory_limit from disabled to 0 (which won't allow any updates to memory_limit).
On Debian, change /etc/php5/conf.d/suhosin.ini
;suhosin.memory_limit = 0
to
suhosin.memory_limit = 2G
Or whichever value you are comfortable with. You can find the changelog of Sushosin at http://www.hardened-php.net/hphp/changelog.html, which says:
Changed the way the memory_limit protection is implemented
i had got the same error. Actually i tried to override the flutter Old SDK Package with new Updated Package. so that error occurred.
i opened flutter sdk directory with VS Code and cleaned the project
use this code in VSCode cmd
git clean -dxf
then use git pull
Personally I like to keep the label outside, like in your second example. That's why the FOR attribute is there. The reason being I'll often apply styles to the label, like a width, to get the form to look nice (shorthand below):
<style>
label {
width: 120px;
margin-right: 10px;
}
</style>
<label for="myinput">My Text</label>
<input type="text" id="myinput" /><br />
<label for="myinput2">My Text2</label>
<input type="text" id="myinput2" />
Makes it so I can avoid tables and all that junk in my forms.
You want to create an empty list, then append the created list to it. This will give you the list of lists. Example:
>>> l = []
>>> l.append([1,2,3])
>>> l.append([4,5,6])
>>> l
[[1, 2, 3], [4, 5, 6]]
Changing parent element based on child element can currently only happen when we have an <input>
element inside the parent element. When an input gets focus, its corresponding parent element can get affected using CSS.
Following example will help you understand using :focus-within
in CSS.
.outer-div {_x000D_
width: 400px;_x000D_
height: 400px;_x000D_
padding: 50px;_x000D_
float: left_x000D_
}_x000D_
_x000D_
.outer-div:focus-within {_x000D_
background: red;_x000D_
}_x000D_
_x000D_
.inner-div {_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
float: left;_x000D_
background: yellow;_x000D_
padding: 50px;_x000D_
}
_x000D_
<div class="outer-div">_x000D_
<div class="inner-div">_x000D_
I want to change outer-div(Background color) class based on inner-div. Is it possible?_x000D_
<input type="text" placeholder="Name" />_x000D_
</div>_x000D_
</div>
_x000D_
I was too facing similar issue and here I found another solution for it.
I have just started Eclipse Luna and not developed/deployed any project yet. I tried adding Tomcat v7.0 Server
and got same error.
In order to resolve the issue I went to Server Perspective
(it's actually server tab next to the console tab located below Project
code). Double click on Server which is added to Eclipse. It will open up Overview page. Look for Server Location and select Use workspace metadata(does not modify Tomcat location). Now restart the Server and error will go away.
Server > (double click) Tomcat v7.0 Server at localhost > (Overview page) Server Location > Select -- Use workspace metadata(does not modify Tomcat location).
Your code sample didn't expand on part of your topic, namely symbols, and so that part of the question went unanswered.
If you have two strings, foo and bar, and both can be either a string or a symbol, you can test equality with
foo.to_s == bar.to_s
It's a little more efficient to skip the string conversions on operands with known type. So if foo is always a string
foo == bar.to_s
But the efficiency gain is almost certainly not worth demanding any extra work on behalf of the caller.
Prior to Ruby 2.2, avoid interning uncontrolled input strings for the purpose of comparison (with strings or symbols), because symbols are not garbage collected, and so you can open yourself to denial of service through resource exhaustion. Limit your use of symbols to values you control, i.e. literals in your code, and trusted configuration properties.
Ruby 2.2 introduced garbage collection of symbols.
By default Wampserver comes configured as securely as it can, so Apache is set to only allow access from the machine running wamp. Afterall it is supposed to be a development server and not a live server.
Also there was a little error released with WAMPServer 2.4 where it used the old Apache 2.2 syntax instead of the new Apache 2.4 syntax for access rights.
You need to change the security setting on Apache to allow access from anywhere else, so edit your httpd.conf
file.
Change this section from :
# onlineoffline tag - don't remove
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
To :
# onlineoffline tag - don't remove
Require local
Require ip 192.168.0
The Require local
allows access from these ip's 127.0.0.1 & localhost & ::1
.
The statement Require ip 192.168.0
will allow you to access the Apache server from any ip on your internal network. Also it will allow access using the server mechines actual ip address from the server machine, as you are trying to do.
In version 3 and > of WAMPServer there is a Virtual Hosts pre defined for localhost
so you have to make the access privilage amendements in the Virtual Host definition config file
First dont amend the httpd.conf
file at all, leave it as you found it.
Using the menus, edit the httpd-vhosts.conf
file.
It should look like this :
<VirtualHost *:80>
ServerName localhost
DocumentRoot D:/wamp/www
<Directory "D:/wamp/www/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
Amend it to
<VirtualHost *:80>
ServerName localhost
DocumentRoot D:/wamp/www
<Directory "D:/wamp/www/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
Hopefully you will have created a Virtual Host for your project and not be using the wamp\www
folder for your site. In that case leave the localhost definition alone and make the change only to your Virtual Host.
Dont forget to restart Apache after making this change
Example:
git tag -a v1.2 9fceb02 -m "Message here"
Where 9fceb02
is the beginning part of the commit id.
You can then push the tag using git push origin v1.2
.
You can do git log
to show all the commit id's in your current branch.
There is also a good chapter on tagging in the Pro Git book.
Warning: This creates tags with the current date (and that value is what will show on a GitHub releases page, for example). If you want the tag to be dated with the commit date, please look at another answer.
I create the tag like this and then I push it to GitHub:
git tag -a v1.1 -m "Version 1.1 is waiting for review"
git push --tags
Counting objects: 1, done.
Writing objects: 100% (1/1), 180 bytes, done.
Total 1 (delta 0), reused 0 (delta 0)
To [email protected]:neoneye/triangle_draw.git
* [new tag] v1.1 -> v1.1
In case you need to apply a dynamic delay with the lodash's debounce
function:
props: {
delay: String
},
data: () => ({
search: null
}),
created () {
this.valueChanged = debounce(function (event) {
// Here you have access to `this`
this.makeAPIrequest(event.target.value)
}.bind(this), this.delay)
},
methods: {
makeAPIrequest (newVal) {
// ...
}
}
And the template:
<template>
//...
<input type="text" v-model="search" @input="valueChanged" />
//...
</template>
NOTE: in the example above I made an example of search input which can call the API with a custom delay which is provided in props
cmsjr had the right solution. I just wanted to point out a couple of things for your future trigger development. If you are using the values statement in an insert in a trigger, there is a stong possibility that you are doing the wrong thing. Triggers fire once for each batch of records inserted, deleted, or updated. So if ten records were inserted in one batch, then the trigger fires once. If you are refering to the data in the inserted or deleted and using variables and the values clause then you are only going to get the data for one of those records. This causes data integrity problems. You can fix this by using a set-based insert as cmsjr shows above or by using a cursor. Don't ever choose the cursor path. A cursor in a trigger is a problem waiting to happen as they are slow and may well lock up your table for hours. I removed a cursor from a trigger once and improved an import process from 40 minutes to 45 seconds.
You may think nobody is ever going to add multiple records, but it happens more frequently than most non-database people realize. Don't write a trigger that will not work under all the possible insert, update, delete conditions. Nobody is going to use the one record at a time method when they have to import 1,000,000 sales target records from a new customer or update all the prices by 10% or delete all the records from a vendor whose products you don't sell anymore.
Try this..
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#CABBBBBB"/>
<corners android:radius="2dp" />
</shape>
</item>
<item
android:left="0dp"
android:right="0dp"
android:top="0dp"
android:bottom="2dp">
<shape android:shape="rectangle">
<solid android:color="@android:color/white"/>
<corners android:radius="2dp" />
</shape>
</item>
</layer-list>
You are running into a problem because you are instantiating and keeping references to your fragments outside of PagerAdapter.getItem
, and are trying to use those references independently of the ViewPager. As Seraph says, you do have guarantees that a fragment has been instantiated/added in a ViewPager at a particular time - this should be considered an implementation detail. A ViewPager does lazy loading of its pages; by default it only loads the current page, and the one to the left and right.
If you put your app into the background, the fragments that have been added to the fragment manager are saved automatically. Even if your app is killed, this information is restored when you relaunch your app.
Now consider that you have viewed a few pages, Fragments A, B and C. You know that these have been added to the fragment manager. Because you are using FragmentPagerAdapter
and not FragmentStatePagerAdapter
, these fragments will still be added (but potentially detached) when you scroll to other pages.
Consider that you then background your application, and then it gets killed. When you come back, Android will remember that you used to have Fragments A, B and C in the fragment manager and so it recreates them for you and then adds them. However, the ones that are added to the fragment manager now are NOT the ones you have in your fragments list in your Activity.
The FragmentPagerAdapter will not try to call getPosition
if there is already a fragment added for that particular page position. In fact, since the fragment recreated by Android will never be removed, you have no hope of replacing it with a call to getPosition
. Getting a handle on it is also pretty difficult to obtain a reference to it because it was added with a tag that is unknown to you. This is by design; you are discouraged from messing with the fragments that the view pager is managing. You should be performing all your actions within a fragment, communicating with the activity, and requesting to switch to a particular page, if necessary.
Now, back to your problem with the missing activity. Calling pagerAdapter.getItem(1)).update(id, name)
after all of this has happened returns you the fragment in your list, which has yet to be added to the fragment manager, and so it will not have an Activity reference. I would that suggest your update method should modify some shared data structure (possibly managed by the activity), and then when you move to a particular page it can draw itself based on this updated data.
Make sure that your <td>
is not display: block;
Floating will do this, but much easier to just: display: inline;
Embed in a stack view. Stack view is a component recently added by Apple in their iOS SDK to reflect grid based implementations in java script web based front end libraries such as bootstrap.
Use
driver.findElement(By.linkText("App Configuration")).click()
Other Approaches will be
JavascriptLibrary jsLib = new JavascriptLibrary();
jsLib.callEmbeddedSelenium(selenium, "triggerMouseEventAt", elementToClick,"click", "0,0");
or
((JavascriptExecutor) driver).executeScript("arguments[0].click();", elementToClick);
For detailed answer, View this post
It's an indication that connection pooling is being used (which is a good thing).
Hi sorry the code for the second one should be:
private static void getAll(CarList c1) {
ArrayList <Car> cars = c1.getAll(); // error incompatible type
for(Car item : cars)
{
System.out.println(item.getMake()
+ " "
+ item.getReg()
);
}
}
I have a class called CarList which contains the arraylist and its method, so in the tester class, i have basically this code to use that CarList class:
CarList c1; c1 = new CarList();
everything else works, such as adding and removing cars and displaying an inidividual car, i just need a code to display all cars in the arraylist.
Make sure you have the EntityFramework Nuget package installed for your project.
From @TonyDing's answer:
Right-click on the Solution from the Visual Studio Solution Explorer click the Manage Nuget packages for solution and install the EntityFramework
Once it is installed, I still had the error, but then did a reinstall per @papergodzilla's comment:
Update-Package -reinstall
and it resolved my issue
Do this in the Package Manager Console (View > Other windows > Package Manager Console).
Now everything is good!
var d = $.parseJSON(result.d);
for(var i =0;i<d.length;i++){
alert(d[i].EmployeeName);
}
If you want to use the version of Javascript called ES 2015 (aka ES6) or later, you can use template strings introduced by ES 2015 and recommended by some guidelines (like Airbnb's style guide):
const after = "test";
const mystr = `This is: ${after}`;
I'd just like to point out that Apache has the worst inheritance rules when using multiple .htaccess files across directory depths. Two key pitfalls:
RewriteOptions InheritDownBefore
directive (or similar) to change this. (see question)This means the suggested global solution on the Apache Wiki does not work if you use any other .htaccess files in subdirectories. I wrote a modified version that does:
RewriteEngine On
# This will enable the Rewrite capabilities
RewriteOptions InheritDownBefore
# This prevents the rule from being overrided by .htaccess files in subdirectories.
RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [QSA,R,L]
# This rule will redirect users from their original location, to the same location but using HTTPS.
# i.e. http://www.example.com/foo/ to https://www.example.com/foo/
The most popular answer is incomplete:
Since this search will generally be performed only for files from installed packages, yum whatprovides is made blisteringly fast by disabling all external repos (the implicit "installed" repo can't be disabled).
yum --disablerepo=* whatprovides <file>
Yes you are right. You have placed WHERE
clause wrong. You can only use one WHERE
clause in single query so try AND
for multiple conditions like this:
SELECT table1.f_id FROM table1
INNER JOIN table2
ON table2.f_id = table1.f_id
WHERE table2.f_type = 'InProcess'
AND f_com_id = '430'
AND f_status = 'Submitted'
Here's possibly the simplest way:
IO.copy_stream(URI.open("https://i.pinimg.com/originals/24/17/d6/2417d6b3f3dc236b0b5b80fb00b3a791.png"), 'destination.png')
Not sure what you table structure is like but see below.
public NamePriceModel[] AllProducts()
{
try
{
using (UserDataDataContext db = new UserDataDataContext())
{
return db.mrobProducts
.Where(x => x.Status == 1)
.Select(x => new NamePriceModel {
Name = x.Name,
Id = x.Id,
Price = x.Price
})
.OrderBy(x => x.Id)
.ToArray();
}
}
catch
{
return null;
}
}
This would return an array of type anonymous with the members you require.
Update:
Create a new class.
public class NamePriceModel
{
public string Name {get; set;}
public decimal? Price {get; set;}
public int Id {get; set;}
}
I've modified the query above to return this as well and you should change your method from returning string[]
to returning NamePriceModel[]
.
You can try this
EndDate.Date.Subtract(DateTime.Now.Date).Days
Do this:
NSString *lname = [NSString stringWithFormat:@"var=%@",tname.text];
NSString *lpassword = [NSString stringWithFormat:@"var=%@",tpassword.text];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://localhost/Merge/AddClient.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"insert" forHTTPHeaderField:@"METHOD"];
NSString *postString = [NSString stringWithFormat:@"name=%@&password=%@",lname,lpassword];
NSString *clearpost = [postString stringByReplacingOccurrencesOfString:@"var=" withString:@""];
NSLog(@"%@",clearpost);
[request setHTTPBody:[clearpost dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:clearpost forHTTPHeaderField:@"Content-Length"];
[NSURLConnection connectionWithRequest:request delegate:self];
NSLog(@"%@",request);
And add to your insert.php
file:
$name = $_POST['name'];
$password = $_POST['password'];
$con = mysql_connect('localhost','root','password');
$db = mysql_select_db('sample',$con);
$sql = "INSERT INTO authenticate(name,password) VALUES('$name','$password')";
$res = mysql_query($sql,$con) or die(mysql_error());
if ($res) {
echo "success" ;
} else {
echo "faild";
}
Iterating over the answer from Tao-Nhan Nguyen, accounting the original value set for every pod, adjusting it only if it's not greater than 8.0... Add the following to the Podfile:
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
if Gem::Version.new('8.0') > Gem::Version.new(config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'])
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '8.0'
end
end
end
end
Poster is asking for an integer value of MS since Epoch, not a time or S since Epoch.
For that, you need to use NOW(3)
which gives you time in fractional seconds to 3 decimal places (ie MS precision): 2020-02-13 16:30:18.236
Then UNIX_TIMESTAMP(NOW(3))
to get the time to fractional seconds since epoc:
1581611418.236
Finally, FLOOR(UNIX_TIMESTAMP(NOW(3))*1000)
to get it to a nice round integer, for ms since epoc:
1581611418236
Make it a MySQL Function:
CREATE FUNCTION UNIX_MS() RETURN BIGINT DETERMINISTIC
BEGIN
RETURN FLOOR(UNIX_TIMESTAMP(NOW(3))*1000);
END
Now run SELECT UNIX_MS();
Note: this was all copied by hand so if there are mistakes feel free to fix ;)
This is not a perfect solution but it sort of does work.
In the select tag, include the following attributes where 'n' is the number of dropdown rows that would be visible.
<select size="1" position="absolute" onclick="size=(size!=1)?n:1;" ...>
There are three problems with this solution. 1) There is a quick flash of all the elements shown during the first mouse click. 2) The position is set to 'absolute' 3) Even if there are less than 'n' items the dropdown box will still be for the size of 'n' items.
You can simply use DataColumnCollection.IndexOf
So that you can get the index of the required column by name then use it with your row:
row[dt.Columns.IndexOf("ColumnName")] = columnValue;
i = 20
"%x" % i #=> "14"
The order of items in the PATH matters. If there are multiple entries for various java installations, the first one in your PATH will be used.
I have had similar issues after installing a product, like Oracle, that puts it's JRE at the beginning of the PATH.
Ensure that the JDK you want to be loaded is the first entry in your PATH (or at least that it appears before C:\Program Files\Java\jre6\bin
appears).
if the array looks like:
the $key will hold the type (fruit or vegetable) for each array value (orange, banana or carrot)
Undoubtly this can be simplified but the results match your expectations.
The gist of this is to
CTE
for each t2ID
CTE
for each t2ID
CTE
's SQL Statement
;WITH MaxPrice AS (
SELECT t2ID
, t1ID
FROM (
SELECT t2.ID AS t2ID
, t1.ID AS t1ID
, rn = ROW_NUMBER() OVER (PARTITION BY t2.ID ORDER BY t1.Price DESC)
FROM @t1 t1
INNER JOIN @relation r ON r.t1ID = t1.ID
INNER JOIN @t2 t2 ON t2.ID = r.t2ID
) maxt1
WHERE maxt1.rn = 1
)
, SumPrice AS (
SELECT t2ID = t2.ID
, Price = SUM(Price)
FROM @t1 t1
INNER JOIN @relation r ON r.t1ID = t1.ID
INNER JOIN @t2 t2 ON t2.ID = r.t2ID
GROUP BY
t2.ID
)
SELECT t2.ID
, t2.Name
, t2.Orders
, mp.t1ID
, t1.ID
, t1.Name
, sp.Price
FROM @t2 t2
INNER JOIN MaxPrice mp ON mp.t2ID = t2.ID
INNER JOIN SumPrice sp ON sp.t2ID = t2.ID
INNER JOIN @t1 t1 ON t1.ID = mp.t1ID
Simply put, this is wrong because it unnecessarily opens up possibilities to MANY bugs. When the @Override
is invoked, the state of the object may be inconsistent and/or incomplete.
A quote from Effective Java 2nd Edition, Item 17: Design and document for inheritance, or else prohibit it:
There are a few more restrictions that a class must obey to allow inheritance. Constructors must not invoke overridable methods, directly or indirectly. If you violate this rule, program failure will result. The superclass constructor runs before the subclass constructor, so the overriding method in the subclass will be invoked before the subclass constructor has run. If the overriding method depends on any initialization performed by the subclass constructor, the method will not behave as expected.
Here's an example to illustrate:
public class ConstructorCallsOverride {
public static void main(String[] args) {
abstract class Base {
Base() {
overrideMe();
}
abstract void overrideMe();
}
class Child extends Base {
final int x;
Child(int x) {
this.x = x;
}
@Override
void overrideMe() {
System.out.println(x);
}
}
new Child(42); // prints "0"
}
}
Here, when Base
constructor calls overrideMe
, Child
has not finished initializing the final int x
, and the method gets the wrong value. This will almost certainly lead to bugs and errors.
Constructors with many parameters can lead to poor readability, and better alternatives exist.
Here's a quote from Effective Java 2nd Edition, Item 2: Consider a builder pattern when faced with many constructor parameters:
Traditionally, programmers have used the telescoping constructor pattern, in which you provide a constructor with only the required parameters, another with a single optional parameters, a third with two optional parameters, and so on...
The telescoping constructor pattern is essentially something like this:
public class Telescope {
final String name;
final int levels;
final boolean isAdjustable;
public Telescope(String name) {
this(name, 5);
}
public Telescope(String name, int levels) {
this(name, levels, false);
}
public Telescope(String name, int levels, boolean isAdjustable) {
this.name = name;
this.levels = levels;
this.isAdjustable = isAdjustable;
}
}
And now you can do any of the following:
new Telescope("X/1999");
new Telescope("X/1999", 13);
new Telescope("X/1999", 13, true);
You can't, however, currently set only the name
and isAdjustable
, and leaving levels
at default. You can provide more constructor overloads, but obviously the number would explode as the number of parameters grow, and you may even have multiple boolean
and int
arguments, which would really make a mess out of things.
As you can see, this isn't a pleasant pattern to write, and even less pleasant to use (What does "true" mean here? What's 13?).
Bloch recommends using a builder pattern, which would allow you to write something like this instead:
Telescope telly = new Telescope.Builder("X/1999").setAdjustable(true).build();
Note that now the parameters are named, and you can set them in any order you want, and you can skip the ones that you want to keep at default values. This is certainly much better than telescoping constructors, especially when there's a huge number of parameters that belong to many of the same types.
see https://www.cybertec-postgresql.com/en/joining-data-from-multiple-postgres-databases/ [published 2017]
These days you also have the option to use https://prestodb.io/
You can run SQL on that PrestoDB node and it will distribute the SQL query as required. It can connect to the same node twice for different databases, or it might be connecting to different nodes on different hosts.
It does not support:
DELETE
ALTER TABLE
CREATE TABLE (CREATE TABLE AS is supported)
GRANT
REVOKE
SHOW GRANTS
SHOW ROLES
SHOW ROLE GRANTS
So you should only use it for SELECT and JOIN needs. Connect directly to each database for the above needs. (It looks like you can also INSERT or UPDATE which is nice)
Client applications connect to PrestoDB primarily using JDBC, but other types of connection are possible including a Tableu compatible web API
This is an open source tool governed by the Linux Foundation and Presto Foundation.
The founding members of the Presto Foundation are: Facebook, Uber, Twitter, and Alibaba.
The current members are: Facebook, Uber, Twitter, Alibaba, Alluxio, Ahana, Upsolver, and Intel.
You can use the below formula to find the distance between the 2 points:
distance*distance = ((x2 - x1)*(x2 - x1)) + ((y2 - y1)*(y2 - y1))
It depends.
Do you need to be able to tell if the value is missing (is it possible for it to not be defined)?
Is the empty string a valid value for the usage of that string?
If you answered "yes" to both, then you'll want to use null. Otherwise you can't tell the difference between "no value" and "empty string".
If you don't need to know if there's no value then the empty string is probably safer, as it allows you to skip null checks wherever you use it.
Also, anyone wanting to manually URLENCODE the address: http://code.google.com/apis/maps/documentation/webservices/index.html#BuildingURLs
You can use that to create specific rules that meet GM standards.
Make sure you add the connection strings after entityFramework
section:
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
</configSections>
<connectionStrings>
<!-- your connection string goes here, after configSection -->
</connectionString>
This answer can be a possible solution from many. This answer is for the people who are facing this error while working with File Upload..
We were using middleware for token based encryption - decryption and we encountered same error.
Following was our code in route file:
router.route("/uploadVideoMessage")
.post(
middleware.checkToken,
upload.single("video_file"),
videoMessageController.uploadVideoMessage
);
here we were calling middleware before upload function and that was causing the error. So when we changed it to this, it worked.
router.route("/uploadVideoMessage")
.post(
upload.single("video_file"),
middleware.checkToken,
videoMessageController.uploadVideoMessage
);
I just made a getter method.
public int getNumberRows(){
try{
statement = connection.creatStatement();
resultset = statement.executeQuery("your query here");
if(resultset.last()){
return resultset.getRow();
} else {
return 0; //just cus I like to always do some kinda else statement.
}
} catch (Exception e){
System.out.println("Error getting row count");
e.printStackTrace();
}
return 0;
}
I have tried this with and without the WRITE_INTERNAL_STORAGE permission.
There is no WRITE_INTERNAL_STORAGE
permission in Android.
How do I create this file for writing?
You don't, except perhaps on a rooted device, if your app is running with superuser privileges. You are trying to write to the root of internal storage, which apps do not have access to.
Please use the version of the FileOutputStream
constructor that takes a File
object. Create that File
object based off of some location that you can write to, such as:
getFilesDir()
(called on your Activity
or other Context
)getExternalFilesDir()
(called on your Activity
or other Context
)The latter will require WRITE_EXTERNAL_STORAGE
as a permission.
Is there an easier way than writing it to a file then reading from it again?
You can temporarily put it in a static data member.
because many people don't have SD card slots
"SD card slots" are irrelevant, by and large. 99% of Android device users will have external storage -- the exception will be 4+ year old devices where the user removed their SD card. Devices manufactured since mid-2010 have external storage as part of on-board flash, not as removable media.
Using object-scan seems a bit overkill, but you can simply do
// const objectScan = require('object-scan');
const get = (obj, p) => objectScan([p], { abort: true, rtn: 'value' })(obj);
const obj = { a: { b: '1', c: '2' } };
console.log(get(obj, 'a.b'));
// => 1
console.log(get(obj, '*.c'));
// => 2
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
Disclaimer: I'm the author of object-scan
There are a lot more advanced examples in the readme.
The Clarify database is an example of a commercial database that has no primary or foreign keys.
http://www.geekinterview.com/question_details/18869
The funny thing is, the technical documentation goes to great lengths to explain how tables are related, what columns to use to join them etc.
In other words, they could have joined the tables with explicit declarations (DRI) but they chose not to.
Consequently, the Clarify database is full of inconsistencies and it underperforms.
But I suppose it made the developers job easier, not having to write code to deal with referential integrity such as checking for related rows before deleting, adding.
And that, I think, is the main benefit of not having foreign key constraints in a relational database. It makes it easier to develop, at least that is from a devil-may-care point of view.
You can use the rather sensibly named xpath function called concat here
<a>
<xsl:attribute name="href">
<xsl:value-of select="concat('myText:', /*/properties/property[@name='report']/@value)" />
</xsl:attribute>
</a>
Of course, it doesn't have to be text here, it can be another xpath expression to select an element or attribute. And you can have any number of arguments in the concat expression.
Do note, you can make use of Attribute Value Templates (represented by the curly braces) here to simplify your expression
<a href="{concat('myText:', /*/properties/property[@name='report']/@value)}"></a>
I'd suggest using the stopPropagation() method as shown in the modified fiddle:
$('body').click(function() {
$(".popup").hide();
});
$('.popup').click(function(e) {
e.stopPropagation();
});
That way you can hide the popup when you click on the body, without having to add an extra if, and when you click on the popup, the event doesn't bubble up to the body by going through the popup.
The easisest way to get a posted json string, for example, is to read the contents of 'php://input' and then decode it. For example i had a simple Zend route:
'save-json' => array(
'type' => 'Zend\Mvc\Router\Http\Segment',
'options' => array(
'route' => '/save-json/',
'defaults' => array(
'controller' => 'CDB\Controller\Index',
'action' => 'save-json',
),
),
),
and i wanted to post data to it using Angular's $http.post. The post was fine but the retrive method in Zend
$this->params()->fromPost('paramname');
didn't get anything in this case. So my solution was, after trying all kinds of methods like $_POST and the other methods stated above, to read from 'php://':
$content = file_get_contents('php://input');
print_r(json_decode($content));
I got my json array in the end. Hope this helps.
I know it's a several years old post and you may solve your problem with above solution. However, i just want to suggest using InverseProperty for someone who still need. At least you don't need to change anything in OnModelCreating.
The below code is un-tested.
public class Team
{
[Key]
public int TeamId { get; set;}
public string Name { get; set; }
[InverseProperty("HomeTeam")]
public virtual ICollection<Match> HomeMatches { get; set; }
[InverseProperty("GuestTeam")]
public virtual ICollection<Match> GuestMatches { get; set; }
}
public class Match
{
[Key]
public int MatchId { get; set; }
public float HomePoints { get; set; }
public float GuestPoints { get; set; }
public DateTime Date { get; set; }
public virtual Team HomeTeam { get; set; }
public virtual Team GuestTeam { get; set; }
}
You can read more about InverseProperty on MSDN: https://msdn.microsoft.com/en-us/data/jj591583?f=255&MSPPError=-2147217396#Relationships
Select 'Shambhu' as ShambhuNewsFeed,Note as [News Fedd],NotificationId
from Notification with(nolock) where DesignationId=@Designation
Union All
Select 'Shambhu' as ShambhuNewsFeed,Note as [Notification],NotificationId
from Notification with(nolock)
where DesignationId=@Designation
order by NotificationId desc
Use this:
echo "${@:2}"
The following syntax:
echo "${*:2}"
would work as well, but is not recommended, because as @Gordon already explained, that using *
, it runs all of the arguments together as a single argument with spaces, while @
preserves the breaks between them (even if some of the arguments themselves contain spaces). It doesn't make the difference with echo
, but it matters for many other commands.
Oh, I found it. You use last instead of break
for my $entry (@array){
if ($string eq "text"){
last;
}
}
To diagnose better, you can capture the standard output and standard error streams of the external program, in order to see what output was generated and why it might not be running as expected.
Look up:
If you set each of those to true, then you can later call process.StandardOutput.ReadToEnd()
and process.StandardError.ReadToEnd()
to get the output into string variables, which you can easily inspect under the debugger, or output to trace or your log file.
ActiveSheet.UsedRange.Rows.Count + ActiveSheet.UsedRange.Rows(1).Row -1
Short. Safe. Fast. Will return the last non-empty row even if there are blank lines on top of the sheet, or anywhere else. Works also for an empty sheet (Excel reports 1 used row on an empty sheet so the expression will be 1). Tested and working on Excel 2002 and Excel 2010.
You can also deny access to a folder using RedirectMatch
Add the following line to htaccess
RedirectMatch 403 ^/folder/?$
This will return a 403 forbidden
error for the folder ie : http://example.com/folder/
but it doest block access to files and folders inside that folder, if you want to block everything inside the folder then just change the regex pattern to ^/folder/.*$
.
Another option is mod-rewrite
If url-rewrting-module
is enabled you can use something like the following in root/.htaccss
:
RewriteEngine on
RewriteRule ^folder/?$ - [F,L]
This will internally map a request for the folder
to forbidden
error page.
One way to get this error is to forget to use the 'new' keyword when instantiating your Date in javascript like this:
> d = Date();
'Tue Mar 15 2016 20:05:53 GMT-0400 (EDT)'
> typeof(d);
'string'
> d.getFullYear();
TypeError: undefined is not a function
Had you used the 'new' keyword, it would have looked like this:
> el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:08:58 GMT-0400 (EDT)
> typeof(d);
'object'
> d.getFullYear(0);
2016
Another way to get that error is to accidentally re-instantiate a variable in javascript between when you set it and when you use it, like this:
el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:12:13 GMT-0400 (EDT)
> d.getFullYear();
2016
> d = 57 + 23;
80
> d.getFullYear();
TypeError: undefined is not a function
The way of dknaack does not work for me, I found this solution as well:
@Html.DropDownList("Chapters", ViewBag.Chapters as SelectList,
"Select chapter", new { @onchange = "location = this.value;" })
where
@Html.DropDownList(controlName, ViewBag.property + cast, "Default value", @onchange event)
In the controller you can add:
DbModel db = new DbModel(); //entity model of Entity Framework
ViewBag.Chapters = new SelectList(db.T_Chapter, "Id", "Name");
If the purpose is to obtain a bitmap, this is very simple:
Canvas canvas = new Canvas();
canvas.setBitmap(image);
canvas.drawBitmap(image2, new Matrix(), null);
In the end, image will contain the overlap of image and image2.
First, Latin-1 is the same as ISO-8859-1, so, the default was already OK for you. Right?
You successfully set the encoding to ISO-8859-1 with your command line parameter. You also set it programmatically to "Latin-1", but, that's not a recognized value of a file encoding for Java. See http://java.sun.com/javase/6/docs/technotes/guides/intl/encoding.doc.html
When you do that, looks like Charset resets to UTF-8, from looking at the source. That at least explains most of the behavior.
I don't know why OutputStreamWriter shows ISO8859_1. It delegates to closed-source sun.misc.* classes. I'm guessing it isn't quite dealing with encoding via the same mechanism, which is weird.
But of course you should always be specifying what encoding you mean in this code. I'd never rely on the platform default.
On IIS hosted sites, try recycling the app pool. It fixed my issue. Thanks
Here is a function that will do it without jQuery:
function getElementOffset(element)
{
var de = document.documentElement;
var box = element.getBoundingClientRect();
var top = box.top + window.pageYOffset - de.clientTop;
var left = box.left + window.pageXOffset - de.clientLeft;
return { top: top, left: left };
}
I've used Xavier's answer quite a bit. I want to add that restricting the package version to a specified range is easy and useful in the latest versions of NuGet.
For example, if you never want Newtonsoft.Json
to be updated past version 3.x.x
in your project, change the corresponding package
element in your packages.config
file to look like this:
<package id="Newtonsoft.Json" version="3.5.8" allowedVersions="[3.0, 4.0)" targetFramework="net40" />
Notice the allowedVersions
attribute. This will limit the version of that package to versions between 3.0
(inclusive) and 4.0
(exclusive). Then, when you do an Update-Package
on the whole solution, you don't need to worry about that particular package being updated past version 3.x.x
.
The documentation for this functionality is here.
Or use this in the JS file after your fancybox is set up:
$('#link_id').trigger('click');
I believe Fancybox 1.2.1 will use default options otherwise from my testing when I needed to do this.
Off the top of my head, no.
I think the best you could do is something like this:
def loop(f,n):
for i in xrange(n): f()
loop(lambda: <insert expression here>, 5)
But I think you can just live with the extra i
variable.
Here is the option to use the _
variable, which in reality, is just another variable.
for _ in range(n):
do_something()
Note that _
is assigned the last result that returned in an interactive python session:
>>> 1+2
3
>>> _
3
For this reason, I would not use it in this manner. I am unaware of any idiom as mentioned by Ryan. It can mess up your interpreter.
>>> for _ in xrange(10): pass
...
>>> _
9
>>> 1+2
3
>>> _
9
And according to Python grammar, it is an acceptable variable name:
identifier ::= (letter|"_") (letter | digit | "_")*
Believe me, no one wants your source as much as you may think they do. When you decided to develop web pages, you became an open source developer.
It's not possible to disable viewing a pages source. You can attempt to circumvent unknowledgeable users from seeing the source, but it won't stop anyone who understands how to use menu's or shortcut keys. Your best bet is to develop your site in a manner that will not be compromised by someone seeing your source. If you're attempting to hide it for any other reason than to protect your intellectual property, then you're doing something wrong.
Like val
, variables defined with the const
keyword are immutable. The difference here is that const
is used for variables that are known at compile-time.
Declaring a variable const
is much like using the static
keyword in Java.
Let's see how to declare a const variable in Kotlin:
const val COMMUNITY_NAME = "wiki"
And the analogous code written in Java would be:
final static String COMMUNITY_NAME = "wiki";
Adding to the answers above -
@JvmField
an be used to instruct the Kotlin compiler not to generate getters/setters for this property and expose it as a field.
@JvmField
val COMMUNITY_NAME: "Wiki"
Static fields
Kotlin properties declared in a named object or a companion object will have static backing fields either in that named object or in the class containing the companion object.
Usually these fields are private but they can be exposed in one of the following ways:
@JvmField
annotation;lateinit
modifier;const
modifier.More details here - https://kotlinlang.org/docs/reference/java-to-kotlin-interop.html#instance-fields
The path should be left blank to make it default component.
{ path: '', component: DashboardComponent },
You can do this with make - with gnu make it is the -j flag (this will also help on a uniprocessor machine).
For example if you want 4 parallel jobs from make:
make -j 4
You can also run gcc in a pipe with
gcc -pipe
This will pipeline the compile stages, which will also help keep the cores busy.
If you have additional machines available too, you might check out distcc, which will farm compiles out to those as well.
try the following to change your array to 1D
a.reshape((1, -1))
There are multiple ways to achieve this. I can explain you in brief about the 4 types which we use in our daily programming life cycle.
Please go through the below points.
1 Query String.
FirstForm.aspx.cs
Response.Redirect("SecondForm.aspx?Parameter=" + TextBox1.Text);
SecondForm.aspx.cs
TextBox1.Text = Request.QueryString["Parameter"].ToString();
This is the most reliable way when you are passing integer kind of value or other short parameters. More advance in this method if you are using any special characters in the value while passing it through query string, you must encode the value before passing it to next page. So our code snippet of will be something like this:
FirstForm.aspx.cs
Response.Redirect("SecondForm.aspx?Parameter=" + Server.UrlEncode(TextBox1.Text));
SecondForm.aspx.cs
TextBox1.Text = Server.UrlDecode(Request.QueryString["Parameter"].ToString());
URL Encoding
2. Passing value through context object
Passing value through context object is another widely used method.
FirstForm.aspx.cs
TextBox1.Text = this.Context.Items["Parameter"].ToString();
SecondForm.aspx.cs
this.Context.Items["Parameter"] = TextBox1.Text;
Server.Transfer("SecondForm.aspx", true);
Note that we are navigating to another page using Server.Transfer instead of Response.Redirect.Some of us also use Session object to pass values. In that method, value is store in Session object and then later pulled out from Session object in Second page.
3. Posting form to another page instead of PostBack
Third method of passing value by posting page to another form. Here is the example of that:
FirstForm.aspx.cs
private void Page_Load(object sender, System.EventArgs e)
{
buttonSubmit.Attributes.Add("onclick", "return PostPage();");
}
And we create a javascript function to post the form.
SecondForm.aspx.cs
function PostPage()
{
document.Form1.action = "SecondForm.aspx";
document.Form1.method = "POST";
document.Form1.submit();
}
TextBox1.Text = Request.Form["TextBox1"].ToString();
Here we are posting the form to another page instead of itself. You might get viewstate invalid or error in second page using this method. To handle this error is to put EnableViewStateMac=false
4. Another method is by adding PostBackURL property of control for cross page post back
In ASP.NET 2.0, Microsoft has solved this problem by adding PostBackURL property of control for cross page post back. Implementation is a matter of setting one property of control and you are done.
FirstForm.aspx.cs
<asp:Button id=buttonPassValue style=”Z-INDEX: 102" runat=”server” Text=”Button” PostBackUrl=”~/SecondForm.aspx”></asp:Button>
SecondForm.aspx.cs
TextBox1.Text = Request.Form["TextBox1"].ToString();
In above example, we are assigning PostBackUrl property of the button we can determine the page to which it will post instead of itself. In next page, we can access all controls of the previous page using Request object.
You can also use PreviousPage class to access controls of previous page instead of using classic Request object.
SecondForm.aspx
TextBox textBoxTemp = (TextBox) PreviousPage.FindControl(“TextBox1");
TextBox1.Text = textBoxTemp.Text;
As you have noticed, this is also a simple and clean implementation of passing value between pages.
Reference: MICROSOFT MSDN WEBSITE
HAPPY CODING!
IF EXISTS (SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'TableName' AND COLUMN_NAME = 'ColumnName'
AND TABLE_SCHEMA = SchemaName)
BEGIN
ALTER TABLE TableName DROP COLUMN ColumnName;
END;
date +%H:%M
Would be easier, I think :). If you really wanted to chop off the seconds, you could have done
date | sed 's/.* \([0-9]*:[0-9]*\):[0-9]*.*/\1/'
For those that are interested: I wrote a generalized solution that takes the best of both worlds, is more generalized to any type of range and puts quotes around non-arithmetic types (desired for string-like types). Additionally, this approach should not have any ADL issues and also avoid 'surprises' (since it's added explicitly on a case-by-case basis):
template <typename T>
inline constexpr bool is_string_type_v = std::is_convertible_v<const T&, std::string_view>;
template<class T>
struct range_out {
range_out(T& range) : r_(range) {
}
T& r_;
static_assert(!::is_string_type_v<T>, "strings and string-like types should use operator << directly");
};
template <typename T>
std::ostream& operator<< (std::ostream& out, range_out<T>& range) {
constexpr bool is_string_like = is_string_type_v<T::value_type>;
constexpr std::string_view sep{ is_string_like ? "', '" : ", " };
if (!range.r_.empty()) {
out << (is_string_like ? "['" : "[");
out << *range.r_.begin();
for (auto it = range.r_.begin() + 1; it != range.r_.end(); ++it) {
out << sep << *it;
}
out << (is_string_like ? "']" : "]");
}
else {
out << "[]";
}
return out;
}
Now it's fairly easy to use on any range:
std::cout << range_out{ my_vector };
The string-like check leaves room for improvement.
I do also have static_assert
check in my solution to avoid std::basic_string<>
, but I left it out here for simplicity.
If the arguments are filenames to be read from, use the diamond (<>) operator to get at their contents:
while (my $line = <>) {
process_line($line);
}
If the arguments are options/switches, use GetOpt::Std or GetOpt::Long, as already shown by slavy13.myopenid.com.
On the off chance that they're something else, you can access them either by walking through @ARGV explicitly or with the shift
command:
while (my $arg = shift) {
print "Found argument $arg\n";
}
(Note that doing this with shift
will only work if you are outside of all sub
s. Within a sub
, it will retrieve the list of arguments passed to the sub
rather than those passed to the program.)
One very useful feature is the ability to partially build a Maven reactor project so that only the parts you need are included.
To make this a little clearer, consider the case of a collection of WAR files with a lot of common resources (e.g. JavaScript, Spring config files etc) being shared between them using the overlay technique. If you are working on some web page (running in Jetty) and want to change some of the overlay code that is held in a separate module then you'd normally expect to have to stop Jetty, run the Maven build, start Jetty again and continue. This is the case with Eclipse and just about every other IDE I've worked with. Not so in IntelliJ. Using the project settings you can define which facet of which module you would like to be included in a background build. Consequently you end up with a process that appears seamless. You make a change to pretty much any code in the project and instantly it is available after you refresh the browser.
Very neat, and very fast.
I couldn't imagine coding a front end in something like YUI backing onto DWR/SpringMVC without it.
MySQL allows a more readable way to combine multiple updates into a single query. This seems to better fit the scenario you describe, is much easier to read, and avoids those difficult-to-untangle multiple conditions.
INSERT INTO table_users (cod_user, date, user_rol, cod_office)
VALUES
('622057', '12082014', 'student', '17389551'),
('2913659', '12082014', 'assistant','17389551'),
('6160230', '12082014', 'admin', '17389551')
ON DUPLICATE KEY UPDATE
cod_user=VALUES(cod_user), date=VALUES(date)
This assumes that the user_rol, cod_office
combination is a primary key. If only one of these is the primary key, then add the other field to the UPDATE list.
If neither of them is a primary key (that seems unlikely) then this approach will always create new records - probably not what is wanted.
However, this approach makes prepared statements easier to build and more concise.
Two options:
for (let item in MotifIntervention) {
if (isNaN(Number(item))) {
console.log(item);
}
}
Or
Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));
String enums look different than regular ones, for example:
enum MyEnum {
A = "a",
B = "b",
C = "c"
}
Compiles into:
var MyEnum;
(function (MyEnum) {
MyEnum["A"] = "a";
MyEnum["B"] = "b";
MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));
Which just gives you this object:
{
A: "a",
B: "b",
C: "c"
}
You can get all the keys (["A", "B", "C"]
) like this:
Object.keys(MyEnum);
And the values (["a", "b", "c"]
):
Object.keys(MyEnum).map(key => MyEnum[key])
Or using Object.values():
Object.values(MyEnum)
followers_df.reset_index()
followers_df.reindex(index=range(0,20))
I had an issue that even when I did overwrite "height" to "unset" or "initial", it behaved differently from when I removed the previous setting.
It turned out I needed to remove the min-height property too!
height: unset;
min-height: none
Edit: I tested on IE 7 and it doesn't recognize "unset", so "auto" works better".
I found the it wonderful to cover multiple variants of date time format like this:
final DateTimeFormatterBuilder dtfb = new DateTimeFormatterBuilder();
dtfb.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"))
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0);
All of that above can work but for a quick and easy fix you can use the time_formatter package.
Using this package you can convert the epoch to human-readable time.
String convertTimeStamp(timeStamp){
//Pass the epoch server time and the it will format it for you
String formatted = formatTime(timeStamp).toString();
return formatted;
}
//Then you can display it
Text(convertTimeStamp['createdTimeStamp'])//< 1 second : "Just now" up to < 730 days : "1 year"
Here you can check the format of the output that is going to be displayed: Formats
None of the answers worked for me.
When I restarted my computer I could get the server up and running.
Mac
shutdown now -r
Linux
sudo shutdown now -r
Just use dynamic
as the argument:
var list = new List<dynamic>();
In any web application, there will be a web.xml
in the WEB-INF/
folder.
If you dont have one in your web app, as it seems to be the case in your folder structure, the default Tomcat web.xml
is under TOMCAT_HOME/conf/web.xml
Either way, the relevant lines of the web.xml are
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
so any file matching this pattern when found will be shown as the home page.
In Tomcat, a web.xml setting within your web app will override the default, if present.
Further Reading
These answers are fine for debugging, but for programmatically testing the exception, isinstance(e, SomeException)
can be handy, as it tests for subclasses of SomeException
too, so you can create functionality that applies to hierarchies of exceptions.
Class
When you define a class, you define a blueprint for a data type. class hold data, have method that interact with that data and are used to instantiate objects.
Module
Modules are a way of grouping together methods, classes, and constants.
Modules give you two major benefits:
=> Modules provide a namespace and prevent name clashes. Namespace help avoid conflicts with functions and classes with the same name that have been written by someone else.
=> Modules implement the mixin facility.
(including Module in Klazz gives instances of Klazz access to Module methods. )
(extend Klazz with Mod giving the class Klazz access to Mods methods.)
Just tried this recently and when trying to select the JDK... /System/Library/Java/JavaVirtualMachines/
appears as empty when opening&selecting through IntelliJ. Therefore i couldn't select the JDK...
I've found that to workaround this, when the finder windows open (pressing [+] JDK) just use the shortcut Shift + CMD + G to specify the path. (/System/Library/Java/JavaVirtualMachines/1.6.0.jdk
in my case)
And voila, IntelliJ can find everything from that point on.
When writing queries, this difference should be kept in mind :
DECLARE @A INT = 2
SELECT @A = TBL.A
FROM ( SELECT 1 A ) TBL
WHERE 1 = 2
SELECT @A
/* @A is 2*/
---------------------------------------------------------------
DECLARE @A INT = 2
SET @A = (
SELECT TBL.A
FROM ( SELECT 1 A) TBL
WHERE 1 = 2
)
SELECT @A
/* @A is null*/
Your query will work in MYSQL
if you set to disable ONLY_FULL_GROUP_BY
server mode (and by default It is). But in this case, you are using different RDBMS. So to make your query work, add all non-aggregated columns to your GROUP BY
clause, eg
SELECT col1, col2, SUM(col3) totalSUM
FROM tableName
GROUP BY col1, col2
Non-Aggregated columns means the column is not pass into aggregated functions like SUM
, MAX
, COUNT
, etc..
From my experience of having trouble applying previous answers, I have found that I needed to modify their approach in order to achieve what the question here is:
How to get rid of columns where for ALL rows the value is NA?
First note that my solution will only work if you do not have duplicate columns (that issue is dealt with here (on stack overflow)
Second, it uses dplyr
.
Instead of
df <- df %>% select_if(~all(!is.na(.)))
I find that what works is
df <- df %>% select_if(~!all(is.na(.)))
The point is that the "not" symbol "!" needs to be on the outside of the universal quantifier. I.e. the select_if
operator acts on columns. In this case, it selects only those that do not satisfy the criterion
every element is equal to "NA"
The other answer didn't work for me. I had to use mongoose.disconnect();
as stated in this answer.
import numpy as np
import PIL
def convert_image(image_file):
image = Image.open(image_file) # this could be a 4D array PNG (RGBA)
original_width, original_height = image.size
np_image = np.array(image)
new_image = np.zeros((np_image.shape[0], np_image.shape[1], 3))
# create 3D array
for each_channel in range(3):
new_image[:,:,each_channel] = np_image[:,:,each_channel]
# only copy first 3 channels.
# flushing
np_image = []
return new_image
select COUNT(*)
from Monitor as m
inner join Monitor_Request as mr on mr.Company_ID=m.Company_id
group by m.Company_id
having COUNT(m.Monitor_id)>=5
#!/bin/bash
req=$(curl -s -X GET http://host:8080/some/resource -H "Accept: application/json") 2>&1
echo "${req}"
My code is amazing it just took 00:00:00.0007143 less than milisecond with 34 file in folder
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
bool IsEmptyDirectory = (Directory.GetFiles("d:\\pdf").Length == 0);
sw.Stop();
Console.WriteLine(sw.Elapsed);
For the fastest result, ping a DNS server:
ping -c1 "8.8.8.8" &>"/dev/null"
if [[ "${?}" -ne 0 ]]; then
echo "offline"
elif [[ "${#args[@]}" -eq 0 ]]; then
echo "online"
fi
Available as a standalone command: linkStatus
This worked. The first row had column names in it.
COPY wheat FROM 'wheat_crop_data.csv' DELIMITER ';' CSV HEADER
$("#div_element").load('script.php');
demo: http://sandbox.phpcode.eu/g/2ecbe/3
whole code:
<div id="submit">ajax</div>
<div id="div_element"></div>
<script>
$('#submit').click(function(event){
$("#div_element").load('script.php?html=some_arguments');
});
</script>
If you are talking about syncing a forked repo then you can follow these steps.
How to sync a fork repository from git
check your current git branch
git branch
checkout to master if you are not on master
git checkout master
Fetch the upstream repository if you have correct access rights
git fetch upstream
If you are getting below error then run
git remote add upstream [email protected]:upstream_clone_repo_url/xyz.git
fatal: 'upstream/master' does not appear to be a git repository
fatal: Could not read from remote repository.
Please make sure you have the correct access rights and the repository exists.
Now run the below command.
git fetch upstream
Now if you are on master then merge the upstream/master into master branch
git merge upstream/master
That's it!!
Crosscheck via git remote
command, more specific git remote -v
If I also have commit rights to the upstream repo, I can create a local upstream branch and do work that will go upstream there.
There is a new API that makes this even simpler.
plt.gca().invert_xaxis()
and/or
plt.gca().invert_yaxis()
What about
var option = $('<option/>');
option.attr({ 'value': 'myValue' }).text('myText');
$('#county').append(option);
Select * from
(
Select ROW_NUMBER() OVER ( order by Id) as 'Row_Number', *
from tbl_Contact_Us
) as tbl
Where tbl.Row_Number = 5
I used the
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
and works perfectly
Since 0.14.1, you can now do nlargest
and nsmallest
on a groupby
object:
In [23]: df.groupby('id')['value'].nlargest(2)
Out[23]:
id
1 2 3
1 2
2 6 4
5 3
3 7 1
4 8 1
dtype: int64
There's a slight weirdness that you get the original index in there as well, but this might be really useful depending on what your original index was.
If you're not interested in it, you can do .reset_index(level=1, drop=True)
to get rid of it altogether.
(Note: From 0.17.1 you'll be able to do this on a DataFrameGroupBy too but for now it only works with Series
and SeriesGroupBy
.)
[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings] "ProxySettingsPerUser"=dword:00000000
The javadoc says this:
"Returns an immutable list containing only the specified object. The returned list is serializable."
You ask:
Why would I want to have a separate method to do that?
Primarily as a convenience ... to save you having to write a sequence of statements to:
It may also be a bit faster and/or save a bit of memory, but it is unlikely that these small savings will be significant. (An application that creates vast numbers of singleton lists is unusual to say the least.)
How does immutability play a role here?
It is part of the specification of the method; see above.
Are there any special useful use-cases for this method, rather than just being a convenience method?
Clearly, there are use-cases where it is convenient to use the singletonList
method. But I don't know how you would (objectively) distinguish between an ordinary use-case and a "specially useful" one ...
select * from tempdb.sys.columns where object_id =
object_id('tempdb..#mytemptable');
You need to consider the case where the user presses enter in the middle of the text, not just at the end. I'd suggest detecting the enter key in the keyup
event, as suggested, and use a regular expression to ensure the value is as you require:
<textarea id="t" rows="4" cols="80"></textarea>
<script type="text/javascript">
function formatTextArea(textArea) {
textArea.value = textArea.value.replace(/(^|\r\n|\n)([^*]|$)/g, "$1*$2");
}
window.onload = function() {
var textArea = document.getElementById("t");
textArea.onkeyup = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 13) {
formatTextArea(this);
}
};
};
</script>
From javascript, you should be able to get the filename in the onsubmit handler. So in your case, you should do something like:
<form onsubmit="if (document.getElementById('fileUpload').value.match(/xls$/) || document.getElementById('fileUpload').value.match(/xlsx$/)) { alert ('Bad file type') ; return false; } else { return true; }">...</form>
The built-in matrix
function has the nice option to enter data byrow
. Combine that with an unlist
on your source list will give you a matrix. We also need to specify the number of rows so it can break up the unlisted data. That is:
> matrix(unlist(a), byrow=TRUE, nrow=length(a) )
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 1 2 3 4 5
[2,] 2 1 2 3 4 5
[3,] 3 1 2 3 4 5
[4,] 4 1 2 3 4 5
[5,] 5 1 2 3 4 5
[6,] 6 1 2 3 4 5
[7,] 7 1 2 3 4 5
[8,] 8 1 2 3 4 5
[9,] 9 1 2 3 4 5
[10,] 10 1 2 3 4 5
Yes. Google Chrome has deprecated the feature in version 50. If you tried to use it in chrome the error is:
getCurrentPosition() and watchPosition() are deprecated on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins for more details.
So, you have to add SSL certificate. Well, that's the only way.
And it's quite easy now using Let's Encrypt. Here's guide
And for testing purpose you could try this:
1.localhost is treated as a secure origin over HTTP, so if you're able to run your server from localhost, you should be able to test the feature on that server.
2.You can run chrome with the --unsafely-treat-insecure-origin-as-secure="http://example.com" flag (replacing "example.com" with the origin you actually want to test), which will treat that origin as secure for this session. Note that you also need to include the --user-data-dir=/test/only/profile/dir to create a fresh testing profile for the flag to work.
I think Firefox also restricted user from accessing GeoLocation API requests from http
. Here's the webkit changelog: https://trac.webkit.org/changeset/200686
The easier way to only change the radio button is simply set selector for drawable right
<RadioButton
...
android:button="@null"
android:checked="false"
android:drawableRight="@drawable/radio_button_selector" />
And the selector is:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_checkbox_checked" android:state_checked="true" />
<item android:drawable="@drawable/ic_checkbox_unchecked" android:state_checked="false" /></selector>
That's all
Your project has to have a builder set for it. If there is not one Eclipse will default to Ant. Which you can use you have to create an Ant build file, which you can Google how to do. It is rather involved though. This is not required to run locally in Eclipse though. If your class is run-able. It looks like yours is, but we can not see all of it.
If you look at your project build path do you have an output folder selected? If you check that folder have the compiled class files been put there? If not the something is not set in Eclpise for it to know to compile. You might check to see if auto build is set for your project.
public ActionResult CreatePerson(int id) //controller
window.location.href = '@Url.Action("CreatePerson", "Person")?id=' + id;
Or
var id = 'some value';
window.location.href = '@Url.Action("CreatePerson", "Person", new {id = id})';
The problem might be your split()
call. Try just split(" ")
without the square brackets.
Maybe a bit late, but this is my RE:
/^(\w*(\d+[a-zA-Z]|[a-zA-Z]+\d)\w*)+$/
Explanation:
\w*
-> 0 or more alphanumeric digits, at the beginning
\d+[a-zA-Z]|[a-zA-Z]+\d
-> a digit + a letter OR a letter + a digit
\w*
-> 0 or more alphanumeric digits, again
I hope it was understandable
Use CSS :
input[type=submit] {
background:url("BUTTON1.jpg");
}
For HTML :
<input type="submit" value="Login" style="background:url("BUTTON1.jpg");">
You should definitely check out the MSDN on what Outlook will support in regards to css and html. The link is here: http://msdn.microsoft.com/en-us/library/aa338201(v=office.12).aspx. If you do not have at least office 2007 you really need to upgrade as there are major differences between 2007 and previous editions. Also try saving the resulting email to file and examine it with firefox you will see what is being changed by outlook and possibly have a more specific question to ask. You can use Word to view the email as a sort of preview as well (but you won't get info on what styles are/are not being applied.
try this
the solution is, work with callbacks like this
$(function() {
var jForm = $('form[name=form]');
var jPWField = $('#employee_password');
function getCheckedState() {
return jForm.data('checked_state');
};
function setChecked(s) {
jForm.data('checked_state', s);
};
jPWField.change(function() {
//reset checked thing
setChecked(null);
}).trigger('change');
jForm.submit(function(){
switch(getCheckedState()) {
case 'valid':
return true;
case 'invalid':
//invalid, don submit
return false;
default:
//make your check
var password = $.trim(jPWField.val());
$.ajax({
type: "POST",
async: "false",
url: "checkpass.php",
data: {
"password": $.trim(jPWField.val);
}
success: function(html) {
var arr=$.parseJSON(html);
setChecked(arr == "Successful" ? 'valid': 'invalid');
//submit again
jForm.submit();
}
});
return false;
}
});
});
If you have space in the name of the keys, you can use this in bash:
redis-cli keys "pattern: *" | xargs -L1 -I '$' echo '"$"' | xargs redis-cli del
for Google Maps v3, you need to trigger the resize event differently:
google.maps.event.trigger(map, "resize");
See the documentation for the resize event (you'll need to search for the word 'resize'): http://code.google.com/apis/maps/documentation/v3/reference.html#event
Update
This answer has been here a long time, so a little demo might be worthwhile & although it uses jQuery, there's no real need to do so.
$(function() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
var map = new google.maps.Map($("#map-canvas")[0], mapOptions);
// listen for the window resize event & trigger Google Maps to update too
$(window).resize(function() {
// (the 'map' here is the result of the created 'var map = ...' above)
google.maps.event.trigger(map, "resize");
});
});
_x000D_
html,
body {
height: 100%;
}
#map-canvas {
min-width: 200px;
width: 50%;
min-height: 200px;
height: 80%;
border: 1px solid blue;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&dummy=.js"></script>
Google Maps resize demo
<div id="map-canvas"></div>
_x000D_
UPDATE 2018-05-22
With a new renderer release in version 3.32 of Maps JavaScript API the resize event is no longer a part of Map
class.
The documentation states
When the map is resized, the map center is fixed
The full-screen control now preserves center.
There is no longer any need to trigger the resize event manually.
source: https://developers.google.com/maps/documentation/javascript/new-renderer
google.maps.event.trigger(map, "resize");
doesn't have any effect starting from version 3.32
My situation is probably a little different. I am dynamically changing the src of an image via javascript and needed to ensure that the new image is sized proportionally to fit a fixed container (in a photo gallery). I initially just removed the width and height attributes of the image after it is loaded (via the image's load event) and reset these after calculating the preferred dimensions. However, that does not work in Safari and possibly IE (I have not tested it in IE thoroughly, but the image doesn't even show, so...).
Anyway, Safari keeps the dimensions of the previous image so the dimensions are always one image behind. I assume that this has something to do with cache. So the simplest solution is to just clone the image and add it to the DOM (it is important that it be added to the DOM the get the with and height). Give the image a visibility value of hidden (do not use display none because it will not work). After you get the dimensions remove the clone.
Here is my code using jQuery:
// Hack for Safari and others
// clone the image and add it to the DOM
// to get the actual width and height
// of the newly loaded image
var cloned,
o_width,
o_height,
src = 'my_image.jpg',
img = [some existing image object];
$(img)
.load(function()
{
$(this).removeAttr('height').removeAttr('width');
cloned = $(this).clone().css({visibility:'hidden'});
$('body').append(cloned);
o_width = cloned.get(0).width; // I prefer to use native javascript for this
o_height = cloned.get(0).height; // I prefer to use native javascript for this
cloned.remove();
$(this).attr({width:o_width, height:o_height});
})
.attr(src:src);
This solution works in any case.
this worked for me
// using Microsoft.AspNetCore.Authentication.Cookies;
// using Microsoft.AspNetCore.Http;
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
options =>
{
options.LoginPath = new PathString("/auth/login");
options.AccessDeniedPath = new PathString("/auth/denied");
});
function randomString(len) {
var p = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
return [...Array(len)].reduce(a=>a+p[~~(Math.random()*p.length)],'');
}
Summary:
- Create an array of the size we want (because there's no
range(len)
equivalent in javascript.- For each element in the array: pick a random character from
p
and add it to a string- Return the generated string.
Some explanation:
[...Array(len)]
Array(len) or new Array(len) creates an array with undefined pointer(s). One-liners are going to be harder to pull off. The Spread syntax conveniently defines the pointers (now they point to undefined objects!).
.reduce(
Reduce the array to, in this case, a single string. The reduce functionality is common in most languages and worth learning.
a=>a+...
We're using an arrow function.
a
is the accumulator. In this case it's the end-result string we're going to return when we're done (you know it's a string because the second argument to the reduce function, the initialValue is an empty string: ''
). So basically: convert each element in the array with p[~~(Math.random()*p.length)]
, append the result to the a
string and give me a
when you're done.
p[...]
p
is the string of characters we're selecting from. You can access chars in a string like an index (E.g., "abcdefg"[3]
gives us "d"
)
~~(Math.random()*p.length)
Math.random()
returns a floating point between [0, 1) Math.floor(Math.random()*max)
is the de facto standard for getting a random integer in javascript. ~
is the bitwise NOT operator in javascript.
~~
is a shorter, arguably sometimes faster, and definitely funner way to say Math.floor(
Here's some info
Timer works fine. Here, I use Timer to search text after 1.5s and update UI. Hope that helps.
private Timer _timer = new Timer();
_timer.schedule(new TimerTask() {
@Override
public void run() {
// use runOnUiThread(Runnable action)
runOnUiThread(new Runnable() {
@Override
public void run() {
search();
}
});
}
}, timeInterval);
Well! I observer Heroku is famous in budding and newly born developers while AWS has advanced developer persona. DigitalOcean is also a major player in this ground. Cloudways has made it much easy to create Lamp stack in a click on DigitalOcean and AWS. Having all services and packages updates in a click is far better than doing all thing manually.
You can check out completely here: https://www.cloudways.com/blog/host-php-on-aws-cloud/
If you are talking about two kinds of enitities, say teachers and students, you would create two tables for each and a third one to store the relationship. This third table can have two columns, say teacherID and StudentId. If this is not what you are looking for, please elaborate your question.
putting backslash "/" at the end of path to bin of mongodb solved my problem.
This one worked in my python script:
print "\t%-5s %-10s %-10s %-10s %-10s %-10s %-20s" % (thread[0],thread[1],thread[2],thread[3],thread[4],thread[5],thread[6])
Prasoon has already offered up a host of different (and good) ways to do this, none of which need repeating here. I'd like to suggest an alternative approach for speed however.
If you're going to be doing this quite a bit, you may want to consider "sub-classing" your vector so that a sum of elements is maintained separately (not actually sub-classing vector which is iffy due to the lack of a virtual destructor - I'm talking more of a class that contains the sum and a vector within it, has-a
rather than is-a
, and provides the vector-like methods).
For an empty vector, the sum is set to zero. On every insertion to the vector, add the element being inserted to the sum. On every deletion, subtract it. Basically, anything that can change the underlying vector is intercepted to ensure the sum is kept consistent.
That way, you have a very efficient O(1) method for "calculating" the sum at any point in time (just return the sum currently calculated). Insertion and deletion will take slightly longer as you adjust the total and you should take this performance hit into consideration.
Vectors where the sum is needed more often than the vector is changed are the ones likely to benefit from this scheme, since the cost of calculating the sum is amortised over all accesses. Obviously, if you only need the sum every hour and the vector is changing three thousand times a second, it won't be suitable.
Something like this would suffice:
class UberVector:
private Vector<int> vec
private int sum
public UberVector():
vec = new Vector<int>()
sum = 0
public getSum():
return sum
public add (int val):
rc = vec.add (val)
if rc == OK:
sum = sum + val
return rc
public delindex (int idx):
val = 0
if idx >= 0 and idx < vec.size:
val = vec[idx]
rc = vec.delindex (idx)
if rc == OK:
sum = sum - val
return rc
Obviously, that's pseudo-code and you may want to have a little more functionality, but it shows the basic concept.
This worked for me:
$("#SelectedCountryId_option_selected")[0].textContent
Just wanted to add extension method for an array.
interface Array<T> {
remove(element: T): Array<T>;
}
Array.prototype.remove = function (element) {
const index = this.indexOf(element, 0);
if (index > -1) {
return this.splice(index, 1);
}
return this;
};
The query either returned no rows or is erroneus, thus FALSE
is returned. Change it to
if (!$dbc || mysqli_num_rows($dbc) == 0)
mysqli_num_rows
:
Return Values
Returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.
Just to follow up on this since the top answer recommends not using materializecss... in the current version of materialize you no longer need to initialize selects.
Argument order matters
Jersey Beans answer (all 3 examples) worked for me. After quite a bit of trial and error I realized that the order of the arguments matter.
Keeps the container running in the background:
docker run -t -d <image-name>
Keeps the container running in the foreground: docker run <image-name> -t -d
It wasn't obvious to me coming from a Powershell background.
No -P needed; -E is sufficient:
grep -E '(^|\s)abc(\s|$)'
or even without -E:
grep '\(^\|\s\)abc\(\s\|$\)'
This should also work and is a closer answer to what is asked in the question:
for i in range(len(x)):
if valeur.item(i) <= 0.6:
print ("this works")
else:
print ("valeur is too high")
Use NetworkService as Identity value in the application pool advanced settings when you are debugging in Visual Studio. ApplicationPoolIdentity is working if you open the site directly from the browser (or go to virtual directory in IIS and use Browse option at right).
It'll need to be something tailored to the needs, which are dependent on the structure you're presented with. For the example you've provided, this works:
$(document).ready(function(){
var $tmp = $('#listItem').children().remove();
$('#listItem').text('').append($tmp);
});
Demo: http://jquery.nodnod.net/cases/2385/run
But it's fairly dependent on the markup being similar to what you posted.
"sqllite" dosn't have "TRUNCATE " order like than mysql, then we have to get other way... this function (reset_table) frist delete all data in table and then reset AUTOINCREMENT key in table.... now you can use this function every where you want...
example :
private SQLiteDatabase mydb;
private final String dbPath = "data/data/your_project_name/databases/";
private final String dbName = "your_db_name";
public void reset_table(String table_name){
open_db();
mydb.execSQL("Delete from "+table_name);
mydb.execSQL("DELETE FROM SQLITE_SEQUENCE WHERE name='"+table_name+"';");
close_db();
}
public void open_db(){
mydb = SQLiteDatabase.openDatabase(dbPath + dbName + ".db", null, SQLiteDatabase.OPEN_READWRITE);
}
public void close_db(){
mydb.close();
}
This should work:
IDTSVariables100 vars = null;
VariableDispenser.LockForRead("System::TaskName");
VariableDispenser.GetVariables(vars);
string TaskName = vars("System::TaskName").Value.ToString();
vars.Unlock();
Your initial code lacks call of the GetVariables() method.
Opacity changes the context of your z-index, as does the static positioning. Either add opacity to the element that doesn't have it or remove it from the element that does. You'll also have to either make both elements static positioned or specify relative or absolute position. Here's some background on contexts: http://philipwalton.com/articles/what-no-one-told-you-about-z-index/
If you are using scrollview and content view,and you want to increase the height depending the TextView content height,then this piece of code will help you.
Hope this will help,it worked perfectly in iOS9.2
and of course set textview.scrollEnabled = NO;
-(void)adjustHeightOfTextView
{
//this pieces of code will helps to adjust the height of the uitextview View W.R.T content
//This block of code work will calculate the height of the textview text content height and calculate the height for the whole content of the view to be displayed.Height --> 400 is fixed,it will change if you change anything in the storybord.
CGSize textViewSize = [self.textview sizeThatFits:CGSizeMake(self.view.frame.size.width, self.view.frame.size.height)];//calulcate the content width and height
float textviewContentheight =textViewSize.height;
self.scrollview.contentSize = CGSizeMake(self.textview.frame.size.width,textviewContentheight + 400);//height value is passed
self.scrollview.frame =CGRectMake(self.scrollview.frame.origin.x, self.scrollview.frame.origin.y, self.scrollview.frame.size.width, textviewContentheight+400);
CGRect Frame = self.contentview.frame;
Frame.size.height = textviewContentheight + 400;
[self.contentview setFrame:Frame];
self.textview.frame =CGRectMake(self.textview.frame.origin.x, self.textview.frame.origin.y, self.textview.frame.size.width, textviewContentheight);
[ self.textview setContentSize:CGSizeMake( self.textview.frame.size.width,textviewContentheight)];
self.contenview_heightConstraint.constant =
self.scrollview.bounds.size.height;
NSLog(@"%f",self.contenview_heightConstraint.constant);
}
You concrete problem is caused because you're mixing discouraged and old school scriptlets <% %>
with its successor EL ${}
. They do not share the same variable scope. The allFestivals
is not available in scriptlet scope and the i
is not available in EL scope.
You should install JSTL (<-- click the link for instructions) and declare it in top of JSP as follows:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
and then iterate over the list as follows:
<c:forEach items="${allFestivals}" var="festival">
<tr>
<td>${festival.festivalName}</td>
<td>${festival.location}</td>
<td>${festival.startDate}</td>
<td>${festival.endDate}</td>
<td>${festival.URL}</td>
</tr>
</c:forEach>
(beware of possible XSS attack holes, use <c:out>
accordingly)
Don't forget to remove the <jsp:useBean>
as it has no utter value here when you're using a servlet as model-and-view controller. It would only lead to confusion. See also our servlets wiki page. Further you would do yourself a favour to disable scriptlets by the following entry in web.xml
so that you won't accidently use them:
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>
</jsp-config>
This worked for me:
curl -u $username:$api_token -FSubmit=Build 'http://<jenkins-server>/job/<job-name>/buildWithParameters?environment='
API token can be obtained from Jenkins user configuration.
I think you can use substring method to get name of the file from the path string.
String path=":/storage/sdcard0/DCIM/Camera/1414240995236.jpg";
// it contains your image path...I'm using a temp string...
String filename=path.substring(path.lastIndexOf("/")+1);
I resolved this by adding following code to the HTML page, since we are using the third party API which is not controlled by us.
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
Hope this would help, and for a record as well.
Add JSTL library as dependency to your project (javax.servlet.jsp.jstl.core.Config
is a part of this package).
For example, if you were using Gradle, you could write in a build.gradle:
dependencies {
compile 'javax.servlet:jstl:1.2'
}
add style="clear:both;"
to the "adm" div
.