It's just a 'safety' warning. It is a relatively common idiom, but also a relatively common error when you meant to have ==
in there. You can make the warning go away by adding another set of parentheses:
while ((list = list->next))
I got a simpler solution which worked perfectly for me :
Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),R.drawable.change_pass);
toolbar.setOverflowIcon(drawable);
Append the following parameter to the Youtube-URL:
144p: &vq=tiny
240p: &vq=small
360p: &vq=medium
480p: &vq=large
720p: &vq=hd720
For instance:
src="http://www.youtube.com/watch?v=oDOXeO9fAg4"
becomes:
src="http://www.youtube.com/watch?v=oDOXeO9fAg4&vq=large"
Selected answer works for one drop down menu only. For multiple solution would be:
$('body').click(function(event){
$dropdowns.not($dropdowns.has(event.target)).hide();
});
android.view.WindowManager$BadTokenException: Unable to add window"
Problem :
This exception occurs when the app is trying to notify the user from the background thread (AsyncTask) by opening a Dialog.
If you are trying to modify the UI from background thread (usually from onPostExecute() of AsyncTask) and if the activity enters finishing stage i.e.) explicitly calling finish(), user pressing home or back button or activity clean up made by Android then you get this error.
Reason :
The reason for this exception is that, as the exception message says, the activity has finished but you are trying to display a dialog with a context of the finished activity. Since there is no window for the dialog to display the android runtime throws this exception.
Solution:
Use
isFinishing()
method which is called by Android to check whether this activity is in the process of finishing: be it explicit finish() call or activity clean up made by Android. By using this method it is very easy to avoid opening dialog from background thread when activity is finishing.Also maintain a
weak reference
for the activity (and not a strong reference so that activity can be destroyed once not needed) and check if the activity is not finishing before performing any UI using this activity reference (i.e. showing a dialog).
eg.
private class chkSubscription extends AsyncTask<String, Void, String>{
private final WeakReference<login> loginActivityWeakRef;
public chkSubscription (login loginActivity) {
super();
this.loginActivityWeakRef= new WeakReference<login >(loginActivity)
}
protected String doInBackground(String... params) {
//web service call
}
protected void onPostExecute(String result) {
if(page.contains("error")) //when not subscribed
{
if (loginActivityWeakRef.get() != null && !loginActivityWeakRef.get().isFinishing()) {
AlertDialog.Builder builder = new AlertDialog.Builder(login.this);
builder.setCancelable(true);
builder.setMessage(sucObject);
builder.setInverseBackgroundForced(true);
builder.setNeutralButton("Ok",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
dialog.dismiss();
}
});
builder.show();
}
}
}
}
Update :
Window Tokens:
As its name implies, a window token is a special type of Binder token that the window manager uses to uniquely identify a window in the system. Window tokens are important for security because they make it impossible for malicious applications to draw on top of the windows of other applications. The window manager protects against this by requiring applications to pass their application's window token as part of each request to add or remove a window. If the tokens don't match, the window manager rejects the request and throws a BadTokenException. Without window tokens, this necessary identification step wouldn't be possible and the window manager wouldn't be able to protect itself from malicious applications.
A real-world scenario:
When an application starts up for the first time, the ActivityManagerService creates a special kind of window token called an application window token, which uniquely identifies the application's top-level container window. The activity manager gives this token to both the application and the window manager, and the application sends the token to the window manager each time it wants to add a new window to the screen. This ensures secure interaction between the application and the window manager (by making it impossible to add windows on top of other applications), and also makes it easy for the activity manager to make direct requests to the window manager.
I know it's been a while since this question was posted, but I was just getting this exact error, and I have a really simple solution that MIGHT work for some. All I did was double click on the folder 'Servers', which then allowed me to start the server with no error message. Sometimes the solution is right in front of your eyes. This might work for some people like me who go straight to google without trying fix the issue themselves!
If you make your parent element be "position: relative", then it will be the "offset parent" for the stuff you're tracking mouse events over. Thus the jQuery "position()" will be relative to that.
This problem will occurred due to some unnecessary changes made in my.cnf file.
Try to diff /etc/mysql/my.cnf
with one of working mysql servers my.cnf file.
I just replaced /etc/mysql/my.cnf
file with new my.cnf file and this works for me.
<?php //-- Very simple variant
$useragent = $_SERVER['HTTP_USER_AGENT'];
$iPod = stripos($useragent, "iPod");
$iPad = stripos($useragent, "iPad");
$iPhone = stripos($useragent, "iPhone");
$Android = stripos($useragent, "Android");
$iOS = stripos($useragent, "iOS");
//-- You can add billion devices
$DEVICE = ($iPod||$iPad||$iPhone||$Android||$iOS||$webOS||$Blackberry||$IEMobile||$OperaMini);
if ($DEVICE !=true) {?>
<!-- What you want for all non-mobile devices. Anything with all HTML codes-->
<?php }else{ ?>
<!-- What you want for all mobile devices. Anything with all HTML codes -->
<?php } ?>
Use the below method for calculating the distance of two different locations.
public double getKilometers(double lat1, double long1, double lat2, double long2) {
double PI_RAD = Math.PI / 180.0;
double phi1 = lat1 * PI_RAD;
double phi2 = lat2 * PI_RAD;
double lam1 = long1 * PI_RAD;
double lam2 = long2 * PI_RAD;
return 6371.01 * acos(sin(phi1) * sin(phi2) + cos(phi1) * cos(phi2) * cos(lam2 - lam1));}
Just set the height and width where you are adding that logo. I tried and its working fine
Yes, You can add
# -*- coding: utf-8 -*-
in your source code's first line.
You can read more details here https://www.python.org/dev/peps/pep-0263/
You can use $lookup
( multiple ) to get the records from multiple collections:
Example:
If you have more collections ( I have 3 collections for demo here, you can have more than 3 ). and I want to get the data from 3 collections in single object:
The collection are as:
db.doc1.find().pretty();
{
"_id" : ObjectId("5901a4c63541b7d5d3293766"),
"firstName" : "shubham",
"lastName" : "verma"
}
db.doc2.find().pretty();
{
"_id" : ObjectId("5901a5f83541b7d5d3293768"),
"userId" : ObjectId("5901a4c63541b7d5d3293766"),
"address" : "Gurgaon",
"mob" : "9876543211"
}
db.doc3.find().pretty();
{
"_id" : ObjectId("5901b0f6d318b072ceea44fb"),
"userId" : ObjectId("5901a4c63541b7d5d3293766"),
"fbURLs" : "http://www.facebook.com",
"twitterURLs" : "http://www.twitter.com"
}
Now your query will be as below:
db.doc1.aggregate([
{ $match: { _id: ObjectId("5901a4c63541b7d5d3293766") } },
{
$lookup:
{
from: "doc2",
localField: "_id",
foreignField: "userId",
as: "address"
}
},
{
$unwind: "$address"
},
{
$project: {
__v: 0,
"address.__v": 0,
"address._id": 0,
"address.userId": 0,
"address.mob": 0
}
},
{
$lookup:
{
from: "doc3",
localField: "_id",
foreignField: "userId",
as: "social"
}
},
{
$unwind: "$social"
},
{
$project: {
__v: 0,
"social.__v": 0,
"social._id": 0,
"social.userId": 0
}
}
]).pretty();
Then Your result will be:
{
"_id" : ObjectId("5901a4c63541b7d5d3293766"),
"firstName" : "shubham",
"lastName" : "verma",
"address" : {
"address" : "Gurgaon"
},
"social" : {
"fbURLs" : "http://www.facebook.com",
"twitterURLs" : "http://www.twitter.com"
}
}
If you want all records from each collections then you should remove below line from query:
{
$project: {
__v: 0,
"address.__v": 0,
"address._id": 0,
"address.userId": 0,
"address.mob": 0
}
}
{
$project: {
"social.__v": 0,
"social._id": 0,
"social.userId": 0
}
}
After removing above code you will get total record as:
{
"_id" : ObjectId("5901a4c63541b7d5d3293766"),
"firstName" : "shubham",
"lastName" : "verma",
"address" : {
"_id" : ObjectId("5901a5f83541b7d5d3293768"),
"userId" : ObjectId("5901a4c63541b7d5d3293766"),
"address" : "Gurgaon",
"mob" : "9876543211"
},
"social" : {
"_id" : ObjectId("5901b0f6d318b072ceea44fb"),
"userId" : ObjectId("5901a4c63541b7d5d3293766"),
"fbURLs" : "http://www.facebook.com",
"twitterURLs" : "http://www.twitter.com"
}
}
The -Contains
operator doesn't do substring comparisons and the match must be on a complete string and is used to search collections.
From the documentation you linked to:
-Contains Description: Containment operator. Tells whether a collection of reference values includes a single test value.
In the example you provided you're working with a collection containing just one string item.
If you read the documentation you linked to you'll see an example that demonstrates this behaviour:
Examples:
PS C:\> "abc", "def" -Contains "def"
True
PS C:\> "Windows", "PowerShell" -Contains "Shell"
False #Not an exact match
I think what you want is the -Match
operator:
"12-18" -Match "-"
Which returns True
.
Important: As pointed out in the comments and in the linked documentation, it should be noted that the -Match
operator uses regular expressions to perform text matching.
I had this issue also and I simply found out that if you simply remove the "#" the issue goes off. Like this :
<a href="" class="disabled" ng-click="doSomething(object)">Do something</a>
I did found a way to convert (even bad) html into well formed XML. I started to base this on the DOM loadHTML function. However during time several issues occurred and I optimized and added patches to correct side effects.
function tryToXml($dom,$content) {
if(!$content) return false;
// xml well formed content can be loaded as xml node tree
$fragment = $dom->createDocumentFragment();
// wonderfull appendXML to add an XML string directly into the node tree!
// aappendxml will fail on a xml declaration so manually skip this when occurred
if( substr( $content,0, 5) == '<?xml' ) {
$content = substr($content,strpos($content,'>')+1);
if( strpos($content,'<') ) {
$content = substr($content,strpos($content,'<'));
}
}
// if appendXML is not working then use below htmlToXml() for nasty html correction
if(!@$fragment->appendXML( $content )) {
return $this->htmlToXml($dom,$content);
}
return $fragment;
}
// convert content into xml
// dom is only needed to prepare the xml which will be returned
function htmlToXml($dom, $content, $needEncoding=false, $bodyOnly=true) {
// no xml when html is empty
if(!$content) return false;
// real content and possibly it needs encoding
if( $needEncoding ) {
// no need to convert character encoding as loadHTML will respect the content-type (only)
$content = '<meta http-equiv="Content-Type" content="text/html;charset='.$this->encoding.'">' . $content;
}
// return a dom from the content
$domInject = new DOMDocument("1.0", "UTF-8");
$domInject->preserveWhiteSpace = false;
$domInject->formatOutput = true;
// html type
try {
@$domInject->loadHTML( $content );
} catch(Exception $e){
// do nothing and continue as it's normal that warnings will occur on nasty HTML content
}
// to check encoding: echo $dom->encoding
$this->reworkDom( $domInject );
if( $bodyOnly ) {
$fragment = $dom->createDocumentFragment();
// retrieve nodes within /html/body
foreach( $domInject->documentElement->childNodes as $elementLevel1 ) {
if( $elementLevel1->nodeName == 'body' and $elementLevel1->nodeType == XML_ELEMENT_NODE ) {
foreach( $elementLevel1->childNodes as $elementInject ) {
$fragment->insertBefore( $dom->importNode($elementInject, true) );
}
}
}
} else {
$fragment = $dom->importNode($domInject->documentElement, true);
}
return $fragment;
}
protected function reworkDom( $node, $level = 0 ) {
// start with the first child node to iterate
$nodeChild = $node->firstChild;
while ( $nodeChild ) {
$nodeNextChild = $nodeChild->nextSibling;
switch ( $nodeChild->nodeType ) {
case XML_ELEMENT_NODE:
// iterate through children element nodes
$this->reworkDom( $nodeChild, $level + 1);
break;
case XML_TEXT_NODE:
case XML_CDATA_SECTION_NODE:
// do nothing with text, cdata
break;
case XML_COMMENT_NODE:
// ensure comments to remove - sign also follows the w3c guideline
$nodeChild->nodeValue = str_replace("-","_",$nodeChild->nodeValue);
break;
case XML_DOCUMENT_TYPE_NODE: // 10: needs to be removed
case XML_PI_NODE: // 7: remove PI
$node->removeChild( $nodeChild );
$nodeChild = null; // make null to test later
break;
case XML_DOCUMENT_NODE:
// should not appear as it's always the root, just to be complete
// however generate exception!
case XML_HTML_DOCUMENT_NODE:
// should not appear as it's always the root, just to be complete
// however generate exception!
default:
throw new exception("Engine: reworkDom type not declared [".$nodeChild->nodeType. "]");
}
$nodeChild = $nodeNextChild;
} ;
}
Now this also allows to add more html pieces into one XML which I needed to use myself. In general it can be used like this:
$c='<p>test<font>two</p>';
$dom=new DOMDocument('1.0', 'UTF-8');
$n=$dom->appendChild($dom->createElement('info')); // make a root element
if( $valueXml=tryToXml($dom,$c) ) {
$n->appendChild($valueXml);
}
echo '<pre/>'. htmlentities($dom->saveXml($n)). '</pre>';
In this example '<p>test<font>two</p>'
will nicely be outputed in well formed XML as '<info><p>test<font>two</font></p></info>
'. The info root tag is added as it will also allow to convert '<p>one</p><p>two</p>
' which is not XML as it has not one root element. However if you html does for sure have one root element then the extra root <info>
tag can be skipped.
With this I'm getting real nice XML out of unstructured and even corrupted HTML!
I hope it's a bit clear and might contribute to other people to use it.
There are three unique situations:
Margin="a,b,c,d"
.Margin="a,b"
.Margin="a"
.If there are 4 numbers, then its left
, top
, right
, bottom
(a clockwise circle starting from the middle left margin). First number is always the "West" like "WPF":
<object Margin="left,top,right,bottom"/>
Example: if we use Margin="10,20,30,40"
it generates:
If there are 2 numbers, then the first is left & right margin thickness, the second is top & bottom margin thickness. First number is always the "West" like "WPF":
<object Margin="a,b"/> // Equivalent to Margin="a,b,a,b".
Example: if we use Margin="10,30"
, the left & right margin are both 10, and the top & bottom are both 30.
If there is 1 number, then the number is repeated (its essentially a border thickness).
<object Margin="a"/> // Equivalent to Margin="a,a,a,a".
Example: if we use Margin="20"
it generates:
Have been working on a large-scale WPF application for the past 5 years with over 100 screens. Part of a team of 5 WPF/C#/Java devs. We eventually settled on either using 1 number (for border thickness) or 4 numbers. We never use 2. It is consistent, and seems to be a good way to reduce cognitive load when developing.
The rule:
All width numbers start on the left (the "West" like "WPF") and go clockwise (if two numbers, only go clockwise twice, then mirror the rest).
Looks like Windows might just let you do this...
Unfortunately I don't think you're going to get around starting a separate process unless you go to a third party component.
The answers did help, but I think a full implementation of this will help a lot of people.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace Dom
{
class Dom
{
public static string make_Sting_From_Dom(string reportname)
{
try
{
WebClient client = new WebClient();
client.Credentials = CredentialCache.DefaultCredentials;
// Retrieve resource as a stream
Stream data = client.OpenRead(new Uri(reportname.Trim()));
// Retrieve the text
StreamReader reader = new StreamReader(data);
string htmlContent = reader.ReadToEnd();
string mtch = "TILDE";
bool b = htmlContent.Contains(mtch);
if (b)
{
int index = htmlContent.IndexOf(mtch);
if (index >= 0)
Console.WriteLine("'{0} begins at character position {1}",
mtch, index + 1);
}
// Cleanup
data.Close();
reader.Close();
return htmlContent;
}
catch (Exception)
{
throw;
}
}
static void Main(string[] args)
{
make_Sting_From_Dom("https://www.w3.org/TR/PNG/iso_8859-1.txt");
}
}
}
Java 8 provides a new way to call the copy constructor or clone method on the element dogs elegantly and compactly: Streams, lambdas and collectors.
Copy constructor:
List<Dog> clonedDogs = dogs.stream().map(Dog::new).collect(toList());
The expression Dog::new
is called a method reference. It creates a function object which calls a constructor on Dog
which takes another dog as argument.
Clone method[1]:
List<Dog> clonedDogs = dogs.stream().map(d -> d.clone()).collect(toList());
ArrayList
as the resultOr, if you have to get an ArrayList
back (in case you want to modify it later):
ArrayList<Dog> clonedDogs = dogs.stream().map(Dog::new).collect(toCollection(ArrayList::new));
If you don't need to keep the original content of the dogs
list you can instead use the replaceAll
method and update the list in place:
dogs.replaceAll(Dog::new);
All examples assume import static java.util.stream.Collectors.*;
.
ArrayList
sThe collector from the last example can be made into a util method. Since this is such a common thing to do I personally like it to be short and pretty. Like this:
ArrayList<Dog> clonedDogs = dogs.stream().map(d -> d.clone()).collect(toArrayList());
public static <T> Collector<T, ?, ArrayList<T>> toArrayList() {
return Collectors.toCollection(ArrayList::new);
}
CloneNotSupportedException
:For this solution to work the clone
method of Dog
must not declare that it throws CloneNotSupportedException
. The reason is that the argument to map
is not allowed to throw any checked exceptions.
Like this:
// Note: Method is public and returns Dog, not Object
@Override
public Dog clone() /* Note: No throws clause here */ { ...
This should not be a big problem however, since that is the best practice anyway. (Effectice Java for example gives this advice.)
Thanks to Gustavo for noting this.
If you find it prettier you can instead use the method reference syntax to do exactly the same thing:
List<Dog> clonedDogs = dogs.stream().map(Dog::clone).collect(toList());
var countChange = function (money,coins) {
function countChangeSub(money,coins,n) {
if(money==0) return 1;
if(money<0 || coins.length ==n) return 0;
return countChangeSub(money-coins[n],coins,n) + countChangeSub(money,coins,n+1);
}
return countChangeSub(money,coins,0);
}
As pointed out before, the problem was that the files were not visible by the fpm container. However to share data among containers the recommended pattern is using data-only containers (as explained in this article).
Long story short: create a container that just holds your data, share it with a volume, and link this volume in your apps with volumes_from
.
Using compose (1.6.2 in my machine), the docker-compose.yml
file would read:
version: "2"
services:
nginx:
build:
context: .
dockerfile: nginx/Dockerfile
ports:
- "80:80"
links:
- fpm
volumes_from:
- data
fpm:
image: php:fpm
volumes_from:
- data
data:
build:
context: .
dockerfile: data/Dockerfile
volumes:
- /var/www/html
Note that data
publishes a volume that is linked to the nginx
and fpm
services. Then the Dockerfile
for the data service, that contains your source code:
FROM busybox
# content
ADD path/to/source /var/www/html
And the Dockerfile
for nginx, that just replaces the default config:
FROM nginx
# config
ADD config/default.conf /etc/nginx/conf.d
For the sake of completion, here's the config file required for the example to work:
server {
listen 0.0.0.0:80;
root /var/www/html;
location / {
index index.php index.html;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass fpm:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
}
}
which just tells nginx to use the shared volume as document root, and sets the right config for nginx to be able to communicate with the fpm container (i.e.: the right HOST:PORT
, which is fpm:9000
thanks to the hostnames defined by compose, and the SCRIPT_FILENAME
).
var datos = $("#id_formulario").serialize();
$.ajax({
url: "url.php",
type: "POST",
dataType: "html",
data: datos,
success: function (prueba) {
alert("funciona!");
}//FIN SUCCES
});//FIN AJAX
You can snoop around in your memory using RTLMoveMemory and retrieve the desired information directly from there:
32-Bit:
Option Explicit
'Provide direct memory access:
Public Declare Sub MemCopy Lib "kernel32" Alias "RtlMoveMemory" ( _
ByVal Destination As Long, _
ByVal Source As Long, _
ByVal Length As Long)
Function CollectionKeys(oColl As Collection) As String()
'Declare Pointer- / Memory-Address-Variables
Dim CollPtr As Long
Dim KeyPtr As Long
Dim ItemPtr As Long
'Get MemoryAddress of Collection Object
CollPtr = VBA.ObjPtr(oColl)
'Peek ElementCount
Dim ElementCount As Long
ElementCount = PeekLong(CollPtr + 16)
'Verify ElementCount
If ElementCount <> oColl.Count Then
'Something's wrong!
Stop
End If
'Declare Simple Counter
Dim index As Long
'Declare Temporary Array to hold our keys
Dim Temp() As String
ReDim Temp(ElementCount)
'Get MemoryAddress of first CollectionItem
ItemPtr = PeekLong(CollPtr + 24)
'Loop through all CollectionItems in Chain
While Not ItemPtr = 0 And index < ElementCount
'increment Index
index = index + 1
'Get MemoryAddress of Element-Key
KeyPtr = PeekLong(ItemPtr + 16)
'Peek Key and add to temporary array (if present)
If KeyPtr <> 0 Then
Temp(index) = PeekBSTR(KeyPtr)
End If
'Get MemoryAddress of next Element in Chain
ItemPtr = PeekLong(ItemPtr + 24)
Wend
'Assign temporary array as Return-Value
CollectionKeys = Temp
End Function
'Peek Long from given MemoryAddress
Public Function PeekLong(Address As Long) As Long
If Address = 0 Then Stop
Call MemCopy(VBA.VarPtr(PeekLong), Address, 4&)
End Function
'Peek String from given MemoryAddress
Public Function PeekBSTR(Address As Long) As String
Dim Length As Long
If Address = 0 Then Stop
Length = PeekLong(Address - 4)
PeekBSTR = Space(Length \ 2)
Call MemCopy(VBA.StrPtr(PeekBSTR), Address, Length)
End Function
64-Bit:
Option Explicit
'Provide direct memory access:
Public Declare PtrSafe Sub MemCopy Lib "kernel32" Alias "RtlMoveMemory" ( _
ByVal Destination As LongPtr, _
ByVal Source As LongPtr, _
ByVal Length As LongPtr)
Function CollectionKeys(oColl As Collection) As String()
'Declare Pointer- / Memory-Address-Variables
Dim CollPtr As LongPtr
Dim KeyPtr As LongPtr
Dim ItemPtr As LongPtr
'Get MemoryAddress of Collection Object
CollPtr = VBA.ObjPtr(oColl)
'Peek ElementCount
Dim ElementCount As Long
ElementCount = PeekLong(CollPtr + 28)
'Verify ElementCount
If ElementCount <> oColl.Count Then
'Something's wrong!
Stop
End If
'Declare Simple Counter
Dim index As Long
'Declare Temporary Array to hold our keys
Dim Temp() As String
ReDim Temp(ElementCount)
'Get MemoryAddress of first CollectionItem
ItemPtr = PeekLongLong(CollPtr + 40)
'Loop through all CollectionItems in Chain
While Not ItemPtr = 0 And index < ElementCount
'increment Index
index = index + 1
'Get MemoryAddress of Element-Key
KeyPtr = PeekLongLong(ItemPtr + 24)
'Peek Key and add to temporary array (if present)
If KeyPtr <> 0 Then
Temp(index) = PeekBSTR(KeyPtr)
End If
'Get MemoryAddress of next Element in Chain
ItemPtr = PeekLongLong(ItemPtr + 40)
Wend
'Assign temporary array as Return-Value
CollectionKeys = Temp
End Function
'Peek Long from given Memory-Address
Public Function PeekLong(Address As LongPtr) As Long
If Address = 0 Then Stop
Call MemCopy(VBA.VarPtr(PeekLong), Address, 4^)
End Function
'Peek LongLong from given Memory Address
Public Function PeekLongLong(Address As LongPtr) As LongLong
If Address = 0 Then Stop
Call MemCopy(VBA.VarPtr(PeekLongLong), Address, 8^)
End Function
'Peek String from given MemoryAddress
Public Function PeekBSTR(Address As LongPtr) As String
Dim Length As Long
If Address = 0 Then Stop
Length = PeekLong(Address - 4)
PeekBSTR = Space(Length \ 2)
Call MemCopy(VBA.StrPtr(PeekBSTR), Address, CLngLng(Length))
End Function
I would not advise hacking browser-specific things manually with JS. Either use a javascript library like "prototype" or "jquery", which will handle all the specific issues transparently.
Or use these libs to determine the browser type if you really must.
It depends what kind of UUID you want.
The standard Java UUID
class generates Version 4 (random) UUIDs. (UPDATE - Version 3 (name) UUIDs can also be generated.) It can also handle other variants, though it cannot generate them. (In this case, "handle" means construct UUID
instances from long
, byte[]
or String
representations, and provide some appropriate accessors.)
The Java UUID Generator (JUG) implementation purports to support "all 3 'official' types of UUID as defined by RFC-4122" ... though the RFC actually defines 4 types and mentions a 5th type.
For more information on UUID types and variants, there is a good summary in Wikipedia, and the gory details are in RFC 4122 and the other specifications.
If you want to use default value for a DateTime parameter in a method, you can only use default(DateTime).
The following line will not compile:
private void MyMethod(DateTime syncedTime = DateTime.MinValue)
This line will compile:
private void MyMethod(DateTime syncedTime = default(DateTime))
I've found that it's best not to mess around with setting the measured dimensions yourself. There's actually a bit of negotiation that goes on between the parent and child views and you don't want to re-write all that code.
What you can do, though, is modify the measureSpecs, then call super with them. Your view will never know that it's getting a modified message from its parent and will take care of everything for you:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
int myWidth = (int) (parentHeight * 0.5);
super.onMeasure(MeasureSpec.makeMeasureSpec(myWidth, MeasureSpec.EXACTLY), heightMeasureSpec);
}
If I use the machine name this works. But is kind of like a hack (because I am just picking the first value of ipv4 address that I get.)
$ipaddress=([System.Net.DNS]::GetHostAddresses('PasteMachineNameHere')|Where-Object {$_.AddressFamily -eq "InterNetwork"} | select-object IPAddressToString)[0].IPAddressToString
Note that you have to replace the value PasteMachineNameHere in the above expression
This works too
$localIpAddress=((ipconfig | findstr [0-9].\.)[0]).Split()[-1]
In case you need to ROUND the result, not truncate, can use this:
select convert(decimal(38,4), round(convert(decimal(38,10), '123456789.1234567'),4))
This will return the following:
'123456789.1235' for '123456789.1234567'
'123456789.1234' for '123456789.1234467'
At least with Django 1.9.9 -- the version I'm currently using --, note that .get_fields()
actually also "considers" any foreign model as a field, which may be problematic. Say you have:
class Parent(models.Model):
id = UUIDField(primary_key=True)
class Child(models.Model):
parent = models.ForeignKey(Parent)
It follows that
>>> map(lambda field:field.name, Parent._model._meta.get_fields())
['id', 'child']
while, as shown by @Rockallite
>>> map(lambda field:field.name, Parent._model._meta.local_fields)
['id']
Let a library handle all the nitty-gritty details for you! :-)
Check out FileHelpers and stay DRY - Don't Repeat Yourself - no need to re-invent the wheel a gazillionth time....
You basically just need to define that shape of your data - the fields in your individual line in the CSV - by means of a public class (and so well-thought out attributes like default values, replacements for NULL values and so forth), point the FileHelpers engine at a file, and bingo - you get back all the entries from that file. One simple operation - great performance!
Given that the trendline is straight, find the slope by choosing any two points and calculating:
(A) slope = (y1-y2)/(x1-x2)
Then you need to find the offset for the line. The line is specified by the equation:
(B) y = offset + slope*x
So you need to solve for offset. Pick any point on the line, and solve for offset:
(C) offset = y - (slope*x)
Now you can plug slope and offset into the line equation (B) and have the equation that defines your line. If your line has noise you'll have to decide on an averaging algorithm, or use curve fitting of some sort.
If your line isn't straight then you'll need to look into Curve fitting, or Least Squares Fitting - non trivial, but do-able. You'll see the various types of curve fitting at the bottom of the least squares fitting webpage (exponential, polynomial, etc) if you know what kind of fit you'd like.
Also, if this is a one-off, use Excel.
Try using the os
module.
import os
os.environ['DEBUSSY'] = '1'
os.environ['FSDB'] = '1'
# Open child processes via os.system(), popen() or fork() and execv()
someVariable = int(os.environ['DEBUSSY'])
See the Python docs on os.environ
. Also, for spawning child processes, see Python's subprocess docs.
According to your updated problem
<div class="home">
<span>blah</span>
<p class="red">first</p>
<p class="red">second</p>
<p class="red">third</p>
<p class="red">fourth</p>
</div>
how about
.home span + .red{
border:1px solid red;
}
This will select class home, then the element span and finally all .red elements that are placed immediately after span elements.
Reference: http://www.w3schools.com/cssref/css_selectors.asp
To be short, use:
write-output "your text" | out-file -append -encoding utf8 "filename"
The issue here is that you've initialized your array, but not its elements; they are all null. So if you try to reference houses[0]
, it will be null
.
Here's a great little helper method you could write for yourself:
T[] InitializeArray<T>(int length) where T : new()
{
T[] array = new T[length];
for (int i = 0; i < length; ++i)
{
array[i] = new T();
}
return array;
}
Then you could initialize your houses
array as:
GameObject[] houses = InitializeArray<GameObject>(200);
There is, of course, another way to do this which has not been discussed in this thread, i.e. by way of inheritance of the class containing the TestMethod. In the following example, only one TestMethod has been defined but two test cases have been made.
In Visual Studio 2012, it creates two tests in the TestExplorer:
DemoTest_A12_B4.test
public class Demo
{
int a, b;
public Demo(int _a, int _b)
{
this.a = _a;
this.b = _b;
}
public int Sum()
{
return this.a + this.b;
}
}
public abstract class DemoTestBase
{
Demo objUnderTest;
int expectedSum;
public DemoTestBase(int _a, int _b, int _expectedSum)
{
objUnderTest = new Demo(_a, _b);
this.expectedSum = _expectedSum;
}
[TestMethod]
public void test()
{
Assert.AreEqual(this.expectedSum, this.objUnderTest.Sum());
}
}
[TestClass]
public class DemoTest_A12_B4 : DemoTestBase
{
public DemoTest_A12_B4() : base(12, 4, 16) { }
}
public abstract class DemoTest_B10_Base : DemoTestBase
{
public DemoTest_B10_Base(int _a) : base(_a, 10, _a + 10) { }
}
[TestClass]
public class DemoTest_B10_A5 : DemoTest_B10_Base
{
public DemoTest_B10_A5() : base(5) { }
}
Define Colors With RGBA Values
Add the Following code under style
<!DOCTYPE html>
<html>
<head>
<style>
#p7 {background-color:rgba(215,215,215,1);}
</style>
</head>
<body>
Disabled Grey none tranparent
<form action="/Media/Add">
<input type="hidden" name="Id" value="123" />
<!-- this does not appear in request -->
<input id="p7" type="textbox" name="Percentage" value="100" readonly="readonly"" />
</form>
Check that Apache has execute rights for /root
, /root/site
and /root/site/about
.
Run:
chmod o+x /root /root/site /root/site/about
You can get the id of clicked one by this code
$("span").on("click",function(e){
console.log(e.target.Id);
});
Use .on()
event for future compatibility
If you meant just ABC as simple value, answer above is the one that works fine.
If you meant concatenation of values of rows that are not selected by your main query, you will need to use a subquery.
Something like this may work:
SELECT t1.col1,
t1.col2,
(SELECT GROUP_CONCAT(col2 SEPARATOR '') FROM Table1 t2 WHERE t2.col1 != 0) as col3
FROM Table1 t1
WHERE t1.col1 = 0;
Actual syntax maybe a bit off though
The problem is that HTML doesn't recognize the escape character. You could work around that by using the single quotes for the HTML attribute and the double quotes for the onclick.
<a href="#" onclick='DoEdit("Preliminary Assessment \"Mini\""); return false;'>edit</a>
"Developing Android REST client applications" by Virgil Dobjanschi led to much discussion, since no source code was presented during the session or was provided afterwards.
The only reference implementation I know (please comment if you know more) is available at Datadroid (the Google IO session is mentioned under /presentation). It is a library which you can use in your own application.
The second link asks for the "best" REST framework, which is discussed heavily on stackoverflow. For me the application size is important, followed by the performance of the implementation.
Therefore I stick to org.json or GSON for complexer scenarios. For the architecture of an org.json implementation, I am using a static class which represents the server use cases (e.g. findPerson, getPerson). I call this functionality from a service and use utility classes which are doing the mapping (project specific) and the network IO (my own REST template for plain GET or POST). I try to avoid the usage of reflection.
Use /config.php
.
Try it:
$table->integer('user_id')->unsigned()->nullable();
I think Nosql is "more suitable" in these scenarios at least (more supplementary is welcome)
Easy to scale horizontally by just adding more nodes.
Query on large data set
Imagine tons of tweets posted on twitter every day. In RDMS, there could be tables with millions (or billions?) of rows, and you don't want to do query on those tables directly, not even mentioning, most of time, table joins are also needed for complex queries.
Disk I/O bottleneck
If a website needs to send results to different users based on users' real-time info, we are probably talking about tens or hundreds of thousands of SQL read/write requests per second. Then disk i/o will be a serious bottleneck.
I used "git://
" instead of "https://
" and that solved the problem. My final command was:
git clone --recursive git://github.com/ceph/ceph.git
For Eclipse: menu bar-> window -> show view then find "debug" option if not in list then select other ...
new window will open and then search using keyword "debug" -> select debug from list
it will added near console tab. use debug tab to terminate and remove previous executions. ( right clicking on executing process will show you many option including terminate)
In a previous project I found that changing from *-imports to specific imports reduced compilation time by half (from about 10 minutes to about 5 minutes). The *-import makes the compiler search each of the packages listed for a class matching the one you used. While this time can be small, it adds up for large projects.
A side affect of the *-import was that developers would copy and paste common import lines rather than think about what they needed.
<textarea rows="4" cols="50"></textarea>
It is equivalent to:
textarea {
height: 4em;
width: 50em;
}
where 1em is equivalent to the current font size, thus make the text area 50 chars wide. see here.
DateFormat originalFormat = new SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat("yyyyMMdd");
Date date = originalFormat.parse("August 21, 2012");
String formattedDate = targetFormat.format(date); // 20120821
Also note that parse
takes a String
, not a Date
object, which is already parsed.
Move excel variables which are global declare in your form to local like in my form I have:
Dim xls As New MyExcel.Interop.Application
Dim xlb As MyExcel.Interop.Workbook
above two lines were declare global in my form so i moved these two lines to local function and now tool is working fine.
You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015
> 01/02/2016
because 09
> 01
. You need to either put your date in a comparable string format or compare DateTime
objects which are comparable.
<?php
$date_now = date("Y-m-d"); // this format is string comparable
if ($date_now > '2016-01-02') {
echo 'greater than';
}else{
echo 'Less than';
}
Or
<?php
$date_now = new DateTime();
$date2 = new DateTime("01/02/2016");
if ($date_now > $date2) {
echo 'greater than';
}else{
echo 'Less than';
}
Extending on what Mike Powell has to say, I am actually a big fan of almost all of the podcasts at http://www.twit.tv. Most of the content is watered down a bit, but some of the speakers are top notch thinkers - especially on "This Week in Tech", the flagship program.
Oh - and Car Talk on NPR but those guys hardly EVER get into the SDLC!
<Ctr>-<Shift>-<F>
Format, does it as well.
This removes trailing whitespace and formats/indents your code.
From here:
-Xmn : the size of the heap for the young generation
Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor".
And a more "official" source from IBM:
-Xmn
Sets the initial and maximum size of the new (nursery) heap to the specified value when using -Xgcpolicy:gencon. Equivalent to setting both -Xmns and -Xmnx. If you set either -Xmns or -Xmnx, you cannot set -Xmn. If you attempt to set -Xmn with either -Xmns or -Xmnx, the VM will not start, returning an error. By default, -Xmn is selected internally according to your system's capability. You can use the -verbose:sizes option to find out the values that the VM is currently using.
This command works like a charm for me:
for /r "$(SolutionDir)libraries" %%f in (*.dll, *.exe) do @xcopy "%%f" "$(TargetDir)"
It recursively copies every dll
and exe
file from MySolutionPath\libraries
into the bin\debug
or bin\release
.
You can find more info in here
None of the answers above worked for me, maybe I was doing completely wrong, but as a beginner that's what we do.
I was initializing the controller in a div
in order to have a list:
<div ng-controller="CategoryController" ng-init="initialize()">
And then using $routeProvider
to map a URL to the same controller. As soon as I removed the ng-init
the controller worked with the route.
I was looking for an example that had default kwargs using type annotation:
def test_var_kwarg(a: str, b: str='B', c: str='', **kwargs) -> str:
return ' '.join([a, b, c, str(kwargs)])
example:
>>> print(test_var_kwarg('A', c='okay'))
A B okay {}
>>> d = {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', c='c', b='b', **d))
a b c {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', 'b', 'c'))
a b c {}
Promise:
An Async Event Handler - The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.
Syntax: new Promise(executor);
Eg:
var promise_eg = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo');
}, 300);
});
promise_eg.then(function(value) {
console.log(value);
// expected output: "foo"
});
console.log(promise_eg);
About Promise: It has one pipeline so, it will return values only once when its called. its one way handler so once called you may not able to cancel. useful syntax you can play around, when() and then()
Observables:
Observables are lazy collections of multiple values over time. its really a great approach for async operations. it can be done with rxjs which has cross platform support can use with angular/react etc.
its act like stream liner. can be multi pipeline. so once defined you can subscribe to get return results in many places.
Syntax: import * as Rx from "@reactivex/rxjs";
to init:
Rx.Observable.fromEvent(button, "click"),
Rx.Subject()
etc
to subscribe: RxLogger.getInstance();
Eg:
import { range } from 'rxjs';
import { map, filter } from 'rxjs/operators';
range(1, 200).pipe(
filter(x => x % 2 === 1),
map(x => x + x)
).subscribe(x => console.log(x));
since it support multi pipeline you can subscribe result in different location, it has much possibilities than promises.
Usage:
it has more possibilities like map, filter, pipe, map, concatMap etc
Structured Query Language - SQL: is an ANSI-standard used by almost all SGBD's vendors around the world. Basically, SQL is a language used to define and manipulate data [DDL and DML].
PL/SQL is a language created by Oracle universe. PL/SQL combine programming procedural instructions and allows the creation of programs that operates directly on database scenario.
T-SQL is Microsoft product align SQL patterns, with some peculiarities. So, feel free to test your limits.
You may checkout this library for the same purpose also:
http://angular-route-segment.com
It looks like what you are looking for, and it is much simpler to use than ui-router. From the demo site:
JS:
$routeSegmentProvider.
when('/section1', 's1.home').
when('/section1/:id', 's1.itemInfo.overview').
when('/section2', 's2').
segment('s1', {
templateUrl: 'templates/section1.html',
controller: MainCtrl}).
within().
segment('home', {
templateUrl: 'templates/section1/home.html'}).
segment('itemInfo', {
templateUrl: 'templates/section1/item.html',
controller: Section1ItemCtrl,
dependencies: ['id']}).
within().
segment('overview', {
templateUrl: 'templates/section1/item/overview.html'}).
Top-level HTML:
<ul>
<li ng-class="{active: $routeSegment.startsWith('s1')}">
<a href="/section1">Section 1</a>
</li>
<li ng-class="{active: $routeSegment.startsWith('s2')}">
<a href="/section2">Section 2</a>
</li>
</ul>
<div id="contents" app-view-segment="0"></div>
Nested HTML:
<h4>Section 1</h4>
Section 1 contents.
<div app-view-segment="1"></div>
I didn't want to install a package just for that purpose so I ended up using this in my init.coffee
:
spawn = require('child_process').spawn
atom.commands.add 'atom-text-editor', 'open-terminal', ->
file = atom.workspace.getActiveTextEditor().getPath()
dir = atom.project.getDirectoryForProjectPath(file).path
spawn 'mate-terminal', ["--working-directory=#{dir}"], {
detached: true
}
With that, I could map ctrl-shift-t
to the open-terminal
command and it opens a mate-terminal.
Create a block using
#define MACRO(...) do { ... } while(false)
Do not add a ; after the while(false)
I know this question is old and already has an accepted answer, but I want to offer a few examples (hoping it'll be useful to someone).
As far as I know old ASCII characters took one byte per character.
Right. Actually, since ASCII is a 7-bit encoding, it supports 128 codes (95 of which are printable), so it only uses half a byte (if that makes any sense).
How many bytes does a Unicode character require?
Unicode just maps characters to codepoints. It doesn't define how to encode them. A text file does not contain Unicode characters, but bytes/octets that may represent Unicode characters.
I assume that one Unicode character can contain every possible character from any language - am I correct?
No. But almost. So basically yes. But still no.
So how many bytes does it need per character?
Same as your 2nd question.
And what do UTF-7, UTF-6, UTF-16 etc mean? Are they some kind Unicode versions?
No, those are encodings. They define how bytes/octets should represent Unicode characters.
A couple of examples. If some of those cannot be displayed in your browser (probably because the font doesn't support them), go to http://codepoints.net/U+1F6AA
(replace 1F6AA
with the codepoint in hex) to see an image.
a
©
®
?
—
‰
€
™
?
?
?
?
?
?
?
?
?
?
Okay I'm getting carried away...
Fun facts:
<session-config>
<session-timeout>-1</session-timeout>
</session-config>
You can use "-1" where the session never expires. Since you do not know how much time it will take for the thread to complete.
Cause: The error occurred since hibernate is not able to connect to the database.
Solution:
1. Please ensure that you have a database present at the server referred to in the configuration file eg. "hibernatedb" in this case.
2. Please see if the username and password for connecting to the db are correct.
3. Check if relevant jars required for the connection are mapped to the project.
Theres' a very easy way.
onClick={this.toggleStart('xyz')} .
toggleStart= (data) => (e) =>{
console.log('value is'+data);
}
Try using a single quote instead of double quotes along with -g
Following scenario worked for me
curl -g -d '{"collection":[{"NumberOfParcels":1,"Weight":1,"Length":1,"Width":1,"Height":1}]}" -H "Accept: application/json" -H "Content-Type: application/json" --user [email protected]:123456 -X POST https://yoururl.com
WITH
curl -g -d "{'collection':[{'NumberOfParcels':1,'Weight':1,'Length':1,'Width':1,'Height':1}]}" -H "Accept: application/json" -H "Content-Type: application/json" --user [email protected]:123456 -X POST https://yoururl.com
This especially resolved my error curl command error : bad url colon is first character
If you just want to update a few packages and not all, you can list them as such:
php composer.phar update vendor/package:2.* vendor/package2:dev-master
You can also use wildcards to update a bunch of packages at once:
php composer.phar update vendor/*
source
when available.dist
when available.php
, hhvm
, lib-*
and ext-*
requirements and force the installation even if the local machine does not fulfill these. See also the platform
config option.require-dev
(this is the default behavior).require-dev
. The autoloader generation skips the autoload-dev
rules.--prefer-stable
.important: in this kind of error you should look for simple mistakes in most cases
besides syntax error, I should say once I had same problem and it was because of bad name I have chosen for function. I have never searched for the reason but I remember that I copied another function and change it to use. I add "1" after the name to changed the function name and I got this error.
Git is supposed to understand what files already exist on the server, unless you somehow made a huge difference to your tree and the new changes need to be sent.
To create a new branch with a copy of your current state
git checkout -b new_branch #< create a new local branch with a copy of your code
git push origin new_branch #< pushes to the server
Can you please describe the steps you did to understand what might have made your repository need to send that much to the server.
The icon on Apple's site is 152x152 pixels.
http://www.apple.com/apple-touch-icon.png
Hope that answers your question.
In order to be able to use decimal numbers in a range expression a cool way for doing it is the following: [x * 0.1 for x in range(0, 10)]
If you're going to use this as an index into something else, you can use boolean indices if the arrays are broadcastable; you don't need explicit indices. The absolute simplest way to do this is to simply index based on a truth value.
other_array[first_array == item]
Any boolean operation works:
a = numpy.arange(100)
other_array[first_array > 50]
The nonzero method takes booleans, too:
index = numpy.nonzero(first_array == item)[0][0]
The two zeros are for the tuple of indices (assuming first_array is 1D) and then the first item in the array of indices.
You can also do this to make it more concise and readable. This is what I've seen done in several of the well written open sourced modules:
var self = module.exports = {
foo: function (req, res, next) {
return ('foo');
},
bar: function(req, res, next) {
self.foo();
}
}
import itertools
foos=[1.0, 2.0, 3.0, 4.0, 5.0]
bars=[1, 2, 3]
print zip(foos, itertools.cycle([bars]))
There is no "colon" operator, but the colon appears in two places:
1: In the ternary operator, e.g.:
int x = bigInt ? 10000 : 50;
In this case, the ternary operator acts as an 'if' for expressions. If bigInt is true, then x will get 10000 assigned to it. If not, 50. The colon here means "else".
2: In a for-each loop:
double[] vals = new double[100];
//fill x with values
for (double x : vals) {
//do something with x
}
This sets x to each of the values in 'vals' in turn. So if vals contains [10, 20.3, 30, ...], then x will be 10 on the first iteration, 20.3 on the second, etc.
Note: I say it's not an operator because it's just syntax. It can't appear in any given expression by itself, and it's just chance that both the for-each and the ternary operator use a colon.
You will have to access db through the ip of host machine, or if you want to access it via localhost:1521, then run webserver like -
docker run --net=host --name oracle-wls wls-image:latest
Incase you're looping the OR conditions, you don't need the the second $query->where from the other posts (actually I don't think you need in general, you can just use orWhere in the nested where if easier)
$attributes = ['first'=>'a','second'=>'b'];
$query->where(function ($query) use ($attributes)
{
foreach ($attributes as $key=>value)
{
//you can use orWhere the first time, doesn't need to be ->where
$query->orWhere($key,$value);
}
});
You can use the following:
$regex = '#<\s*?code\b[^>]*>(.*?)</code\b[^>]*>#s';
\b
ensures that a typo (like <codeS>
) is not captured.[^>]*
captures the content of a tag with attributes (eg a class).s
capture content with newlines.See the result here : http://lumadis.be/regex/test_regex.php?id=1081
All answers above contribute important info on the original question. However, there is a generalization that seems wrong.
It is possible to set width and height to at least one inline element (that I can think of) – the <img>
element.
Both accepted answers here and on this duplicate state that this is not possible but this doesn’t seem like a valid general rule.
Example:
img {_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
border: 1px solid red;_x000D_
}
_x000D_
<img src="#" />
_x000D_
The img
has display: inline
, but its width
and height
were successfully set.
for eg. you may take
driver.get('https://www.naukri.com/')
since, it is a current window ,we can name it
main_page = driver.current_window_handle
if there are atleast 1 window popup except the current window,you may try this method and put if condition in break statement by hit n trial for the index
for handle in driver.window_handles:
if handle != main_page:
print(handle)
login_page = handle
break
driver.switch_to.window(login_page)
Now ,whatever the credentials you have to apply,provide after it is loggen in. Window will disappear, but you have to come to main page window and you are done
driver.switch_to.window(main_page)
sleep(10)
Alternatively, you could write a factory function which return a decorator which wraps the return value of the decorated function in a tag passed to the factory function. For example:
from functools import wraps
def wrap_in_tag(tag):
def factory(func):
@wraps(func)
def decorator():
return '<%(tag)s>%(rv)s</%(tag)s>' % (
{'tag': tag, 'rv': func()})
return decorator
return factory
This enables you to write:
@wrap_in_tag('b')
@wrap_in_tag('i')
def say():
return 'hello'
or
makebold = wrap_in_tag('b')
makeitalic = wrap_in_tag('i')
@makebold
@makeitalic
def say():
return 'hello'
Personally I would have written the decorator somewhat differently:
from functools import wraps
def wrap_in_tag(tag):
def factory(func):
@wraps(func)
def decorator(val):
return func('<%(tag)s>%(val)s</%(tag)s>' %
{'tag': tag, 'val': val})
return decorator
return factory
which would yield:
@wrap_in_tag('b')
@wrap_in_tag('i')
def say(val):
return val
say('hello')
Don't forget the construction for which decorator syntax is a shorthand:
say = wrap_in_tag('b')(wrap_in_tag('i')(say)))
I just love getting information like BalusC gives here - and he is kind enough to help SO many people with such GOOD information that I regard his words as gospel, but I was not able to use that order of events to solve this same kind of timing issue in my project. Since BalusC put a great general reference here that I even bookmarked, I thought I would donate my solution for some advanced timing issues in the same place since it does solve the original poster's timing issues as well. I hope this code helps someone:
<p:pickList id="formPickList"
value="#{mediaDetail.availableMedia}"
converter="MediaPicklistConverter"
widgetVar="formsPicklistWidget"
var="mediaFiles"
itemLabel="#{mediaFiles.mediaTitle}"
itemValue="#{mediaFiles}" >
<f:facet name="sourceCaption">Available Media</f:facet>
<f:facet name="targetCaption">Chosen Media</f:facet>
</p:pickList>
<p:commandButton id="viewStream_btn"
value="Stream chosen media"
icon="fa fa-download"
ajax="true"
action="#{mediaDetail.prepareStreams}"
update=":streamDialogPanel"
oncomplete="PF('streamingDialog').show()"
styleClass="ui-priority-primary"
style="margin-top:5px" >
<p:ajax process="formPickList" />
</p:commandButton>
The dialog is at the top of the XHTML outside this form and it has a form of its own embedded in the dialog along with a datatable which holds additional commands for streaming the media that all needed to be primed and ready to go when the dialog is presented. You can use this same technique to do things like download customized documents that need to be prepared before they are streamed to the user's computer via fileDownload buttons in the dialog box as well.
As I said, this is a more complicated example, but it hits all the high points of your problem and mine. When the command button is clicked, the result is to first insure the backing bean is updated with the results of the pickList, then tell the backing bean to prepare streams for the user based on their selections in the pick list, then update the controls in the dynamic dialog with an update, then show the dialog box ready for the user to start streaming their content.
The trick to it was to use BalusC's order of events for the main commandButton and then to add the <p:ajax process="formPickList" />
bit to ensure it was executed first - because nothing happens correctly unless the pickList updated the backing bean first (something that was not happening for me before I added it). So, yea, that commandButton rocks because you can affect previous, pending and current components as well as the backing beans - but the timing to interrelate all of them is not easy to get a handle on sometimes.
Happy coding!
In simple terms ReactJS is parent library which returns something to render as per the host-environment(browser, mobile, server, desktop..etc). Apart from rendering it also provides other methods like lifecycle hooks.. etc.
In the browser, it uses another library react-dom to render DOM elements. In mobile, it uses React-Native components to render platform specific(Both IOS and Android) native UI components. SO,
react + react-dom = web developement
react + react-native = mobile developement
I have written a SP for the this which returns the search results in form of Table name, the Column names in which the search keyword string was found as well as the searches the corresponding rows as shown in below screen shot.
This might not be the most efficient solution but you can always modify and use it according to your need.
IF OBJECT_ID('sp_KeywordSearch', 'P') IS NOT NULL
DROP PROC sp_KeywordSearch
GO
CREATE PROCEDURE sp_KeywordSearch @KeyWord NVARCHAR(100)
AS
BEGIN
DECLARE @Result TABLE
(TableName NVARCHAR(300),
ColumnName NVARCHAR(MAX))
DECLARE @Sql NVARCHAR(MAX),
@TableName NVARCHAR(300),
@ColumnName NVARCHAR(300),
@Count INT
DECLARE @tableCursor CURSOR
SET @tableCursor = CURSOR LOCAL SCROLL FOR
SELECT N'SELECT @Count = COUNT(1) FROM [dbo].[' + T.TABLE_NAME + '] WITH (NOLOCK) WHERE CAST([' + C.COLUMN_NAME +
'] AS NVARCHAR(MAX)) LIKE ''%' + @KeyWord + N'%''',
T.TABLE_NAME,
C.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLES AS T WITH (NOLOCK)
INNER JOIN INFORMATION_SCHEMA.COLUMNS AS C WITH (NOLOCK)
ON T.TABLE_SCHEMA = C.TABLE_SCHEMA AND
T.TABLE_NAME = C.TABLE_NAME
WHERE T.TABLE_TYPE = 'BASE TABLE' AND
C.TABLE_SCHEMA = 'dbo' AND
C.DATA_TYPE NOT IN ('image', 'timestamp')
OPEN @tableCursor
FETCH NEXT FROM @tableCursor INTO @Sql, @TableName, @ColumnName
WHILE (@@FETCH_STATUS = 0)
BEGIN
SET @Count = 0
EXEC sys.sp_executesql
@Sql,
N'@Count INT OUTPUT',
@Count OUTPUT
IF @Count > 0
BEGIN
INSERT INTO @Result
(TableName, ColumnName)
VALUES (@TableName, @ColumnName)
END
FETCH NEXT FROM @tableCursor INTO @Sql, @TableName, @ColumnName
END
CLOSE @tableCursor
DEALLOCATE @tableCursor
SET @tableCursor = CURSOR LOCAL SCROLL FOR
SELECT SUBSTRING(TB.Sql, 1, LEN(TB.Sql) - 3) AS Sql, TB.TableName, SUBSTRING(TB.Columns, 1, LEN(TB.Columns) - 1) AS Columns
FROM (SELECT R.TableName, (SELECT R2.ColumnName + ', ' FROM @Result AS R2 WHERE R.TableName = R2.TableName FOR XML PATH('')) AS Columns,
'SELECT * FROM ' + R.TableName + ' WITH (NOLOCK) WHERE ' +
(SELECT 'CAST(' + R2.ColumnName + ' AS NVARCHAR(MAX)) LIKE ''%' + @KeyWord + '%'' OR '
FROM @Result AS R2
WHERE R.TableName = R2.TableName
FOR
XML PATH('')) AS Sql
FROM @Result AS R
GROUP BY R.TableName) TB
ORDER BY TB.Sql
OPEN @tableCursor
FETCH NEXT FROM @tableCursor INTO @Sql, @TableName, @ColumnName
WHILE (@@FETCH_STATUS = 0)
BEGIN
PRINT @Sql
SELECT @TableName AS [Table],
@ColumnName AS Columns
EXEC(@Sql)
FETCH NEXT FROM @tableCursor INTO @Sql, @TableName, @ColumnName
END
CLOSE @tableCursor
DEALLOCATE @tableCursor
END
Alternatively, you can also use a special function known as the linear-gradient() function to split browser screen into two equal halves. Check out the following code snippet:
body
{
background-image:linear-gradient(90deg, lightblue 50%, skyblue 50%);
}
Here, linear-gradient() function accepts three arguments
90deg
for vertical division of screen.( Similarly, you can use 180deg
for horizontal division of screen)lightblue
color is used to represent the left half of the screen.skyblue
color has been used to represent the right half of the split screen.
Here, 50%
has been used for equal division of the browser screen. You can use any other value if you don't want an equal division of the screen.
Hope this helps. :)
Happy Coding!This is a good article about the subject.
To summarize,
An application program that is executed within a runtime engine installed in the same machine. The application cannot run without it. The runtime environment provides the general library of software routines that the program uses and typically performs memory management. It may also provide just-in-time (JIT) conversion from source code to executable code or from an intermediate language to executable code. Java, Visual Basic and .NET's Common Language Runtime (CLR) are examples of runtime engines. (Read more)
An executable program that runs by itself. Launched from the operating system, the program calls upon and uses the software routines in the operating system, but does not require another software system to be used. Assembly language programs that have been assembled into machine language and C/C++ programs compiled into machine language for a particular platform are examples of unmanaged code.(Read more)
You can describe your css selection like cascading style sheet dows:
protected override void When()
{
SUT.Browser.FindElements(By.CssSelector("#carousel > a.tiny.button"))
}
Google already published a guide on optimization of PHP and the conclusion was:
No getter and setter Optimizing PHP
And no, you must not use magic methods. For PHP, Magic Method are evil. Why?
PHP is not Java, C++, or C#. PHP is different and plays with different roles.
Junit xml format is used outside of Java/Maven/Ant word. Jenkins with http://wiki.jenkins-ci.org/display/JENKINS/xUnit+Plugin is a solution.
For the one shot solution I have found this tool that does the job: https://www.npmjs.com/package/junit-viewer
junit-viewer --results=surefire-reports --save=file_location.html
--results=
is directory with xml files (test reports)
From Java 9 there is some optimizations in replace method.
In Java 8 it uses a regex.
public String replace(CharSequence target, CharSequence replacement) {
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
From Java 9 and on.
And Stringlatin implementation.
Which perform way better.
A while ago i wrote a detailed article about Hibernate key generators: http://blog.eyallupu.com/2011/01/hibernatejpa-identity-generators.html
Choosing the correct generator is a complicated task but it is important to try and get it right as soon as possible - a late migration might be a nightmare.
A little off topic but a good chance to raise a point usually overlooked which is sharing keys between applications (via API). Personally I always prefer surrogate keys and if I need to communicate my objects with other systems I don't expose my key (even though it is a surrogate one) – I use an additional ‘external key’. As a consultant I have seen more than once 'great' system integrations using object keys (the 'it is there let's just use it' approach) just to find a year or two later that one side has issues with the key range or something of the kind requiring a deep migration on the system exposing its internal keys. Exposing your key means exposing a fundamental aspect of your code to external constrains shouldn’t really be exposed to.
Try this, but i don't sure that will work every where :)
public enum MyEnum {
A("Start There"),
B("Start Here");
MyEnum(String name) {
try {
Field fieldName = getClass().getSuperclass().getDeclaredField("name");
fieldName.setAccessible(true);
fieldName.set(this, name);
fieldName.setAccessible(false);
} catch (Exception e) {}
}
}
A slight variation on andrew.fox answer, as the string to decode might not be a correct base64 encoded string:
using System;
namespace Service.Support
{
public static class Base64
{
public static string ToBase64(this System.Text.Encoding encoding, string text)
{
if (text == null)
{
return null;
}
byte[] textAsBytes = encoding.GetBytes(text);
return Convert.ToBase64String(textAsBytes);
}
public static bool TryParseBase64(this System.Text.Encoding encoding, string encodedText, out string decodedText)
{
if (encodedText == null)
{
decodedText = null;
return false;
}
try
{
byte[] textAsBytes = Convert.FromBase64String(encodedText);
decodedText = encoding.GetString(textAsBytes);
return true;
}
catch (Exception)
{
decodedText = null;
return false;
}
}
}
}
The problem in my case occurred when I tried to use a command on the command-line for the Post-build event in my Test Class Library. When you use quotation marks like so:
"$(SolutionDir)\packages\NUnit.Runners.2.6.2\tools\nunit" "$(TargetPath)"
or if you're using the console:
"$(SolutionDir)\packages\NUnit.Runners.2.6.2\tools\nunit-console" "$(TargetPath)"
This fixed the issue for me.
How do Python's
any
andall
functions work?
any
and all
take iterables and return True
if any and all (respectively) of the elements are True
.
>>> any([0, 0.0, False, (), '0']), all([1, 0.0001, True, (False,)])
(True, True) # ^^^-- truthy non-empty string
>>> any([0, 0.0, False, (), '']), all([1, 0.0001, True, (False,), {}])
(False, False) # ^^-- falsey
If the iterables are empty, any
returns False
, and all
returns True
.
>>> any([]), all([])
(False, True)
I was demonstrating all
and any
for students in class today. They were mostly confused about the return values for empty iterables. Explaining it this way caused a lot of lightbulbs to turn on.
They, any
and all
, both look for a condition that allows them to stop evaluating. The first examples I gave required them to evaluate the boolean for each element in the entire list.
(Note that list literal is not itself lazily evaluated - you could get that with an Iterator - but this is just for illustrative purposes.)
Here's a Python implementation of any and all:
def any(iterable):
for i in iterable:
if i:
return True
return False # for an empty iterable, any returns False!
def all(iterable):
for i in iterable:
if not i:
return False
return True # for an empty iterable, all returns True!
Of course, the real implementations are written in C and are much more performant, but you could substitute the above and get the same results for the code in this (or any other) answer.
all
all
checks for elements to be False
(so it can return False
), then it returns True
if none of them were False
.
>>> all([1, 2, 3, 4]) # has to test to the end!
True
>>> all([0, 1, 2, 3, 4]) # 0 is False in a boolean context!
False # ^--stops here!
>>> all([])
True # gets to end, so True!
any
The way any
works is that it checks for elements to be True
(so it can return True), then it returns
Falseif none of them were
True`.
>>> any([0, 0.0, '', (), [], {}]) # has to test to the end!
False
>>> any([1, 0, 0.0, '', (), [], {}]) # 1 is True in a boolean context!
True # ^--stops here!
>>> any([])
False # gets to end, so False!
I think if you keep in mind the short-cutting behavior, you will intuitively understand how they work without having to reference a Truth Table.
all
and any
shortcutting:First, create a noisy_iterator:
def noisy_iterator(iterable):
for i in iterable:
print('yielding ' + repr(i))
yield i
and now let's just iterate over the lists noisily, using our examples:
>>> all(noisy_iterator([1, 2, 3, 4]))
yielding 1
yielding 2
yielding 3
yielding 4
True
>>> all(noisy_iterator([0, 1, 2, 3, 4]))
yielding 0
False
We can see all
stops on the first False boolean check.
And any
stops on the first True boolean check:
>>> any(noisy_iterator([0, 0.0, '', (), [], {}]))
yielding 0
yielding 0.0
yielding ''
yielding ()
yielding []
yielding {}
False
>>> any(noisy_iterator([1, 0, 0.0, '', (), [], {}]))
yielding 1
True
Let's look at the source to confirm the above.
Here's the source for any
:
static PyObject *
builtin_any(PyObject *module, PyObject *iterable)
{
PyObject *it, *item;
PyObject *(*iternext)(PyObject *);
int cmp;
it = PyObject_GetIter(iterable);
if (it == NULL)
return NULL;
iternext = *Py_TYPE(it)->tp_iternext;
for (;;) {
item = iternext(it);
if (item == NULL)
break;
cmp = PyObject_IsTrue(item);
Py_DECREF(item);
if (cmp < 0) {
Py_DECREF(it);
return NULL;
}
if (cmp > 0) {
Py_DECREF(it);
Py_RETURN_TRUE;
}
}
Py_DECREF(it);
if (PyErr_Occurred()) {
if (PyErr_ExceptionMatches(PyExc_StopIteration))
PyErr_Clear();
else
return NULL;
}
Py_RETURN_FALSE;
}
And here's the source for all
:
static PyObject *
builtin_all(PyObject *module, PyObject *iterable)
{
PyObject *it, *item;
PyObject *(*iternext)(PyObject *);
int cmp;
it = PyObject_GetIter(iterable);
if (it == NULL)
return NULL;
iternext = *Py_TYPE(it)->tp_iternext;
for (;;) {
item = iternext(it);
if (item == NULL)
break;
cmp = PyObject_IsTrue(item);
Py_DECREF(item);
if (cmp < 0) {
Py_DECREF(it);
return NULL;
}
if (cmp == 0) {
Py_DECREF(it);
Py_RETURN_FALSE;
}
}
Py_DECREF(it);
if (PyErr_Occurred()) {
if (PyErr_ExceptionMatches(PyExc_StopIteration))
PyErr_Clear();
else
return NULL;
}
Py_RETURN_TRUE;
}
Tim Lentine's answer seems to be true even in the full release. There is just one other thing I would like to mention.
If you complete your import without going into "Advanced..." and saving the spec, but you do save the import for reuse at the end of the wizard (new feature AFAIK), you will not be able to go back and edit that spec. It is built into the "Saved Import". This may be what Knox was referring to.
You can, however, do a partial work around:
You can use the CONCAT function to do that:
UPDATE tbl SET col=CONCAT('test',col);
If you want to get cleverer and only update columns which don't already have test prepended, try
UPDATE tbl SET col=CONCAT('test',col)
WHERE col NOT LIKE 'test%';
Example for you to work from
HTML:
<input type="text" value="This is some text" id="text" style="width: 150px;" />
<br />
<input type="button" value="Click Me" id="button" />?
jQuery:
<script type="text/javascript">
$(function () {
$('#button').on('click', function () {
var text = $('#text');
text.val(text.val() + ' after clicking');
});
});
<script>
Javascript
<script type="text/javascript">
document.getElementById("button").addEventListener('click', function () {
var text = document.getElementById('text');
text.value += ' after clicking';
});
</script>
Working jQuery example: http://jsfiddle.net/geMtZ/ ?
I would recommend using jQuery with this function:
$(document).ready(function(){
$('#about').addClass('expand');
});
This will add the expand class to an element with id of about when the dom is ready on page load.
If you want to check syntax error for any nginx files, you can use the -c option.
[root@server ~]# sudo nginx -t -c /etc/nginx/my-server.conf
nginx: the configuration file /etc/nginx/my-server.conf syntax is ok
nginx: configuration file /etc/nginx/my-server.conf test is successful
[root@server ~]#
Fellas, I know this is old but hey I've this solution which I think works better than all. First and foremost overcomes the Case Sensitivity that the jquery :contains() is shipped with:
var text = "text";
var search = $( "ul li label" ).filter( function ()
{
return $( this ).text().toLowerCase().indexOf( text.toLowerCase() ) >= 0;
}).first(); // Returns the first element that matches the text. You can return the last one with .last()
Hope someone in the near future finds it helpful.
public static async Task<byte[]> GetBytesAsync(string url) {
var request = (HttpWebRequest)WebRequest.Create(url);
using (var response = await request.GetResponseAsync())
using (var content = new MemoryStream())
using (var responseStream = response.GetResponseStream()) {
await responseStream.CopyToAsync(content);
return content.ToArray();
}
}
public static async Task<string> GetStringAsync(string url) {
var bytes = await GetBytesAsync(url);
return Encoding.UTF8.GetString(bytes, 0, bytes.Length);
}
Tried this in the console, and it works.
var aFileParts = ['<a id="a"><b id="b">hey!</b></a>'];
var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // the blob
window.open(URL.createObjectURL(oMyBlob));
Use const App instead of const app
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.
I've created a simple extension, as a few of the other answers threw null exceptions if there wasn't a QueryString
to start with:
public static string TrimQueryString(this string source)
{
if (string.IsNullOrEmpty(source))
return source;
var hasQueryString = source.IndexOf('?') != -1;
if (!hasQueryString)
return source;
var result = source.Substring(0, source.IndexOf('?'));
return result;
}
Usage:
var url = Request.Url?.AbsoluteUri.TrimQueryString()
If you are expecting double, decimal, float, integer
why not use the one which accomodates all namely decimal (128 bits are enough for most numbers you are looking at).
instead of (double)value
use decimal.Parse(value.ToString())
or Convert.ToDecimal(value)
Cappuccino or PhoneGap.
Sometimes though trying to find a shortcut does not save you time or give you a comparable end product.
This is difficult.
I think we should;
Return 4xx errors only when the client has the power to make a change to the request, headers or body, that will result in the request succeeding with the same intent.
Return error range codes when the expected mutation has not occured, i.e. a DELETE didn't happen or a PUT didn't change anything. However, a POST is more interesting because the spec says it should be used to either create resources at a new location, or just process a payload.
Using the example in Vish's answer, if the request intends to add employee Priya to a department Marketing but Priya wasn't found or her account is archived, then this is an application error.
The request worked fine, it got to your application rules, the client did everything properly, the ETags matched etc. etc.
Because we're using HTTP we must respond based on the effect of the request on the state of the resource. And that depends on your API design.
Perhaps you designed this.
PUT { updated members list } /marketing/members
Returning a success code would indicate that the "replacement" of the resource worked; a GET on the resource would reflect your changes, but it wouldn't.
So now you have to choose a suitable negative HTTP code, and that's the tricky part, since the codes are strongly intended for the HTTP protocol, not your application.
When I read the official HTTP codes, these two look suitable.
The 409 (Conflict) status code indicates that the request could not be completed due to a conflict with the current state of the target resource. This code is used in situations where the user might be able to resolve the conflict and resubmit the request. The server SHOULD generate a payload that includes enough information for a user to recognize the source of the conflict.
And
The 500 (Internal Server Error) status code indicates that the server encountered an unexpected condition that prevented it from fulfilling the request.
Though we've traditionally considered the 500 to be like an unhandled exception :-/
I don't think its unreasonable to invent your own status code so long as its consistently applied and designed.
This design is easier to deal with.
PUT { membership add command } /accounts/groups/memberships/instructions/1739119
Then you could design your API to always succeed in creating the instruction, it returns 201 Created and a Location header and any problems with the instruction are held within that new resource.
A POST is more like that last PUT to a new location. A POST allows for any kind of server processing of a message, which opens up designs that say something like "The action successfully failed."
Probably you already wrote an API that does this, a website. You POST the payment form and it was successfully rejected because the credit card number was wrong.
With a POST, whether you return 200 or 201 along with your rejection message depends on whether a new resource was created and is available to GET at another location, or not.
With that all said, I'd be inclined to design APIs that need fewer PUTs, perhaps just updating data fields, and actions and stuff that invokes rules and processing or just have a higher chance of expected failures, can be designed to POST an instruction form.
In addition, use collections.Counter to refactor your code:
from collections import Counter
words = ['a', 'b', 'c', 'a']
Counter(words).keys() # equals to list(set(words))
Counter(words).values() # counts the elements' frequency
Output:
['a', 'c', 'b']
[2, 1, 1]
A couple of different ways to solve the problem:
Just replace Environment.Exit with return. The compiler knows that return ends the method, but doesn't know that Environment.Exit does.
static void Main(string[] args) {
if(args.Length != 0) {
if(Byte.TryParse(args[0], out maxSize))
queue = new Queue(){MaxSize = maxSize};
else
return;
} else {
return;
}
Of course, you can really only get away with that because you're using 0 as your exit code in all cases. Really, you should return an int instead of using Environment.Exit. For this particular case, this would be my preferred method
static int Main(string[] args) {
if(args.Length != 0) {
if(Byte.TryParse(args[0], out maxSize))
queue = new Queue(){MaxSize = maxSize};
else
return 1;
} else {
return 2;
}
}
Initialize queue to null, which is really just a compiler trick that says "I'll figure out my own uninitialized variables, thank you very much". It's a useful trick, but I don't like it in this case - you have too many if branches to easily check that you're doing it properly. If you really wanted to do it this way, something like this would be clearer:
static void Main(string[] args) {
Byte maxSize;
Queue queue = null;
if(args.Length == 0 || !Byte.TryParse(args[0], out maxSize)) {
Environment.Exit(0);
}
queue = new Queue(){MaxSize = maxSize};
for(Byte j = 0; j < queue.MaxSize; j++)
queue.Insert(j);
for(Byte j = 0; j < queue.MaxSize; j++)
Console.WriteLine(queue.Remove());
}
Add a return statement after Environment.Exit. Again, this is more of a compiler trick - but is slightly more legit IMO because it adds semantics for humans as well (though it'll keep you from that vaunted 100% code coverage)
static void Main(String[] args) {
if(args.Length != 0) {
if(Byte.TryParse(args[0], out maxSize)) {
queue = new Queue(){MaxSize = maxSize};
} else {
Environment.Exit(0);
return;
}
} else {
Environment.Exit(0);
return;
}
for(Byte j = 0; j < queue.MaxSize; j++)
queue.Insert(j);
for(Byte j = 0; j < queue.MaxSize; j++)
Console.WriteLine(queue.Remove());
}
Improving the answer https://stackoverflow.com/a/14720445/6654512 to work with Python3. That piece of code would sometimes generate numbers greater than 1 and matplotlib would throw an error.
for X,Y in data:
scatter(X, Y, c=numpy.random.random(3))
GregorianCalendar c = GregorianCalendar.from((LocalDate.parse("2016-06-22")).atStartOfDay(ZoneId.systemDefault()));
XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
This is a shorthand Ajax function, which is equivalent to:
$.ajax({ type: "POST",
url: url,
data: { username: value_login.val(), firstname: value_firstname.val(),
lastname: value_lastname.val(), email: value_email.val(),
password: value_password.val()
},
dataType: "json"
success: success// -> call your func here
});
Hope This helps
Step1 (inside command prompt [I hope you cd TO YOUR FOLDER]) : npm install express
Step 2: Create a file server.js
var fs = require("fs");
var host = "127.0.0.1";
var port = 1337;
var express = require("express");
var app = express();
app.use(express.static(__dirname + "/public")); //use static files in ROOT/public folder
app.get("/", function(request, response){ //root dir
response.send("Hello!!");
});
app.listen(port, host);
Please note, you should add WATCHFILE (or use nodemon) too. Above code is only for a simple connection server.
STEP 3: node server.js
or nodemon server.js
There is now more easy method if you just want host simple HTTP server.
npm install -g http-server
and open our directory and type http-server
Try the rename
command in the folder with the files:
rename 's/^/Unix_/' *
The argument of rename (sed s command) indicates to replace the regex ^ with Unix_. The caret (^) is a special character that means start of the line.
I am using the following to get the desired results:
#include <time.h>
#include <iostream>
using namespace std;
int main (int argc, char** argv)
{
// reset the clock
timespec tS;
tS.tv_sec = 0;
tS.tv_nsec = 0;
clock_settime(CLOCK_PROCESS_CPUTIME_ID, &tS);
...
... <code to check for the time to be put here>
...
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &tS);
cout << "Time taken is: " << tS.tv_sec << " " << tS.tv_nsec << endl;
return 0;
}
The worst thing of using just
console.log({'some stuff': 2} + '\n' + 'something')
is that all stuff are converted to the string and if you need object to show you may see next:
[object Object]
Thus my variant is the next code:
console.log({'some stuff': 2},'\n' + 'something');
I needed my ASP.NET drop down list to take up all available space, and this is all I put in the CSS and it is working in Firefox and IE11:
width: 100%
I had to add the CSS class into the asp:DropDownList element
Why does it work in Chrome and not Firefox?
The W3 spec for CORS preflight requests clearly states that user credentials should be excluded. There is a bug in Chrome and WebKit where OPTIONS
requests returning a status of 401 still send the subsequent request.
Firefox has a related bug filed that ends with a link to the W3 public webapps mailing list asking for the CORS spec to be changed to allow authentication headers to be sent on the OPTIONS
request at the benefit of IIS users. Basically, they are waiting for those servers to be obsoleted.
How can I get the OPTIONS
request to send and respond consistently?
Simply have the server (API in this example) respond to OPTIONS
requests without requiring authentication.
Kinvey did a good job expanding on this while also linking to an issue of the Twitter API outlining the catch-22 problem of this exact scenario interestingly a couple weeks before any of the browser issues were filed.
Adding to what was already said.
if you want to *ngFor
an element , and hide \ show elements in it, on hover, like you added in the comments, you should re-think the whole concept.
a more appropriate way to do it, does not involve angular at all.
I would go with pure CSS instead, using its native :hover
property.
something like:
App.Component.css
div span.only-show-on-hover {
visibility: hidden;
}
div:hover span.only-show-on-hover {
visibility: visible;
}
App.Component.html
<div *ngFor="let i of [1,2,3,4]" > hover me please.
<span class="only-show-on-hover">you only see me when hovering</span>
</div>
added a demo: https://stackblitz.com/edit/hello-angular-6-hvgx7n?file=src%2Fapp%2Fapp.component.html
For me, it was not using authentication in the request.
Just use string methods .replace()
if they occur throughout, or .strip()
if they only occur at the start and/or finish:
a = '"sajdkasjdsak" "asdasdasds"'
a = a.replace('"', '')
'sajdkasjdsak asdasdasds'
# or, if they only occur at start and end...
a = a.strip('\"')
'sajdkasjdsak" "asdasdasds'
# or, if they only occur at start...
a = a.lstrip('\"')
# or, if they only occur at end...
a = a.rstrip('\"')
Use this.
if(_dialog!=null && _dialog.isShowing()) _dialog.dismiss();
OnClientClick seems to be very picky when used with OnClick.
I tried unsuccessfully with the following use cases:
OnClientClick="return ValidateSearch();"
OnClientClick="if(ValidateSearch()) return true;"
OnClientClick="ValidateSearch();"
But they did not work. The following worked:
<asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1"
OnClick="keywordSearch_Click"
OnClientClick="if (!ValidateSearch()) { return false;};" />
moment.utc(date).format(...);
is the way to go, since
moment().utc(date).format(...);
does behave weird...
Im my case i just moved the folder to root directory like so.
move <source directory> c:\
And then ran the command to remove the directory
rmdir c:\<moved directory> /s /q
I had same issue as I had missed adding composeEnhancers. Once this is setup then you can take a look into action creators. You get this error when this is not setup as well.
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
rootReducer,
composeEnhancers(applyMiddleware(thunk))
);
Actually they are the same. LEFT OUTER JOIN
is same as LEFT JOIN
and RIGHT OUTER JOIN
is same as RIGHT JOIN
. It is more informative way to compare from INNER Join
.
See this Wikipedia article for details.
Modify onClick()
as follows:
@Override
public void onClick(View v) {
if(v == btn) {
canvas=sv.getHolder().lockCanvas();
if(canvas!=null) {
canvas.drawBitmap(bitmap, 100, 100, null);
sv.getHolder().unlockCanvasAndPost(canvas);
}
} else if(v == btn1) {
saveBitmapToInternalStorage(bitmap);
}
}
There are several ways to enforce that btn
must be pressed before btn1
so that the bitmap
is painted before you attempt to save it.
I suggest that you initially disable btn1
, and that you enable it when btn
is clicked, like this:
if(v == btn) {
...
btn1.setEnabled(true);
}
For chinese Rails developers:
DateTime.strptime('2012-12-09 00:01:36', '%Y-%m-%d %H:%M:%S')
=> Sun, 09 Dec 2012 00:01:36 +0000
A long while ago now but in reply to the original question, would this help ?
Just put onClick
into the SELECT
line.
Then put what you want each OPTION
to do in the OPTION
lines.
ie:
<SELECT name="your name" onClick>
<option value ="Kilometres" onClick="YourFunction()">Kilometres
-------
-------
</SELECT>
If you want to extract a raw-ish value from a HSSF cell, you can use something like this code fragment:
CellBase base = (CellBase) cell;
CellType cellType = cell.getCellType();
base.setCellType(CellType.STRING);
String result = cell.getStringCellValue();
base.setCellType(cellType);
At least for strings that are completely composed of digits (and automatically converted to numbers by Excel), this returns the original string (e.g. "12345"
) instead of a fractional value (e.g. "12345.0"
). Note that setCellType
is available in interface Cell
(as of v. 4.1) but deprecated and announced to be eliminated in v 5.x, whereas this method is still available in class CellBase
. Obviously, it would be nicer either to have getRawValue
in the Cell
interface or at least to be able use getStringCellValue
on non STRING cell types. Unfortunately, all replacements of setCellType
mentioned in the description won't cover this use case (maybe a member of the POI dev team reads this answer).
revalidate()
just request to layout the container, when you experienced simply call revalidate()
works, it could be caused by the updating of child components bounds triggers the repaint()
when their bounds are changed during the re-layout. In the case you mentioned, only component removed and no component bounds are changed, this case no repaint()
is "accidentally" triggered.
The other answers do a good job of recreating the default header view, but don't actually answer your main question:
is there any way to get default section header ?
There is a way - just implement tableView:willDisplayHeaderView:forSection:
in your delegate. The default header view will be passed into the second parameter, and from there you can cast it to a UITableViewHeaderFooterView
and then add/change subviews as you wish.
Obj-C
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
// Do whatever with the header view... e.g.
// headerView.textLabel.textColor = [UIColor whiteColor]
}
Swift
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
{
let headerView = view as! UITableViewHeaderFooterView
// Do whatever with the header view... e.g.
// headerView.textLabel?.textColor = UIColor.white
}
You can't do it. But you can use custom Alert and Confirm boxes.
You can read about some User Interface libraries here:
http://speckyboy.com/2010/05/17/15-javascript-web-ui-libraries-frameworks-and-libraries/
Most common libraries are:
Install tesseract from https://github.com/UB-Mannheim/tesseract/wiki and add the path of tesseract.exe to the Path environment variable.
member b of object pointed to by a a->b
In Android Studio:
Build
Build APK(s)
Wait and go to the location shown in a pop-up window. On right bottom side
Typescript is (a superset of) javascript, so you just use JSON.parse
as you would in javascript:
let obj = JSON.parse(jsonString);
Only that in typescript you can have a type to the resulting object:
interface MyObj {
myString: string;
myNumber: number;
}
let obj: MyObj = JSON.parse('{ "myString": "string", "myNumber": 4 }');
console.log(obj.myString);
console.log(obj.myNumber);
Felipsmartins is correct.
It is worth mentioning that it is because you cannot really use the -d/--data option if this is not a POST request. But this is still possible if you use the -G option.
Which means you can do this:
curl -X DELETE -G 'http://localhost:5000/locations' -d 'id=3'
Here it is a bit silly but when you are on the command line and you have a lot of parameters, it is a lot tidier.
I am saying this because cURL commands are usually quite long, so it is worth making it on more than one line escaping the line breaks.
curl -X DELETE -G \
'http://localhost:5000/locations' \
-d id=3 \
-d name=Mario \
-d surname=Bros
This is obviously a lot more comfortable if you use zsh. I mean when you need to re-edit the previous command because zsh lets you go line by line. (just saying)
Hope it helps.
<script type="text/javascript" src="jquery.js">
</script>
<script type="text/javascript">
function omtCallFromAjax(urlVariable)
{
alert("omt:"+urlVariable);
$("#omtDiv").load("omtt.php?"+urlVariable);
}
</script>
try this it work for me
If your array of objects is items
, you can do:
var items = [{_x000D_
id: 1,_x000D_
name: 'john'_x000D_
}, {_x000D_
id: 2,_x000D_
name: 'jane'_x000D_
}, {_x000D_
id: 2000,_x000D_
name: 'zack'_x000D_
}];_x000D_
_x000D_
var names = items.map(function(item) {_x000D_
return item['name'];_x000D_
});_x000D_
_x000D_
console.log(names);_x000D_
console.log(items);
_x000D_
Documentation: map()
there is an official YouTube Android Player API wich you can use. This is a bit more complicated but it is working better than other solutions using webclients.
First you must register your app in Googles API Console. This is completely free until your app gets over 25k request a month (or something like that). There are complete anf great tutorials under the link. I hope you can understand them. If not, ask! :)
var root = document.createElement("div");
root.innerHTML = "My name is <b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";
var texts = [].map.call( root.querySelectorAll("b"), function(v){
return v.textContent || v.innerText || "";
});
//["Bob", "20", "programming"]
Here's a great scripted solution for logging people out remotely or locally. I'm using qwinsta to get session information and building an array out of the given output. This makes it really easy to iterate through each entry and log out only the actual users, and not the system or RDP listener itself which usually just throws an access denied error anyway.
$serverName = "Name of server here OR localhost"
$sessions = qwinsta /server $serverName| ?{ $_ -notmatch '^ SESSIONNAME' } | %{
$item = "" | Select "Active", "SessionName", "Username", "Id", "State", "Type", "Device"
$item.Active = $_.Substring(0,1) -match '>'
$item.SessionName = $_.Substring(1,18).Trim()
$item.Username = $_.Substring(19,20).Trim()
$item.Id = $_.Substring(39,9).Trim()
$item.State = $_.Substring(48,8).Trim()
$item.Type = $_.Substring(56,12).Trim()
$item.Device = $_.Substring(68).Trim()
$item
}
foreach ($session in $sessions){
if ($session.Username -ne "" -or $session.Username.Length -gt 1){
logoff /server $serverName $session.Id
}
}
In the first line of this script give $serverName the appropriate value or localhost if running locally. I use this script to kick users before an automated process attempts to move some folders around. Prevents "file in use" errors for me. Another note, this script will have to be ran as an administrator user otherwise you can get accessed denied trying to log someone out. Hope this helps!
Differences might not be meaningful in a typical use case, but using the standard DOM functionality
$("#el")[0].outerHTML
is about twice as fast as
$("<div />").append($("#el").clone()).html();
so I would go with:
/*
* Return outerHTML for the first element in a jQuery object,
* or an empty string if the jQuery object is empty;
*/
jQuery.fn.outerHTML = function() {
return (this[0]) ? this[0].outerHTML : '';
};
To put a require rule on a select list you just need an option with an empty value
<option value="">Year</option>
then just applying required on its own is enough
<script>
$(function () {
$("form").validate();
});
</script>
with form
<form>
<select name="year" id="year" class="required">
<option value="">Year</option>
<option value="1">1919</option>
<option value="2">1920</option>
<option value="3">1921</option>
<option value="4">1922</option>
</select>
<input type="submit" />
</form>
I think that this below is accurate and it may help. Feel free to correct it if you find any errors. I'm new at C.
char str[]
including termination null character '\0'
&str
, &str[0]
and str
, all three represent the same location in memory which is address of the first element of the array str
char *strPtr = &str[0]; //declaration and initialization
alternatively, you can split this in two:
char *strPtr; strPtr = &str[0];
strPtr
is a pointer to a char
strPtr
points at array str
strPtr
is a variable with its own address in memorystrPtr
is a variable that stores value of address &str[0]
strPtr
own address in memory is different from the memory address that it stores (address of array in memory a.k.a &str[0])&strPtr
represents the address of strPtr itselfI think that you could declare a pointer to a pointer as:
char **vPtr = &strPtr;
declares and initializes with address of strPtr pointer
Alternatively you could split in two:
char **vPtr;
*vPtr = &strPtr
*vPtr
points at strPtr pointer*vPtr
is a variable with its own address in memory*vPtr
is a variable that stores value of address &strPtrstr++
, str
address is a const
, but
you can do strPtr++
var myContent = '<div id="test">Hello <span>world!</span></div>';
alert($(myContent).text());
That results in hello world. Does that answer your question?
http://jsfiddle.net/D2tEf/ for an example
Here's a solution that does not require any libraries.
This routine transmits every file in the directory d:/data/mpf10
to urlToConnect
String boundary = Long.toHexString(System.currentTimeMillis());
URLConnection connection = new URL(urlToConnect).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
PrintWriter writer = null;
try {
writer = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
File dir = new File("d:/data/mpf10");
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
continue;
}
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\"" + file.getName() + "\"; filename=\"" + file.getName() + "\"");
writer.println("Content-Type: text/plain; charset=UTF-8");
writer.println();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
writer.println(line);
}
} finally {
if (reader != null) {
reader.close();
}
}
}
writer.println("--" + boundary + "--");
} finally {
if (writer != null) writer.close();
}
// Connection is lazily executed whenever you request any status.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
// Handle response
df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3], 'new':['apple', 'banana', 'pear']})
df['combined'] = df['foo'].astype(str)+'_'+df['bar'].astype(str)
If you concatenate with string('_') please you convert the column to string which you want and after you can concatenate the dataframe.
If you're not able to use NewChart.js you just need to change the way to set the color using array instead. Find the helper iteration inside Chart.js:
Replace this line:
fillColor : dataset.fillColor,
For this one:
fillColor : dataset.fillColor[index],
The resulting code:
//Iterate through each of the datasets, and build this into a property of the chart
helpers.each(data.datasets,function(dataset,datasetIndex){
var datasetObject = {
label : dataset.label || null,
fillColor : dataset.fillColor,
strokeColor : dataset.strokeColor,
bars : []
};
this.datasets.push(datasetObject);
helpers.each(dataset.data,function(dataPoint,index){
//Add a new point for each piece of data, passing any required data to draw.
datasetObject.bars.push(new this.BarClass({
value : dataPoint,
label : data.labels[index],
datasetLabel: dataset.label,
strokeColor : dataset.strokeColor,
//Replace this -> fillColor : dataset.fillColor,
// Whith the following:
fillColor : dataset.fillColor[index],
highlightFill : dataset.highlightFill || dataset.fillColor,
highlightStroke : dataset.highlightStroke || dataset.strokeColor
}));
},this);
},this);
And in your js:
datasets: [
{
label: "My First dataset",
fillColor: ["rgba(205,64,64,0.5)", "rgba(220,220,220,0.5)", "rgba(24,178,235,0.5)", "rgba(220,220,220,0.5)"],
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: [2000, 1500, 1750, 50]
}
]
Open the pom.xml file.
under the project
tag add <dependencies>
as another tag, and google for the Maven dependencies. I used this to search.
So after getting the dependency create another tag dependency
inside <dependencies>
tag.
So ultimately it will look something like this.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>doc-examples</groupId>
<artifactId>lambda-java-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>lambda-java-example</name>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.amazonaws/aws-lambda-java-core -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-lambda-java-core</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
</project>
Hope it helps.
You can't access your fieldname
as a global variable. Use document.getElementById:
function updateInput(ish){
document.getElementById("fieldname").value = ish;
}
and
onchange="updateInput(this.value)"
Try this:
function add()
{
var sum = 0;
var inputs = document.getElementsByTagName("input");
for(i = 0; i <= inputs.length; i++)
{
if( inputs[i].name == 'qty'+i)
{
sum += parseInt(input[i].value);
}
}
console.log(sum)
}
I faced same issue when converting an eclipse project to Android studio.In my case i had the design lirary jar file in eclipse project and I have added dependency of the same in gradle caused the error.I solved it by deleting jar from libs.
Tensorflow upgrade -Python3
>> pip3 install --upgrade tensorflow --user
if you got this
"ERROR: tensorboard 2.0.2 has requirement grpcio>=1.24.3, but you'll have grpcio 1.22.0 which is incompatible."
Upgrade grpcio
>> pip3 install --upgrade grpcio --user
DocumentElement
is the root node of the document so childNodes[1]
doesn't exist in that document. childNodes[0]
would be the <Settings> node
<IF>
<CONDITIONS>
<CONDITION field="time" from="5pm" to="9pm"></CONDITION>
</CONDITIONS>
<RESULTS><...some actions defined.../></RESULTS>
<ELSE>
<RESULTS><...some other actions defined.../></RESULTS>
</ELSE>
</IF>
Here's my take on it. This will allow you to have multiple conditions.
This seems to work for me:
>>>a = ['x', 'y', 'z']
>>>type(a)
<class 'list'>
>>>isinstance(a, list)
True
Think of it as a placeholder. It can be quite useful when you have code that follows a certain pattern but need not be tied to any particular functionality.
For example, consider the Enumerable.Select
extension method.
This method takes a Func<T, TResult>
instead of any concrete function. This allows it to be used in any context where the above pattern applies.
So for example, say I have a List<Person>
and I want just the name of every person in the list. I can do this:
var names = people.Select(p => p.Name);
Or say I want the age of every person:
var ages = people.Select(p => p.Age);
Right away, you can see how I was able to leverage the same code representing a pattern (with Select
) with two different functions (p => p.Name
and p => p.Age
).
The alternative would be to write a different version of Select
every time you wanted to scan a sequence for a different kind of value. So to achieve the same effect as above, I would need:
// Presumably, the code inside these two methods would look almost identical;
// the only difference would be the part that actually selects a value
// based on a Person.
var names = GetPersonNames(people);
var ages = GetPersonAges(people);
With a delegate acting as placeholder, I free myself from having to write out the same pattern over and over in cases like this.
I agree with the sentiment in the comments above — this can be pretty annoying. We can only hope you give the user the option to turn the music off.
However...
audio { display:none;}
_x000D_
<audio autoplay="true" src="https://upload.wikimedia.org/wikipedia/commons/c/c8/Example.ogg">
_x000D_
The css hides the audio
element, and the autoplay="true"
plays it automatically.
UPDATE totals
SET total = total + 1
WHERE name = 'bill';
If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:
UPDATE totals
SET total = total + 1
WHERE name = 'bill'
AND total = 203;
You need a mechanism which avoids busy-waiting. The old wait/notify
mechanism is fraught with pitfalls so prefer something from the java.util.concurrent
library, for example the CountDownLatch
:
public final CountDownLatch latch = new CountDownLatch(1);
public void run () {
latch.await();
...
}
And at the other side call
yourRunnableObj.latch.countDown();
However, starting a thread to do nothing but wait until it is needed is still not the best way to go. You could also employ an ExecutorService
to which you submit as a task the work which must be done when the condition is met.
Here's a class I wrote do multiple inserts with purge option:
<?php
/**
* $pdo->beginTransaction();
* $pmi = new PDOMultiLineInserter($pdo, "foo", array("a","b","c","e"), 10);
* $pmi->insertRow($data);
* ....
* $pmi->insertRow($data);
* $pmi->purgeRemainingInserts();
* $pdo->commit();
*
*/
class PDOMultiLineInserter {
private $_purgeAtCount;
private $_bigInsertQuery, $_singleInsertQuery;
private $_currentlyInsertingRows = array();
private $_currentlyInsertingCount = 0;
private $_numberOfFields;
private $_error;
private $_insertCount = 0;
function __construct(\PDO $pdo, $tableName, $fieldsAsArray, $bigInsertCount = 100) {
$this->_numberOfFields = count($fieldsAsArray);
$insertIntoPortion = "INSERT INTO `$tableName` (`".implode("`,`", $fieldsAsArray)."`) VALUES";
$questionMarks = " (?".str_repeat(",?", $this->_numberOfFields - 1).")";
$this->_purgeAtCount = $bigInsertCount;
$this->_bigInsertQuery = $pdo->prepare($insertIntoPortion.$questionMarks.str_repeat(", ".$questionMarks, $bigInsertCount - 1));
$this->_singleInsertQuery = $pdo->prepare($insertIntoPortion.$questionMarks);
}
function insertRow($rowData) {
// @todo Compare speed
// $this->_currentlyInsertingRows = array_merge($this->_currentlyInsertingRows, $rowData);
foreach($rowData as $v) array_push($this->_currentlyInsertingRows, $v);
//
if (++$this->_currentlyInsertingCount == $this->_purgeAtCount) {
if ($this->_bigInsertQuery->execute($this->_currentlyInsertingRows) === FALSE) {
$this->_error = "Failed to perform a multi-insert (after {$this->_insertCount} inserts), the following errors occurred:".implode('<br/>', $this->_bigInsertQuery->errorInfo());
return false;
}
$this->_insertCount++;
$this->_currentlyInsertingCount = 0;
$this->_currentlyInsertingRows = array();
}
return true;
}
function purgeRemainingInserts() {
while ($this->_currentlyInsertingCount > 0) {
$singleInsertData = array();
// @todo Compare speed - http://www.evardsson.com/blog/2010/02/05/comparing-php-array_shift-to-array_pop/
// for ($i = 0; $i < $this->_numberOfFields; $i++) $singleInsertData[] = array_pop($this->_currentlyInsertingRows); array_reverse($singleInsertData);
for ($i = 0; $i < $this->_numberOfFields; $i++) array_unshift($singleInsertData, array_pop($this->_currentlyInsertingRows));
if ($this->_singleInsertQuery->execute($singleInsertData) === FALSE) {
$this->_error = "Failed to perform a small-insert (whilst purging the remaining rows; the following errors occurred:".implode('<br/>', $this->_singleInsertQuery->errorInfo());
return false;
}
$this->_currentlyInsertingCount--;
}
}
public function getError() {
return $this->_error;
}
}
Simple change to syntax is all that is needed:
create table ImagenesUsuario (
idImagen int not null identity(1,1) primary key
)
By explicitly using the "constraint" keyword, you can give the primary key constraint a particular name rather than depending on SQL Server to auto-assign a name:
create table ImagenesUsuario (
idImagen int not null identity(1,1) constraint pk_ImagenesUsario primary key
)
Add the "CLUSTERED" keyword if that makes the most sense based on your use of the table (i.e., the balance of searches for a particular idImagen and amount of writing outweighs the benefits of clustering the table by some other index).
Send XML requests with the raw
data type, then set the Content-Type to text/xml
.
After creating a request, use the dropdown to change the request type to POST.
Open the Body tab and check the data type for raw.
Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)
Enter your raw XML data into the input field below
Click Send to submit your XML Request to the specified server.
I had the same problem , and I solved by putting jQuery at the top of all javascript codes I have in my code.
Something like this:
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="js/app.js" type="text/javascript"></script>
<script src="js/form.js" type="text/javascript"></script>
<script src="js/create.js" type="text/javascript"></script>
<script src="js/tween.js" type="text/javascript"></script>
Hope can help some one in future.
It might be late but can help. On the first fragment or activity do declare a class...for example
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
description des = new description();
if (requestCode == PICK_IMAGE_REQUEST && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
constan.photoMap = bitmap;
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static class constan {
public static Bitmap photoMap = null;
public static String namePass = null;
}
Then on the second class/fragment do this..
Bitmap bm = postFragment.constan.photoMap;
final String itemName = postFragment.constan.namePass;
Hope it helps.
Move doSomething
definition outside of its class declaration and after B
and also make add
accessible to A
by public
-ing it or friend
-ing it.
class B;
class A
{
void doSomething(B * b);
};
class B
{
public:
void add() {}
};
void A::doSomething(B * b)
{
b->add();
}
Work 100%. maybe not relation to creator answer but i share it for users have a problem with export mysql query to excel with phpexcel. Good Luck.
require('../phpexcel/PHPExcel.php');
require('../phpexcel/PHPExcel/Writer/Excel5.php');
$filename = 'userReport'; //your file name
$objPHPExcel = new PHPExcel();
/*********************Add column headings START**********************/
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'username')
->setCellValue('B1', 'city_name');
/*********************Add data entries START**********************/
//get_result_array_from_class**You can replace your sql code with this line.
$result = $get_report_clas->get_user_report();
//set variable for count table fields.
$num_row = 1;
foreach ($result as $value) {
$user_name = $value['username'];
$c_code = $value['city_name'];
$num_row++;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$num_row, $user_name )
->setCellValue('B'.$num_row, $c_code );
}
/*********************Autoresize column width depending upon contents START**********************/
foreach(range('A','B') as $columnID) {
$objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
}
$objPHPExcel->getActiveSheet()->getStyle('A1:B1')->getFont()->setBold(true);
//Make heading font bold
/*********************Add color to heading START**********************/
$objPHPExcel->getActiveSheet()
->getStyle('A1:B1')
->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
->getStartColor()
->setARGB('99ff99');
$objPHPExcel->getActiveSheet()->setTitle('userReport'); //give title to sheet
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment;Filename=$filename.xls");
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
First of all, you don't need to "clean up" string
s and int
s - they will be taken care of automatically by the garbage collector. The only thing that needs to be cleaned up in Dispose
are unmanaged resources or managed recources that implement IDisposable
.
However, assuming this is just a learning exercise, the recommended way to implement IDisposable
is to add a "safety catch" to ensure that any resources aren't disposed of twice:
public void Dispose()
{
Dispose(true);
// Use SupressFinalize in case a subclass
// of this type implements a finalizer.
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// Clear all property values that maybe have been set
// when the class was instantiated
id = 0;
name = String.Empty;
pass = String.Empty;
}
// Indicate that the instance has been disposed.
_disposed = true;
}
}
You can use the row_number()
function for this.
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
row_number() over (order by (select NULL))
FROM PM_Ingrediants
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
If you want to start with the maximum already in the table then do:
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
FROM PM_Ingrediants cross join
(select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
Finally, you can just make the sequence
column an auto-incrementing identity column. This saves the need to increment it each time:
create table PM_Ingrediants_Arrangement_Temp ( . . .
sequence int identity(1, 1) -- and might consider making this a primary key too
. . .
)
If you are already using the input file stream class (ifstream
), you could use its function fail()
.
Example:
ifstream myFile;
myFile.open("file.txt");
// Check for errors
if (myFile.fail()) {
cerr << "Error: File could not be found";
exit(1);
}
I've gotten this error because the user trying to login was lacking permissions.
I don't recommend doing this, but I fixed it by granting the user db_owner
globally. It was a local instance, so not a huge security concern.
SQL> DECLARE
2 a integer;
3 b integer;
4 BEGIN
5 a:=&a;
6 b:=&b;
7 dbms_output.put_line('The a value is : ' || a);
8 dbms_output.put_line('The b value is : ' || b);
9 END;
10 /
Simple java8 solution with capturing both outputs and reactive processing using CompletableFuture
:
static CompletableFuture<String> readOutStream(InputStream is) {
return CompletableFuture.supplyAsync(() -> {
try (
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
){
StringBuilder res = new StringBuilder();
String inputLine;
while ((inputLine = br.readLine()) != null) {
res.append(inputLine).append(System.lineSeparator());
}
return res.toString();
} catch (Throwable e) {
throw new RuntimeException("problem with executing program", e);
}
});
}
And the usage:
Process p = Runtime.getRuntime().exec(cmd);
CompletableFuture<String> soutFut = readOutStream(p.getInputStream());
CompletableFuture<String> serrFut = readOutStream(p.getErrorStream());
CompletableFuture<String> resultFut = soutFut.thenCombine(serrFut, (stdout, stderr) -> {
// print to current stderr the stderr of process and return the stdout
System.err.println(stderr);
return stdout;
});
// get stdout once ready, blocking
String result = resultFut.get();
As suggested above the inclusion of
/usr/lib/openmpi/include
in the include path takes care of this (in my case)
Like that
var purchCount = (from purchase in myBlaContext.purchases select purchase).Count();
or even easier
var purchCount = myBlaContext.purchases.Count()
Usually, one would call the reduce
method using Math.max(int, int)
as follows:
reduce(new IntBinaryOperator() {
int applyAsInt(int left, int right) {
return Math.max(left, right);
}
});
That requires a lot of syntax for just calling Math.max
. That's where lambda expressions come into play. Since Java 8 it is allowed to do the same thing in a much shorter way:
reduce((int left, int right) -> Math.max(left, right));
How does this work? The java compiler "detects", that you want to implement a method that accepts two int
s and returns one int
. This is equivalent to the formal parameters of the one and only method of interface IntBinaryOperator
(the parameter of method reduce
you want to call). So the compiler does the rest for you - it just assumes you want to implement IntBinaryOperator
.
But as Math.max(int, int)
itself fulfills the formal requirements of IntBinaryOperator
, it can be used directly. Because Java 7 does not have any syntax that allows a method itself to be passed as an argument (you can only pass method results, but never method references), the ::
syntax was introduced in Java 8 to reference methods:
reduce(Math::max);
Note that this will be interpreted by the compiler, not by the JVM at runtime! Although it produces different bytecodes for all three code snippets, they are semantically equal, so the last two can be considered to be short (and probably more efficient) versions of the IntBinaryOperator
implementation above!
(See also Translation of Lambda Expressions)
Try adding td {word-wrap: break-word;}
to the css and see if it fixes it.
If you trying to get worked hours with some accuracy, try this (tested in SQL Server 2016)
SELECT DATEDIFF(MINUTE,job_start, job_end)/60.00;
Various DATEDIFF functionalities are:
SELECT DATEDIFF(year, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(quarter, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(month, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(dayofyear, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(day, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(week, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(hour, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(minute, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(second, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(millisecond, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
Ref: https://docs.microsoft.com/en-us/sql/t-sql/functions/datediff-transact-sql?view=sql-server-2017
use this expression
var RegExpression = /^[a-zA-Z\s]*$/;
for more refer this http://tools.netshiftmedia.com
The builtin command for properly indenting the code has already been mentioned (gg=G
). If you want to beautify the code, you'll need to use an external application like indent. Since %
denotes the current file in ex mode, you can use it like this:
:!indent %
On Mac Sierra if using Homebrew then do:
sudo ln -s /usr/local/Cellar/[email protected]/5.6.34/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib
There is a good stackoverflow answer here by Mark Rajcok:
AngularJS directive controllers requiring parent directive controllers?
with a link to this very clear jsFiddle: http://jsfiddle.net/mrajcok/StXFK/
<div ng-controller="MyCtrl">
<div screen>
<div component>
<div widget>
<button ng-click="widgetIt()">Woo Hoo</button>
</div>
</div>
</div>
</div>
JavaScript
var myApp = angular.module('myApp',[])
.directive('screen', function() {
return {
scope: true,
controller: function() {
this.doSomethingScreeny = function() {
alert("screeny!");
}
}
}
})
.directive('component', function() {
return {
scope: true,
require: '^screen',
controller: function($scope) {
this.componentFunction = function() {
$scope.screenCtrl.doSomethingScreeny();
}
},
link: function(scope, element, attrs, screenCtrl) {
scope.screenCtrl = screenCtrl
}
}
})
.directive('widget', function() {
return {
scope: true,
require: "^component",
link: function(scope, element, attrs, componentCtrl) {
scope.widgetIt = function() {
componentCtrl.componentFunction();
};
}
}
})
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.name = 'Superhero';
}
For Best solution, Use async/await statement for ecma script 2017
await can use only inside of async function
function sleep(time) {
return new Promise((resolve) => {
setTimeout(resolve, time || 1000);
});
}
await sleep(10000); //this method wait for 10 sec.
Note : async / await not actualy stoped thread like Thread.sleep but simulate it
after I add the property:
<prop key="hibernate.current_session_context_class">thread</prop>
I get the exception like:
org.hibernate.HibernateException: createQuery is not valid without active transaction
org.hibernate.HibernateException: save is not valid without active transaction.
so I think setting that property is not a good solution.
finally I solve "No Hibernate Session bound to thread" problem :
1.<!-- <prop key="hibernate.current_session_context_class">thread</prop> -->
2.add <tx:annotation-driven />
to servlet-context.xml or dispatcher-servlet.xml
3.add @Transactional after @Service and @Repository
Something like:
find /path/ -type f -exec stat \{} --printf="%y\n" \; |
sort -n -r |
head -n 1
Explanation:
User.destroy
User.destroy(1)
will delete user with id == 1
and :before_destroy
and :after_destroy
callbacks occur. For example if you have associated records
has_many :addresses, :dependent => :destroy
After user is destroyed his addresses will be destroyed too. If you use delete action instead, callbacks will not occur.
User.destroy
, User.delete
User.destroy_all(<conditions>)
or User.delete_all(<conditions>)
Notice: User is a class and user is an instance object
You may need to call frame.repaint()
as well to force the frame to actually redraw itself. I've had issues before where I tried to repaint a component and it wasn't updating what was displayed until the parent's repaint() method was called.