yaml.load
Consider the following example YAML. It is well-formed YAML syntax, however it uses (non-standard) curly-brace placeholders with embedded expressions.
The embedded expressions do not produce the desired result in YAML, because they are not part of the native YAML specification. Nevertheless, they are used in this example only to help illustrate what is available with standard YAML and what is not.
part01_customer_info:
cust_fname: "Homer"
cust_lname: "Himpson"
cust_motto: "I love donuts!"
cust_email: [email protected]
part01_government_info:
govt_sales_taxrate: 1.15
part01_purchase_info:
prch_unit_label: "Bacon-Wrapped Fancy Glazed Donut"
prch_unit_price: 3.00
prch_unit_quant: 7
prch_product_cost: "{{prch_unit_price * prch_unit_quant}}"
prch_total_cost: "{{prch_product_cost * govt_sales_taxrate}}"
part02_shipping_info:
cust_fname: "{{cust_fname}}"
cust_lname: "{{cust_lname}}"
ship_city: Houston
ship_state: Hexas
part03_email_info:
cust_email: "{{cust_email}}"
mail_subject: Thanks for your DoughNutz order!
mail_notes: |
We want the mail_greeting to have all the expected values
with filled-in placeholders (and not curly-braces).
mail_greeting: |
Greetings {{cust_fname}} {{cust_lname}}!
We love your motto "{{cust_motto}}" and we agree with you!
Your total purchase price is {{prch_total_cost}}
The substitutions marked in GREEN are readily available in standard YAML, using anchors, aliases, and merge keys.
The substitutions marked in YELLOW are technically available in standard YAML, but not without a custom type declaration, or some other binding mechanism.
The substitutions marked in RED are not available in standard YAML. Yet there are workarounds and alternatives; such as through string formatting or string template engines (such as python's str.format
).
A frequently-requested feature for YAML is the ability to insert arbitrary variable placeholders that support arbitrary cross-references and expressions that relate to the other content in the same (or transcluded) YAML file(s).
YAML supports anchors and aliases, but this feature does not support arbitrary placement of placeholders and expressions anywhere in the YAML text. They only work with YAML nodes.
YAML also supports custom type declarations, however these are less common, and there are security implications if you accept YAML content from potentially untrusted sources.
There are YAML extension libraries, but these are not part of the native YAML spec.
sprintf
or str.format
style functionality from the hosting languageThere are errors here :
var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");
The code must change to:
var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");
By the way, there is another error at line 129 :
var createLi.appendChild(createSubList);
Replace it with:
createLi.appendChild(createSubList);
In website panels like cPanel you may add a single %
(percentage sign) in allowed hostnames to access your MySQL database.
By adding a single %
you can access your database from any IP or website even from desktop applications.
This is in fact the best example ever for Image Zoom and Pan in android,
http://blog.sephiroth.it/2011/04/04/imageview-zoom-and-scroll/
tl;dr
Developer Key = Api Key (any of yours)
find it in Google Console -> Google API -> Credentials
Here is one aditional free Floating Action Button library for Android It has many customizations and requires SDK version 9 and higher
Probably the most elegant way of doing this is to do it in one step. See val()
.
$("#text").val(function(i, val) {
return val.replace('.', ':');
});
compared to:
var val = $("#text").val();
$("#text").val(val.replace('.', ':'));
From the docs:
.val( function(index, value) )
function(index, value)A function returning the value to set.
This method is typically used to set the values of form fields. For
<select multiple="multiple">
elements, multiple s can be selected by passing in an array.The
.val()
method allows us to set the value by passing in a function. As of jQuery 1.4, the function is passed two arguments, the current element's index and its current value:$('input:text.items').val(function(index, value) { return value + ' ' + this.className; });
This example appends the string " items" to the text inputs' values.
This requires jQuery 1.4+.
I think SELECT CAST( CAST([field] AS VARBINARY(120)) AS varchar(120)) for your update
'Error Code: 1046'.
This error shows that the table does not exist may sometimes be caused by having selected a different database and running a query referring to another table. The results indicates 'No database selected Select the default DB to be used by double-clicking its name in the SCHEMAS list in the sidebar'. Will solve the issue and it worked for me very well.
Updating a pull request in GitHub is as easy as committing the wanted changes into existing branch (that was used with pull request), but often it is also wanted to squash the changes into single commit:
git checkout yourbranch
git rebase -i origin/master
# Edit command names accordingly
pick 1fc6c95 My pull request
squash 6b2481b Hack hack - will be discarded
squash dd1475d Also discarded
git push -f origin yourbranch
...and now the pull request contains only one commit.
Related links about rebasing:
I don't know if it's possible to run it just like that.
I usually first copy it with scp and then log in to run it.
scp foo.sh user@host:~
ssh user@host
./foo.sh
To get just a correct number of dimensions in NumPy:
len(a.shape)
In the first case:
import numpy as np
a = np.array([[[1,2,3],[1,2,3]],[[12,3,4],[2,1,3]]])
print("shape = ",np.shape(a))
print("dimensions = ",len(a.shape))
The output will be:
shape = (2, 2, 3)
dimensions = 3
Dictionary<,> is the equivalent. While it doesn't have a Get(...) method, it does have an indexed property called Item which you can access in C# directly using index notation:
class Test {
Dictionary<int,String> entities;
public String getEntity(int code) {
return this.entities[code];
}
}
If you want to use a custom key type then you should consider implementing IEquatable<> and overriding Equals(object) and GetHashCode() unless the default (reference or struct) equality is sufficient for determining equality of keys. You should also make your key type immutable to prevent weird things happening if a key is mutated after it has been inserted into a dictionary (e.g. because the mutation caused its hash code to change).
Both choices refer to what algorithm the identity provider uses to sign the JWT. Signing is a cryptographic operation that generates a "signature" (part of the JWT) that the recipient of the token can validate to ensure that the token has not been tampered with.
RS256 (RSA Signature with SHA-256) is an asymmetric algorithm, and it uses a public/private key pair: the identity provider has a private (secret) key used to generate the signature, and the consumer of the JWT gets a public key to validate the signature. Since the public key, as opposed to the private key, doesn't need to be kept secured, most identity providers make it easily available for consumers to obtain and use (usually through a metadata URL).
HS256 (HMAC with SHA-256), on the other hand, involves a combination of a hashing function and one (secret) key that is shared between the two parties used to generate the hash that will serve as the signature. Since the same key is used both to generate the signature and to validate it, care must be taken to ensure that the key is not compromised.
If you will be developing the application consuming the JWTs, you can safely use HS256, because you will have control on who uses the secret keys. If, on the other hand, you don't have control over the client, or you have no way of securing a secret key, RS256 will be a better fit, since the consumer only needs to know the public (shared) key.
Since the public key is usually made available from metadata endpoints, clients can be programmed to retrieve the public key automatically. If this is the case (as it is with the .Net Core libraries), you will have less work to do on configuration (the libraries will fetch the public key from the server). Symmetric keys, on the other hand, need to be exchanged out of band (ensuring a secure communication channel), and manually updated if there is a signing key rollover.
Auth0 provides metadata endpoints for the OIDC, SAML and WS-Fed protocols, where the public keys can be retrieved. You can see those endpoints under the "Advanced Settings" of a client.
The OIDC metadata endpoint, for example, takes the form of https://{account domain}/.well-known/openid-configuration
. If you browse to that URL, you will see a JSON object with a reference to https://{account domain}/.well-known/jwks.json
, which contains the public key (or keys) of the account.
If you look at the RS256 samples, you will see that you don't need to configure the public key anywhere: it's retrieved automatically by the framework.
This is a great question (+1) and the answers were almost helpful ;) Sorry guys, but I had a heck of a time slogging through this, though both Gonso & AVeryDev gave good hints. Hopefully, this answer will help others.
MyVC
is the view controller holding all this stuff.
MySubview
is the view that we want to load from a xib
MySubView
that is the right size & shape & positioned where you want it.In MyVC.h, have
IBOutlet MySubview *mySubView
// ...
@property (nonatomic, retain) MySubview *mySubview;
In MyVC.m, @synthesize mySubView;
and don't forget to release it in dealloc
.
UIView *view
(may be unnecessary, but worked for me.) Synthesize & release it in .mMySubview
, and link the view property to your view.IBOutlet
's as desiredBack in MyVC.m, have
NSArray *xibviews = [[NSBundle mainBundle] loadNibNamed: @"MySubview" owner: mySubview options: NULL];
MySubview *msView = [xibviews objectAtIndex: 0];
msView.frame = mySubview.frame;
UIView *oldView = mySubview;
// Too simple: [self.view insertSubview: msView aboveSubview: mySubview];
[[mySubview superview] insertSubview: msView aboveSubview: mySubview]; // allows nesting
self.mySubview = msView;
[oldCBView removeFromSuperview];
The tricky bit for me was: the hints in the other answers loaded my view from the xib, but did NOT replace the view in MyVC (duh!) -- I had to swap that out on my own.
Also, to get access to mySubview
's methods, the view
property in the .xib file must be set to MySubview
. Otherwise, it comes back as a plain-old UIView
.
If there's a way to load mySubview
directly from its own xib, that'd rock, but this got me where I needed to be.
Use __cplusplus
as suggested.
Only one note for Microsoft compiler, use Zc:__cplusplus
compiler switch to enable __cplusplus
Source https://devblogs.microsoft.com/cppblog/msvc-now-correctly-reports-__cplusplus/
Another way to use target="_blank"
is:
onclick="this.target='_blank'"
Example:
<a href="http://www.url.com" onclick="this.target='_blank'">Your Text<a>
For me setting autocomplete="off" in form and inputs worked. But can be flake. Some times it will suggest password or some saved login+password option. But don't come pre-filled.
Chrome Version: 81.0.4044.138
<form role="form" method="post" action="#" autocomplete="off">
<label for="login">Login</label><br/>
<input type="text" name="login" id="login" autocomplete="off" />
<br/><br/>
<label for="password">Password</label><br/>
<input type="password" name="password" autocomplete="off" />
<br/><br/>
<input type="submit" name="submit" value="Submit" />
</form>
_x000D_
Others Options:
Usually I have to find another work around every few months...
all examples are good....Here is nice visual illustration... source courtesy : DataFlair training of spark
Map : A map is a transformation operation in Apache Spark. It applies to each element of RDD and it returns the result as new RDD. In the Map, operation developer can define his own custom business logic. The same logic will be applied to all the elements of RDD.
Spark RDD map
function takes one element as input process it according to custom code (specified by the developer) and returns one element at a time. Map transforms an RDD of length N into another RDD of length N. The input and output RDDs will typically have the same number of records.
Example of map
using scala :
val x = spark.sparkContext.parallelize(List("spark", "map", "example", "sample", "example"), 3)
val y = x.map(x => (x, 1))
y.collect
// res0: Array[(String, Int)] =
// Array((spark,1), (map,1), (example,1), (sample,1), (example,1))
// rdd y can be re writen with shorter syntax in scala as
val y = x.map((_, 1))
y.collect
// res1: Array[(String, Int)] =
// Array((spark,1), (map,1), (example,1), (sample,1), (example,1))
// Another example of making tuple with string and it's length
val y = x.map(x => (x, x.length))
y.collect
// res3: Array[(String, Int)] =
// Array((spark,5), (map,3), (example,7), (sample,6), (example,7))
FlatMap :
A flatMap
is a transformation operation. It applies to each element of RDD and it returns the result as new RDD
. It is similar to Map, but FlatMap allows returning 0, 1 or more elements from map function. In the FlatMap operation, a developer can define his own custom business logic. The same logic will be applied to all the elements of the RDD.
What does "flatten the results" mean?
A FlatMap function takes one element as input process it according to custom code (specified by the developer) and returns 0 or more element at a time. flatMap
() transforms an RDD of length N into another RDD of length M.
Example of flatMap
using scala :
val x = spark.sparkContext.parallelize(List("spark flatmap example", "sample example"), 2)
// map operation will return Array of Arrays in following case : check type of res0
val y = x.map(x => x.split(" ")) // split(" ") returns an array of words
y.collect
// res0: Array[Array[String]] =
// Array(Array(spark, flatmap, example), Array(sample, example))
// flatMap operation will return Array of words in following case : Check type of res1
val y = x.flatMap(x => x.split(" "))
y.collect
//res1: Array[String] =
// Array(spark, flatmap, example, sample, example)
// RDD y can be re written with shorter syntax in scala as
val y = x.flatMap(_.split(" "))
y.collect
//res2: Array[String] =
// Array(spark, flatmap, example, sample, example)
you can use the previousSibling
property to iterate back through the siblings until you get back null
and count how many siblings you've encountered:
var i = 0;
while( (child = child.previousSibling) != null )
i++;
//at the end i will contain the index.
Please note that in languages like Java, there is a getPreviousSibling()
function, however in JS this has become a property -- previousSibling
.
I know this is a very old question but I post this solution in case it helps somebody. I recently met this problem and google led me here. The answer here helps me to understand the problem but there are still issues due to my parameter combination. What eventually solves my problem is curl to C# converter. It is a very powerful tool and supports most of the parameters for Curl. The code it generates is almost immediately runnable.
Use the <apply> task.
It executes a command once for each file. Specify the files by means of filesets or any other resource. <apply> is built-in; no additional dependency needed; no custom task implementation needed.
It's also possible to run the command only once, appending all files as arguments in one go. Use the parallel attribute to switch the behaviour.
Sorry for being late a year.
FragmentStatePagerAdapter:
with FragmentStatePagerAdapter
,your unneeded fragment is
destroyed.A transaction is committed to completely remove the
fragment from your activity's FragmentManager
.
The state in FragmentStatePagerAdapter
comes from the fact that it
will save out your fragment's Bundle
from savedInstanceState
when
it is destroyed.When the user navigates back,the new fragment will be
restored using the fragment's state.
FragmentPagerAdapter:
By comparision FragmentPagerAdapter
does nothing of the kind.When
the fragment is no longer needed.FragmentPagerAdapter
calls
detach(Fragment)
on the transaction instead of remove(Fragment)
.
This destroy's the fragment's view but leaves the fragment's instance
alive in the FragmentManager
.so the fragments created in the
FragmentPagerAdapter
are never destroyed.
Remove a space in fileName
ex)
To check on elasticsearch cluster health you need to use
curl localhost:9200/_cat/health
More on the cat APIs here.
I usually use elasticsearch-head plugin to visualize that.
You can find it's github project here.
It's easy to install sudo $ES_HOME/bin/plugin -i mobz/elasticsearch-head
and then you can open localhost:9200/_plugin/head/
in your web brower.
You should have something that looks like this :
I don't know if you fixed it, but I did had the same issue, finally it was a dumb thing, I had:
<script src="jquery-ui/jquery-ui.min.css" rel="stylesheet">
but it should be:
<link href="jquery-ui/jquery-ui.min.css" rel="stylesheet">
Just change <scrip>
to <link>
and src
to href
Change
$array=array_map('intval', explode(',', $string));
To:
$array= implode(',', array_map('intval', explode(',', $string)));
array_map returns an array, not a string. You need to convert the array to a comma separated string in order to use in the WHERE clause.
I just had to solve a similar problem where I added a Sequence number (so that items as grouped by a parent ID, have a Sequence that I can order by (and presumably the user can change the sequence number to change the ordering).
In my case, it's insurance for a Patient, and the user gets to set the order they are assigned, so just going by the primary key isn't useful for long-term, but is useful for setting a default.
The problem with all the other solutions is that certain aggregate functions aren't allowed outside of a SELECT
This SELECT gets you the new Sequence number:
select PatientID,
PatientInsuranceID,
Sequence,
Row_Number() over(partition by PatientID order by PatientInsuranceID) as RowNum
from PatientInsurance
order by PatientID, PatientInsuranceID
This update command, would be simple, but isn't allowed:
update PatientInsurance
set Sequence = Row_Number() over(partition by PatientID order by PatientInsuranceID)
The solution that worked (I just did it), and is similar to eKek0's solution:
UPDATE PatientInsurance
SET PatientInsurance.Sequence = q.RowNum
FROM (select PatientInsuranceID,
Row_Number() over(partition by PatientID order by PatientInsuranceID) as RowNum
from PatientInsurance
) as q
WHERE PatientInsurance.PatientInsuranceID=q.PatientInsuranceID
this lets me select the ID I need to match things up to, and the value I need to set for that ID. Other solutions would have been fine IF I wasn't using Row_Number() which won't work outside of a SELECT.
Given that this is a 1 time operation, it's coding is still simple, and run-speed is fast enough for 4000+ rows
Replace the * with a /
So instead of
COPY * <destination>
use
COPY / <destination>
Based on Ben's answer you you could do the following when running apache on Linux (Debian in my case).
First create the file rewrite-log.load
/etc/apache2/mods-availabe/rewrite-log.load
RewriteLog "/var/log/apache2/rewrite.log"
RewriteLogLevel 3
Then enter
$ a2enmod rewrite-log
followed by
$ service apache2 restart
And when you finished with debuging your rewrite rules
$ a2dismod rewrite-log && service apache2 restart
emanuel.directive('hymn', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
// some ode
},
templateUrl: function(elem,attrs) {
return attrs.templateUrl || 'some/path/default.html'
}
}
});
So you can provide templateUrl via markup
<hymn template-url="contentUrl"><hymn>
Now you just take a care that property contentUrl populates with dynamically generated path.
Just to add to the above answer, anyone finding an issue of the installers taking forever, I found my issue was python, I uninstalled both my versions 3 and versions 2.
The re-ran the command in PowerShell terminal as the admin and it installed almost straight away.
npm install --global --production windows-build-tools
There are a set of available properties to all Maven projects.
From Introduction to the POM:
project.basedir
: The directory that the current project resides in.
This means this points to where your Maven projects resides on your system. It corresponds to the location of the pom.xml
file. If your POM is located inside /path/to/project/pom.xml
then this property will evaluate to /path/to/project
.
Some properties are also inherited from the Super POM, which is the case for project.build.directory
. It is the value inside the <project><build><directory>
element of the POM. You can get a description of all those values by looking at the Maven model. For project.build.directory
, it is:
The directory where all files generated by the build are placed. The default value is
target
.
This is the directory that will hold every generated file by the build.
I store my data this way:
accountsTable ->
key1 -> account1
key2 -> account2
in order to get object data:
accountsDb = mDatabase.child("accountsTable");
accountsDb.child("some key").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
try{
Account account = snapshot.getChildren().iterator().next()
.getValue(Account.class);
} catch (Throwable e) {
MyLogger.error(this, "onCreate eror", e);
}
}
@Override public void onCancelled(DatabaseError error) { }
});
You could also do this
#include <comdef.h>
BSTR bs = SysAllocString("Hello");
std::wstring myString = _bstr_t(bs, false); // will take over ownership, so no need to free
or std::string if you prefer
EDIT: if your original string contains multiple embedded \0 this approach will not work.
Not only can you return a function which you have passed into another function as a variable, you can also use it for calculation inside but defining it outside. See this example:
function calculate(a,b,fn) {
var c = a * 3 + b + fn(a,b);
return c;
}
function sum(a,b) {
return a+b;
}
function product(a,b) {
return a*b;
}
document.write(calculate (10,20,sum)); //80
document.write(calculate (10,20,product)); //250
Simple jQuery solution - find the <a>
element where href="x"
and click it:
$('a[href="#tabs-2"]').click();
You can use the text editing controller to manipulate the value inside a textfield.
var textController = new TextEditingController();
Now, create a new textfield and set textController
as the controller for the textfield as shown below.
new TextField(controller: textController)
Now, create a RaisedButton
anywhere in your code and set the desired text in the onPressed
method of the RaisedButton
.
new RaisedButton(
onPressed: () {
textController.text = "New text";
}
),
Create a Bash (tools.sh) to select a serial from devices (or emulator):
clear;
echo "====================================================================================================";
echo " ADB DEVICES";
echo "====================================================================================================";
echo "";
adb_devices=( $(adb devices | grep -v devices | grep device | cut -f 1)#$(adb devices | grep -v devices | grep device | cut -f 2) );
if [ $((${#adb_devices[@]})) -eq "1" ] && [ "${adb_devices[0]}" == "#" ]
then
echo "No device found";
echo "";
echo "====================================================================================================";
device=""
// Call Main Menu function fxMenu;
else
read -p "$(
f=0
for dev in "${adb_devices[@]}"; do
nm="$(echo ${dev} | cut -f1 -d#)";
tp="$(echo ${dev} | cut -f2 -d#)";
echo " $((++f)). ${nm} [${tp}]";
done
echo "";
echo " 0. Quit"
echo "";
echo "====================================================================================================";
echo "";
echo ' Please select a device: '
)" selection
error="You think it's over just because I am dead. It's not over. The games have just begun.";
// Call Validation Numbers fxValidationNumberMenu ${#adb_devices[@]} ${selection} "${error}"
case "${selection}" in
0)
// Call Main Menu function fxMenu;
*)
device="$(echo ${adb_devices[$((selection-1))]} | cut -f1 -d#)";
// Call Main Menu function fxMenu;
esac
fi
Then in another option can use adb -s
(global option -s use device with given serial number that overrides $ANDROID_SERIAL):
adb -s ${device} <command>
I tested this code on MacOS terminal, but I think it can be used on windows across Git Bash Terminal.
Also remember configure environmental variables and Android SDK paths on .bash_profile
file:
export ANDROID_HOME="/usr/local/opt/android-sdk/"
export PATH="$ANDROID_HOME/platform-tools:$PATH"
export PATH="$ANDROID_HOME/tools:$PATH"
You want the list items to line up next to each other, but not really be inline elements. So float them instead:
ol.widgets li {
float: left;
margin-left: 10px;
}
If you are using the Python wrappers, then (assuming your matrix name is mat):
mat.shape gives you an array of the type- [height, width, channels]
mat.size gives you the size of the array
Sample Code:
import cv2
mat = cv2.imread('sample.png')
height, width, channel = mat.shape[:3]
size = mat.size
from cmd run: SVN List URL you will be provided with 3 options (r)eject, (a)ccept, (p)ermanently. enter p. This resolved issue for me
You can return json in PHP this way:
header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;
SHOW CREATE TABLE yourTable;
or
SHOW COLUMNS FROM yourTable;
You don't need to declare the variable. Ajax success function automatically takes up to 3 parameters: Function( Object data, String textStatus, jqXHR jqXHR )
The Docker command set is simple and holds together well:
docker stack ls
docker service ls
docker image ls
docker container ls
Teaching the aliases first is confusing. Once you understand what's going on, they can save some keystrokes:
docker images -> docker image ls
docker ps -> docker container ls
docker rmi -> docker image rm
docker rm -> docker container rm
There are several aliases in Docker. For instance:
docker rmi
docker image rm
docker image rmi
docker image remove
are all the same command (see for your self using docker help image rm
).
Good news. Starting from the version 3.35 of Maps JavaScript API, that was launched on February 14, 2019, you can use new restriction
option in order to limit the viewport of the map.
According to the documentation
MapRestriction interface
A restriction that can be applied to the Map. The map's viewport will not exceed these restrictions.
source: https://developers.google.com/maps/documentation/javascript/reference/map#MapRestriction
So, now you just add restriction option during a map initialization and that it. Have a look at the following example that limits viewport to Switzerland
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 46.818188, lng: 8.227512},
minZoom: 7,
maxZoom: 14,
zoom: 7,
restriction: {
latLngBounds: {
east: 10.49234,
north: 47.808455,
south: 45.81792,
west: 5.95608
},
strictBounds: true
},
});
}
_x000D_
#map {
height: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
_x000D_
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initMap" async defer></script>
_x000D_
I hope this helps!
Add Serializable()
before the type you expose
Serializable()
Public Class YourType
Put Serializable
into <>
On Linux/Unix (note: Mac OS is a Unix) use top
and press M (Shift+M) to sort processes by memory usage.
On Windows use the Task Manager.
The primary difference is, @Autowired
is a spring annotation. Whereas @Resource
is specified by the JSR-250, as you pointed out yourself. So the latter is part of Java whereas the former is Spring specific.
Hence, you are right in suggesting that, in a sense. I found folks use @Autowired
with @Qualifier
because it is more powerful. Moving from some framework to some other is considered very unlikely, if not myth, especially in the case of Spring.
Thanks to kind and patient help from golang-nuts, recipe is the following:
1) One needs to compile Go compiler for different target platforms and architectures. This is done from src folder in go installation. In my case Go installation is located in /usr/local/go
thus to compile a compiler you need to issue make
utility. Before doing this you need to know some caveats.
There is an issue about CGO library when cross compiling so it is needed to disable CGO library.
Compiling is done by changing location to source dir, since compiling has to be done in that folder
cd /usr/local/go/src
then compile the Go compiler:
sudo GOOS=windows GOARCH=386 CGO_ENABLED=0 ./make.bash --no-clean
You need to repeat this step for each OS and Architecture you wish to cross compile by changing the GOOS and GOARCH parameters.
If you are working in user mode as I do, sudo is needed because Go compiler is in the system dir. Otherwise you need to be logged in as super user. On Mac you may need to enable/configure SU access (it is not available by default), but if you have managed to install Go you possibly already have root access.
2) Once you have all cross compilers built, you can happily cross compile your application by using the following settings for example:
GOOS=windows GOARCH=386 go build -o appname.exe appname.go
GOOS=linux GOARCH=386 CGO_ENABLED=0 go build -o appname.linux appname.go
Change the GOOS and GOARCH to targets you wish to build.
If you encounter problems with CGO include CGO_ENABLED=0 in the command line. Also note that binaries for linux and mac have no extension so you may add extension for the sake of having different files. -o switch instructs Go to make output file similar to old compilers for c/c++ thus above used appname.linux can be any other extension.
If I check with Count() Linq executes a "SELECT COUNT(*).." in the database, but I need to check if the results contains data, I resolved to introducing FirstOrDefault() instead of Count();
Before
var cfop = from tabelaCFOPs in ERPDAOManager.GetTable<TabelaCFOPs>()
if (cfop.Count() > 0)
{
var itemCfop = cfop.First();
//....
}
After
var cfop = from tabelaCFOPs in ERPDAOManager.GetTable<TabelaCFOPs>()
var itemCfop = cfop.FirstOrDefault();
if (itemCfop != null)
{
//....
}
Here is the end-to-end workflow showing the various commands and their associated inputs and outputs. That should clarify the relationship between an image and a container.
+------------+ docker build +--------------+ docker run -dt +-----------+ docker exec -it +------+
| Dockerfile | --------------> | Image | ---------------> | Container | -----------------> | Bash |
+------------+ +--------------+ +-----------+ +------+
^
| docker pull
|
+--------------+
| Registry |
+--------------+
To list the images you could run, execute:
docker image ls
To list the containers you could execute commands on:
docker ps
IN my case i had to send the data backwards from FragmentB->FragmentA hence Intents was not an option as the fragment would already be initialised All though all of the above answers sounds good it takes a lot of boiler plate code to implement, so i went with a much simpler approach of using LocalBroadcastManager, it exactly does the above said but without alll the nasty boilerplate code. An example is shared below.
In Sending Fragment(Fragment B)
public class FragmentB {
private void sendMessage() {
Intent intent = new Intent("custom-event-name");
intent.putExtra("message", "your message");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
And in the Message to be Received Fragment(FRAGMENT A)
public class FragmentA {
@Override
public void onCreate(Bundle savedInstanceState) {
...
// Register receiver
LocalBroadcastManager.getInstance(this).registerReceiver(receiver,
new IntentFilter("custom-event-name"));
}
// This will be called whenever an Intent with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
}
};
}
Hope it helps someone
Quoting API on referencedColumnName:
The name of the column referenced by this foreign key column.
Default (only applies if single join column is being used): The same name as the primary key column of the referenced table.
Where this would be used?
When there is a composite PK in referenced table, then you need to specify column name you are referencing.
They are viewport meta tags, and is most applicable on mobile browsers.
This means, we are telling to the browser “my website adapts to your device width”.
This defines the scale of the website, This parameter sets the initial zoom level, which means 1 CSS pixel is equal to 1 viewport pixel. This parameter help when you're changing orientation, or preventing default zooming. Without this parameter, responsive site won't work.
Maximum-scale defines the maximum zoom. When you access the website, top priority is maximum-scale=1
, and it won’t allow the user to zoom.
Minimum-scale defines the minimum zoom. This works the same as above, but it defines the minimum scale. This is useful, when maximum-scale
is large, and you want to set minimum-scale
.
User-scalable assigned to 1.0 means the website is allowing the user to zoom in or zoom out.
But if you assign it to user-scalable=no
, it means the website is not allowing the user to zoom in or zoom out.
I had similar requirement of running a LAMP stack, Mongo DB and my own services
Docker is OS based virtualisation, which is why it isolates its container around a running process, hence it requires least one process running in FOREGROUND.
So you provide your own startup script as the entry point, thus your startup script becomes an extended Docker image script, in which you can stack any number of the services as far as AT LEAST ONE FOREGROUND SERVICE IS STARTED, WHICH TOO TOWARDS THE END
So my Docker image file has two line below in the very end:
COPY myStartupScript.sh /usr/local/myscripts/myStartupScript.sh
CMD ["/bin/bash", "/usr/local/myscripts/myStartupScript.sh"]
In my script I run all MySQL, MongoDB, Tomcat etc. In the end I run my Apache as a foreground thread.
source /etc/apache2/envvars
/usr/sbin/apache2 -DFOREGROUND
This enables me to start all my services and keep the container alive with the last service started being in the foreground
Hope it helps
UPDATE: Since I last answered this question, new things have come up like Docker compose, which can help you run each service on its own container, yet bind all of them together as dependencies among those services, try knowing more about docker-compose and use it, it is more elegant way unless your need does not match with it.
You have to repeat your expression everywhere you want to use it:
SELECT Replace(Postcode, ' ', '') AS P
FROM Contacts
WHERE Replace(Postcode, ' ', '') LIKE 'NW101%'
or you can make it a subquery
select P
from (
SELECT Replace(Postcode, ' ', '') AS P
FROM Contacts
) t
WHERE P LIKE 'NW101%'
You can use the latest version of the jQuery library by any of the following.
Google Ajax API CDN (also supports SSL via HTTPS)
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2"></script>
/jquery.min.js
Microsoft CDN (also aupports SSL via HTTPS)
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
Ajax CDN Announcement, Microsoft Ajax CDN Documentation
jQuery CDN (via Media Temple)
<script type="text/javascript" src=" http://code.jquery.com/jquery-1.7.2.min.js"></script>
** Minified version
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.js"></script>
** Development (Full) version
Here it is: http://jsfiddle.net/tQyvp/
Here's the code if you don't like going to jsfiddle:
html
<input id="myinputfield" value="This is some text" type="button">?
Javascript:
$('body').on('click', '#myinputfield', function(){
var textField = $('#myinputfield');
textField.val(textField.val()+' after clicking')
});?
find out the lib depends on the support v4, and exclude it.
code in build.gradle
is like this:
androidTestCompile('com.android.support.test.espresso:espresso-contrib:2.2.1') {
// http://stackoverflow.com/a/30931887/5210
exclude group: 'com.android.support', module: 'appcompat'
exclude group: 'com.android.support', module: 'support-v4'
exclude module: 'recyclerview-v7'
}
In my situation, the lib 'espresso' has a jar called support-v4 and in my project 'app' have the same support-v4, exclude the support-v4 when import espresso.
PS: it seems compile project
can not work with the exclude
parseDouble() method is used to initialise a STRING (which should contains some numerical value)....the value it returns is of primitive data type, like int, float, etc.
But valueOf() creates an object of Wrapper class. You have to unwrap it in order to get the double value. It can be compared with a chocolate. The manufacturer wraps the chocolate with some foil or paper to prevent from pollution. The user takes the chocolate, removes and throws the wrapper and eats it.
Observe the following conversion.
int k = 100;
Integer it1 = new Integer(k);
The int data type k is converted into an object, it1 using Integer class. The it1 object can be used in Java programming wherever k is required an object.
The following code can be used to unwrap (getting back int from Integer object) the object it1.
int m = it1.intValue();
System.out.println(m*m); // prints 10000
//intValue() is a method of Integer class that returns an int data type.
You can use pydoc
.
Open your terminal and type python -m pydoc list.append
The advantage of pydoc
over help()
is that you do not have to import a module to look at its help text.
For instance python -m pydoc random.randint
.
Also you can start an HTTP server to interactively browse documentation by typing python -m pydoc -b
(python 3)
For more information python -m pydoc
The accepted answer currently fires twice for animations in Chrome. Presumably this is because it recognizes webkitAnimationEnd
as well as animationEnd
. The following will definitely only fires once:
/* From Modernizr */
function whichTransitionEvent(){
var el = document.createElement('fakeelement');
var transitions = {
'animation':'animationend',
'OAnimation':'oAnimationEnd',
'MSAnimation':'MSAnimationEnd',
'WebkitAnimation':'webkitAnimationEnd'
};
for(var t in transitions){
if( transitions.hasOwnProperty(t) && el.style[t] !== undefined ){
return transitions[t];
}
}
}
$("#elementToListenTo")
.on(whichTransitionEvent(),
function(e){
console.log('Transition complete! This is the callback!');
$(this).off(e);
});
php test.php
should do it, or
php -f test.php
to be explicit.
I'm using flow with vscode but had the same problem. I solved it with these steps:
Install the extension Flow Language Support
Disable the built-in TypeScript extension:
I'd like to do this way :)
const sthError = () => Promise.reject('sth error');
const test = opts => {
return (async () => {
// do sth
await sthError();
return 'ok';
})().catch(err => {
console.error(err); // error will be catched there
});
};
test().then(ret => {
console.log(ret);
});
It's similar to handling error with co
const test = opts => {
return co(function*() {
// do sth
yield sthError();
return 'ok';
}).catch(err => {
console.error(err);
});
};
Yes, Mid
.
Dim sub_str
sub_str = Mid(source_str, 10, 5)
The first parameter is the source string, the second is the start index, and the third is the length.
@bobobobo: Note that VBScript strings are 1-based, not 0-based. Passing 0 as an argument to Mid
results in "invalid procedure call or argument Mid".
For $
Your Ruby version is 2.3.0, but your Gemfile specified 2.4.1.
Changed 2.4.1 in Gemfile to 2.3.0
wouldn't
margin-left:auto;
margin-right:auto;
added to the .image_block
a img do the trick?
Note that that won't work in IE6 (maybe 7 not sure)
there you will have to do on .image_block
the container Div
text-align:center;
position:relative;
could be a problem too.
merge
actually doesn't work like OR
. It's simply intersection (AND
)
I struggled with this problem to combine to ActiveRecord::Relation objects into one and I didn't found any working solution for me.
Instead of searching for right method creating an union from these two sets, I focused on algebra of sets. You can do it in different way using De Morgan's law
ActiveRecord provides merge method (AND) and also you can use not method or none_of (NOT).
search.where.none_of(search.where.not(id: ids_to_exclude).merge(search.where.not("title ILIKE ?", "%#{query}%")))
You have here (A u B)' = A' ^ B'
UPDATE: The solution above is good for more complex cases. In your case smth like that will be enough:
User.where('first_name LIKE ? OR last_name LIKE ?', 'Tobias', 'Fünke')
You can do the following
git cherry-pick --abort
From the git cherry-pick
docs
--abort
Cancel the operation and return to the pre-sequence state.
An AnyCPU assembly will JIT to 64-bit code when loaded into a 64-bit process and 32 bit when loaded into a 32-bit process.
By limiting the CPU you would be saying: There is something being used by the assembly (something likely unmanaged) that requires 32 bits or 64 bits.
Multiline comment in bash
: <<'END_COMMENT'
This is a heredoc (<<) redirected to a NOP command (:).
The single quotes around END_COMMENT are important,
because it disables variable resolving and command resolving
within these lines. Without the single-quotes around END_COMMENT,
the following two $() `` commands would get executed:
$(gibberish command)
`rm -fr mydir`
comment1
comment2
comment3
END_COMMENT
Try this
$file = basename($_SERVER['PATH_INFO']);//Filename requested
_x000D_
There is a wonderful print_r
implementation for JavaScript in php.js library.
Note, you should also add echo
support in the code.
After loading jquery.svg.js
you must load this file: http://keith-wood.name/js/jquery.svgdom.js
.
Source: http://keith-wood.name/svg.html#dom
Working example: http://jsfiddle.net/74RbC/99/
The app can't be run natively, but it could be run on an emulator. You can use ManyMo to embed them in a website and make users add your app to their home screen. This link should be useful for making the app more realistic. Users could then only press the share button and add the app to their home screen. All data will be deleted when the "app" is closed in their iOS devices so you should use the Internet/cloud for storage. It can't access camera or multi touch, but it may be useful.
you can set the environment variable JAVA_TOOL_OPTS like as follows, which will be picked by JVM for any application.
set JAVA_TOOL_OPTS=-Djava.net.preferIPv4Stack=true
You can set this from the command prompt or set in system environment variables, based on your need. Note that this will reflect into all the java applications that run in your machine, even if it's a java interpreter that you have in a private setup.
The easiest way to enumerate a dictionary is
for (NSString *key in tDictionary.keyEnumerator)
{
//do something here;
}
where tDictionary
is the NSDictionary
or NSMutableDictionary
you want to iterate.
For some reason android studio doesn't like calling app icon from drawable folder. So in that case I created mipmap resource directory under res folder.
Right click res folder > new > android resource directory > resource type: mipmap and now drop any icon in there then reference that into manifest file. Sharing this since this method worked for me.
android:icon:@drawable/ic_launcher"
to
android:icon="@mipmap/ic_launcher"
mydict = {'george': 16, 'amber': 19}
print mydict.keys()[mydict.values().index(16)] # Prints george
Or in Python 3.x:
mydict = {'george': 16, 'amber': 19}
print(list(mydict.keys())[list(mydict.values()).index(16)]) # Prints george
Basically, it separates the dictionary's values in a list, finds the position of the value you have, and gets the key at that position.
More about keys()
and .values()
in Python 3: How can I get list of values from dict?
Here is the actual code that does it...
$(document).ready(function()
{
var oTable = $('#myTable').dataTable();
// Sort immediately with column 2 (at position 1 in the array (base 0). More could be sorted with additional array elements
oTable.fnSort( [ [1,'asc'] ] );
// And to sort another column descending (at position 2 in the array (base 0).
oTable.fnSort( [ [2,'desc'] ] );
} );
To not have the column highlighted, modify the CSS like so:
table.dataTable tr.odd td.sorting_1 { background-color: transparent; }
table.dataTable tr.even td.sorting_1 { background-color: transparent; }
Have you considered using the "xcopy" command?
The xcopy command will do all that for you.
This code may help you:
double d = double.Parse(input_value);
string output= d.ToString("F2", CultureInfo.InvariantCulture) + "%";
If you are using MariaDB this will work
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private Long id;
For more, you can check https://thorben-janssen.com/hibernate-tips-use-auto-incremented-column-primary-key/
Have a look at either Left or Substring if you need to chop it up even more.
Google and the MySQL docs are a good place to start - you'll usually not get such a warm response if you've not even tried to help yourself before asking a question.
%s
indicates a conversion type of string when using python's string formatting capabilities. More specifically, %s
converts a specified value to a string using the str()
function. Compare this with the %r
conversion type that uses the repr()
function for value conversion.
Take a look at the docs for string formatting.
You can and should never assume that $_SERVER['HTTP_REFERER']
will be present.
If you control the previous page, you can pass the URL as a parameter "site.com/page2.php?prevUrl=".urlencode("site.com/page1.php")
.
If you don't control the page, then there is nothing you can do.
I prefer an answer from Best way to print the result of a bool as 'false' or 'true' in c?, just like
printf("%s\n", "false\0true"+6*x);
//path to directory to scan
$directory = "../data/team/";
//get all text files with a .txt extension.
$texts = glob($directory . "*.txt");
//print each file name
foreach($texts as $text)
{
echo $text;
}
This is my solution in java 8:
public static Boolean isValidCity(String cityCode) {
return Arrays.stream(CITY_ENUM.values())
.map(CITY_ENUM::getCityCode)
.anyMatch(cityCode::equals);
}
You can redirect the output to /dev/null
. For more info regarding /dev/null read this link.
You can hide the output of a comand in the following ways :
echo -n "Installing nano ......"; yum install nano > /dev/null; echo " done.";
Redirect the standard output to /dev/null
, but not the standard error. This will show the errors occurring during the installation, for example if yum
cannot find a package.
echo -n "Installing nano ......"; yum install nano &> /dev/null; echo " done.";
While this code will not show anything in the terminal since both standard error and standard output are redirected and thus nullified to /dev/null
.
I tried almost all of this. but still couldn't work. Finally I found it was because of 24bitmap problems. If you tried some bitmap which less than 24bit. Most of those above methods should work.
Try this:
<?php
//This function prints a text array as an html list.
function alist ($array) {
$alist = "<ul>";
for ($i = 0; $i < sizeof($array); $i++) {
$alist .= "<li>$array[$i]";
}
$alist .= "</ul>";
return $alist;
}
//Try to get ImageMagick "convert" program version number.
exec("convert -version", $out, $rcode);
//Print the return code: 0 if OK, nonzero if error.
echo "Version return code is $rcode <br>";
//Print the output of "convert -version"
echo alist($out);
?>
I needed something similar, the ability to click on a set of icons to indicate a choice, or a text-based choice and have that update the model (2-way-binding) with the represented value and to also a way to indicate which was selected visually. I created an AngularJS directive for it, since it needed to be flexible enough to handle any HTML element being clicked on to indicate a choice.
<ul ng-repeat="vote in votes" ...>
<li data-choice="selected" data-value="vote.id">...</li>
</ul>
Tests
On the Tests
class we will add an @XmlRootElement
annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData
property differs from the default mapping we will use the @XmlElement
annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted
package forum11221136;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Tests {
TestData testData;
@XmlElement(name="test-data")
public TestData getTestData() {
return testData;
}
public void setTestData(TestData testData) {
this.testData = testData;
}
}
TestData
On this class I used the @XmlType
annotation to specify the order in which the elements should be ordered in. I added a testData
property that appeared to be missing. I also used an @XmlElement
annotation for the same reason as in the Tests
class.
package forum11221136;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
String title;
String book;
String count;
List<TestData> testData;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBook() {
return book;
}
public void setBook(String book) {
this.book = book;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
@XmlElement(name="test-data")
public List<TestData> getTestData() {
return testData;
}
public void setTestData(List<TestData> testData) {
this.testData = testData;
}
}
Demo
Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.
package forum11221136;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Tests.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11221136/input.xml");
Tests tests = (Tests) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(tests, System.out);
}
}
Unless there is an overwhelming need to create a mess of variable names, I would just use a dictionary, where you can dynamically create the key names and associate a value to each.
a = {}
k = 0
while k < 10:
<dynamically create key>
key = ...
<calculate value>
value = ...
a[key] = value
k += 1
There are also some interesting data structures in the new 'collections' module that might be applicable:
copy2(src,dst)
is often more useful than copyfile(src,dst)
because:
dst
to be a directory (instead of the complete target filename), in which case the basename of src
is used for creating the new file;Here is a short example:
import shutil
shutil.copy2('/src/dir/file.ext', '/dst/dir/newname.ext') # complete target filename given
shutil.copy2('/src/file.ext', '/dst/dir') # target filename is /dst/dir/file.ext
If you stored the complete model, not only the weights, in the HDF5 file, then it is as simple as
from keras.models import load_model
model = load_model('model.h5')
If you're brave and willing to roll your own, you could start with a PostScript library and augment it to deal with PDF, taking advantage of Adobe's free online PDF reference.
You could look at using Lattice. In this example I have defined a grid over which I want to plot z~x,y. It looks something like this. Note that most of the code is just building a 3D shape that I plot using the wireframe function.
The variables "b" and "s" could be x or y.
require(lattice)
# begin generating my 3D shape
b <- seq(from=0, to=20,by=0.5)
s <- seq(from=0, to=20,by=0.5)
payoff <- expand.grid(b=b,s=s)
payoff$payoff <- payoff$b - payoff$s
payoff$payoff[payoff$payoff < -1] <- -1
# end generating my 3D shape
wireframe(payoff ~ s * b, payoff, shade = TRUE, aspect = c(1, 1),
light.source = c(10,10,10), main = "Study 1",
scales = list(z.ticks=5,arrows=FALSE, col="black", font=10, tck=0.5),
screen = list(z = 40, x = -75, y = 0))
open D:\xampp\apache\conf\extra\httpd-vhosts.conf
ServerName localhost
DocumentRoot "D:\xampp\htdocs"
SetEnv APPLICATION_ENV "development"
DirectoryIndex index.php
AllowOverride FileInfo
Require all granted
Restart Apache server
and then refresh your given url
In addition to DCookie's answer above, you can also use chr(39) for a single quote.
I find this particularly useful when I have to create a number of insert/update statements based on a large amount of existing data.
Here's a very quick example:
Lets say we have a very simple table, Customers, that has 2 columns, FirstName and LastName. We need to move the data into Customers2, so we need to generate a bunch of INSERT statements.
Select 'INSERT INTO Customers2 (FirstName, LastName) ' ||
'VALUES (' || chr(39) || FirstName || chr(39) ',' ||
chr(39) || LastName || chr(39) || ');' From Customers;
I've found this to be very useful when moving data from one environment to another, or when rebuilding an environment quickly.
if you have numbers in list, you can use map
to apply str
to each element:
print ', '.join(map(str, LIST))
^ map
is C code so it's faster than str(i) for i in LIST
Below is the way we can do Multiple projection to perform Distinct
package org.hibernate.criterion;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.type.Type;
/**
* A count for style : count (distinct (a || b || c))
*/
public class MultipleCountProjection extends AggregateProjection {
private boolean distinct;
protected MultipleCountProjection(String prop) {
super("count", prop);
}
public String toString() {
if(distinct) {
return "distinct " + super.toString();
} else {
return super.toString();
}
}
public Type[] getTypes(Criteria criteria, CriteriaQuery criteriaQuery)
throws HibernateException {
return new Type[] { Hibernate.INTEGER };
}
public String toSqlString(Criteria criteria, int position, CriteriaQuery criteriaQuery)
throws HibernateException {
StringBuffer buf = new StringBuffer();
buf.append("count(");
if (distinct) buf.append("distinct ");
String[] properties = propertyName.split(";");
for (int i = 0; i < properties.length; i++) {
buf.append( criteriaQuery.getColumn(criteria, properties[i]) );
if(i != properties.length - 1)
buf.append(" || ");
}
buf.append(") as y");
buf.append(position);
buf.append('_');
return buf.toString();
}
public MultipleCountProjection setDistinct() {
distinct = true;
return this;
}
}
ExtraProjections.java
package org.hibernate.criterion;
public final class ExtraProjections
{
public static MultipleCountProjection countMultipleDistinct(String propertyNames) {
return new MultipleCountProjection(propertyNames).setDistinct();
}
}
Sample Usage:
String propertyNames = "titleName;titleDescr;titleVersion"
criteria countCriteria = ....
countCriteria.setProjection(ExtraProjections.countMultipleDistinct(propertyNames);
Referenced from https://forum.hibernate.org/viewtopic.php?t=964506
Just a bit from me to very good readers:
#!/bin/bash -e
docker build -t smpp-gateway smpp
(if [ $(docker ps -a | grep smpp-gateway | cut -d " " -f1) ]; then \
echo $(docker rm -f smpp-gateway); \
else \
echo OK; \
fi;);
docker run --restart always -d --network="host" --name smpp-gateway smpp-gateway:latest
docker logs --tail 50 --follow --timestamps smpp-gateway
sudo docker exec -it \
$(sudo docker ps | grep "smpp-gateway:latest" | cut -d " " -f1) \
/bin/bash
You're declaring a virtual
function and not defining it:
virtual void calculateCredits();
Either define it or declare it as:
virtual void calculateCredits() = 0;
Or simply:
virtual void calculateCredits() { };
Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table
The method .transpose() converts columns to rows and rows to column, hence you could even write
df.transpose().ix[3]
Yes, you can do this use this below code it may help you.
.parentDiv{_x000D_
margin : 25px;_x000D_
_x000D_
}_x000D_
.parentDiv span{_x000D_
display : block;_x000D_
padding : 10px;_x000D_
text-align : center;_x000D_
border: 5px solid #000;_x000D_
margin : 5px;_x000D_
}_x000D_
_x000D_
.parentDiv div{_x000D_
padding:30px;_x000D_
border: 10px solid green;_x000D_
display : inline-block;_x000D_
align : cente;_x000D_
}_x000D_
_x000D_
.parentDiv:hover{_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
.parentDiv:hover .childDiv1{_x000D_
border: 10px solid red;_x000D_
}_x000D_
_x000D_
.parentDiv:hover .childDiv2{_x000D_
border: 10px solid yellow;_x000D_
} _x000D_
.parentDiv:hover .childDiv3{_x000D_
border: 10px solid orange;_x000D_
}
_x000D_
<div class="parentDiv">_x000D_
<span>Hover me to change Child Div colors</span>_x000D_
<div class="childDiv1">_x000D_
First Div Child_x000D_
</div>_x000D_
<div class="childDiv2">_x000D_
Second Div Child_x000D_
</div>_x000D_
<div class="childDiv3">_x000D_
Third Div Child_x000D_
</div>_x000D_
<div class="childDiv4">_x000D_
Fourth Div Child_x000D_
</div>_x000D_
</div>
_x000D_
Highlight the cells, format cells, select Custom then select zero.
For store associative arrays you can use serialize
:
$arr = array(
'a' => 1,
'b' => 2,
'c' => 3
);
file_put_contents('stored-array.txt', serialize($arr));
And load using unserialize
:
$arr = unserialize(file_get_contents('stored-array.txt'));
print_r($arr);
But if need creat dinamic .php
files with array (for example config files), you can use var_export(..., true);
, like this:
Save in file:
$arr = array(
'a' => 1,
'b' => 2,
'c' => 3
);
$str = preg_replace('#,(\s+|)\)#', '$1)', var_export($arr, true));
$str = '<?php' . PHP_EOL . 'return ' . $str . ';';
file_put_contents('config.php', $str);
Get array values:
$arr = include 'config.php';
print_r($arr);
The first 2 examples act very differently if you are REPLACING them by something. If you match on this:
str = str.replace(/^(7|8|9)/ig,'');
you would replace 7 or 8 or 9 by the empty string.
If you match on this
str = str.replace(/^[7|8|9]/ig,'');
you will replace 7
or 8
or 9
OR THE VERTICAL BAR!!!! by the empty string.
I just found this out the hard way.
if you have a fixed height footer (for example 712px) you can do this with js like so:
var bgTop = 0;
window.addEventListener("resize",theResize);
function theResize(){
bgTop = winHeight - 712;
document.getElementById("bg").style.marginTop = bgTop+"px";
}
You must place the label after a caption in order to for label
to store the table's number, not the chapter's number.
\begin{table} \begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |} -- cut -- \end{tabular} \caption{My table} \label{table:kysymys} \end{table} Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...
The easiest way to handle this is to install the full package installer with all weblogic add ons from the oracle site. This will install eclipse with all the features/plug ins you need.
Easier alternative to above answers
If Object(Model Class/POJO) contains the date in String datatype.
private void sortArray(ArrayList<myObject> arraylist) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); //your own date format
if (reports != null) {
Collections.sort(arraylist, new Comparator<myObject>() {
@Override
public int compare(myObject o1, myObject o2) {
try {
return simpleDateFormat.parse(o2.getCreated_at()).compareTo(simpleDateFormat.parse(o1.getCreated_at()));
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
});
}
If Object(Model Class/POJO) contains date in Date datatype
private void sortArray(ArrayList<myObject> arrayList) {
if (arrayList != null) {
Collections.sort(arrayList, new Comparator<myObject>() {
@Override
public int compare(myObject o1, myObject o2) {
return o2.getCreated_at().compareTo(o1.getCreated_at()); }
});
} }
The above code is for sorting the array in descending order of date, swap o1 and o2 for ascending order.
this is working for me:
<td>
<div class="avoid">
Cell content.
</div>
</td>
...
<style type="text/css">
.avoid {
page-break-inside: avoid !important;
margin: 4px 0 4px 0; /* to keep the page break from cutting too close to the text in the div */
}
</style>
From this thread: avoid page break inside row of table
You can create a bitmap transfer. try this....
In the first class:
1) Create:
private static Bitmap bitmap_transfer;
2) Create getter and setter
public static Bitmap getBitmap_transfer() {
return bitmap_transfer;
}
public static void setBitmap_transfer(Bitmap bitmap_transfer_param) {
bitmap_transfer = bitmap_transfer_param;
}
3) Set the image:
ImageView image = (ImageView) view.findViewById(R.id.image);
image.buildDrawingCache();
setBitmap_transfer(image.getDrawingCache());
Then, in the second class:
ImageView image2 = (ImageView) view.findViewById(R.id.img2);
imagem2.setImageDrawable(new BitmapDrawable(getResources(), classe1.getBitmap_transfer()));
Make sure your refs for pushing are correct. This tutorial is pretty great, right from the documentation:
http://wiki.eclipse.org/EGit/User_Guide#GitHub_Tutorial
You can clone directly from GitHub, you choose where you clone that repository. And when you import that repository to Eclipse, you choose what refspec to push into upstream.
Click on the Git Repository workspace view, and make sure your remote refs are valid. Make sure you are pointing to the right local branch and pushing to the correct remote branch.
What I don't understand is what's the point of having a byte? Why not say 8 bits?
Apart from the technical point that a byte isn't necessarily 8 bits, the reasons for having a term is simple human nature:
economy of effort (aka laziness) - it is easier to say "byte" rather than "eight bits"
tribalism - groups of people like to use jargon / a private language to set them apart from others.
Just go with the flow. You are not going to change 50+ years of accumulated IT terminology and cultural baggage by complaining about it.
FWIW - the correct term to use when you mean "8 bits independent of the hardware architecture" is "octet".
Pasting the jar files in WebContent\WEB-INF\lib via the file system was the only way it worked for me.
They then appeared under the Deployed Resources and WebContent lib sub-folders.
When I looked, the build path had the jars in the Web App Libraries and everything built and ran fine.
compileSdkVersion : The compileSdkVersion is the version of the API the app is compiled against. This means you can use Android API features included in that version of the API (as well as all previous versions, obviously). If you try and use API 16 features but set compileSdkVersion to 15, you will get a compilation error. If you set compileSdkVersion to 16 you can still run the app on a API 15 device.
minSdkVersion : The min sdk version is the minimum version of the Android operating system required to run your application.
targetSdkVersion : The target sdk version is the version your app is targeted to run on.
The main issue is that the inner query cannot be related to your where
clause on the outer update
statement, because the where filter applies first to the table being updated before the inner subquery even executes. The typical way to handle a situation like this is a multi-table update.
Update
Competition as C
inner join (
select CompetitionId, count(*) as NumberOfTeams
from PicksPoints as p
where UserCompetitionID is not NULL
group by CompetitionID
) as A on C.CompetitionID = A.CompetitionID
set C.NumberOfTeams = A.NumberOfTeams
There's a better way to do this in modern browsers using the vh
and vw
units.
vh is the viewport height.
So you can try something like this:
<style>
canvas {
border: solid 2px purple;
background-color: green;
width: 100%;
height: 80vh;
}
</style>
This will distort the aspect ration.
You can keep the aspect ratio by using the same unit for each. Here's an example with a 2:1 aspect ratio:
<style>
canvas {
width: 40vh;
height: 80vh;
}
</style>
My OS is Yosemite
.
I resolve this issue, by finding configuration paths:
php --ini
Example output:
Configuration File (php.ini) Path: /usr/local/etc/php/5.5
Loaded Configuration File: /usr/local/etc/php/5.5/php.ini
Scan for additional .ini files in: /usr/local/etc/php/5.5/conf.d
Additional .ini files parsed: (none)
Next steps:
Commands:
mv /usr/local/etc/php/5.5/php.ini /usr/local/etc/php/5.5/php.ini.default
ln -s /etc/php.ini /usr/local/etc/php/5.5/php.ini
sudo apachectl restart
Then you can check your php modules via:
php -m
import os, sys, re, glob
pattern = re.compile(r"\<\[\d\>")
replacementStringMatchesPattern = "<[1>"
for infile in glob.glob(os.path.join(os.getcwd(), '*.txt')):
for line in reader:
retline = pattern.sub(replacementStringMatchesPattern, "", line)
sys.stdout.write(retline)
print (retline)
This is the sample code for the email and javascript.
params = getParams();
subject = "ULM Query of: ";
subject += unescape(params["FormsEditField3"]);
content = "Email: ";
content += unescape(params["FormsMultiLine2"]);
content += " Query: ";
content += unescape(params["FormsMultiLine4"]);
var email = "[email protected]";
document.write('<a href="mailto:'+email+'?subject='+subject+'&body='+content+'">SUBMIT QUERY</a>');
In addition to Michael Sorens' answer:
Start-Process PowerShell {[void][System.Console]::ReadKey($true)} -Wait -NoNewWindow
As of Typescript 3.5, the Omit helper will be included: TypeScript 3.5 RC - The Omit Helper Type
You can use it directly, and you should remove your own definition of the Omit helper when updating.
var array = [];
//length array now = 0
array[array.length] = 'hello';
//length array now = 1
// 0
//array = ['hello'];//length = 1
You can simply append the row to the end of the DataFrame, and then adjust the index.
For instance:
df = df.append(pd.DataFrame([[2,3,4]],columns=df.columns),ignore_index=True)
df.index = (df.index + 1) % len(df)
df = df.sort_index()
Or use concat
as:
df = pd.concat([pd.DataFrame([[1,2,3,4,5,6]],columns=df.columns),df],ignore_index=True)
Do C-b
, :show
which will show you all your current settings. /green
, nnn
will find you which properties have been set to green, the default. Do C-b
, :set window-status-bg cyan
and the bottom bar should change colour.
List available colours for tmux
You can tell more easily by the titles and the colours as they're actually set in your live session :show
, than by searching through the man
page, in my opinion. It is a very well-written man
page when you have the time though.
If you don't like one of your changes and you can't remember how it was originally set, you can open do a new tmux session. To change settings for good edit ~/.tmux.conf
with a line like set window-status-bg -g cyan
. Here's mine: https://gist.github.com/9083598
I need to sum the span elements so I edited Akhil Sekharan's answer below.
var arr = document.querySelectorAll('span[id^="score"]');
var total=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].innerHTML))
total+= parseInt(arr[i].innerHTML);
}
console.log(total)
You can change the elements with other elements link will guide you with editing.
Look at the lsof command (list open files) -- it can tell you which processes are holding what open. Sometimes it's tricky but often something as simple as sudo lsof | grep (your device name here)
could do it for you.
I just kept it simple. I created a list of items with the enum values in my ViewModel:
public enum InputsOutputsBoth
{
Inputs,
Outputs,
Both
}
private IList<InputsOutputsBoth> _ioTypes = new List<InputsOutputsBoth>()
{
InputsOutputsBoth.Both,
InputsOutputsBoth.Inputs,
InputsOutputsBoth.Outputs
};
public IEnumerable<InputsOutputsBoth> IoTypes
{
get { return _ioTypes; }
set { }
}
private InputsOutputsBoth _selectedIoType;
public InputsOutputsBoth SelectedIoType
{
get { return _selectedIoType; }
set
{
_selectedIoType = value;
OnPropertyChanged("SelectedIoType");
OnSelectionChanged();
}
}
In my xaml code I just need this:
<ComboBox ItemsSource="{Binding IoTypes}" SelectedItem="{Binding SelectedIoType, Mode=TwoWay}">
You can simply use Apache Commons Lang:
result = ObjectUtils.compare(firstComparable, secondComparable)
i hope this code is work well,try this.
add css file.
.scrollbar {
height: auto;
max-height: 180px;
overflow-x: hidden;
}
HTML code:
<div class="col-sm-2 scrollable-menu" role="menu">
<div>
<ul>
<li><a class="active" href="#home">Tutorials</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
</div>
</div>
The call to InitializeComponent()
(which is usually called in the default constructor of at least Window
and UserControl
) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).
This method locates a URI to the XAML for the Window
/UserControl
that is loading, and passes it to the System.Windows.Application.LoadComponent()
static method. LoadComponent()
loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.
In more detail, LoadComponent
creates an instance of the XamlParser
, and builds a tree of the XAML. Each node is parsed by the XamlParser.ProcessXamlNode()
. This gets passed to the BamlRecordWriter
class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.
Note: Interestingly, the InitializeComponent
is a method on the System.Windows.Markup.IComponentConnector
interface, of which Window
/UserControl
implement in the partial generated class.
Hope this helps!
imageView.setImageBitmap(BitmapFactory.decodeStream(imageUrl.openStream()));//try/catch IOException and MalformedURLException outside
While using replace
seems to solve the problem, I would like to propose an alternative. Problem with mix of numeric and some string values in the column not to have strings replaced with np.nan, but to make whole column proper. I would bet that original column most likely is of an object type
Name: y, dtype: object
What you really need is to make it a numeric column (it will have proper type and would be quite faster), with all non-numeric values replaced by NaN.
Thus, good conversion code would be
pd.to_numeric(df['y'], errors='coerce')
Specify errors='coerce'
to force strings that can't be parsed to a numeric value to become NaN. Column type would be
Name: y, dtype: float64
You should use one way encryption (which is a way to encrypt a value so that is very hard to revers it). I'm not familiar with MySQL, but a quick search shows that it has a password() function that does exactly this kind of encryption. In the DB you will store the encrypted value and when the user wants to authenticate you take the password he provided, you encrypt it using the same algorithm/function and then you check that the value is the same with the password stored in the database for that user. This assumes that the communication between the browser and your server is secure, namely that you use https.
Thanks Guillermo Hernandez, I created a variation of your code that works. I added the namespaces in this code for reference.
System.Reflection.Assembly theAsm = Assembly.LoadFrom("My.dll");
// Get a stream to the embedded resource
System.IO.Stream stream = theAsm.GetManifestResourceStream(@"picture.png");
// Here is the most important part:
System.Windows.Media.Imaging.BitmapImage bmi = new BitmapImage();
bmi.BeginInit();
bmi.StreamSource = stream;
bmi.EndInit();
Not really. GUID is more Microsoft-centric whereas UUID is used more widely (e.g., as in the urn:uuid: URN scheme, and in CORBA).
android.os.NetworkOnMainThreadException
occurs when you try to access network on your main thread (You main activity execution). To avoid this, you must create a separate thread or AsyncTask
or Runnable
implementation to execute your JSON data loading. Since HoneyComb you can not further execute the network task on main thread.
Here is the implementation using AsyncTask
for a network task execution
Wrong quoting: (and missing option closing tag xd)
$out.='<option value="'.$key.'">'.$value["name"].'</option>';
You can also use the toBase64Image() method setting animation: false
var options = {
bezierCurve : false,
animation: false
};
Your issue here is that you've supplied a -webkit-TRANSITION-timing-function
when you want a -webkit-ANIMATION-timing-function
. Your values of 0 to 360 will work properly.
The driver connector is not in your build path. Configure the build path and point it to the 'mysql-connector-java-5.1.25-bin.jar' (check the version which you are using). Alternatively you can use maven :D
Just open the Window(in eclipse IDE) -> click on Reset Perspective. It worked for me.
If you're looking for bin()
as an equivalent to hex()
, it was added in python 2.6.
Example:
>>> bin(10)
'0b1010'
Similar question here.
With Entity Framework there is EntityFramework-Plus (extensions library).
Available on NuGet. Then you can write something like:
// DELETE all users which has been inactive for 2 years
ctx.Users.Where(x => x.LastLoginDate < DateTime.Now.AddYears(-2))
.Delete();
It is also useful for bulk deletes.
Expanding on Adis H's example to include the null case (got bit on this one)
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings["HostName"] != null)
config.AppSettings.Settings["HostName"].Value = hostName;
else
config.AppSettings.Settings.Add("HostName", hostName);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
If --grace-period=0
is not working then you can do:
kubectl delete pods <pod> --grace-period=0 --force
@ModelAttribute
will create a attribute with the name specified by you (@ModelAttribute("Testing") Test test) as Testing
in the given example ,Test being the bean test being the reference to the bean and Testing will be available in model so that you can further use it on jsp pages for retrieval of values that you stored in you ModelAttribute
.
For everyone struggling with this issue, you simply need to upgrade your openssl installation. I'm running windows 10, installed the latest anaconda 64-bit and am getting this error when I try to install/upgrade anything with 'conda' or 'pip'. If I uninstall the 64-bit anaconda and install the 32-bit, it works fine. I had a 64-bit version of openssl for windows installed, version 1.1.0 something. I uninstalled that and installed the latest I could find from here: https://slproweb.com/products/Win32OpenSSL.html -- there is a 64-bit version of 1.1.1 on there that worked. Now I can install packages via pip and conda successfully. Hope this helps.
Docker, basically containers, supports OS virtualization i.e. your application feels that it has a complete instance of an OS whereas VM supports hardware virtualization. You feel like it is a physical machine in which you can boot any OS.
In Docker, the containers running share the host OS kernel, whereas in VMs they have their own OS files. The environment (the OS) in which you develop an application would be same when you deploy it to various serving environments, such as "testing" or "production".
For example, if you develop a web server that runs on port 4000, when you deploy it to your "testing" environment, that port is already used by some other program, so it stops working. In containers there are layers; all the changes you have made to the OS would be saved in one or more layers and those layers would be part of image, so wherever the image goes the dependencies would be present as well.
In the example shown below, the host machine has three VMs. In order to provide the applications in the VMs complete isolation, they each have their own copies of OS files, libraries and application code, along with a full in-memory instance of an OS. Whereas the figure below shows the same scenario with containers. Here, containers simply share the host operating system, including the kernel and libraries, so they don’t need to boot an OS, load libraries or pay a private memory cost for those files. The only incremental space they take is any memory and disk space necessary for the application to run in the container. While the application’s environment feels like a dedicated OS, the application deploys just like it would onto a dedicated host. The containerized application starts in seconds and many more instances of the application can fit onto the machine than in the VM case.
Source: https://azure.microsoft.com/en-us/blog/containers-docker-windows-and-trends/
Dim
and Private
work the same, though the common convention is to use Private
at the module level, and Dim
at the Sub/Function level. Public
and Global
are nearly identical in their function, however Global
can only be used in standard modules, whereas Public
can be used in all contexts (modules, classes, controls, forms etc.) Global
comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public
.
Easiest way which I've found, supports all android versions
Arrays.sort(series1Numbers);
int maxSeries = Integer.parseInt(String.valueOf(series1Numbers[series1Numbers.length-1]));
Have encountered the same issue in my asp.net project, in the end i found the issue is with the target function not static, the issue fixed after I put the keyword static.
[WebMethod]
public static List<string> getRawData()
You use something like
from flask import send_file
@app.route('/get_image')
def get_image():
if request.args.get('type') == '1':
filename = 'ok.gif'
else:
filename = 'error.gif'
return send_file(filename, mimetype='image/gif')
to send back ok.gif
or error.gif
, depending on the type query parameter. See the documentation for the send_file
function and the request
object for more information.
Other answers rightly point out that there is no need to use jQuery in order to navigate to another URL; that's why there's no jQuery function which does so!
If you're asking how to click a link via jQuery then assuming you have markup which looks like:
<a id="my-link" href="/relative/path.html">Click Me!</a>
You could click()
it by executing:
$('#my-link').click();
I used the code below and it worked for me.
String email="";
SqlDataReader reader=cmd.ExecuteReader();
if(reader.Read()){
email=reader["Email"].ToString();
}
String To=email;
I had given permissions I shouldn't have to write in some folders (especially /usr/bin/), and that caused the problem. I fixed it by opening Disk Utility and running 'Repair Disk Permissions' on the Macintosh HD disk.
You can also find dependencies version details in package.json file as following:
I have successfully installed Composer (and Laravel) on my shared hosting with only FTP access:
Download and install PHPShell on a shared hosting
In PHPShell's config.php
add a user and an alias:
php = "php -d suhosin.executor.include.whitelist=phar"
Log in to PHPShell and type: curl -sS https://getcomposer.org/installer | php
When successfully installed, run Composer: php composer.phar
Check out CodingBat! It really helped me learn java way back when (although it used to be JavaBat back then). It's a lot like Codecademy.
This makes sure that redirects work for all combinations of intransparent proxies.
This includes the case client <http> proxy <https> webserver.
# behind proxy
RewriteCond %{HTTP:X-FORWARDED-PROTO} ^http$
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]
# plain
RewriteCond %{HTTP:X-FORWARDED-PROTO} ^$
RewriteCond %{REQUEST_SCHEME} ^http$ [NC,OR]
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]
I got same problem, I tried all above, noting solved my problem. Luckely, I solved the problem this way:
echo $SHELL
Output
/bin/zsh
OR
/bin/bash
If it showing "bash" in output. You have to add env properties in .bashrc file (.bash_profile i did not tried, you can try) or else
It is showing 'zsh' in output. You have to add env properties in .zshrc file, if not exist already you create one no issue.
For C++ strings, there's no reason to use strlen
. Just use string::length
:
std::cout << str.length() << std::endl;
You should strongly prefer this to strlen(str.c_str())
for the following reasons:
Clarity: The length()
(or size()
) member functions unambiguously give back the length of the string. While it's possible to figure out what strlen(str.c_str())
does, it forces the reader to pause for a bit.
Efficiency: length()
and size()
run in time O(1), while strlen(str.c_str())
will take Θ(n) time to find the end of the string.
Style: It's good to prefer the C++ versions of functions to the C versions unless there's a specific reason to do so otherwise. This is why, for example, it's usually considered better to use std::sort
over qsort
or std::lower_bound
over bsearch
, unless some other factors come into play that would affect performance.
The only reason I could think of where strlen
would be useful is if you had a C++-style string that had embedded null characters and you wanted to determine how many characters appeared before the first of them. (That's one way in which strlen
differs from string::length
; the former stops at a null terminator, and the latter counts all the characters in the string). But if that's the case, just use string::find
:
size_t index = str.find(0);
if (index == str::npos) index = str.length();
std::cout << index << std::endl;
Hope this helps!
I know it really late for another answer but I just wanted to share what helped me at the end. It will also load resources/files from the absolute path of the file system (not only the classpath's).
public class ResourceLoader {
public static URL getResource(String resource) {
final List<ClassLoader> classLoaders = new ArrayList<ClassLoader>();
classLoaders.add(Thread.currentThread().getContextClassLoader());
classLoaders.add(ResourceLoader.class.getClassLoader());
for (ClassLoader classLoader : classLoaders) {
final URL url = getResourceWith(classLoader, resource);
if (url != null) {
return url;
}
}
final URL systemResource = ClassLoader.getSystemResource(resource);
if (systemResource != null) {
return systemResource;
} else {
try {
return new File(resource).toURI().toURL();
} catch (MalformedURLException e) {
return null;
}
}
}
private static URL getResourceWith(ClassLoader classLoader, String resource) {
if (classLoader != null) {
return classLoader.getResource(resource);
}
return null;
}
}
This works for me (reference):
# PHP error handling for production servers
# Disable display of startup errors
php_flag display_startup_errors off
# Disable display of all other errors
php_flag display_errors off
# Disable HTML markup of errors
php_flag html_errors off
# Enable logging of errors
php_flag log_errors on
# Disable ignoring of repeat errors
php_flag ignore_repeated_errors off
# Disable ignoring of unique source errors
php_flag ignore_repeated_source off
# Enable logging of PHP memory leaks
php_flag report_memleaks on
# Preserve most recent error via php_errormsg
php_flag track_errors on
# Disable formatting of error reference links
php_value docref_root 0
# Disable formatting of error reference links
php_value docref_ext 0
# Specify path to PHP error log
php_value error_log /home/path/public_html/domain/PHP_errors.log
# Specify recording of all PHP errors
# [see footnote 3] # php_value error_reporting 999999999
php_value error_reporting -1
# Disable max error string length
php_value log_errors_max_len 0
# Protect error log by preventing public access
<Files PHP_errors.log>
Order allow,deny
Deny from all
Satisfy All
</Files>
There is a way of doing this with tags, which allows for multiple defaults.
Assume you have the following struct, with 2 default tags default0 and default1.
type A struct {
I int `default0:"3" default1:"42"`
S string `default0:"Some String..." default1:"Some Other String..."`
}
Now it's possible to Set the defaults.
func main() {
ptr := &A{}
Set(ptr, "default0")
fmt.Printf("ptr.I=%d ptr.S=%s\n", ptr.I, ptr.S)
// ptr.I=3 ptr.S=Some String...
Set(ptr, "default1")
fmt.Printf("ptr.I=%d ptr.S=%s\n", ptr.I, ptr.S)
// ptr.I=42 ptr.S=Some Other String...
}
Here's the complete program in a playground.
If you're interested in a more complex example, say with slices and maps, then, take a look at creasty/defaultse
You're not actually storing the global in a local variable, just creating a local reference to the same object that your original global reference refers to. Remember that pretty much everything in Python is a name referring to an object, and nothing gets copied in usual operation.
If you didn't have to explicitly specify when an identifier was to refer to a predefined global, then you'd presumably have to explicitly specify when an identifier is a new local variable instead (for example, with something like the 'var' command seen in JavaScript). Since local variables are more common than global variables in any serious and non-trivial system, Python's system makes more sense in most cases.
You could have a language which attempted to guess, using a global variable if it existed or creating a local variable if it didn't. However, that would be very error-prone. For example, importing another module could inadvertently introduce a global variable by that name, changing the behaviour of your program.
The .join()
function is using the index
of the passed as argument dataset, so you should use set_index
or use .merge
function instead.
Please find the two examples that should work in your case:
join_df = LS_sgo.join(MSU_pi.set_index('mukey'), on='mukey', how='left')
or
join_df = df_a.merge(df_b, on='mukey', how='left')
using LINQ query expression
IEnumerable<SelectListItem> stores =
from store in database.Stores
where store.CompanyID == curCompany.ID
select new SelectListItem { Value = store.Name, Text = store.ID };
ViewBag.storeSelector = stores;
or using LINQ extension methods with lambda expressions
IEnumerable<SelectListItem> stores = database.Stores
.Where(store => store.CompanyID == curCompany.ID)
.Select(store => new SelectListItem { Value = store.Name, Text = store.ID });
ViewBag.storeSelector = stores;
This is not a perfect solution but it sort of does work.
In the select tag, include the following attributes where 'n' is the number of dropdown rows that would be visible.
<select size="1" position="absolute" onclick="size=(size!=1)?n:1;" ...>
There are three problems with this solution. 1) There is a quick flash of all the elements shown during the first mouse click. 2) The position is set to 'absolute' 3) Even if there are less than 'n' items the dropdown box will still be for the size of 'n' items.
IE and Firefox both contain ways to execute JavaScript from CSS. As Paolo mentions, one way in IE is the expression
technique, but there's also the more obscure HTC behavior, in which a seperate XML that contains your script is loaded via CSS. A similar technique for Firefox exists, using XBL. These techniques don't exectue JavaScript from CSS directly, but the effect is the same.
Use a CSS rule like so:
body {
behavior:url(script.htc);
}
and within that script.htc file have something like:
<PUBLIC:COMPONENT TAGNAME="xss">
<PUBLIC:ATTACH EVENT="ondocumentready" ONEVENT="main()" LITERALCONTENT="false"/>
</PUBLIC:COMPONENT>
<SCRIPT>
function main()
{
alert("HTC script executed.");
}
</SCRIPT>
The HTC file executes the main()
function on the event ondocumentready
(referring to the HTC document's readiness.)
Firefox supports a similar XML-script-executing hack, using XBL.
Use a CSS rule like so:
body {
-moz-binding: url(script.xml#mycode);
}
and within your script.xml:
<?xml version="1.0"?>
<bindings xmlns="http://www.mozilla.org/xbl" xmlns:html="http://www.w3.org/1999/xhtml">
<binding id="mycode">
<implementation>
<constructor>
alert("XBL script executed.");
</constructor>
</implementation>
</binding>
</bindings>
All of the code within the constructor tag will be executed (a good idea to wrap code in a CDATA section.)
In both techniques, the code doesn't execute unless the CSS selector matches an element within the document. By using something like body
, it will execute immediately on page load.
The Python time.strftime
docs say:
When used with the strptime() function, the
%p
directive only affects the output hour field if the%I
directive is used to parse the hour.
Sure enough, changing your %H
to %I
makes it work.
JS does not have a sleep function, it has setTimeout() or setInterval() functions.
If you can move the code that you need to run after the pause into the setTimeout()
callback, you can do something like this:
//code before the pause
setTimeout(function(){
//do what you need here
}, 2000);
see example here : http://jsfiddle.net/9LZQp/
This won't halt the execution of your script, but due to the fact that setTimeout()
is an asynchronous function, this code
console.log("HELLO");
setTimeout(function(){
console.log("THIS IS");
}, 2000);
console.log("DOG");
will print this in the console:
HELLO
DOG
THIS IS
(note that DOG is printed before THIS IS)
You can use the following code to simulate a sleep for short periods of time:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
now, if you want to sleep for 1 second, just use:
sleep(1000);
example: http://jsfiddle.net/HrJku/1/
please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.
Simply speaking, you can think of an abstract class as like an Interface with a bit more capabilities.
You cannot instantiate an Interface, which also holds for an abstract class.
On your interface you can just define the method headers and ALL of the implementers are forced to implement all of them. On an abstract class you can also define your method headers but here - to the difference of the interface - you can also define the body (usually a default implementation) of the method. Moreover when other classes extend (note, not implement and therefore you can also have just one abstract class per child class) your abstract class, they are not forced to implement all of your methods of your abstract class, unless you specified an abstract method (in such case it works like for interfaces, you cannot define the method body).
public abstract class MyAbstractClass{
public abstract void DoSomething();
}
Otherwise for normal methods of an abstract class, the "inheriters" can either just use the default behavior or override it, as usual.
Example:
public abstract class MyAbstractClass{
public int CalculateCost(int amount){
//do some default calculations
//this can be overriden by subclasses if needed
}
//this MUST be implemented by subclasses
public abstract void DoSomething();
}
I usually use this way that works well:
mv fold/file /tmp
git checkout fold/file
Arrays.fill(myArray, 'c');
Although it is quite possible that this is doing the loop in the background and is therefore not any more efficient than what you have (other than the lines of code savings). If you really care about efficiency, try the following in comparison to the above:
int size = 50;
char[] array = new char[size];
for (int i=0; i<size; i++){
array[i] = 'c';
}
Notice that the above doesn't call array.size() for each iteration.
Solution for Windows (Windows 10) is:
Build time: 2020-11-16 17:09:24 UTC Revision: 2972ff02f3210d2ceed2f1ea880f026acfbab5c0
Kotlin: 1.3.72 Groovy: 2.5.12 Ant: Apache Ant(TM) version 1.10.8 compiled on May 10 2020 JVM: 1.8.0_144 (Oracle Corporation 25.144-b01) OS: Windows 10 10.0 x86
C:>
Finally, run [Cordova environments] to check that all is set for development.
C:\Users\opiyog\AndroidStudioProjects\IONIC\SecondApp>cordova requirements
Requirements check results for android: Java JDK: installed 1.8.0 Android SDK: installed true Android target: installed android-30,android-29,android-28,android-27,android-26,android-25,android-24,android-23,android-22,android-21,android-19 Gradle: installed C:\Gradle\gradle-6.7.1\bin\gradle.BAT
Here is a swift 4 sample code which execute API calling using SOAP service format.
func callSOAPWSToGetData() {
let strSOAPMessage =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<CelsiusToFahrenheit xmlns=\"http://www.yourapi.com/webservices/\">" +
"<Celsius>50</Celsius>" +
"</CelsiusToFahrenheit>" +
"</soap:Body>" +
"</soap:Envelope>"
guard let url = URL.init(string: "http://www.example.org") else {
return
}
var request = URLRequest.init(url: url)
let length = (strSOAPMessage as NSString).length
request.addValue("application/soap+xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue("http://www.yourapi.com/webservices/CelsiusToFahrenheit", forHTTPHeaderField: "SOAPAction")
request.addValue(String(length), forHTTPHeaderField: "Content-Length")
request.httpMethod = "POST"
request.httpBody = strSOAPMessage.data(using: .utf8)
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: request) { (data, response, error) in
guard let responseData = data else {
print("Error: did not receive data")
return
}
guard error == nil else {
print("error calling GET on /todos/1")
print(error ?? "")
return
}
print(responseData)
let strData = String.init(data: responseData, encoding: .utf8)
print(strData ?? "")
}
task.resume()
}
Instead of using long command like
php artisan make:model <Model Name> --migration --controller --resource
for make migration, model and controller, you may use even shorter as -mcr.
php artisan make:model <Model Name> -mcr
Please show us more parts of the script and tell us what commands you had to individually execute and want to simply.
Meanwhile you have to use double quotes not single quote to expand variables:
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
Semicolons at the end of a single command are also unnecessary.
So far:
#!/bin/sh
echo "Perform Operation in su mode"
export ARCH=arm
echo "Export ARCH=arm Executed"
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
echo "Export path done"
export CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-' ## What's next to -?
echo "Export CROSS_COMPILE done"
# continue your compilation commands here
...
For su
you can run it with:
su -c 'sh /path/to/script.sh'
Note: The OP was not explicitly asking for steps on how to create export variables in an interactive shell using a shell script. He only asked his script to be assessed at most. He didn't mention details on how his script would be used. It could have been by using .
or source
from the interactive shell. It could have been a standalone scipt, or it could have been source
'd from another script. Environment variables are not specific to interactive shells. This answer solved his problem.
In both Visual Basic 6.0 and VB.NET you would use:
Exit For
to break from For loopWend
to break from While loopExit Do
to break from Do loopdepending on the loop type. See Exit Statements for more details.
vars(obj)
returns the attributes of an object.
I've had a look in date_pipe.ts and it has two bits of info which are of interest. near the top are the following two lines:
// TODO: move to a global configurable location along with other i18n components.
var defaultLocale: string = 'en-US';
Near the bottom is this line:
return DateFormatter.format(value, defaultLocale, pattern);
This suggests to me that the date pipe is currently hard-coded to be 'en-US'.
Please enlighten me if I am wrong.
Just add the <mat-icon>
inside mat-button
or mat-raised-button
. See the example below. Note that I am using material icon instead of your svg for demo purpose:
<button mat-button>
<mat-icon>mic</mat-icon>
Start Recording
</button>
OR
<button mat-raised-button color="accent">
<mat-icon>mic</mat-icon>
Start Recording
</button>
Here is a link to stackblitz demo.
Not sure if you want jQuery.
var form;
form.onsubmit = function (e) {
// stop the regular form submission
e.preventDefault();
// collect the form data while iterating over the inputs
var data = {};
for (var i = 0, ii = form.length; i < ii; ++i) {
var input = form[i];
if (input.name) {
data[input.name] = input.value;
}
}
// construct an HTTP request
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
// send the collected data as JSON
xhr.send(JSON.stringify(data));
xhr.onloadend = function () {
// done
};
};
Nimgoble's is the version I used in 2015. Thought I'd put it here as this question was top of the list in google for "wpf autocomplete textbox"
Install nuget package for project in Visual Studio
Add a reference to the library in the xaml:
xmlns:behaviors="clr-namespace:WPFTextBoxAutoComplete;assembly=WPFTextBoxAutoComplete"
Create a textbox and bind the AutoCompleteBehaviour to List<String>
(TestItems):
<TextBox Text="{Binding TestText, UpdateSourceTrigger=PropertyChanged}"
behaviors:AutoCompleteBehavior.AutoCompleteItemsSource="{Binding TestItems}" />
IMHO this is much easier to get started and manage than the other options listed above.
I can recommend Ninject. It's incredibly fast and easy to use but only if you don't need XML configuration, else you should use Windsor.
Pass a keyword argument name with value as your view name e.g home
or home-view
etc. to url()
function.
url(r'^home$', 'common.views.view1', 'home'),
url(r'^home$', 'common.views.view1', name='home'),
You should read and write data from xml files since you can save a whole object to xml and also you can populate a object from a saved xml. It is better an easy to manipulate objects.
Here is how to do it: Write Object Data to an XML File: https://msdn.microsoft.com/en-us/library/ms172873.aspx Read Object Data from an XML File: https://msdn.microsoft.com/en-us/library/ms172872.aspx
In my case, static fields will not be injected.
If you have several dialogs that could be opened on a page, this will allow any of them to be closed by clicking on the background:
$('body').on('click','.ui-widget-overlay', function() {
$('.ui-dialog').filter(function () {
return $(this).css("display") === "block";
}).find('.ui-dialog-content').dialog('close');
});
(Only works for modal dialogs, as it relies on '.ui-widget-overlay'. And it does close all open dialogs any time the background of one of them is clicked.)
just change the extension to .bmp.
Do this:
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.PNG, 40, bytes);
//you can create a new file name "test.BMP" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.bmp")
It'll sound that I'm just fooling around, but try it once and it'll get saved in BMP
format. Cheers!
At the risk of irritating you;
You're asking the wrong question. You don't need a reason NOT to deviate from the defaults, but the other way around. You need a reason to do so. Timeouts are absolutely essential when running a web server and to disable that setting without a reason is inherently contrary to good practice, even if it's running on a web server that happens to have a timeout directive of its own.
Now, as for the real answer; probably it doesn't matter at all in this particular case, but it's bad practice to go by the setting of a separate system. What if the script is later run on a different server with a different timeout? If you can safely say that it will never happen, fine, but good practice is largely about accounting for seemingly unlikely events and not unnecessarily tying together the settings and functionality of completely different systems. The dismissal of such principles is responsible for a lot of pointless incompatibilities in the software world. Almost every time, they are unforeseen.
What if the web server later is set to run some other runtime environment which only inherits the timeout setting from the web server? Let's say for instance that you later need a 15-year-old CGI program written in C++ by someone who moved to a different continent, that has no idea of any timeout except the web server's. That might result in the timeout needing to be changed and because PHP is pointlessly relying on the web server's timeout instead of its own, that may cause problems for the PHP script. Or the other way around, that you need a lesser web server timeout for some reason, but PHP still needs to have it higher.
It's just not a good idea to tie the PHP functionality to the web server because the web server and PHP are responsible for different roles and should be kept as functionally separate as possible. When the PHP side needs more processing time, it should be a setting in PHP simply because it's relevant to PHP, not necessarily everything else on the web server.
In short, it's just unnecessarily conflating the matter when there is no need to.
Last but not least, 'stillstanding' is right; you should at least rather use set_time_limit()
than ini_set()
.
Hope this wasn't too patronizing and irritating. Like I said, probably it's fine under your specific circumstances, but it's good practice to not assume your circumstances to be the One True Circumstance. That's all. :)