If using backbone.js (which contains url anchor
as route), url query string
may appear:
before url anchor
:
var url = 'http://example.com?a=1&b=3#routepath/subpath';
after url anchor
:
var url = 'http://example.com#routepath/subpath?a=1&b=3';
Solution:
window.location.href.replace(window.location.search, '');
// run as: 'http://example.com#routepath/subpath?a=1&b=3'.replace('?a=1&b=3', '');
You can use the BIT
field
To create new table:
CREATE TABLE Tb_Table1
(
ID INT,
BitColumn BIT DEFAULT 1
)
Adding Column in existing Table:
ALTER TABLE Tb_Table1 ADD BitColumn BIT DEFAULT 1
To Insert record:
INSERT Tb_Table1 VALUES(11,0)
It depends on either the configuration or programmatic change.
Therefore the most reliable way to check the current value is at runtime via code.
See the HttpSessionState.Timeout property; default value is 20 minutes.
You can access this propery in ASP.NET via HttpContext:
this.HttpContext.Session.Timeout // ASP.NET MVC controller
Page.Session.Timeout // ASP.NET Web Forms code-behind
HttpContext.Current.Session.Timeout // Elsewhere
As it has been pointed out, font awesome icons are text, consequently you style it using the appropriate CSS attributes. For example:
.fa-twitter-square {
font-size: 15px;
color: red;
}
If, as it happens quite a bit to me, the icon size doesn't change at all, add "!important" to the font-size attribute.
.fa-twitter-square {
font-size: 15px !important;
color: red;
}
You Can use EXTRACT function pgSQL
EX- date = 1981-05-31
EXTRACT(MONTH FROM date)
it will Give 05
For more details PGSQL Date-Time
I came up with this to overcome a .NET shortcoming having to manually deep copy List<T>.
I use this:
static public IEnumerable<SpotPlacement> CloneList(List<SpotPlacement> spotPlacements)
{
foreach (SpotPlacement sp in spotPlacements)
{
yield return (SpotPlacement)sp.Clone();
}
}
And at another place:
public object Clone()
{
OrderItem newOrderItem = new OrderItem();
...
newOrderItem._exactPlacements.AddRange(SpotPlacement.CloneList(_exactPlacements));
...
return newOrderItem;
}
I tried to come up with oneliner that does this, but it's not possible, due to yield not working inside anonymous method blocks.
Better still, use generic List<T> cloner:
class Utility<T> where T : ICloneable
{
static public IEnumerable<T> CloneList(List<T> tl)
{
foreach (T t in tl)
{
yield return (T)t.Clone();
}
}
}
text.substr(0, start.length()) == start
>>> import requests
>>> response = requests.get('https://website.com/id', headers={'Authorization': 'access_token myToken'})
If the above doesnt work , try this:
>>> import requests
>>> response = requests.get('https://api.buildkite.com/v2/organizations/orgName/pipelines/pipelineName/builds/1230', headers={ 'Authorization': 'Bearer <your_token>' })
>>> print response.json()
EDIT: Okay, so you don't want your local time (which isn't Australia) to contribute to the result, but instead the Australian time zone. Your existing code should be absolutely fine then, although Sydney is currently UTC+11, not UTC+10.. Short but complete test app:
import java.util.*;
import java.text.*;
public class Test {
public static void main(String[] args) throws InterruptedException {
Date date = new Date(1318386508000L);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String formatted = format.format(date);
System.out.println(formatted);
format.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
formatted = format.format(date);
System.out.println(formatted);
}
}
Output:
12/10/2011 02:28:28
12/10/2011 13:28:28
I would also suggest you start using Joda Time which is simply a much nicer date/time API...
EDIT: Note that if your system doesn't know about the Australia/Sydney
time zone, it would show UTC. For example, if I change the code about to use TimeZone.getTimeZone("blah/blah")
it will show the UTC value twice. I suggest you print TimeZone.getTimeZone("Australia/Sydney").getDisplayName()
and see what it says... and check your code for typos too :)
Managed to get answer after do some google..
echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer
Use git reset HEAD
to reset the index without removing files. (If you only want to reset a particular file in the index, you can use git reset HEAD -- /path/to/file
to do so.)
The pipe operator, in a shell, takes the stdout
of the process on the left and passes it as stdin
to the process on the right. It's essentially the equivalent of:
$ proc1 > proc1.out
$ proc2 < proc1.out
$ rm proc1.out
but instead it's $ proc1 | proc2
, the second process can start getting data before the first is done outputting it, and there's no actual file involved.
Name = editTextName.getText().toString().trim();
Email = editTextEmail.getText().toString().trim();
Phone = editTextMobile.getText().toString().trim();
JSONArray jsonArray = new JSONArray();
jsonArray.put(Name);
jsonArray.put(Email);
jsonArray.put(Phone);
final String mRequestBody = jsonArray.toString();
StringRequest stringRequest = new StringRequest(Request.Method.PUT, OTP_Url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.v("LOG_VOLLEY", response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG_VOLLEY", error.toString());
}
}) {
@Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
return null;
}
}
};
stringRequest.setShouldCache(false);
VollySupport.getmInstance(RegisterActivity.this).addToRequestque(stringRequest);
Here is the alternative solution to check whether a particular string contains some predefined string. It uses IndexOf
Function:
'this is your string
Dim strMyString As String = "aaSomethingbb"
'if your string contains these strings
Dim TargetString1 As String = "Something"
Dim TargetString2 As String = "Something2"
If strMyString.IndexOf(TargetString1) <> -1 Or strMyString.IndexOf(TargetString2) <> -1 Then
End If
NOTE: This solution has been tested with Visual Studio 2010.
This line causes the [unchecked] warning:
List<String> list = new LinkedList();
So, the question transforms: why [unchecked] warning is not suppressed automatically only for the case when new collection is created?
I think, it would be much more difficult task then adding <>
feature.
UPD: I also think that there would be a mess if it were legally to use raw types 'just for a few things'.
I was trying to @Autowire
a Spring-managed service into my Deserializer
. Somebody tipped me off to Jackson using the new
operator when invoking the serializers/deserializers. This meant no auto-wiring of Jackson's instance of my Deserializer
. Here's how I was able to @Autowire
my service class into my Deserializer
:
context.xml
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="objectMapper" />
</bean>
</mvc:message-converters>
</mvc>
<bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<!-- Add deserializers that require autowiring -->
<property name="deserializersByType">
<map key-type="java.lang.Class">
<entry key="com.acme.Anchor">
<bean class="com.acme.AnchorDeserializer" />
</entry>
</map>
</property>
</bean>
Now that my Deserializer
is a Spring-managed bean, auto-wiring works!
AnchorDeserializer.java
public class AnchorDeserializer extends JsonDeserializer<Anchor> {
@Autowired
private AnchorService anchorService;
public Anchor deserialize(JsonParser parser, DeserializationContext context)
throws IOException, JsonProcessingException {
// Do stuff
}
}
AnchorService.java
@Service
public class AnchorService {}
Update: While my original answer worked for me back when I wrote this, @xi.lin's response is exactly what is needed. Nice find!
I would also suggest running a few virtual machines rather than running multiple versions of Internet Explorer on the same instance of Windows.
Microsoft provides Virtual PC disk images with Internet Explorer 6, 7, and 8 at the Internet Explorer Application Compatibility VPC Image download page.
The current list of virtual disk images available from the above link are:
(List is current as of October 11, 2009. All versions have expiration dates.)
Read this Bug Issue: http://bugs.jquery.com/ticket/11586
Quoting the RFC 2616 Fielding
The
DELETE
method requests that the origin server delete the resource identified by the Request-URI.
So you need to pass the data in the URI
$.ajax({
url: urlCall + '?' + $.param({"Id": Id, "bolDeleteReq" : bolDeleteReq}),
type: 'DELETE',
success: callback || $.noop,
error: errorCallback || $.noop
});
The activity is declared NOT be recreated by rotation or keyboard slide.
Just got the same problem. Fix for API level 13 or higer.
From Android docs:
Note: If your application targets API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), then you should also declare the "screenSize" configuration, because it also changes when a device switches between portrait and landscape orientations.
So i've changed my manifest to this:
<activity
android:name="MyActivity"
android:configChanges="orientation|screenSize"
android:label="MyActivityName" >
</activity>
And now it works fine. Activity is not recreating when i rotate the phone, progress dialog and view stay the same. No error for me.
The report definition is not valid or supported by this version of Reporting Services. This could be the result of publishing a report definition of a later version of Reporting Services, or that the report definition contains XML that is not well-formed or the XML is not valid based on the Report Definition schema.
I got this error when I used ReportSync to upload some .rdl files to SQL Server Report Services. In my case, the issue was that these .rdl files had some Text Box containing characters like ©
, —
(Em dash), –
(En dash) characters, etc. When uploading .rdl files using ReportSync, I had to encode these characters (©
, —
, –
, etc.) and use Placeholder Properties to set the Markup type to HTML in order to get rid of this error.
I wouldn't get this error If I manually uploaded each of the .rdl files one-by-one using SQL Server Reporting Services. But I have a lot of .rdl files and uploading each one individually would be time-consuming, which is why I use ReportSync to mass upload all .rdl files.
Sorry, if my answer doesn't seem relevant, but I hope this helps anyone else getting this error message when dealing with SSRS .rdl files.
I added the vendor prefixes, and changed the animation to all
, so you have both opacity and width that are animated.
Is this what you're looking for ? http://jsfiddle.net/u2FKM/3/
fetch
/merge
vs. pull
People often advise you to separate "fetching" from "merging". They say instead of this:
git pull remoteR branchB
do this:
git fetch remoteR
git merge remoteR branchB
What they don't mention is that such a fetch command will actually fetch all branches from the remote repo, which is not what that pull command does. If you have thousands of branches in the remote repo, but you do not want to see all of them, you can run this obscure command:
git fetch remoteR refs/heads/branchB:refs/remotes/remoteR/branchB
git branch -a # to verify
git branch -t branchB remoteR/branchB
Of course, that's ridiculously hard to remember, so if you really want to avoid fetching all branches, it is better to alter your .git/config
as described in ProGit.
The best explanation of all this is in Chapter 9-5 of ProGit, Git Internals - The Refspec (or via github). That is amazingly hard to find via Google.
First, we need to clear up some terminology. For remote-branch-tracking, there are typically 3 different branches to be aware of:
refs/heads/branchB
inside the other reporefs/remotes/remoteR/branchB
in your reporefs/heads/branchB
inside your repoRemote-tracking branches (in refs/remotes
) are read-only. You do not modify those directly. You modify your own branch, and then you push to the corresponding branch at the remote repo. The result is not reflected in your refs/remotes
until after an appropriate pull or fetch. That distinction was difficult for me to understand from the git man-pages, mainly because the local branch (refs/heads/branchB
) is said to "track" the remote-tracking branch when .git/config
defines branch.branchB.remote = remoteR
.
Think of 'refs' as C++ pointers. Physically, they are files containing SHA-digests, but basically they are just pointers into the commit tree. git fetch
will add many nodes to your commit-tree, but how git decides what pointers to move is a bit complicated.
As mentioned in another answer, neither
git pull remoteR branchB
nor
git fetch remoteR branchB
would move refs/remotes/branches/branchB
, and the latter certainly cannot move refs/heads/branchB
. However, both move FETCH_HEAD
. (You can cat
any of these files inside .git/
to see when they change.) And git merge
will refer to FETCH_HEAD
, while setting MERGE_ORIG
, etc.
You should use HTML5 data attributes. You can create your own attributes and save different values in them.
I found the SimpleLogger from heiswayi on GitHub good.
The result returned by find is an array.
Try this instead:
console.log(user[0]["_id"]);
set this :
#inner-right {
height: 100%;
max-height: 96%;//change here
overflow: auto;
background: ivory;
}
this will solve your problem.
You have to log the responseText:
$.ajax({
type: 'POST',
url: 'status.ajax.php',
data: {
deviceId: id
}
})
.done(
function (data) {
//your code
}
)
.fail(function (data) {
console.log( "Ajax failed: " + data['responseText'] );
})
You have to inherit nusoap.php
class and put it in your project directory, you can download it from the Internet.
Use this code:
require_once('nusoap.php');
I think you can use thread like demon-thread for reading your input and your output reader will already be in while loop in main thread so you can read and write at same time.You can modify your program like this:
Thread T=new Thread(new Runnable() {
@Override
public void run() {
while(true)
{
String input = scan.nextLine();
input += "\n";
try {
writer.write(input);
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} );
T.start();
and you can reader will be same as above i.e.
while ((line = reader.readLine ()) != null) {
System.out.println ("Stdout: " + line);
}
make your writer as final otherwise it wont be able to accessible by inner class.
You should have a table with the list of emails to check. Then do this query:
SELECT E.Email, CASE WHEN U.Email IS NULL THEN 'Not Exists' ELSE 'Exists' END Status
FROM EmailsToCheck E
LEFT JOIN (SELECT DISTINCT Email FROM Users) U
ON E.Email = U.Email
I think you should not use spaces between the [(ngModel)]
the =
and the str
. Then you should use a button or something like this with a click function and in this function you can use the values of your inputfields
.
<input id="str" [(ngModel)]="str"/>
<button (click)="sendValues()">Send</button>
and in your component file
str: string;
sendValues(): void {
//do sth with the str e.g. console.log(this.str);
}
Hope I can help you.
I've used this "portable plotter". It's very small, multiplatform, easy to use and you can plug it into different graphical libraries. pplot
(Only for the plots part)
If you use or plan to use Qt, another multiplatform solution is Qwt and Qchart
An enum is just another class in Java, it should be possible.
More accurately, an enum is an instance of Object: http://docs.oracle.com/javase/6/docs/api/java/lang/Enum.html
So yes, it should work.
\w\-
is probably the best but here just another alternative
Use [:alnum:]
if(!preg_match("/[^[:alnum:]\-_]/",$str)) echo "valid";
@NathanClement was a bit faster. Yet, here is the complete code (slightly more elaborate):
Option Explicit
Public Sub ExportWorksheetAndSaveAsCSV()
Dim wbkExport As Workbook
Dim shtToExport As Worksheet
Set shtToExport = ThisWorkbook.Worksheets("Sheet1") 'Sheet to export as CSV
Set wbkExport = Application.Workbooks.Add
shtToExport.Copy Before:=wbkExport.Worksheets(wbkExport.Worksheets.Count)
Application.DisplayAlerts = False 'Possibly overwrite without asking
wbkExport.SaveAs Filename:="C:\tmp\test.csv", FileFormat:=xlCSV
Application.DisplayAlerts = True
wbkExport.Close SaveChanges:=False
End Sub
you just have to add this.
public int getActionBarHeight() {
int height;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
height = getActivity().getActionBar().getHeight();
} else {
height = ((ActionBarActivity) getActivity()).getSupportActionBar().getHeight();
}
return height;
}
Using [name=elementName]{}
without tag before will work too.
It will affect all elements with this name.
For example:
[name=test] {_x000D_
width: 100px;_x000D_
}
_x000D_
<input type=text name=test>_x000D_
<div name=test></div>
_x000D_
My case is a bit different, since it is not a form but to return a view. Add method ->name('route')
.
MyView.blade.php
looks like this:
<a href="{{route('admin')}}">CATEGORIES</a>
And web.php
routes file is defined like this:
Route::view('admin', 'admin.index')->name('admin');
From the Jquery docs (link):
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
Script and JSONP requests are not subject to the same origin policy restrictions.
So I would take it that you need to use jsonp for the request. But haven't tried this myself.
I think it is a better idea to start working with a raw data and then translate it to DOM (document object model)
I would suggest you to work with array of objects and then output it to the DOM in order to accomplish your task.
You can see working example of following code at http://www.softxml.com/stackoverflow/shoppingCart.htm
You can try following approach:
//create array that will hold all ordered products
var shoppingCart = [];
//this function manipulates DOM and displays content of our shopping cart
function displayShoppingCart(){
var orderedProductsTblBody=document.getElementById("orderedProductsTblBody");
//ensure we delete all previously added rows from ordered products table
while(orderedProductsTblBody.rows.length>0) {
orderedProductsTblBody.deleteRow(0);
}
//variable to hold total price of shopping cart
var cart_total_price=0;
//iterate over array of objects
for(var product in shoppingCart){
//add new row
var row=orderedProductsTblBody.insertRow();
//create three cells for product properties
var cellName = row.insertCell(0);
var cellDescription = row.insertCell(1);
var cellPrice = row.insertCell(2);
cellPrice.align="right";
//fill cells with values from current product object of our array
cellName.innerHTML = shoppingCart[product].Name;
cellDescription.innerHTML = shoppingCart[product].Description;
cellPrice.innerHTML = shoppingCart[product].Price;
cart_total_price+=shoppingCart[product].Price;
}
//fill total cost of our shopping cart
document.getElementById("cart_total").innerHTML=cart_total_price;
}
function AddtoCart(name,description,price){
//Below we create JavaScript Object that will hold three properties you have mentioned: Name,Description and Price
var singleProduct = {};
//Fill the product object with data
singleProduct.Name=name;
singleProduct.Description=description;
singleProduct.Price=price;
//Add newly created product to our shopping cart
shoppingCart.push(singleProduct);
//call display function to show on screen
displayShoppingCart();
}
//Add some products to our shopping cart via code or you can create a button with onclick event
//AddtoCart("Table","Big red table",50);
//AddtoCart("Door","Big yellow door",150);
//AddtoCart("Car","Ferrari S23",150000);
<table cellpadding="4" cellspacing="4" border="1">
<tr>
<td valign="top">
<table cellpadding="4" cellspacing="4" border="0">
<thead>
<tr>
<td colspan="2">
Products for sale
</td>
</tr>
</thead>
<tbody>
<tr>
<td>
Table
</td>
<td>
<input type="button" value="Add to cart" onclick="AddtoCart('Table','Big red table',50)"/>
</td>
</tr>
<tr>
<td>
Door
</td>
<td>
<input type="button" value="Add to cart" onclick="AddtoCart('Door','Yellow Door',150)"/>
</td>
</tr>
<tr>
<td>
Car
</td>
<td>
<input type="button" value="Add to cart" onclick="AddtoCart('Ferrari','Ferrari S234',150000)"/>
</td>
</tr>
</tbody>
</table>
</td>
<td valign="top">
<table cellpadding="4" cellspacing="4" border="1" id="orderedProductsTbl">
<thead>
<tr>
<td>
Name
</td>
<td>
Description
</td>
<td>
Price
</td>
</tr>
</thead>
<tbody id="orderedProductsTblBody">
</tbody>
<tfoot>
<tr>
<td colspan="3" align="right" id="cart_total">
</td>
</tr>
</tfoot>
</table>
</td>
</tr>
</table>
Please have a look at following free client-side shopping cart:
SoftEcart(js) is a Responsive, Handlebars & JSON based, E-Commerce shopping cart written in JavaScript with built-in PayPal integration.
Documentation
http://www.softxml.com/softecartjs-demo/documentation/SoftecartJS_free.html
Hope you will find it useful.
You can use
@PostConstruct
public void init() {
// ...
}
This turns out to be a very interesting question. With over a hundred properties being set, you'd think that you'd be allowed to type .clickable { onclick : "alert('hi!');" ; } in your CSS, and it'd work. It's intuitive, it makes so much sense. This would be amazingly useful in monkey-patching dynamically-generated massive UIs.
The problem:
The CSS police, in their infinite wisdom, have drawn a Chinese wall between presentation and behavior. Any HTML properly labeled on-whatever is intentionally not supported by CSS. (Full Properties Table)
The best way around this is to use jQuery, which sets up an interpreted engine in the background to execute what you were trying to do with the CSS anyway. See this page: Add Javascript Onclick To .css File.
Good luck.
The intended use for App_Data is to store database related file. Usually SQL Server Express .mdf files.
2007 might be a bit complicated as well.
The .docx format is a zip file that contains a few folders with other files in them for formatting and other stuff.
Rename a .docx file to .zip and you'll see what I mean.
So if you can work within zip files in PHP, you should be on the right path.
Simply:
String abc="abcdefghight";
byte[] b = abc.getBytes();
You're almost there, you just have to append:
-Dhttp.proxyUser=someUserName
-Dhttp.proxyPassword=somePassword
In PHP 5.3 or greater, you can get it like this:
$ip = getenv('HTTP_CLIENT_IP')?:
getenv('HTTP_X_FORWARDED_FOR')?:
getenv('HTTP_X_FORWARDED')?:
getenv('HTTP_FORWARDED_FOR')?:
getenv('HTTP_FORWARDED')?:
getenv('REMOTE_ADDR');
Since you are copying tha same data to all rows, you don't actually need to loop at all. Try this:
Sub ARRAYER()
Dim Number_of_Sims As Long
Dim rng As Range
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Number_of_Sims = 100000
Set rng = Range("C4:G4")
rng.Offset(1, 0).Resize(Number_of_Sims) = rng.Value
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
It is possible of course, use -l:
instead of -l
. For example -l:libXYZ.a
to link with libXYZ.a
. Notice the lib
written out, as opposed to -lXYZ
which would auto expand to libXYZ
.
If you want the column names only, you can do:
List<string> columns = new List<string>();
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly))
{
DataTable dt = reader.GetSchemaTable();
foreach (DataRow row in dt.Rows)
{
columns.Add(row.Field<String>("ColumnName"));
}
}
But if you only need one row, I like my AdoHelper addition. This addition is great if you have a single line query and you don't want to deal with data table in you code. It's returning a case insensitive dictionary of column names and values.
public static Dictionary<string, string> ExecuteCaseInsensitiveDictionary(string query, string connectionString, Dictionary<string, string> queryParams = null)
{
Dictionary<string, string> CaseInsensitiveDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
// Add the parameters for the SelectCommand.
if (queryParams != null)
foreach (var param in queryParams)
cmd.Parameters.AddWithValue(param.Key, param.Value);
using (SqlDataReader reader = cmd.ExecuteReader())
{
DataTable dt = new DataTable();
dt.Load(reader);
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
CaseInsensitiveDictionary.Add(column.ColumnName, row[column].ToString());
}
}
}
}
conn.Close();
}
}
catch (Exception ex)
{
throw ex;
}
return CaseInsensitiveDictionary;
}
I believe this would work. It takes const char*'s as a parameter.
//params find and replace cannot be NULL
void FindAndReplace( std::string& source, const char* find, const char* replace )
{
//ASSERT(find != NULL);
//ASSERT(replace != NULL);
size_t findLen = strlen(find);
size_t replaceLen = strlen(replace);
size_t pos = 0;
//search for the next occurrence of find within source
while ((pos = source.find(find, pos)) != std::string::npos)
{
//replace the found string with the replacement
source.replace( pos, findLen, replace );
//the next line keeps you from searching your replace string,
//so your could replace "hello" with "hello world"
//and not have it blow chunks.
pos += replaceLen;
}
}
Looks like you're missing the SEPARATOR keyword in the GROUP_CONCAT function.
GROUP_CONCAT(artists.artistname SEPARATOR '----')
The way you've written it, you're concatenating artists.artistname
with the '----'
string using the default comma separator.
Yet another solution as my own reminder; I got this error with FacebookSDK, importing project fails to build because it doesn't have default.properties, it has project.properties.
You asked:
I was looking for a one-liner like:
Ask and ye shall receive. Convert from terrible legacy class Date
to its modern replacement, Instant
.
myJavaUtilDate.toInstant().toString()
2020-05-05T19:46:12.912Z
In Java 8 and later we have the new java.time package built in (Tutorial). Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.
The best solution is to sort your date-time objects rather than strings. But if you must work in strings, read on.
An Instant
represents a moment on the timeline, basically in UTC (see class doc for precise details). The toString
implementation uses the DateTimeFormatter.ISO_INSTANT
format by default. This format includes zero, three, six or nine digits digits as needed to display fraction of a second up to nanosecond precision.
String output = Instant.now().toString(); // Example: '2015-12-03T10:15:30.120Z'
If you must interoperate with the old Date
class, convert to/from java.time via new methods added to the old classes. Example: Date::toInstant
.
myJavaUtilDate.toInstant().toString()
You may want to use an alternate formatter if you need a consistent number of digits in the fractional second or if you need no fractional second.
Another route if you want to truncate fractions of a second is to use ZonedDateTime
instead of Instant
, calling its method to change the fraction to zero.
Note that we must specify a time zone for ZonedDateTime
(thus the name). In our case that means UTC. The subclass of ZoneID
, ZoneOffset
, holds a convenient constant for UTC. If we omit the time zone, the JVM’s current default time zone is implicitly applied.
String output = ZonedDateTime.now( ZoneOffset.UTC ).withNano( 0 ).toString(); // Example: 2015-08-27T19:28:58Z
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
UPDATE: The Joda -Time project is now in maintenance mode, with the team advising migration to the java.time classes.
I was looking for a one-liner
Easy if using the Joda-Time 2.3 library. ISO 8601 is the default formatting.
In the code example below, note that I am specifying a time zone rather than depending on the default time zone. In this case, I'm specifying UTC per your question. The Z
on the end, spoken as "Zulu", means no time zone offset from UTC.
// import org.joda.time.*;
String output = new DateTime( DateTimeZone.UTC );
Output…
2013-12-12T18:29:50.588Z
I am try to convert Object type variable into string using this line of code
try this to convert object value to string:
Java Code
Object dataobject=value;
//convert object into String
String convert= String.valueOf(dataobject);
A CTE worked for me:
with cte as (
select 1 col1
from temptable
group by column_1
)
select COUNT(col1)
from cte;
To expand Hitesh's answer if you want to drop rows where 'x' specifically is nan, you can use the subset parameter. His answer will drop rows where other columns have nans as well
dat.dropna(subset=['x'])
This is not an Array. Better declare it like this:
var assoc_pagine = {};
assoc_pagine["home"]=0;
assoc_pagine["about"]=1;
assoc_pagine["work"]=2;
or
var assoc_pagine = {
home:0,
about:1,
work:2
};
To check if an object contains some label you simply do something like this:
if('work' in assoc_pagine){
// do your thing
};
Your second delegate is not a rewrite of the first in anonymous delegate (rather than lambda) format. Look at your conditions.
First:
x.ID == packageId || x.Parent.ID == packageId || x.Parent.Parent.ID == packageId
Second:
(x.ID == packageId) || (x.Parent != null && x.Parent.ID == packageId) ||
(x.Parent != null && x.Parent.Parent != null && x.Parent.Parent.ID == packageId)
The call to the lambda would throw an exception for any x
where the ID doesn't match and either the parent is null or doesn't match and the grandparent is null. Copy the null checks into the lambda and it should work correctly.
If your original object is not a List<T>
, then we have no way of knowing what the return type of FindAll()
is, and whether or not this implements the IQueryable
interface. If it does, then that likely explains the discrepancy. Because lambdas can be converted at compile time into an Expression<Func<T>>
but anonymous delegates cannot, then you may be using the implementation of IQueryable
when using the lambda version but LINQ-to-Objects when using the anonymous delegate version.
This would also explain why your lambda is not causing a NullReferenceException
. If you were to pass that lambda expression to something that implements IEnumerable<T>
but not IQueryable<T>
, runtime evaluation of the lambda (which is no different from other methods, anonymous or not) would throw a NullReferenceException
the first time it encountered an object where ID
was not equal to the target and the parent or grandparent was null.
Consider the following simple example:
IQueryable<MyObject> source = ...; // some object that implements IQueryable<MyObject>
var anonymousMethod = source.Where(delegate(MyObject o) { return o.Name == "Adam"; });
var expressionLambda = source.Where(o => o.Name == "Adam");
These two methods produce entirely different results.
The first query is the simple version. The anonymous method results in a delegate that's then passed to the IEnumerable<MyObject>.Where
extension method, where the entire contents of source
will be checked (manually in memory using ordinary compiled code) against your delegate. In other words, if you're familiar with iterator blocks in C#, it's something like doing this:
public IEnumerable<MyObject> MyWhere(IEnumerable<MyObject> dataSource, Func<MyObject, bool> predicate)
{
foreach(MyObject item in dataSource)
{
if(predicate(item)) yield return item;
}
}
The salient point here is that you're actually performing your filtering in memory on the client side. For example, if your source were some SQL ORM, there would be no WHERE
clause in the query; the entire result set would be brought back to the client and filtered there.
The second query, which uses a lambda expression, is converted to an Expression<Func<MyObject, bool>>
and uses the IQueryable<MyObject>.Where()
extension method. This results in an object that is also typed as IQueryable<MyObject>
. All of this works by then passing the expression to the underlying provider. This is why you aren't getting a NullReferenceException
. It's entirely up to the query provider how to translate the expression (which, rather than being an actual compiled function that it can just call, is a representation of the logic of the expression using objects) into something it can use.
An easy way to see the distinction (or, at least, that there is) a distinction, would be to put a call to AsEnumerable()
before your call to Where
in the lambda version. This will force your code to use LINQ-to-Objects (meaning it operates on IEnumerable<T>
like the anonymous delegate version, not IQueryable<T>
like the lambda version currently does), and you'll get the exceptions as expected.
The long and the short of it is that your lambda expression is being translated into some kind of query against your data source, whereas the anonymous method version is evaluating the entire data source in memory. Whatever is doing the translating of your lambda into a query is not representing the logic that you're expecting, which is why it isn't producing the results you're expecting.
I wanted to add a concrete example to accompany the other answers
You need to specify the name of the class that you want to test, so if you have the following project (this is a Play project):
You can test just the Login
tests by running the following command from the SBT console:
test:testOnly *LoginServiceSpec
If you are running the command from outside the SBT console, you would do the following:
sbt "test:testOnly *LoginServiceSpec"
You could try this:
SELECT OBJECT_SCHEMA_NAME(ps.object_Id) AS [schemaname],
OBJECT_NAME(ps.object_id) AS [tablename],
row_count AS [rows]
FROM sys.dm_db_partition_stats ps
WHERE OBJECT_SCHEMA_NAME(ps.object_Id) <> 'sys' AND ps.index_id < 2
ORDER BY
OBJECT_SCHEMA_NAME(ps.object_Id),
OBJECT_NAME(ps.object_id)
you can install it dirctly via
$ npm install --save react react-dom
$ npm install --save react-bootstrap
then import what you really need from the bootstrap like :
import Button from 'react-bootstrap/lib/Button';
// or
import Button from 'react-bootstrap';
and also you can install :
npm install --save reactstrap@next react react-dom
check this out click here .
and for the CSS you can read this link also carfuly
XMLReader is well documented on PHP site. This is a XML Pull Parser, which means it's used to iterate through nodes (or DOM Nodes) of given XML document. For example, you could go through the entire document you gave like this:
<?php
$reader = new XMLReader();
if (!$reader->open("data.xml"))
{
die("Failed to open 'data.xml'");
}
while($reader->read())
{
$node = $reader->expand();
// process $node...
}
$reader->close();
?>
It is then up to you to decide how to deal with the node returned by XMLReader::expand().
Really cheap solution:
urllib.urlopen('http://user:[email protected]/api')
(which you may decide is not suitable for a number of reasons, like security of the url)
>>> import urllib, json
>>> result = urllib.urlopen('https://personal-access-token:[email protected]/repos/:owner/:repo')
>>> r = json.load(result.fp)
>>> result.close()
If you ever had to support, say, Mac OS X, which doesn't have /proc/, what would you have done? Use #ifdefs to isolate the platform-specific code (NSBundle, for example)?
Yes, isolating platform-specific code with #ifdefs
is the conventional way this is done.
Another approach would be to have a have clean #ifdef
-less header which contains function declarations and put the implementations in platform specific source files.
For example, check out how POCO (Portable Components) C++ library does something similar for their Environment class.
A vector is a container class while an array is an allocated memory.
If the rest of your system is OK with DateTimeOffset instead of DateTime, there's a really convenient feature:
long unixSeconds = DateTimeOffset.Now.ToUnixTimeSeconds();
Try something like this:
public boolean checkNull() throws IllegalAccessException {
for (Field f : getClass().getDeclaredFields())
if (f.get(this) != null)
return false;
return true;
}
Although it would probably be better to check each variable if at all feasible.
for everything related to Python's style guide: i'd recommend you read PEP8.
To answer your question:
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
Some of the other solutions might not work if you created the cookie manually.
Here's a quick way to delete a cookie:
document.cookie = 'COOKIE_NAME=; Max-Age=0; path=/; domain=' + location.host;
Some hash tables (cuckoo hashing) have guaranteed O(1) lookup
Add this in parent layout of the XML.
android:focusable="true"
android:focusableInTouchMode="true"
It ensures the focus isn't on the editText when the Activity starts.
Error: 403.13 when running WebForms ASP.Net website from Visual Studio.
Access to the root is denied: http://localhost:51365
Navigate to the Login page or any page that exists and it will work:
One line solution:
var x = 3, y = 4;
var ar = new Array(x).fill(new Array(y).fill(0));
It creates matrix array with values = 0
Goto http://buildtry.com
Upload .ipa (iOS) or .apk (Android) file
Copy and Share the link with testers
Open the link in iOS or Android device browser and click Install
The validate_required function seems to expect an HTML form control (e.g, text input field) as first argument, and check whether there is a value there at all. That is not what you want in this case.
Also, when you write ['password'].value
, you create a new array of length one, containing the string
'password'
, and then read the non-existing property "value"
from it, yielding the undefined value.
What you may want to try instead is:
if (password.value != cpassword.value) { cpassword.focus(); return false; }
(You also need to write the error message somehow, but I can't see from your code how that is done.).
pip freeze lists all installed packages even if not by pip/easy_install. On CentOs/Redhat a package installed through rpm is found.
Add your C:\WinPython-64bit-3.4.4.1\python_***\Scripts folder to your system PATH variable by doing the following:
Click Environment Variables. ...
In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. ...
I spent quite a bit of time spelunking through the internet for an elegant solution to this. As is usually the case, I found a lot of conflicting information.
I finally ended with:
EXIT_ON_CLOSE
as this can leave resources behind;Do use something like the following in the JFrame initialization:
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
The real discovery was how to actually dispatch a window message to the JFrame. As an example, as part of your JMenuItem for exiting the application, use the following, where the function getFrame()
returns a reference to the JFrame:
public class AppMenuFileExit extends JMenuItem implements ActionListener
{
// do your normal menu item code here
@Override
public void actionPerformed(ActionEvent e)
{
WindowEvent we;
we = new WindowEvent((Window) App.getFrame(), WindowEvent.WINDOW_CLOSING);
App.getFrame().dispatchEvent(we);
}
}
JFrame is a subclass of Window so may be cast to Window for this purpose.
And, have the following in your JFrame class to handle Window messages:
public class AppFrame extends JFrame implements WindowListener
{
// Do all the things you need to for the class
@Override
public void windowOpened(WindowEvent e)
{}
@Override
public void windowClosing(WindowEvent e)
{/* can do cleanup here if necessary */}
@Override
public void windowClosed(WindowEvent e)
{
dispose();
System.exit(0);
}
@Override
public void windowActivated(WindowEvent e)
{}
@Override
public void windowDeactivated(WindowEvent e)
{}
@Override
public void windowDeiconified(WindowEvent e)
{}
@Override
public void windowIconified(WindowEvent e)
{}
}
I think it's too late to answer this question, but actually there is a way to achieve your goal. You just need to add the following line to your checkbox:
android:button="@null"
android:drawableRight="?android:attr/listChoiceIndicatorMultiple"
You can use your customized drawable for checkbox as well.
And for a radioButton:
android:button="@null"
android:drawableRight="@android:drawable/btn_radio"
And if you want to do it programmatically:
Define a layout and name it RightCheckBox and copy the following lines :
<?xml version="1.0" encoding="utf-8"?>
<CheckBox xmlns:android="http://schemas.android.com/apk/res/android"
android:text="hello"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:button="@null"
android:drawableRight="?android:attr/listChoiceIndicatorMultiple"/>
and when you need to add it programmatically you just need to inflate it to a CheckBox and add it to the root view.
CheckBox cb = (CheckBox)((LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE)).inflate(R.layout.check_right_checkbox,null);
rootView.addView(cb);
Generating a single random number in a program is problematic. Random number generators are only "random" in the sense that repeated invocations produce numbers from a given probability distribution.
Seeding the RNG won't help, especially if you just seed it from a low-resolution timer. You'll just get numbers that are a hash function of the time, and if you call the program often, they may not change often. You might improve a little bit by using srand(time(NULL) + getpid())
(_getpid()
on Windows), but that still won't be random.
The ONLY way to get numbers that are random across multiple invocations of a program is to get them from outside the program. That means using a system service such as /dev/random
(Linux) or CryptGenRandom()
(Windows), or from a service like random.org
.
You can also use this method:
<input type="text" class="@(@mvccondition ? "true-class" : "false-class")">
Try this .. Good luck Thanks.
if You are Using Toolbar the just Add
android:layout_gravity="center_horizontal"
Under the Toolbar Just like this snippet
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay">
<TextView
android:id="@+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" //Important
android:textColor="@color/whitecolor"
android:textSize="20sp"
android:textStyle="bold" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
UPDATE user_account student
SET (student.student_education_facility_id) = (
SELECT teacher.education_facility_id
FROM user_account teacher
WHERE teacher.user_account_id = student.teacher_id AND teacher.user_type = 'ROLE_TEACHER'
)
WHERE student.user_type = 'ROLE_STUDENT';
The Python executable might be installed at a location other than /usr/bin, but env
is nearly always present in that location so using /usr/bin/env
is more portable.
You can easily create a static object that represents a NULL return.
class Attr;
extern Attr AttrNull;
class Node {
....
Attr& getAttribute(const string& attribute_name) const {
//search collection
//if found at i
return attributes[i];
//if not found
return AttrNull;
}
bool IsNull(const Attr& test) const {
return &test == &AttrNull;
}
private:
vector<Attr> attributes;
};
And somewhere in a source file:
static Attr AttrNull;
Declare an instance of MyClass, and then call the member function on that instance:
MyClass m;
m.printInformation();
When you say "in you package folder," do you mean your local app files? If so you can get a list of them using the Context.fileList() method. Just iterate through and look for your file. That's assuming you saved the original file with Context.openFileOutput().
Sample code (in an Activity):
public void onCreate(...) {
super.onCreate(...);
String[] files = fileList();
for (String file : files) {
if (file.equals(myFileName)) {
//file exits
}
}
}
Swift 1.1
extension String {
var length: Int { return countElements(self) } //
}
Swift 1.2
extension String {
var length: Int { return count(self) } //
}
Swift 2.0
extension String {
var length: Int { return characters.count } //
}
Swift 4.2
extension String {
var length: Int { return self.count }
}
let str = "Hello"
let count = str.length // returns 5 (Int)
The C# / .NET engine we use for licence key generation is now maintained as open source:
https://github.com/appsoftware/.NET-Licence-Key-Generator.
It's based on a "Partial Key Verification" system which means only a subset of the key that you use to generate the key has to be compiled into your distributable. You create the keys your self, so the licence implementation is unique to your software.
As stated above, if your code can be decompiled, it's relatively easy to circumvent most licencing systems.
You can use TagLib# which is used by applications such as F-Spot. Besides Exif, it will read a good amount of metadata formats for image, audio and video.
I also like ExifUtils API but it is buggy and is not actively developed.
For SQL Server use exec sp_help
USE db_name;
exec sp_help 'dbo.table_name'
For MySQL, use describe
DESCRIBE table_name;
In JavaScript when you create any object through a constructor call like below
step 1 : create a function say Person..
function Person(name){
this.name=name;
}
person.prototype.print=function(){
console.log(this.name);
}
step 2 : create an instance for this function..
var obj=new Person('venkat')
//above line will instantiate this function(Person) and return a brand new object called Person {name:'venkat'}
if you don't want to instantiate this function and call at same time.we can also do like below..
var Person = {
init: function(name){
this.name=name;
},
print: function(){
console.log(this.name);
}
};
var obj=Object.create(Person);
obj.init('venkat');
obj.print();
in the above method init will help in instantiating the object properties. basically init is like a constructor call on your class.
After that you have to parse the results. Suppose results are in integers, then
int testint1 = Integer.parse(test1);
Similarly others should be parsed. Now the results should be checked for two higher marks in them, by using if statement After that take out the average.
Used This Line In Your Code
error_reporting(E_ALL ^ E_NOTICE);
I think its helf full to you.
This worked for me (Select2 4.0.4):
$(document).on('change', 'select#your_id', function(e) {
// your code
console.log('this.value', this.value);
});
class Singleton(object[,...]):
staticVar1 = None
staticVar2 = None
def __init__(self):
if self.__class__.staticVar1==None :
# create class instance variable for instantiation of class
# assign class instance variable values to class static variables
else:
# assign class static variable values to class instance variables
Note: Using Android Support Library v22.1.0 and targeting API level 11 and up? Scroll down to the last update.
My application style is set to Theme.Holo which is dark and I would like the check boxes on my list view to be of style Theme.Holo.Light. I am not trying to create a custom style. The code below doesn't seem to work, nothing happens at all.
At first it may not be apparent why the system exhibits this behaviour, but when you actually look into the mechanics you can easily deduce it. Let me take you through it step by step.
First, let's take a look what the Widget.Holo.Light.CompoundButton.CheckBox
style defines. To make things more clear, I've also added the 'regular' (non-light) style definition.
<style name="Widget.Holo.Light.CompoundButton.CheckBox" parent="Widget.CompoundButton.CheckBox" />
<style name="Widget.Holo.CompoundButton.CheckBox" parent="Widget.CompoundButton.CheckBox" />
As you can see, both are empty declarations that simply wrap Widget.CompoundButton.CheckBox
in a different name. So let's look at that parent style.
<style name="Widget.CompoundButton.CheckBox">
<item name="android:background">@android:drawable/btn_check_label_background</item>
<item name="android:button">?android:attr/listChoiceIndicatorMultiple</item>
</style>
This style references both a background and button drawable. btn_check_label_background
is simply a 9-patch and hence not very interesting with respect to this matter. However, ?android:attr/listChoiceIndicatorMultiple
indicates that some attribute based on the current theme (this is important to realise) will determine the actual look of the CheckBox
.
As listChoiceIndicatorMultiple
is a theme attribute, you will find multiple declarations for it - one for each theme (or none if it gets inherited from a parent theme). This will look as follows (with other attributes omitted for clarity):
<style name="Theme">
<item name="listChoiceIndicatorMultiple">@android:drawable/btn_check</item>
...
</style>
<style name="Theme.Holo">
<item name="listChoiceIndicatorMultiple">@android:drawable/btn_check_holo_dark</item>
...
</style>
<style name="Theme.Holo.Light" parent="Theme.Light">
<item name="listChoiceIndicatorMultiple">@android:drawable/btn_check_holo_light</item>
...
</style>
So this where the real magic happens: based on the theme's listChoiceIndicatorMultiple
attribute, the actual appearance of the CheckBox
is determined. The phenomenon you're seeing is now easily explained: since the appearance is theme-based (and not style-based, because that is merely an empty definition) and you're inheriting from Theme.Holo
, you will always get the CheckBox
appearance matching the theme.
Now, if you want to change your CheckBox
's appearance to the Holo.Light version, you will need to take a copy of those resources, add them to your local assets and use a custom style to apply them.
As for your second question:
Also can you set styles to individual widgets if you set a style to the application?
Absolutely, and they will override any activity- or application-set styles.
Is there any way to set a theme(style with images) to the checkbox widget. (...) Is there anyway to use this selector: link?
Update:
Let me start with saying again that you're not supposed to rely on Android's internal resources. There's a reason you can't just access the internal namespace as you please.
However, a way to access system resources after all is by doing an id lookup by name. Consider the following code snippet:
int id = Resources.getSystem().getIdentifier("btn_check_holo_light", "drawable", "android");
((CheckBox) findViewById(R.id.checkbox)).setButtonDrawable(id);
The first line will actually return the resource id of the btn_check_holo_light
drawable resource. Since we established earlier that this is the button selector that determines the look of the CheckBox
, we can set it as 'button drawable' on the widget. The result is a CheckBox
with the appearance of the Holo.Light
version, no matter what theme/style you set on the application, activity or widget in xml. Since this sets only the button drawable, you will need to manually change other styling; e.g. with respect to the text appearance.
Below a screenshot showing the result. The top checkbox uses the method described above (I manually set the text colour to black in xml), while the second uses the default theme-based Holo
styling (non-light, that is).
Update2:
With the introduction of Support Library v22.1.0, things have just gotten a lot easier! A quote from the release notes (my emphasis):
Lollipop added the ability to overwrite the theme at a view by view level by using the
android:theme
XML attribute - incredibly useful for things such as dark action bars on light activities. Now, AppCompat allows you to useandroid:theme
for Toolbars (deprecating theapp:theme
used previously) and, even better, bringsandroid:theme
support to all views on API 11+ devices.
In other words: you can now apply a theme on a per-view basis, which makes solving the original problem a lot easier: just specify the theme you'd like to apply for the relevant view. I.e. in the context of the original question, compare the results of below:
<CheckBox
...
android:theme="@android:style/Theme.Holo" />
<CheckBox
...
android:theme="@android:style/Theme.Holo.Light" />
The first CheckBox
is styled as if used in a dark theme, the second as if in a light theme, regardless of the actual theme set to your activity or application.
Of course you should no longer be using the Holo theme, but instead use Material.
For the following HTML document:
<html>
<body>
<a href="http://www.example.com">Example</a>
<a href="http://www.stackoverflow.com">SO</a>
</body>
</html>
The xpath query /html/body//a/@href
(or simply //a/@href
) will return:
http://www.example.com http://www.stackoverflow.com
To select a specific instance use /html/body//a[N]/@href
,
$ /html/body//a[2]/@href http://www.stackoverflow.com
To test for strings contained in the attribute and return the attribute itself place the check on the tag not on the attribute:
$ /html/body//a[contains(@href,'example')]/@href http://www.example.com
Mixing the two:
$ /html/body//a[contains(@href,'com')][2]/@href http://www.stackoverflow.com
The for
-in
loops for each property in an object or array. You can use this property to get to the value as well as change it.
Note: Private properties are not available for inspection, unless you use a "spy"; basically, you override the object and write some code which does a for-in loop inside the object's context.
For in looks like:
for (var property in object) loop();
Some sample code:
function xinspect(o,i){
if(typeof i=='undefined')i='';
if(i.length>50)return '[MAX ITERATIONS]';
var r=[];
for(var p in o){
var t=typeof o[p];
r.push(i+'"'+p+'" ('+t+') => '+(t=='object' ? 'object:'+xinspect(o[p],i+' ') : o[p]+''));
}
return r.join(i+'\n');
}
// example of use:
alert(xinspect(document));
Edit: Some time ago, I wrote my own inspector, if you're interested, I'm happy to share.
Edit 2: Well, I wrote one up anyway.
I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:
multiDexEnabled true
And it worked!
Example
android {
compileSdkVersion 27
buildToolsVersion '27.0.1'
defaultConfig {
applicationId "com.xx.xxx"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
multiDexEnabled true //Add this
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
And clean the project.
Today i also face this type of problem during visual studio 2015 Community installation. As i have 64bit OS. I used https://www.microsoft.com/en-us/download/details.aspx?id=49093 link to update KB2999226 mannualy.
Try It. Good luck.
For those who like me doing same mistake. Here is the elaborated answer Tested in Laravel 5.7
UserFile::orderBy('created_at','desc')->get()->toArray();
Array
(
[0] => Array
(
[id] => 2073
[type] => 'DL'
[url] => 'https://i.picsum.photos/12/884/200/300.jpg'
[created_at] => 2020-08-05 17:16:48
[updated_at] => 2020-08-06 18:08:38
)
[1] => Array
(
[id] => 2074
[type] => 'PROFILE'
[url] => 'https://i.picsum.photos/13/884/200/300.jpg'
[created_at] => 2020-08-05 17:20:06
[updated_at] => 2020-08-06 18:08:38
)
[2] => Array
(
[id] => 2076
[type] => 'PROFILE'
[url] => 'https://i.picsum.photos/13/884/200/300.jpg'
[created_at] => 2020-08-05 17:22:01
[updated_at] => 2020-08-06 18:08:38
)
[3] => Array
(
[id] => 2086
[type] => 'PROFILE'
[url] => 'https://i.picsum.photos/13/884/200/300.jpg'
[created_at] => 2020-08-05 19:22:41
[updated_at] => 2020-08-06 18:08:38
)
)
UserFile::select('type','url','updated_at)->distinct('type')->get()->toArray();
Array
(
[0] => Array
(
[type] => 'DL'
[url] => 'https://i.picsum.photos/12/884/200/300.jpg'
[updated_at] => 2020-08-06 18:08:38
)
[1] => Array
(
[type] => 'PROFILE'
[url] => 'https://i.picsum.photos/13/884/200/300.jpg'
[updated_at] => 2020-08-06 18:08:38
)
)
So Pass only those columns in "select()"
, values of which are same.
For example: 'type','url'
. You can add more columns provided they have same value like 'updated_at'
.
If you try to pass "created_at"
or "id"
in "select()"
, then you will get the records same as A.
Because they are different for each row in DB.
With MVC data transfer objects are often used to map domain models to simpler objects that will ultimately get displayed by the view.
From Wikipedia:
Data transfer object (DTO), formerly known as value objects or VO, is a design pattern used to transfer data between software application subsystems. DTOs are often used in conjunction with data access objects to retrieve data from a database.
Extending on Bumptious Q Bangwhistle's answer:
$('#select2').append($('<option>', {
value: item,
text : item
})).select2();
This would add the new options into the <select>
tags and lets select2 re-render it.
Please read the official Django DOC carefully and you will find the most fit answer.
The best and easist way to solve this is like below.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
The fetch mode will only work when selecting the object by id i.e. using entityManager.find()
. Since Spring Data will always create a query, the fetch mode configuration will have no use to you. You can either use dedicated queries with fetch joins or use entity graphs.
When you want best performance, you should select only the subset of the data you really need. To do this, it is generally recommended to use a DTO approach to avoid unnecessary data to be fetched, but that usually results in quite a lot of error prone boilerplate code, since you need define a dedicated query that constructs your DTO model via a JPQL constructor expression.
Spring Data projections can help here, but at some point you will need a solution like Blaze-Persistence Entity Views which makes this pretty easy and has a lot more features in it's sleeve that will come in handy! You just create a DTO interface per entity where the getters represent the subset of data you need. A solution to your problem could look like this
@EntityView(Identified.class)
public interface IdentifiedView {
@IdMapping
Integer getId();
}
@EntityView(Identified.class)
public interface UserView extends IdentifiedView {
String getName();
}
@EntityView(Identified.class)
public interface StateView extends IdentifiedView {
String getName();
}
@EntityView(Place.class)
public interface PlaceView extends IdentifiedView {
UserView getAuthor();
CityView getCity();
}
@EntityView(City.class)
public interface CityView extends IdentifiedView {
StateView getState();
}
public interface PlaceRepository extends JpaRepository<Place, Long>, PlaceRepositoryCustom {
PlaceView findById(int id);
}
public interface UserRepository extends JpaRepository<User, Long> {
List<UserView> findAllByOrderByIdAsc();
UserView findById(int id);
}
public interface CityRepository extends JpaRepository<City, Long>, CityRepositoryCustom {
CityView findById(int id);
}
Disclaimer, I'm the author of Blaze-Persistence, so I might be biased.
Since the value of $var
is the empty string, this:
if [ $var == $var1 ]; then
expands to this:
if [ == abcd ]; then
which is a syntax error.
You need to quote the arguments:
if [ "$var" == "$var1" ]; then
You can also use =
rather than ==
; that's the original syntax, and it's a bit more portable.
If you're using bash, you can use the [[
syntax, which doesn't require the quotes:
if [[ $var = $var1 ]]; then
Even then, it doesn't hurt to quote the variable reference, and adding quotes:
if [[ "$var" = "$var1" ]]; then
might save a future reader a moment trying to remember whether [[
... ]]
requires them.
More generic way - use file structure to determine bitness and image type:
public static CompilationMode GetCompilationMode(this FileInfo info)
{
if (!info.Exists) throw new ArgumentException($"{info.FullName} does not exist");
var intPtr = IntPtr.Zero;
try
{
uint unmanagedBufferSize = 4096;
intPtr = Marshal.AllocHGlobal((int)unmanagedBufferSize);
using (var stream = File.Open(info.FullName, FileMode.Open, FileAccess.Read))
{
var bytes = new byte[unmanagedBufferSize];
stream.Read(bytes, 0, bytes.Length);
Marshal.Copy(bytes, 0, intPtr, bytes.Length);
}
//Check DOS header magic number
if (Marshal.ReadInt16(intPtr) != 0x5a4d) return CompilationMode.Invalid;
// This will get the address for the WinNT header
var ntHeaderAddressOffset = Marshal.ReadInt32(intPtr + 60);
// Check WinNT header signature
var signature = Marshal.ReadInt32(intPtr + ntHeaderAddressOffset);
if (signature != 0x4550) return CompilationMode.Invalid;
//Determine file bitness by reading magic from IMAGE_OPTIONAL_HEADER
var magic = Marshal.ReadInt16(intPtr + ntHeaderAddressOffset + 24);
var result = CompilationMode.Invalid;
uint clrHeaderSize;
if (magic == 0x10b)
{
clrHeaderSize = (uint)Marshal.ReadInt32(intPtr + ntHeaderAddressOffset + 24 + 208 + 4);
result |= CompilationMode.Bit32;
}
else if (magic == 0x20b)
{
clrHeaderSize = (uint)Marshal.ReadInt32(intPtr + ntHeaderAddressOffset + 24 + 224 + 4);
result |= CompilationMode.Bit64;
}
else return CompilationMode.Invalid;
result |= clrHeaderSize != 0
? CompilationMode.CLR
: CompilationMode.Native;
return result;
}
finally
{
if (intPtr != IntPtr.Zero) Marshal.FreeHGlobal(intPtr);
}
}
Compilation mode enumeration
[Flags]
public enum CompilationMode
{
Invalid = 0,
Native = 0x1,
CLR = Native << 1,
Bit32 = CLR << 1,
Bit64 = Bit32 << 1
}
Source code with explanation at GitHub
For posterity, I think this is quicker:
a = np.array([np.array(list()) for _ in y])
You might even be able to pass in a generator (i.e. [] -> ()), in which case the inner list is never fully stored in memory.
Responding to comment below:
>>> import numpy as np
>>> y = range(10)
>>> a = np.array([np.array(list) for _ in y])
>>> a
array([array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object),
array(<type 'list'>, dtype=object)], dtype=object)
var cols = $(".container .item").length;
if (cols == 5){
$('div.item').removeClass('col-md-2..etc').addClass('col-md-3').css('width', '20%');
}
Jquery and Done! Framework!
try this:
In [110]: (df.groupby('Company Name')
.....: .agg({'Organisation Name':'count', 'Amount': 'sum'})
.....: .reset_index()
.....: .rename(columns={'Organisation Name':'Organisation Count'})
.....: )
Out[110]:
Company Name Amount Organisation Count
0 Vifor Pharma UK Ltd 4207.93 5
or if you don't want to reset index:
df.groupby('Company Name')['Amount'].agg(['sum','count'])
or
df.groupby('Company Name').agg({'Amount': ['sum','count']})
Demo:
In [98]: df.groupby('Company Name')['Amount'].agg(['sum','count'])
Out[98]:
sum count
Company Name
Vifor Pharma UK Ltd 4207.93 5
In [99]: df.groupby('Company Name').agg({'Amount': ['sum','count']})
Out[99]:
Amount
sum count
Company Name
Vifor Pharma UK Ltd 4207.93 5
I wish I'd known basic visual block mode stuff earlier. Even if you don't use Vim for anything else, it can be a big time saver to open up a file in Vim just for some block operations. I'm quite sure I wasted a ton of time doing this kind of thing manually.
Examples I've found particularly useful, when, say, refactoring lists of symbolic constant names consistently:
Enter Visual Block mode (Ctrl + Q for me on Windows instead of Ctrl + V)
Move the cursor to highlight the desired block.
Then, I whatever text
and press Esc to have the text inserted in front of the block on every line.
Use A
instead of I
to have the text inserted after the block on every line.
Also - simply toggling the case of a visual selection with ~
can be a big time saver.
And simply deleting columns, too, with d
of course.
For converting all *.ipynb format files in current directory to python scripts recursively:
for i in *.ipynb **/*.ipynb; do
echo "$i"
jupyter nbconvert "$i" "$i"
done
You can either use the readonly
or the disabled
attribute. Note that when disabled, the input's value will not be submitted when submitting the form.
<input id="price_to" value="price to" readonly="readonly">
<input id="price_to" value="price to" disabled="disabled">
This is an old question, but this is another way, using jQuery to reuse the popover and to keep using the original bootstrap data attributes to make it more semantic:
<a href="#" rel="popover" data-trigger="focus" data-popover-content="#popover">
Show it!
</a>
<!-- Let's show the Bootstrap nav on the popover-->
<div id="list-popover" class="hide">
<ul class="nav nav-pills nav-stacked">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li><a href="#">Separated link</a></li>
</ul>
</div>
$('[rel="popover"]').popover({
container: 'body',
html: true,
content: function () {
var clone = $($(this).data('popover-content')).clone(true).removeClass('hide');
return clone;
}
});
Fiddle with complete example: http://jsfiddle.net/tomsarduy/262w45L5/
I just ran into a VERY insidious example of this problem. My original fragment was much more complex, which made it difficult to see the error.
<ItemsControl
Foreground="Black" Background="White" Grid.IsSharedSizingScope="True"
x:Name="MyGrid" ItemsSource="{Binding}">
>
<ItemsControl.ItemsPanel>
<!-- All is fine here -->
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<!-- All is fine here -->
</ItemsControl.ItemTemplate>
<!-- Have you caught the error yet? -->
</ItemsControl>
The bug? The extra > after the initial opening <ItemsControl>
tag! The <
got applied to the built-in Items collection. When the DataContext was later set, instant crashola. So look out for more than just errors surround your ItemsControl specific data children when debugging this problem.
2^31-1 bytes. So, a little less than 2^31-1 characters for varchar(max) and half that for nvarchar(max).
In case anyone is still looking for this functionality: I made an Android library that has this ability and much more, called ExpandableFab (https://github.com/nambicompany/expandable-fab).
The Material Design spec refers to this functionality as 'Speed Dial' and ExpandableFab implements it along with many additional features.
Nearly everything is customizable (colors, text, size, placement, margins, animations and more) and optional (don't need an Overlay, or FabOptions, or Labels, or icons, etc). Every property can be accessed or set through XML layouts or programmatically - whatever you prefer.
Written 100% in Kotlin but comes with full JavaDoc and KDoc (published API is well documented). Also comes with an example app so you can see different use cases with 0 coding.
Github: https://github.com/nambicompany/expandable-fab
Library website (w/ links to full documentation): https://nambicompany.github.io/expandable-fab/
If you're using Swift, you can create a UILabel extension:
extension UILabel {
@objc var substituteFontName : String {
get { return self.font.fontName }
set { self.font = UIFont(name: newValue, size: self.font.pointSize) }
}
}
And then where you do your appearance proxying:
UILabel.appearance().substituteFontName = applicationFont
There is equivalent Objective-C code using UI_APPEARANCE_SELECTOR
on a property with the name substituteFontName
.
Addition
For the case where you'd want to set bold and regular fonts separately:
extension UILabel {
@objc var substituteFontName : String {
get { return self.font.fontName }
set {
if self.font.fontName.range(of:"Medium") == nil {
self.font = UIFont(name: newValue, size: self.font.pointSize)
}
}
}
@objc var substituteFontNameBold : String {
get { return self.font.fontName }
set {
if self.font.fontName.range(of:"Medium") != nil {
self.font = UIFont(name: newValue, size: self.font.pointSize)
}
}
}
}
Then for your UIAppearance proxies:
UILabel.appearance().substituteFontName = applicationFont
UILabel.appearance().substituteFontNameBold = applicationFontBold
Note: if you're finding that the bold substitution isn't working, it's possible the default font name doesn't contain "Medium". Switch out that string for another match as needed (thanks to Mason in the comments below) .
use below code , change proper database name and user name and then take that output and execute in SSMS. FOR SQL 2005 ABOVE
USE <database_name>
select 'GRANT EXECUTE ON ['+name+'] TO [userName] '
from sys.objects
where type ='P'
and is_ms_shipped = 0
The .bak file from SQL Server is specific to that database dialect, and not compatible with MySQL.
Try using etlalchemy to migrate your SQL Server database into MySQL. It is an open-sourced tool that I created to facilitate easy migrations between different RDBMS's.
Quick installation and examples are provided here on the github page, and a more detailed explanation of the project's origins can be found here.
inArray
returns the index of the element in the array, not a boolean indicating if the item exists in the array. If the element was not found, -1
will be returned.
So, to check if an item is in the array, use:
if(jQuery.inArray("test", myarray) !== -1)
I think this is the easiest way to loop in react js
<ul>
{yourarray.map((item)=><li>{item}</li>)}
</ul>
public static T ParseEnum<T>(string value) //function declaration
{
return (T) Enum.Parse(typeof(T), value);
}
Importance imp = EnumUtil.ParseEnum<Importance>("Active"); //function call
====================A Complete Program====================
using System;
class Program
{
enum PetType
{
None,
Cat = 1,
Dog = 2
}
static void Main()
{
// Possible user input:
string value = "Dog";
// Try to convert the string to an enum:
PetType pet = (PetType)Enum.Parse(typeof(PetType), value);
// See if the conversion succeeded:
if (pet == PetType.Dog)
{
Console.WriteLine("Equals dog.");
}
}
}
-------------
Output
Equals dog.
firstly you have to change the drive, which is allocated to your usb.
follow these step to access your pendrive using CMD. 1- type drivename follow by the colon just like k: 2- type dir it will show all the files and directory in your usb 3- now you can access any file or directory of your usb.
I would use the yattag library. I think it's the most pythonic way:
from yattag import Doc
doc, tag, text = Doc().tagtext()
with tag('food'):
with tag('name'):
text('French Breakfast')
with tag('price', currency='USD'):
text('6.95')
with tag('ingredients'):
for ingredient in ('baguettes', 'jam', 'butter', 'croissants'):
with tag('ingredient'):
text(ingredient)
print(doc.getvalue())
There are couple of good free service that let you do the same. Ideal for showing something quickly for testing:
Edits:
Depending on the usecase it makes a difference whether you use javascript (element.value = x
) or jQuery $(element).val(x);
When x
is undefined
jQuery results in an empty String whereas javascript results in "undefined"
as a String.
For me I had multiple versions of the same library included in /app/libs
. I was using Parse and I had both ParseFacebookUtilsV3-1.9.0.jar
and ParseFacebookUtilsV4-1.9.0.jar
.
Deleting the V3
jar solves the problem.
I'm not quite sure if you mean 'can i use sqlite (websql) in chrome' or 'can i use sqlite (websql) in firefox', so I'll answer both:
Note that WebSQL is not a full-access pipe into an .sqlite database. It's WebSQL. You will not be able to run some specific queries like VACUUM
It's awesome for Create / Read / Update / Delete though. I made a little library that helps with all the annoying nitty gritty like creating tables and querying and a provides a little ORM/ActiveRecord pattern with relations and all and a huge stack of examples that should get you started in no-time, you can check that here
Also, be aware that if you want to build a FireFox extension: Their extension format is about to change. Make sure you want to invest the time twice.
While the WebSQL spec has been deprecated for years, even now in 2017 still does not look like it will be be removed from Chrome for the foreseeable time. They are tracking usage statistics and there are still a large number of chrome extensions and websites out there in the real world implementing the spec.
1) When you use an initializer, for a struct or an array like that, the unspecified values are essentially default constructed. In the case of a primitive type like ints, that means they will be zeroed. Note that this applies recursively: you could have an array of structs containing arrays and if you specify just the first field of the first struct, then all the rest will be initialized with zeros and default constructors.
2) The compiler will probably generate initializer code that is at least as good as you could do by hand. I tend to prefer to let the compiler do the initialization for me, when possible.
Well, there's an alternate way! You can use a button instead of hyperlink. Hence, when the button is clicked the web page specified in "name_of_webpage" is opened in the target frame named "name_of_iframe". It works for me!
<form method="post" action="name_of_webpage" target="name_of_iframe">
<input type="submit" value="any_name_you_want" />
</form>
<iframe name="name_of_iframe"></iframe>
From performance point of view if two lists contain number of elements that differ significantly, you can try such approach (using conditional operator ?:):
1.First you need to declare a converter:
Converter<string, int> del = delegate(string s) { return Int32.Parse(s); };
2.Then you use a conditional operator:
var r = data1.Count > data2.Count ?
data2.ConvertAll<int>(del).Intersect(data1) :
data1.Select(v => v.ToString()).Intersect(data2).ToList<string>().ConvertAll<int>(del);
You convert elements of shorter list to match the type of longer list. Imagine an execution speed if your first set contains 1000 elements and second only 10 (or opposite as it doesn't matter) ;-)
As you want to have a result as List, in a last line you convert the result (only result) back to int.
You have name spaces so you can have globally unique elements. However, 99% of the time this doesn't really matter, but when you put it in the perspective of The Semantic Web, it starts to become important.
For example, you could make an XML mash-up of different schemes just by using the appropriate xmlns
. For example, mash up friend of a friend with vCard, etc.
Adding <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
solves the issue
Here is ultimate unique id generator for you. made by me.
<?php
$d=date ("d");
$m=date ("m");
$y=date ("Y");
$t=time();
$dmt=$d+$m+$y+$t;
$ran= rand(0,10000000);
$dmtran= $dmt+$ran;
$un= uniqid();
$dmtun = $dmt.$un;
$mdun = md5($dmtran.$un);
$sort=substr($mdun, 16); // if you want sort length code.
echo $mdun;
?>
you can echo any 'var' for your id as you like. but $mdun is better, you can replace md5 to sha1 for better code but that will be very long which may you dont need.
Thank you.
Step by step:
In the new window you should see your connected phone.
The equals sign (=) is used as padding in certain forms of base64 encoding. The Wikipedia article on base64 has all the details.
For Chrome they changed autoplay policy, so you can read about here:
var promise = document.querySelector('audio').play();
if (promise !== undefined) {
promise.then(_ => {
// Autoplay started!
}).catch(error => {
// Autoplay was prevented.
// Show a "Play" button so that user can start playback.
});
}
Without annotations, inferred property name (to match from JSON) would be "set", and not -- as seems to be the intent -- "isSet". This is because as per Java Beans specification, methods of form "isXxx" and "setXxx" are taken to mean that there is logical property "xxx" to manage.
import codecs
import shutil
import sys
s = sys.stdin.read(3)
if s != codecs.BOM_UTF8:
sys.stdout.write(s)
shutil.copyfileobj(sys.stdin, sys.stdout)
I ran into this problem on the Raspberry Pi. After trying everything but a reinstall, on a whim, I deleted /var/run/apache2/apache2.pid. I restarted Apache and everything worked. Not sure how to explain that.
Commit before:
To fix author for all commits you can apply command from @Amber's answer:
git commit --amend --author="Author Name <[email protected]>"
Or to reuse your name and email you can just write:
git commit --amend --author=Eugen
Commit after the command:
For example to change all starting from 4025621
:
You must run:
git rebase --onto 4025621 --exec "git commit --amend --author=Eugen" 4025621
Note: To include an author containing spaces such as a name and email address, the author must be surrounded by escaped quotes. For example:
git rebase --onto 4025621 --exec "git commit --amend --author=\"Foo Bar <[email protected]>\"" 4025621
or add this alias into ~/.gitconfig
:
[alias]
reauthor = !bash -c 'git rebase --onto $1 --exec \"git commit --amend --author=$2\" $1' --
And then run:
git reauthor 4025621 Eugen
Thanks, that really clarified my thinking. Now here is (almost) 10 (almost) good reasons NOT to use getters and setters:
The last three I'm just leaving (N/A or D/C)...
I think in general, you'd want a web service for a blocking task (this tasks needs to be completed before we execute more code), and a message queue for a non-blocking task (could take quite a while, but we don't need to wait for it).
On windows 7 and for JDK6, I had to add -Duser.timezone="Europe/Sofia"
to the JAVA_TOOL_OPTIONS system variable located under "My computer=>Properties=>Advanced System Settings=>Environment Variables".
If you already have some other property set for JAVA_TOOL_OPTIONS
just append a space and then insert your property string.
System.getProperties()
can be overridden by calls to System.setProperty(String key, String value)
or with command line parameters -Dfile.separator=/
File.separator
gets the separator for the default filesystem.
FileSystems.getDefault()
gets you the default filesystem.
FileSystem.getSeparator()
gets you the separator character for the filesystem. Note that as an instance method you can use this to pass different filesystems to your code other than the default, in cases where you need your code to operate on multiple filesystems in the one JVM.
Try this
#generic_search_button
{
float: left;
width: 24px; /*new width*/
height: 24px; /*new width*/
border: none !important; /* no border and override any inline styles*/
margin-top: 7px;
cursor: pointer;
background-color: White;
background-image: url(/Images/search.png);
background-repeat: no-repeat;
background-position: center center;
}
I think the image size might be wrong
Use this extension, it generates xpaths based on id or class, which is probably what you want to use.
Click on the browser icon, the panel is shown on the right corner of the page, then click start inspect, then click on any element to get your xpath.
Forwarding the example by @ritiek, I'm a beginner in ML too, maybe this kind of formatting will help see the name instead of just class number.
images = np.vstack([x, y])
prediction = model.predict(images)
print(prediction)
i = 1
for things in prediction:
if(things == 0):
print('%d.It is cancer'%(i))
else:
print('%d.Not cancer'%(i))
i = i + 1
Have you included the System.Web
assembly in the application?
using System.Web;
If not, try specifying the System.Web
namespace, for example:
System.Web.HttpContext.Current
The best answer is this
function f1(){_x000D_
var r=document.getElementById('ms');_x000D_
for(i=0;i<r.length;i++)_x000D_
if(r.options[i].selected==true)_x000D_
{_x000D_
r.remove(i);_x000D_
i--;_x000D_
}_x000D_
}
_x000D_
<select id="ms" size="5" multiple="multiple">_x000D_
<option>A</option>_x000D_
<option>B</option>_x000D_
<option>C</option>_x000D_
<option>D</option>_x000D_
<option>E</option>_x000D_
<option>F</option>_x000D_
</select>_x000D_
<input type="button" value="btn1" id="b1" onclick="f1()"/>
_x000D_
Because your visitor can also add custom options as he want and delete them without need any info about his options . This code is the most responsive delete code that you can write as your selected delete..
enjoy it:))))
Stream::anyMatch
Since Java 8 you could use Stream::anyMatch
.
setA.stream().anyMatch(setB::contains)
This worked for me in Kotlin class
fun hideKeyboard(activity: Activity) {
try {
val inputManager = activity
.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
val currentFocusedView = activity.currentFocus
if (currentFocusedView != null) {
inputManager.hideSoftInputFromWindow(currentFocusedView.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
you can do it with visual Basic, put a Webbrowser control on the form, load an html that opens a popup with Location=no
and it will open a new browser without address bar. Probably not what you are looking for but just thought throw it in :)
Change the checkboxes so that the name includes the index inside the brackets:
<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>">
The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.
You might want to use raw.githack.com. It supports GitHub, Bitbucket, Gitlab and GitHub gists.
https://raw.githubusercontent.com/[user]/[repository]/[branch]/[filename.ext]
In your case .html
extension
Development (throttled)
https://raw.githack.com/[user]/[repository]/[branch]/[filename.ext]
Production (CDN)
https://rawcdn.githack.com/[user]/[repository]/[branch]/[filename.ext]
In your case .html
extension
raw.githack.com also supports other services:
https://bitbucket.org/[user]/[repository]/raw/[branch]/[filename.ext]
Development (throttled)
https://bb.githack.com/[user]/[repository]/raw/[branch]/[filename.ext]
Production (CDN)
https://bbcdn.githack.com/[user]/[repository]/raw/[branch]/[filename.ext]
https://gitlab.com/[user]/[repository]/raw/[branch]/[filename.ext]
Development (throttled)
https://gl.githack.com/[user]/[repository]/raw/[branch]/[filename.ext]
Production (CDN)
https://glcdn.githack.com/[user]/[repository]/raw/[branch]/[filename.ext]
https://gist.githubusercontent.com/[user]/[gist]/raw/[revision]/[filename.ext]
Development (throttled)
https://gist.githack.com/[user]/[gist]/raw/[revision]/[filename.ext]
Production (CDN)
https://gistcdn.githack.com/[user]/[gist]/raw/[revision]/[filename.ext]
Update: rawgit was discontinued
Using @DrunkenDaddy extension function, in my case at least (creating EditText programmatically), it was displaying the keyboard on first click and then the date picker on second click.
Apparently, it's irrelevant to set isFocusable and isFocusableInTouchMode to false, because first click is always interpreted as a focus change by the EditText. So I had to trigger a click when the EditText gained focus. Now it works as expected: on first click it opens directly the date picker and never the keyboard (thanks to setting showSoftInputOnFocus to false):
fun EditText.transformIntoDatePicker(context: Context, format: String = "dd/MM/yyyy", maxDate: Date? = null) {
isClickable = true
showSoftInputOnFocus = false
isCursorVisible = false
setOnFocusChangeListener { _, hasFocus -> if (hasFocus) callOnClick()}
val myCalendar = Calendar.getInstance()
val datePickerOnDataSetListener =
DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth ->
myCalendar.set(Calendar.YEAR, year)
myCalendar.set(Calendar.MONTH, monthOfYear)
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
val sdf = SimpleDateFormat(format, Locale.getDefault())
setText(sdf.format(myCalendar.time))
}
setOnClickListener {
DatePickerDialog(
context, datePickerOnDataSetListener,
myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)
).run {
maxDate?.time?.also { datePicker.maxDate = it }
show()
}
}
The latest set of guidance is as follows: (from https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library#environment-variables)
Use:
System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
From the docs:
public static class EnvironmentVariablesExample
{
[FunctionName("GetEnvironmentVariables")]
public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
{
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
log.LogInformation(GetEnvironmentVariable("AzureWebJobsStorage"));
log.LogInformation(GetEnvironmentVariable("WEBSITE_SITE_NAME"));
}
public static string GetEnvironmentVariable(string name)
{
return name + ": " +
System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
}
}
App settings can be read from environment variables both when developing locally and when running in Azure. When developing locally, app settings come from the
Values
collection in the local.settings.json file. In both environments, local and Azure,GetEnvironmentVariable("<app setting name>")
retrieves the value of the named app setting. For instance, when you're running locally, "My Site Name" would be returned if your local.settings.json file contains{ "Values": { "WEBSITE_SITE_NAME": "My Site Name" } }
.The System.Configuration.ConfigurationManager.AppSettings property is an alternative API for getting app setting values, but we recommend that you use
GetEnvironmentVariable
as shown here.
You can sort a map by value as below, more example here
//Sort a Map by their Value.
Map<Integer, String> random = new HashMap<Integer, String>();
random.put(1,"z");
random.put(6,"k");
random.put(5,"a");
random.put(3,"f");
random.put(9,"c");
Map<Integer, String> sortedMap =
random.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(e1, e2) -> e2, LinkedHashMap::new));
System.out.println("Sorted Map: " + Arrays.toString(sortedMap.entrySet().toArray()));
Just new Date(st);
Assuming that it's the proper format.
There was same problem in my Colleague's code. This sounds as your Radio Group is not properly set with your Radio Buttons. This is the reason you can multi-select the radio buttons. I tried many things, finally i did a trick which is wrong actually, but works fine.
for ( int i = 0 ; i < myCount ; i++ )
{
if ( i != k )
{
System.out.println ( "i = " + i );
radio1[i].setChecked(false);
}
}
Here I set one for loop, which checks for the available radio buttons and de-selects every one except the new clicked one. try it.
If you want to estimate the order of your code empirically rather than by analyzing the code, you could stick in a series of increasing values of n and time your code. Plot your timings on a log scale. If the code is O(x^n), the values should fall on a line of slope n.
This has several advantages over just studying the code. For one thing, you can see whether you're in the range where the run time approaches its asymptotic order. Also, you may find that some code that you thought was order O(x) is really order O(x^2), for example, because of time spent in library calls.
Does m
really need to be a data.frame()
or will a matrix()
suffice?
m <- matrix(0, ncol = 30, nrow = 2)
You can wrap a data.frame()
around that if you need to:
m <- data.frame(m)
or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))
If you already have the databinding in place John Myczek answer is complete. If not you have at least 2 options I know of if you want to specify the source of your data. (However I am not sure whether or not this is in line with most guidelines, like MVVM)
Then you just bind to Users collections and columns are autogenerated as you speficy them. Strings passed to property descriptors are names for column headers. At runtime you can add more PropertyDescriptors to 'Users' add another column to the grid.
Following your comment posted to ceejayoz's answer, two things are messed up a litte:
$first
is not an array, it's a string. Replace $first = $first[0] . "%"
by $first .= "%"
. Just for simplicity. (PHP string operators)
The string being compared with LIKE
operator should be quoted. Replace LIKE ".$first."")
by LIKE '".$first."'")
. (MySQL String Comparison Functions)
Declare @v1 varchar(max), @v2 varchar(200);
Declare @sql nvarchar(max);
Set @sql = N'SELECT @v1 = value1, @v2 = value2
FROM dbo.TblTest -- always use schema
WHERE ID = 61;';
EXEC sp_executesql @sql,
N'@v1 varchar(max) output, @v2 varchar(200) output',
@v1 output, @v2 output;
You should also pass your input, like wherever 61 comes from, as proper parameters (but you won't be able to pass table and column names that way).
Have a look at the following apache commons function:
org.apache.commons.io.FileUtils.readFileToByteArray(File)
Double is a wrapper class,
The Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double.
In addition, this class provides several methods for converting a double to a String and a String to a double, as well as other constants and methods useful when dealing with a double.
The double data type,
The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.
Check each datatype with their ranges : Java's Primitive Data Types.
Important Note : If you'r thinking to use double for precise values, you need to re-think before using it. Java Traps: double
Check the namespace from where we are importing
import { MatDialogModule } from **"@angular/material/dialog";**
import { MatCardModule } from **"@angular/material/card";**
import { MatButtonModule } from **"@angular/material/button";**
I have bundled the answers here and made it version independent;
function generateRandom($min = 1, $max = 20) {
if (function_exists('random_int')):
return random_int($min, $max); // more secure
elseif (function_exists('mt_rand')):
return mt_rand($min, $max); // faster
endif;
return rand($min, $max); // old
}
Below is how I got this working.
The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.
[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]
[HttpPost]
public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)
{
var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
}
The JQuery script used to call this action method:
var requestData = {
InvoiceNumber: $.trim(this.value),
SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
};
$.ajax({
url: '/en/myController/GetDataForInvoiceNumber',
type: 'POST',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
CheckIfInvoiceFound(result);
},
async: true,
processData: false
});
This was a good waste of an hour of my time. For you eager beavers, the following format worked for me:
<input type="datetime-local" name="to" id="to" value="2014-12-08T15:43:00">
The spec was a little confusing to me, it said to use RFC 3339, but on my PHP server when I used the format DATE_RFC3339 it wasn't initializing my hmtl input :( PHP's constant for DATE_RFC3339 is "Y-m-d\TH:i:sP" at the time of writing, it makes sense that you should get rid of the timezone info (we're using datetime-LOCAL, folks). So the format that worked for me was:
"Y-m-d\TH:i:s"
I would've thought it more intuitive to be able to set the value of the datepicker as the datepicker displays the date, but I'm guessing the way it is displayed differs across browsers.
Am adding this answer for the purpose of those who google about this..
There was an episode of DevBytes (ListView Cell Dragging and Rearranging) recently which explains how to do this
You can find it here also the sample code is available here.
What this code basically does is that it creates a dynamic listview
by the extension of listview
that supports cell dragging and swapping. So that you can use the DynamicListView
instead of your basic ListView
and that's it you have implemented a ListView with Drag and Drop.
Another strange thing. You wont see the libs folder in Android Studio, unless you have at least 1 file in the folder. So, I had to go to the libs folder using File Explorer, and then place the jar file there. Then, it showed up in Android Studio.
Here you go with:
from b in _dbContext.Burden
join bl in _dbContext.BurdenLookups on
new { Organization_Type = b.Organization_Type_ID, Cost_Type = b.Cost_Type_ID } equals
new { Organization_Type = bl.Organization_Type_ID, Cost_Type = bl.Cost_Type_ID }
This stems from the fact that on deletion, the iteration skips one element as it semms only to work on the index.
Workaround could be:
x = ["ok", "jj", "uy", "poooo", "fren"]
for item in x[:]: # make a copy of x
if len(item) != 2:
print "length of %s is: %s" %(item, len(item))
x.remove(item)
In the list of arguments, each entry must be on its own. Using
output = subprocess.check_output(["ping", "-c","2", "-W","2", "1.1.1.1"])
should fix your problem.
I had the same issue for my angular project, then I make it work in Chrome by changing the setting. Go to Chrome setting -->site setting -->Insecure content --> click add button of allow, then add your domain name [*.]XXXX.biz
Now problem will be solved.
I tried changing the repository list with:
http://security.ubuntu.com/ubuntu bionic-security main universe http://archive.ubuntu.com/ubuntu bionic main restricted universe
But none of them seem to work, but I finally found a repository that works running the following command
add-apt-repository ppa:ondrej/php
And then updating and installing normally the package using apt-get
As you can see it's installed at last.
To add an element to an array you need to use the format:
array[index] = element;
Where array
is the array you declared, index
is the position where the element will be stored, and element
is the item you want to store in the array.
In your code, you'd want to do something like this:
int[] num = new int[args.length];
for (int i = 0; i < args.length; i++) {
int neki = Integer.parseInt(args[i]);
num[i] = neki;
}
The add()
method is available for Collections
like List
and Set
. You could use it if you were using an ArrayList
(see the documentation), for example:
List<Integer> num = new ArrayList<>();
for (String s : args) {
int neki = Integer.parseInt(s);
num.add(neki);
}
It can happen if you have a tag named same as a branch.
Example: if "release/0.1" is tag name, then
git checkout release/0.1
produces detached HEAD at "release/0.1". If you expect release/0.1 to be a branch name, then you get confused.
I found that using the latest version will fix this problem:
http://code.jquery.com/jquery-git.js
This thread is a bit old, but I still want to add a little demonstration since it is still not an intuitive problem:
me$ git status
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# new file: to-be-added
# modified: to-be-modified
# deleted: to-be-removed
#
me$ git reset -q HEAD to-be-added
# ok
me$ git reset -q HEAD to-be-modified
# ok
me$ git reset -q HEAD to-be-removed
# ok
# or alternatively:
me$ git reset -q HEAD to-be-added to-be-removed to-be-modified
# ok
me$ git status
# On branch master
# Changes not staged for commit:
# (use "git add/rm <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: to-be-modified
# deleted: to-be-removed
#
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# to-be-added
no changes added to commit (use "git add" and/or "git commit -a")
git reset HEAD
(without -q
) gives a warning about the modified file and its exit code is 1 which will be considered as an error in a script.
Edit: git checkout HEAD to-be-modified to-be-removed
also works for unstaging, but removes the change completely from the workspace
Update git 2.23.0: From time to time, the commands change. Now, git status
says:
(use "git restore --staged <file>..." to unstage)
... which works for all three types of change
use android-28
with build-tools
at version 28.0.3
; or build-tools
at version 26.0.3
.
or try this: yes | sudo sdkmanager --licenses
On toolbar -> Help Menu -> Show log in explorer.
It opens log folder, where you can find all logs
First make your file delegate for UITextField
@interface MYLoginViewController () <UITextFieldDelegate>
@end
Then add this method to your code.
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}
Also add self.textField.delegate = self;
str= str.Remove(str.Length - 3);
Create a new branch using the svn copy
command as follows:
$ svn copy svn+ssh://host.example.com/repos/project/trunk \
svn+ssh://host.example.com/repos/project/branches/NAME_OF_BRANCH \
-m "Creating a branch of project"
TCPDF 5.9.010 (2010-10-27) - Support for CSS properties 'border-spacing' and 'padding' for tables were added.
If the script creates any variables or functions in the global space you can check for their existance:
External JS (in global scope) --
var myCustomFlag = true;
And to check if this has run:
if (typeof window.myCustomFlag == 'undefined') {
//the flag was not found, so the code has not run
$.getScript('<external JS>');
}
You can check for the existence of the <script>
tag in question by selecting all of the <script>
elements and checking their src
attributes:
//get the number of `<script>` elements that have the correct `src` attribute
var len = $('script').filter(function () {
return ($(this).attr('src') == '<external JS>');
}).length;
//if there are no scripts that match, the load it
if (len === 0) {
$.getScript('<external JS>');
}
Or you can just bake this .filter()
functionality right into the selector:
var len = $('script[src="<external JS>"]').length;
You can use git stash - if something goes wrong, you can still revert from the stash. Similar to some other answer here, but this one also removes all unstaged files and also all unstaged deletes:
git add .
git stash
if you check that everything is OK, throw the stash away:
git stash drop
The answer from Bilal Maqsood with git clean
also worked for me, but with the stash I have more control - if I do sth accidentally, I can still get my changes back
UPDATE
I think there is 1 more change (don't know why this worked for me before):
git add . -A
instead of git add .
without the -A
the removed files will not be staged
I downloaded the jar file manually and replace the one in my local directory and it worked
The following worked for me with tomcat 8.
Add these lines to apache-tomcat-8.0.9/conf/tomcat-users.xml
For Manager:
<role rolename="manager-gui"/>
<user username="admin" password="pass" roles="manager-gui"/>
For Host Manager:
<role rolename="admin-gui"/>
<user username="admin" password="pass" roles="admin-gui"/>
My solution involved a bit of javascript. Keep the 100% or 100vh on the div (this will avoid the div not appearing on initial page load). Then when the page loads, grab the window height and apply it to the element in question. Avoids the jump because now you have a static height on your div.
var $hero = $('#hero-wrapper'),
h = window.innerHeight;
$hero.css('height', h);
From time to time I present MR concepts to people. I find processing tasks familiar to people and then map them to the MR paradigm.
Usually I take two things:
Group By / Aggregations. Here the advantage of the shuffling stage is clear. An explanation that shuffling is also distributed sort + an explanation of distributed sort algorithm also helps.
Join of two tables. People working with DB are familiar with the concept and its scalability problem. Show how it can be done in MR.
You can use filter like this
angular.module('app').filter('trustAs', ['$sce',
function($sce) {
return function (input, type) {
if (typeof input === "string") {
return $sce.trustAs(type || 'html', input);
}
console.log("trustAs filter. Error. input isn't a string");
return "";
};
}
]);
usage
<div ng-bind-html="myData | trustAs"></div>
it can be used for other resource types, for example source link for iframes and other types declared here