The below code solved my problem :
request.ProtocolVersion = HttpVersion.Version10; // THIS DOES THE TRICK
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
Erik's answer doesn't work on Windows Phone as is. The following does:
class WebClientEx : WebClient
{
private WebResponse m_Resp = null;
protected override WebResponse GetWebResponse(WebRequest Req, IAsyncResult ar)
{
try
{
this.m_Resp = base.GetWebResponse(request);
}
catch (WebException ex)
{
if (this.m_Resp == null)
this.m_Resp = ex.Response;
}
return this.m_Resp;
}
public HttpStatusCode StatusCode
{
get
{
if (m_Resp != null && m_Resp is HttpWebResponse)
return (m_Resp as HttpWebResponse).StatusCode;
else
return HttpStatusCode.OK;
}
}
}
At least it does when using OpenReadAsync
; for other xxxAsync
methods, careful testing would be highly recommended. The framework calls GetWebResponse somewhere along the code path; all one needs to do is capture and cache the response object.
The fallback code is 200 in this snippet because genuine HTTP errors - 500, 404, etc - are reported as exceptions anyway. The purpose of this trick is to capture non-error codes, in my specific case 304 (Not modified). So the fallback assumes that if the status code is somehow unavailable, at least it's a non-erroneous one.
At one time, I remember seeing the MSDN library state to use CStr() because it was faster. I do not know if this is true though.
AngularJS Developer Guide - CSS classes used by AngularJS
- @property {boolean} $untouched True if control has not lost focus yet.
- @property {boolean} $touched True if control has lost focus.
- @property {boolean} $pristine True if user has not interacted with the control yet.
- @property {boolean} $dirty True if user has already interacted with the control.
You can use Path.GetFileNameWithoutExtension
:
foreach (FileInfo fi in smFiles)
{
builder.Append(Path.GetFileNameWithoutExtension(fi.Name));
builder.Append(", ");
}
Although I am surprised there isn't a way to get this directly from the FileInfo
(or at least I can't see it).
select type, craft, sum(NVL(regular, 0) + NVL(overtime, 0)) as total_hours
from hours_t
group by type, craft
order by type, craft
FragmentPagerAdapter
stores the previous data which is fetched from the adapter while FragmentStatePagerAdapter
takes the new value from the adapter everytime it is executed.
In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size
like this:
#include <vector>
int main () {
std::vector<int> v;
auto size = v.size();
}
Your third call
int size = v.size();
triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.
int size = static_cast<int>(v.size());
would always compile cleanly and also explicitly states that your conversion from std::vector::size_type
to int
was intended.
Note that if the size of the vector
is greater than the biggest number an int
can represent, size
will contain an implementation defined (de facto garbage) value.
You can make a simple hashMap yourself. What a hashMap does is storing items in a array using the hash as index/key. Hash-functions give collisions once in a while (not often, but they may do), so you have to store multiple items for an entry in the hashMap. That simple is a hashMap:
class IEqualityComparer {
public function equals($x, $y) {
throw new Exception("Not implemented!");
}
public function getHashCode($obj) {
throw new Exception("Not implemented!");
}
}
class HashMap {
private $map = array();
private $comparer;
public function __construct(IEqualityComparer $keyComparer) {
$this->comparer = $keyComparer;
}
public function has($key) {
$hash = $this->comparer->getHashCode($key);
if (!isset($this->map[$hash])) {
return false;
}
foreach ($this->map[$hash] as $item) {
if ($this->comparer->equals($item['key'], $key)) {
return true;
}
}
return false;
}
public function get($key) {
$hash = $this->comparer->getHashCode($key);
if (!isset($this->map[$hash])) {
return false;
}
foreach ($this->map[$hash] as $item) {
if ($this->comparer->equals($item['key'], $key)) {
return $item['value'];
}
}
return false;
}
public function del($key) {
$hash = $this->comparer->getHashCode($key);
if (!isset($this->map[$hash])) {
return false;
}
foreach ($this->map[$hash] as $index => $item) {
if ($this->comparer->equals($item['key'], $key)) {
unset($this->map[$hash][$index]);
if (count($this->map[$hash]) == 0)
unset($this->map[$hash]);
return true;
}
}
return false;
}
public function put($key, $value) {
$hash = $this->comparer->getHashCode($key);
if (!isset($this->map[$hash])) {
$this->map[$hash] = array();
}
$newItem = array('key' => $key, 'value' => $value);
foreach ($this->map[$hash] as $index => $item) {
if ($this->comparer->equals($item['key'], $key)) {
$this->map[$hash][$index] = $newItem;
return;
}
}
$this->map[$hash][] = $newItem;
}
}
For it to function you also need a hash-function for your key and a comparer for equality (if you only have a few items or for another reason don't need speed you can let the hash-function return 0; all items will be put in same bucket and you will get O(N) complexity)
Here is an example:
class IntArrayComparer extends IEqualityComparer {
public function equals($x, $y) {
if (count($x) !== count($y))
return false;
foreach ($x as $key => $value) {
if (!isset($y[$key]) || $y[$key] !== $value)
return false;
}
return true;
}
public function getHashCode($obj) {
$hash = 0;
foreach ($obj as $key => $value)
$hash ^= $key ^ $value;
return $hash;
}
}
$hashmap = new HashMap(new IntArrayComparer());
for ($i = 0; $i < 10; $i++) {
for ($j = 0; $j < 10; $j++) {
$hashmap->put(array($i, $j), $i * 10 + $j);
}
}
echo $hashmap->get(array(3, 7)) . "<br/>";
echo $hashmap->get(array(5, 1)) . "<br/>";
echo ($hashmap->has(array(8, 4))? 'true': 'false') . "<br/>";
echo ($hashmap->has(array(-1, 9))? 'true': 'false') . "<br/>";
echo ($hashmap->has(array(6))? 'true': 'false') . "<br/>";
echo ($hashmap->has(array(1, 2, 3))? 'true': 'false') . "<br/>";
$hashmap->del(array(8, 4));
echo ($hashmap->has(array(8, 4))? 'true': 'false') . "<br/>";
Which gives as output:
37
51
true
false
false
false
false
localStorage.username = 'blah'
If you're guaranteed to be on a modern browser. Though know your values will all be turned into strings.
Also has the handy benefit of being cached between reloads.
I prefer using Symfony for this. Their libraries are pretty nice.
Use the The DomCrawler Component
Example:
$browser = new HttpBrowser(HttpClient::create());
$crawler = $browser->request('GET', 'example.com');
$class = $crawler->filter('.class')->first();
use your code within
<script type="text/javascript">
function window.onload()
{
var d = new Date()
var gmtOffSet = -d.getTimezoneOffset();
var gmtHours = Math.floor(gmtOffSet / 60);
var GMTMin = Math.abs(gmtOffSet % 60);
var dot = ".";
var retVal = "" + gmtHours + dot + GMTMin;
document.getElementById('<%= offSet.ClientID%>').value = retVal;
}
</script>
This indicates you are trying to put something too big into a column. For example, you have a VARCHAR2(10) column and you are putting in 11 characters. Same thing with number.
This is happening at line 176 of package UMAIN. You would need to go and have a look at that to see what it is up to. Hopefully you can look it up in your source control (or from user_source). Later versions of Oracle report this error better, telling you which column and what value.
Simply from command prompt or Linux environment run the following command.
python -c 'import torch; print(torch.cuda.is_available())'
The above should print True
python -c 'import torch; print(torch.rand(2,3).cuda())'
This one should print the following:
tensor([[0.7997, 0.6170, 0.7042], [0.4174, 0.1494, 0.0516]], device='cuda:0')
Most of the other methods listed here are Rails specific. If you want do do this with pure Ruby, the following is the most concise way I've come up with (thanks to @ulysse-bn for the suggested improvement)
x="this_should_be_camel_case"
x.gsub(/(?:_|^)(\w)/){$1.upcase}
#=> "ThisShouldBeCamelCase"
Let's suppose you want to find all int
not preceded by unsigned
:
With support for negative look-behind:
(?<!unsigned )int
Without support for negative look-behind:
((?!unsigned ).{9}|^.{0,8})int
Basically idea is to grab n preceding characters and exclude match with negative look-ahead, but also match the cases where there's no preceeding n characters. (where n is length of look-behind).
So the regex in question:
(?<!filename)\.js$
would translate to:
((?!filename).{8}|^.{0,7})\.js$
You might need to play with capturing groups to find exact spot of the string that interests you or you want't to replace specific part with something else.
A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.
Consider the following code:
void Foo(int i, float f)
{
// Do things
}
void Bar()
{
int anInt = 1;
Foo(anInt, 2.0);
}
Here i
and f
are the parameters, and anInt
and 2.0
are the arguments.
Here is the Answer
CSS
#outer
{
width:100%;
text-align: center;
}
.inner
{
display: inline-block;
}
HTML
<div id="outer">
<div class="inner"><button type="submit" class="msgBtn" onClick="return false;" >Save</button></div>
<div class="inner"><button type="submit" class="msgBtn2" onClick="return false;">Publish</button></div>
<div class="inner"><button class="msgBtnBack">Back</button></div>
</div>
as simple and easy as :
that's done
This can be done with MySQL, although it's highly unintuitive:
CREATE PROCEDURE p25 (OUT return_val INT)
BEGIN
DECLARE a,b INT;
DECLARE cur_1 CURSOR FOR SELECT s1 FROM t;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET b = 1;
OPEN cur_1;
REPEAT
FETCH cur_1 INTO a;
UNTIL b = 1
END REPEAT;
CLOSE cur_1;
SET return_val = a;
END;//
Check out this guide: mysql-storedprocedures.pdf
I tried to get this working using FINDSTR, but for some reason my "debugging" command always output an error level of 0:
ECHO %ERRORLEVEL%
My workaround is to use Grep from Cygwin, which outputs the right errorlevel (it will give an errorlevel greater than 0) if a string is not found:
dir c:\*.tib >out 2>>&1
grep "1 File(s)" out
IF %ERRORLEVEL% NEQ 0 "Run other commands" ELSE "Run Errorlevel 0 commands"
Cygwin's grep will also output errorlevel 2 if the file is not found. Here's the hash from my version:
C:\temp\temp>grep --version grep (GNU grep) 2.4.2
C:\cygwin64\bin>md5sum grep.exe c0a50e9c731955628ab66235d10cea23 *grep.exe
C:\cygwin64\bin>sha1sum grep.exe ff43a335bbec71cfe99ce8d5cb4e7c1ecdb3db5c *grep.exe
Very simple example and it always works.
/**
* Setup stretch and scrollable TabLayout.
* The TabLayout initial parameters in layout must be:
* android:layout_width="wrap_content"
* app:tabMaxWidth="0dp"
* app:tabGravity="fill"
* app:tabMode="fixed"
*
* @param context your Context
* @param tabLayout your TabLayout
*/
public static void setupStretchTabLayout(Context context, TabLayout tabLayout) {
tabLayout.post(() -> {
ViewGroup.LayoutParams params = tabLayout.getLayoutParams();
if (params.width == ViewGroup.LayoutParams.MATCH_PARENT) { // is already set up for stretch
return;
}
int deviceWidth = context.getResources()
.getDisplayMetrics().widthPixels;
if (tabLayout.getWidth() < deviceWidth) {
tabLayout.setTabMode(TabLayout.MODE_FIXED);
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
} else {
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
params.width = ViewGroup.LayoutParams.WRAP_CONTENT;
}
tabLayout.setLayoutParams(params);
});
}
.search-table-outter {border:2px solid red; overflow-x:scroll;}
.search-table{table-layout: fixed; margin:40px auto 0px auto; }
.search-table, td, th{border-collapse:collapse; border:1px solid #777;}
th{padding:20px 7px; font-size:15px; color:#444; background:#66C2E0;}
td{padding:5px 10px; height:35px;}
You should provide scroll in div.
I defined a generic Pair class that I use all the time. It's great. As a bonus, by defining a static factory method (Pair.create) I only have to write the type arguments half as often.
public class Pair<A, B> {
private A component1;
private B component2;
public Pair() {
super();
}
public Pair(A component1, B component2) {
this.component1 = component1;
this.component2 = component2;
}
public A fst() {
return component1;
}
public void setComponent1(A component1) {
this.component1 = component1;
}
public B snd() {
return component2;
}
public void setComponent2(B component2) {
this.component2 = component2;
}
@Override
public String toString() {
return "<" + component1 + "," + component2 + ">";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((component1 == null) ? 0 : component1.hashCode());
result = prime * result
+ ((component2 == null) ? 0 : component2.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Pair<?, ?> other = (Pair<?, ?>) obj;
if (component1 == null) {
if (other.component1 != null)
return false;
} else if (!component1.equals(other.component1))
return false;
if (component2 == null) {
if (other.component2 != null)
return false;
} else if (!component2.equals(other.component2))
return false;
return true;
}
public static <A, B> Pair<A, B> create(A component1, B component2) {
return new Pair<A, B>(component1, component2);
}
}
I think ImageFont module available in PIL
should be helpful in solving text font size problem. Just check what font type and size is appropriate for you and use following function to change font values.
# font = ImageFont.truetype(<font-file>, <font-size>)
# font-file should be present in provided path.
font = ImageFont.truetype("sans-serif.ttf", 16)
So your code will look something similar to:
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
img = Image.open("sample_in.jpg")
draw = ImageDraw.Draw(img)
# font = ImageFont.truetype(<font-file>, <font-size>)
font = ImageFont.truetype("sans-serif.ttf", 16)
# draw.text((x, y),"Sample Text",(r,g,b))
draw.text((0, 0),"Sample Text",(255,255,255),font=font)
img.save('sample-out.jpg')
You might need to put some extra effort to calculate font size. In case you want to change it based on amount of text user has provided in TextArea
.
To add text wrapping (Multiline thing) just take a rough idea of how many characters can come in one line, Then you can probably write a pre-pprocessing function for your Text, Which basically finds the character which will be last in each line and converts white space before this character to new-line.
This is the most succinct solution I can come up with:
var a = {};
conditionB && a.b = 5;
conditionC && a.c = 5;
conditionD && a.d = 5;
// ...
public class LogicconvertmillistotimeActivity extends Activity {
/** Called when the activity is first created. */
EditText millisedit;
Button millisbutton;
TextView millistextview;
long millislong;
String millisstring;
int millisec=0,sec=0,min=0,hour=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
millisedit=(EditText)findViewById(R.id.editText1);
millisbutton=(Button)findViewById(R.id.button1);
millistextview=(TextView)findViewById(R.id.textView1);
millisbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
millisbutton.setClickable(false);
millisec=0;
sec=0;
min=0;
hour=0;
millisstring=millisedit.getText().toString().trim();
millislong= Long.parseLong(millisstring);
Calendar cal = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
if(millislong>1000){
sec=(int) (millislong/1000);
millisec=(int)millislong%1000;
if(sec>=60){
min=sec/60;
sec=sec%60;
}
if(min>=60){
hour=min/60;
min=min%60;
}
}
else
{
millisec=(int)millislong;
}
cal.clear();
cal.set(Calendar.HOUR_OF_DAY,hour);
cal.set(Calendar.MINUTE,min);
cal.set(Calendar.SECOND, sec);
cal.set(Calendar.MILLISECOND,millisec);
String DateFormat = formatter.format(cal.getTime());
// DateFormat = "";
millistextview.setText(DateFormat);
}
});
}
}
If you're running on a macOS it's just easier to first check go to 'System Preferences' and see if MySQL is running or not.
You can use strcmp()
if you wish to order/compare strings lexicographically. If you just wish to check for equality then ==
is just fine.
Knibb High football rules!
This should be relatively fast and accurate but I admit I didn't put it through a thorough test, just a few.
It avoids expensive exceptions, regex, and also avoids looping through a character set, instead using ascii ranges for validation.
public static bool IsBase64String(string s)
{
s = s.Trim();
int mod4 = s.Length % 4;
if(mod4!=0){
return false;
}
int i=0;
bool checkPadding = false;
int paddingCount = 1;//only applies when the first is encountered.
for(i=0;i<s.Length;i++){
char c = s[i];
if (checkPadding)
{
if (c != '=')
{
return false;
}
paddingCount++;
if (paddingCount > 3)
{
return false;
}
continue;
}
if(c>='A' && c<='z' || c>='0' && c<='9'){
continue;
}
switch(c){
case '+':
case '/':
continue;
case '=':
checkPadding = true;
continue;
}
return false;
}
//if here
//, length was correct
//, there were no invalid characters
//, padding was correct
return true;
}
I encountered the same problem!
ps --no-headers -o comm 1
After running this in the terminal, the system will return either systemd or init
if it returns 'init', then the 'systemctl' command won't work for your system
You can use substring()
to do this.
But there are two different cases:
Case 1
If the String
you are capitalizing is meant to be human-readable, you should also specify the default locale:
String firstLetterCapitalized =
myString.substring(0, 1).toUpperCase(Locale.getDefault()) + myString.substring(1);
Case 2
If the String
you are capitalizing is meant to be machine-readable, avoid using Locale.getDefault()
because the string that is returned will be inconsistent across different regions, and in this case always specify the same locale (for example, toUpperCase(Locale.ENGLISH)
). This will ensure that the strings you are using for internal processing are consistent, which will help you avoid difficult-to-find bugs.
Note: You do not have to specify Locale.getDefault()
for toLowerCase()
, as this is done automatically.
Stack Smashing here is actually caused due to a protection mechanism used by gcc to detect buffer overflow errors. For example in the following snippet:
#include <stdio.h>
void func()
{
char array[10];
gets(array);
}
int main(int argc, char **argv)
{
func();
}
The compiler, (in this case gcc) adds protection variables (called canaries) which have known values. An input string of size greater than 10 causes corruption of this variable resulting in SIGABRT to terminate the program.
To get some insight, you can try disabling this protection of gcc using option -fno-stack-protector
while compiling. In that case you will get a different error, most likely a segmentation fault as you are trying to access an illegal memory location. Note that -fstack-protector
should always be turned on for release builds as it is a security feature.
You can get some information about the point of overflow by running the program with a debugger. Valgrind doesn't work well with stack-related errors, but like a debugger, it may help you pin-point the location and reason for the crash.
As of version 11.2.0
Firebase and Google Play services dependencies are available via Google's Maven Repo. You no longer need to use the Android SDK manager to import these dependencies.
In your root build.gradle
file add the repo:
allprojects {
repositories {
// ...
maven { url "https://maven.google.com" }
}
}
If you are using gradle 4.0
or higher you can replace maven { url "https://maven.google.com" }
with just google()
.
The 9.0.0
version of Firebase was built using Google Play services 9.0 and is now available under the new packaging com.google.firebase:*
See Release Notes for Google Play services 9.0 https://developers.google.com/android/guides/releases#may_2016_-_v90
New versions of packages Google Play Services (rev 30) and Google Repository (rev 26) were just released in the SDK manager so it's likely you just need to update.
Tools
> Android
> SDK Manager
.SDK Tools
tab.Google Play Services
(rev 30) and Google Repository
(rev 26). See the image below.Sync
and Build
your project.As of April 2017, the latest versions of Google Play Services and Repository are listed below.
Tools
> Android
> SDK Manager
.Packages
panel, Look for the Extras
.Google Play Services
(rev 39) and Google Repository
(rev 46). See the image below.Perform a gradle project sync
and Build
your project. It's probably worth mentioning that for http/https some people proxy their browser traffic through Burp/ZAP or another intercepting "attack proxy". A thread that covers options for this on Android devices can be found here: https://android.stackexchange.com/questions/32366/which-browser-does-support-proxies
Here is the implementation of custom filter, which will filter the data using array of values.It will support multiple key object with both array and single value of keys. As mentioned inangularJS API AngularJS filter Doc supports multiple key filter with single value, but below custom filter will support same feature as angularJS and also supports array of values and combination of both array and single value of keys.Please find the code snippet below,
myApp.filter('filterMultiple',['$filter',function ($filter) {
return function (items, keyObj) {
var filterObj = {
data:items,
filteredData:[],
applyFilter : function(obj,key){
var fData = [];
if (this.filteredData.length == 0)
this.filteredData = this.data;
if (obj){
var fObj = {};
if (!angular.isArray(obj)){
fObj[key] = obj;
fData = fData.concat($filter('filter')(this.filteredData,fObj));
} else if (angular.isArray(obj)){
if (obj.length > 0){
for (var i=0;i<obj.length;i++){
if (angular.isDefined(obj[i])){
fObj[key] = obj[i];
fData = fData.concat($filter('filter')(this.filteredData,fObj));
}
}
}
}
if (fData.length > 0){
this.filteredData = fData;
}
}
}
};
if (keyObj){
angular.forEach(keyObj,function(obj,key){
filterObj.applyFilter(obj,key);
});
}
return filterObj.filteredData;
}
}]);
Usage:
arrayOfObjectswithKeys | filterMultiple:{key1:['value1','value2','value3',...etc],key2:'value4',key3:[value5,value6,...etc]}
Here is a fiddle example with implementation of above "filterMutiple" custom filter. :::Fiddle Example:::
Pattern p = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher("I am a string");
boolean b = m.find();
if (b)
System.out.println("There is a special character in my string");
This has happened to me multiple times. I have used Amazon Linux AMI 2013.09.2 and Ubuntu Server 12.04.3 LTS which are both on the free tier.
Every time I have launched an instance I have permission denied show up. I haven't verified this but my theory is that the server is not completely set up before I try to ssh into it. After a few tries with permission denied, I wait a few minutes and then I am able to connect. If you are having this problem I suggest waiting five minutes and trying again.
--First create one function
CREATE FUNCTION [dbo].[GetNumericonly]
(@strAlphaNumeric VARCHAR(256))
RETURNS VARCHAR(256)
AS
BEGIN
DECLARE @intAlpha INT
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)
BEGIN
WHILE @intAlpha > 0
BEGIN
SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )
SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )
END
END
RETURN ISNULL(@strAlphaNumeric,0)
END
Now call this function like
select [dbo].[GetNumericonly]('Abhi12shek23jaiswal')
Its result like
1223
First of all insert field in your code:
<input id="reloadValue" type="hidden" name="reloadValue" value="" />
then run jQuery:
<script type="text/javascript">
jQuery(document).ready(function()
{
var d = new Date();
d = d.getTime();
if (jQuery('#reloadValue').val().length === 0)
{
jQuery('#reloadValue').val(d);
jQuery('body').show();
}
else
{
jQuery('#reloadValue').val('');
location.reload();
}
});
You could try using this tool which automatically removes the Team Foundation Bindings from a project. http://www.softpedia.com/get/Programming/Other-Programming-Files/Team-Foundation-Binding-Remover.shtml
you can also use $sce.trustAsHtml('"<h1>" + str + "</h1>"')
,if you want to know more detail, please refer to $sce
As DPA says, the easiest way to generate a war file of your project is through the IDE. Open the Files tab from your left hand panel, right click on the build.xml file and tell it what type of ant target you want to run.
"cell one","cell "" two","cell "" ,three"
Save this to csv file and see the results, so double quote is used to escape itself
Important Note
"cell one","cell "" two", "cell "" ,three"
will give you a different result because there is a space after the comma, and that will be treated as "
Use the in
keyword.
if 'apples' in d:
if d['apples'] == 20:
print('20 apples')
else:
print('Not 20 apples')
If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get
function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None
instead):
if d.get('apples', 0) == 20:
print('20 apples.')
else:
print('Not 20 apples.')
$(".thumbs").hover(
function(){
if (!$(this).hasClass("selected")) {
$(this).stop().fadeTo("normal", 1.0);
}
},
function(){
if (!$(this).hasClass("selected")) {
$(this).stop().fadeTo("slow", 0.3);
}
}
);
Putting an if inside of each part of the hover will allow you to change the select class dynamically and the hover will still work.
$(".thumbs").click(function() {
$(".thumbs").each(function () {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
$(this).hover();
}
});
$(this).addClass("selected");
});
As an example I've also attached a click handler to switch the selected class to the clicked item. Then I fire the hover event on the previous item to make it fade out.
Use this query and then check the results.
$query = 'show tables like "test1"';
SimpleDateFormat
sdf=new SimpleDateFormat("dd/MM/YYYY hh:mm:ss");
String dateString=sdf.format(date);
It will give the output 28/09/2013 09:57:19
as you expected.
According to the Git repo of the BFG tool, it "removes large or troublesome blobs as git-filter-branch does, but faster - and is written in Scala".
Sine you've mentioned you're using Eclipse... Eclipse can create the JARs for you, so long as you've run each class that has a main once. Right-click the project and click Export, then select "Runnable JAR file" under the Java folder. Select the class name in the launch configuration, choose a place to save the jar, and make a decision how to handle libraries if necessary. Click finish, wipe hands on pants.
Try the following:
$("#myanchor")[0].click()
As simple as that.
You can try this one:
String newFileName = "my-image";
File imageFile = new File("/users/victor/images/image.png");
GridFS gfsPhoto = new GridFS(db, "photo");
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
gfsFile.setFilename(newFileName);
gfsFile.save();
If you use androidx.appcompat:appcompat and want a custom drawable (of type selector
with android:state_checked
) to work on old platform versions in addition to new platform versions, you need to use
<CheckBox
app:buttonCompat="@drawable/..."
instead of
<CheckBox
android:button="@drawable/..."
System.Net.WebException: The remote server returned an error: (411) Length Required.
This is a pretty common issue that comes up when trying to make call a REST based API method through POST. Luckily, there is a simple fix for this one.
This is the code I was using to call the Windows Azure Management API. This particular API call requires the request method to be set as POST, however there is no information that needs to be sent to the server.
var request = (HttpWebRequest) HttpWebRequest.Create(requestUri);
request.Headers.Add("x-ms-version", "2012-08-01"); request.Method =
"POST"; request.ContentType = "application/xml";
To fix this error, add an explicit content length to your request before making the API call.
request.ContentLength = 0;
Here's a 2020 answer - if you don't need to support the older .xls format (so pre 2003) you could use either:
or
Pros :
Cons:
Disclaimer: I am the author of LightweightExcelReader and ExcelToEnumerable
Take a look at http://developer.android.com/reference/org/json/JSONTokener.html
This might fix your issue.
I am using Windows 7 Professional and I was having same problem @Bayu Mohammad Lufty not worked for me.
I simply delete .AndroidStudio1.2 from my C:\Users\UserName\ and restart my Android studio again. It open Android Studio perfectly! It configured everything again in next start :)
If you use jQuery you can write:
$( _checkbox ).click( function( e ){ /*process event here*/ } )
if you'd like to avoid numeric indices, you can use
a <- setdiff(names(a),c("name1", ..., "namen"))
to delete names namea...namen
from a. this works for lists
> l <- list(a=1,b=2)
> l[setdiff(names(l),"a")]
$b
[1] 2
as well as for vectors
> v <- c(a=1,b=2)
> v[setdiff(names(v),"a")]
b
2
XHTML solution:
<input type="radio" name="imgsel" value="" checked="checked" />
Please note, that the actual value of checked
attribute does not actually matter; it's just a convention to assign "checked"
. Most importantly, strings like "true"
or "false"
don't have any special meaning.
If you don't aim for XHTML conformance, you can simplify the code to:
<input type="radio" name="imgsel" value="" checked>
The only difference between slice and substring method is of arguments
Both take two arguments e.g. start/from and end/to.
You cannot pass a negative value as first argument for substring method but for slice method to traverse it from end.
Slice method argument details:
REF: http://www.thesstech.com/javascript/string_slice_method
Arguments
start_index Index from where slice should begin. If value is provided in negative it means start from last. e.g. -1 for last character. end_index Index after end of slice. If not provided slice will be taken from start_index to end of string. In case of negative value index will be measured from end of string.
Substring method argument details:
REF: http://www.thesstech.com/javascript/string_substring_method
Arguments
from It should be a non negative integer to specify index from where sub-string should start. to An optional non negative integer to provide index before which sub-string should be finished.
You can not simply ping in Java as it relies on ICMP, which is sadly not supported in Java
http://mindprod.com/jgloss/ping.html
Use sockets instead
Hope it helps
Try:
<div style="@(Model.booleanVariable ? "display:block" : "display:none")">Some links</div>
Use the "Display" style attribute with your bool model attribute to define the div's visibility.
Another option is to delete all the classes and rebuild. Having build file is an ideal solution to control whole process like compilation, packaging and deployment. You can also specify source/target versions
JavaScript only simple solution
datePickerId.max = new Date().toISOString().split("T")[0];
_x000D_
<input type="date" id="datePickerId" />
_x000D_
If the required data is not too large (limits I don´t know, would depend on a lot of things), you might also download the data (in XML, JSON, whatever) from a website/webapp. AFter receiving, execute the SQL statements using the received data creating your tables and inserting the data.
If your mobile app contains lots of data, it might be easier later on to update the data in the installed apps with more accurate data or changes.
I have been using Perforce for a long time and recently I also started to use GIT. Here is my "objective" opinion:
Perforce features:
GIT features:
Overall for OpenSource/Distributed projects I would always recommend GIT, because it is more like a P2P application and everyone can participate in development. For example, I remember that when I was doing remote development with Perforce I was syncing 4GB Projects over 1Mbps link once in a week. Alot of time was simply wasted because of that. Also we needed set up VPN to do that.
If you have a small company and P4 server will be always up then I would say that Perforce is also a very good option.
Interfaces are a way to make your code more flexible. What you do is this:
Ibox myBox=new Rectangle();
Then, later, if you decide you want to use a different kind of box (maybe there's another library, with a better kind of box), you switch your code to:
Ibox myBox=new OtherKindOfBox();
Once you get used to it, you'll find it's a great (actually essential) way to work.
Another reason is, for example, if you want to create a list of boxes and perform some operation on each one, but you want the list to contain different kinds of boxes. On each box you could do:
myBox.close()
(assuming IBox has a close() method) even though the actual class of myBox changes depending on which box you're at in the iteration.
Running this approach will in fact toggle the checkbox; .isSelected()
in Java/Selenium 2 apparently always returns false
(at least with the Java, Selenium, and Firefox versions I tested it with).
The selection of the proper checkbox isn't where the problem lies -- rather, it is in distinguishing correctly the initial state to needlessly avoid reclicking an already-checked box.
Or, if you need to access the element that has that property and it does not use an id, you could go this route:
$("img").each(function () {
if ($(this).css("float") == "left") { $(this).addClass("left"); }
if ($(this).css("float") == "right") { $(this).addClass("right"); }
})
In addition to the native versions, but you may want to try BitNami MAMP Stacks (disclaimer, I am one of the developers). They are completely free, all-in-one bundles of Apache, MySQL, PHP and a several other third-party libraries and utilities that are useful when developing locally. In particular, they are completely self-contained so you can have several one installed at the same time, with different versions of Apache and MySQL and they will not interfere with each other. You can get them from http://bitnami.org/stack/mampstack or directly from the Mac OS X app store https://itunes.apple.com/app/mamp-stack/id571310406
I wanted to keep the formulas in place, which the above code did not do.
Here's what I've been doing, note that this leaves one empty row in the table.
Sub DeleteTableRows(ByRef Table As ListObject, KeepFormulas as boolean)
On Error Resume Next
if not KeepFormulas then
Table.DataBodyRange.clearcontents
end if
Table.DataBodyRange.Rows.Delete
On Error GoTo 0
End Sub
(PS don't ask me why!)
The following seems to work for my use cases:
$ tern 1 YES NO
YES
$ tern 0 YES NO
NO
$ tern 52 YES NO
YES
$ tern 52 YES NO 52
NO
and can be used in a script like so:
RESULT=$(tern 1 YES NO)
echo "The result is $RESULT"
function show_help()
{
echo ""
echo "usage: BOOLEAN VALUE_IF_TRUE VALUE_IF_FALSE {FALSE_VALUE}"
echo ""
echo "e.g. "
echo ""
echo "tern 1 YES NO => YES"
echo "tern 0 YES NO => NO"
echo "tern "" YES NO => NO"
echo "tern "ANY STRING THAT ISNT 1" YES NO => NO"
echo "ME=$(tern 0 YES NO) => ME contains NO"
echo ""
exit
}
if [ "$1" == "help" ]
then
show_help
fi
if [ -z "$3" ]
then
show_help
fi
# Set a default value for what is "false" -> 0
FALSE_VALUE=${4:-0}
function main
{
if [ "$1" == "$FALSE_VALUE" ]; then
echo $3
exit;
fi;
echo $2
}
main "$1" "$2" "$3"
try installing 4.0.30 as mentioned in this documentation: http://developer.android.com/google/play-services/setup.html
The solution that worked for me with default value 0 is the following
ALTER TABLE reservations ADD COLUMN isGuest BIT DEFAULT 0
null
is a special value that is not an instance of any class. This is illustrated by the following program:
public class X {
void f(Object o)
{
System.out.println(o instanceof String); // Output is "false"
}
public static void main(String[] args) {
new X().f(null);
}
}
For Windows 10, 5.29.18 :
Using command promt I just got in the emulator directory:
cd C:\Android\sdk\emulator
and then typed the command:
emulator -avd Nexus_S_API_27
Nexus_S_API_27
is the name of my custom emulator.
Othewize it will abuse :
PANIC: Missing emulator engine program for 'x86' CPU.
Although there is an accepted answer I don't feel that it is the right one. It is the simplest way to achieve what is needed, but even if already enabled in InnoDB (actually docs tell you that you still should get NULL ...), if you read MySQL docs, even in current version (8.0) using UPDATE_TIME is not the right option, because:
Timestamps are not persisted when the server is restarted or when the table is evicted from the InnoDB data dictionary cache.
If I understand correctly (can't verify it on a server right now), timestamp gets reset after server restart.
As for real (and, well, costly) solutions, you have Bill Karwin's solution with CURRENT_TIMESTAMP and I'd like to propose a different one, that is based on triggers (I'm using that one).
You start by creating a separate table (or maybe you have some other table that can be used for this purpose) which will work like a storage for global variables (here timestamps). You need to store two fields - table name (or whatever value you'd like to keep here as table id) and timestamp. After you have it, you should initialize it with this table id + starting date (NOW() is a good choice :) ).
Now, you move to tables you want to observe and add triggers AFTER INSERT/UPDATE/DELETE with this or similar procedure:
CREATE PROCEDURE `timestamp_update` ()
BEGIN
UPDATE `SCHEMA_NAME`.`TIMESTAMPS_TABLE_NAME`
SET `timestamp_column`=DATE_FORMAT(NOW(), '%Y-%m-%d %T')
WHERE `table_name_column`='TABLE_NAME';
END
Following works out for me.
#!/usr/bin/env python
a = [{ 'main_color': 'red', 'second_color':'blue'},
{ 'main_color': 'yellow', 'second_color':'green'},
{ 'main_color': 'yellow', 'second_color':'blue'}]
found_event = next(
filter(
lambda x: x['main_color'] == 'red',
a
),
#return this dict when not found
dict(
name='red',
value='{}'
)
)
if found_event:
print(found_event)
$python /tmp/x
{'main_color': 'red', 'second_color': 'blue'}
Here is something you can do with Ajax, PHP and JQuery. Hope this helps or gives you a start. Check the mysql query in php. It matches the pattern starting from first.
See live demo and source code here.
http://purpledesign.in/blog/to-create-a-live-search-like-google/
Create a search box, may be an input field like this.
<input type="text" id="search" autocomplete="off">
Now we need listen to whatever the user types on the text area. For this we will use the jquery live() and the keyup event. On every keyup we have a jquery function “search” that will run a php script.
Suppose we have the html like this. We have an input field and a list to display the results.
<div class="icon"></div>
<input type="text" id="search" autocomplete="off">
<ul id="results"></ul>
We have a Jquery script that will listen to the keyup event on the input field and if it is not empty it will invoke the search() function. The search() function will run the php script and display the result on the same page using AJAX.
Here is the JQuery.
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
//Listen for the event
$("input#search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search_st.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
}); In the php, shoot a query to the mysql database. The php will return the results that will be put into the html using AJAX. Here the result is put into a html list.
Suppose there is a dummy database containing two tables animals and bird with two similar column names ‘type’ and ‘desc’.
//search.php
// Credentials
$dbhost = "localhost";
$dbname = "live";
$dbuser = "root";
$dbpass = "";
// Connection
global $tutorial_db;
$tutorial_db = new mysqli();
$tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$tutorial_db->set_charset("utf8");
// Check Connection
if ($tutorial_db->connect_errno) {
printf("Connect failed: %s\n", $tutorial_db->connect_error);
exit();
$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);
// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
// Build Query
$query = "SELECT *
FROM animals
WHERE type REGEXP '^".$search_string."'
UNION ALL SELECT *
FROM birf
WHERE type REGEXP '^".$search_string."'"
;
$result = $tutorial_db->query($query);
while($results = $result->fetch_array()) {
$result_array[] = $results;
}
// Check If We Have Results
if (isset($result_array)) {
foreach ($result_array as $result) {
// Format Output Strings And Hightlight Matches
$display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['desc']);
$display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['type']);
$display_url = 'https://www.google.com/search?q='.urlencode($result['type']).'&ie=utf-8&oe=utf-8';
// Insert Name
$output = str_replace('nameString', $display_name, $html);
// Insert Description
$output = str_replace('functionString', $display_function, $output);
// Insert URL
$output = str_replace('urlString', $display_url, $output);
// Output
echo($output);
}
}else{
// Format No Results Output
$output = str_replace('urlString', 'javascript:void(0);', $html);
$output = str_replace('nameString', '<b>No Results Found.</b>', $output);
$output = str_replace('functionString', 'Sorry :(', $output);
// Output
echo($output);
}
}
JSX will evaluate JavaScript expressions in curly braces
In this case, this.props.removeTaskFunction(todo)
is invoked and the return value is assigned to onClick
What you have to provide for onClick
is a function. To do this, you can wrap the value in an anonymous function.
export const samepleComponent = ({todoTasks, removeTaskFunction}) => {
const taskNodes = todoTasks.map(todo => (
<div>
{todo.task}
<button type="submit" onClick={() => removeTaskFunction(todo)}>Submit</button>
</div>
);
return (
<div className="todo-task-list">
{taskNodes}
</div>
);
}
});
Both pandas
and matplotlib.dates
use matplotlib.units
for locating the ticks.
But while matplotlib.dates
has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).
So for the moment it seems more reasonable to use matplotlib.dates
(as mentioned by @BrenBarn in his comment).
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)
fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()
(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])
You can change the working directory with:
import os
os.chdir(path)
There are two best practices to follow when using this method:
Changing the current working directory in a subprocess does not change the current working directory in the parent process. This is true of the Python interpreter as well. You cannot use os.chdir()
to change the CWD of the calling process.
I feel the above answers miss a scenario where this error occurs even when your code has a main(). When you are using JNI that uses Reflection to invoke a method. During runtime if the method is not found, you will get a
java.lang.NoSuchMethodError: No virtual method
Your annotations look fine. Here are the things to check:
make sure the annotation is javax.persistence.Entity
, and not org.hibernate.annotations.Entity
. The former makes the entity detectable. The latter is just an addition.
if you are manually listing your entities (in persistence.xml, in hibernate.cfg.xml, or when configuring your session factory), then make sure you have also listed the ScopeTopic
entity
make sure you don't have multiple ScopeTopic
classes in different packages, and you've imported the wrong one.
input[name=username] { disabled: true; /* Does not work */ }
I know this question is quite old but for other users who come across this problem, I suppose the easiest way to disable input is simply by ':disabled'
<input type="text" name="username" value="admin" disabled />
<style type="text/css">
input[name=username]:disabled {
opacity: 0.5 !important; /* Fade effect */
cursor: not-allowed; /* Cursor change to disabled state*/
}
</style>
In reality, if you have some script to disable the input dynamically/automatically with javascript or jquery that would automatically disable based on the condition you add.
In jQuery for Example:
if (condition) {
// Make this input prop disabled state
$('input').prop('disabled', true);
}
else {
// Do something else
}
Hope the answer in CSS helps.
the following solution worked for me other solution gave me some space in the sides i.e not full screen
You need to make changes in onStart and onCreate method
@Override
public void onStart() {
super.onStart();
Dialog dialog = getDialog();
if (dialog != null)
{
int width = ViewGroup.LayoutParams.MATCH_PARENT;
int height = ViewGroup.LayoutParams.MATCH_PARENT;
dialog.getWindow().setLayout(width, height);
}
}
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
final Dialog dialog = new Dialog(requireContext());
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
Use this equation:
calc(42px + (60 - 42) * (100vw - 768px) / (1440 - 768));
For anything larger or smaller than 1440 and 768, you can either give it a static value, or apply the same approach.
The drawback with vw solution is that you cannot set a scale ratio, say a 5vw at screen resolution 1440 may end up being 60px font-size, your idea font size, but when you shrink the window width down to 768, it may ended up being 12px, not the minimal you want.
With this approach, you can set your upper boundary and lower boundary, and the font will scale itself in between.
I tried and found out that if you add a class called btn
you can get that hand
or cursor
icon if you hover over the mouse to that element. Try and see.
Example:
<span class="btn">Hovering over must have mouse cursor set to hand or pointer!</span>
Cheers!
Java 8:
java -version
Java 9+:
java --version
Try giving these values:
<corners android:topLeftRadius="6dp" android:topRightRadius="6dp"
android:bottomLeftRadius="0.1dp" android:bottomRightRadius="0.1dp"/>
Note that I have changed 0dp
to 0.1dp
.
EDIT: See Aleks G comment below for a cleaner version
foreach($data as $value)
{
$value["transaction_date"] = date('d/m/Y',$value["transaction_date"]);
}
return $data;
The GUI based approach would be to add an additional module in your project.
One final piece of advice. Make sure that the JAR file you include is build with at most JDK 1.7. Many problems relating to error message "com.android.dx.cf.iface.ParseException: bad class file magic (cafebabe) or version (0034.0000)" root straight to this :0.
The answer by @Darius is the most idiomatic (and probably more performant) method. One limitation is that the type you are checking has to be of type interface{}
. If you use a concrete type it will fail.
An alternative way to determine the type of something at run-time, including concrete types, is to use the Go reflect
package. Chaining TypeOf(x).Kind()
together you can get a reflect.Kind
value which is a uint
type: http://golang.org/pkg/reflect/#Kind
You can then do checks for types outside of a switch block, like so:
import (
"fmt"
"reflect"
)
// ....
x := 42
y := float32(43.3)
z := "hello"
xt := reflect.TypeOf(x).Kind()
yt := reflect.TypeOf(y).Kind()
zt := reflect.TypeOf(z).Kind()
fmt.Printf("%T: %s\n", xt, xt)
fmt.Printf("%T: %s\n", yt, yt)
fmt.Printf("%T: %s\n", zt, zt)
if xt == reflect.Int {
println(">> x is int")
}
if yt == reflect.Float32 {
println(">> y is float32")
}
if zt == reflect.String {
println(">> z is string")
}
Which prints outs:
reflect.Kind: int
reflect.Kind: float32
reflect.Kind: string
>> x is int
>> y is float32
>> z is string
Again, this is probably not the preferred way to do it, but it's good to know alternative options.
Thanks to duncan answer, I end up with this:
marker.addListener('mouseover', () => infoWindow.open(map, marker))
marker.addListener('mouseout', () => infoWindow.close())
Please note, the option presented below is apparently no longer supported as of Laravel 5.4 (thanks @Alex).
In Laravel 5.3 and below, there is a method to set the fetch mode for select queries.
In this case, it might be more efficient to do:
DB::connection()->setFetchMode(PDO::FETCH_ASSOC);
$result = DB::table('user')->where('name',=,'Jhon')->get();
That way, you won't waste time creating objects and then converting them back into arrays.
As mentioned in other answers ORDER BY 1
orders by the first column.
I came across another example of where you might use it though. We have certain queries which need to be ordered select the same column. You would get a SQL error if ordering by Name
in the below.
SELECT Name, Name FROM Segment ORDER BY 1
The URI depends on the version of JSTL you are using. For Version 1.0 use:
http://java.sun.com/jstl/core
and for 1.1 (and later), you need to use:
http://java.sun.com/jsp/jstl/core
Although this is very complicated but it is possible. I have check this code on latest Firefox and Google Chrome browser. Older browser may not support the css shape-outside
property. For further detail check this reference.
window.addEventListener('load', function() {
var imageHolder = document.querySelector('.image-holder');
var containerHeight = document.querySelector('.container').offsetHeight;
var imageHolderHeight = imageHolder.offsetHeight;
var countPadding = containerHeight - imageHolderHeight;
imageHolder.style.paddingTop = countPadding + 'px';
containerHeight = document.querySelector('.container').offsetHeight;
var x1 = '0' + 'px ' + countPadding + 'px';
var x2 = imageHolder.offsetWidth + 'px' + ' ' + countPadding + 'px';
var x3 = imageHolder.offsetWidth + 'px' + ' ' + containerHeight + 'px';
var x4 = 0 + 'px' + ' ' + containerHeight + 'px';
var value = 'polygon(' + x1 + ',' + x2 + ',' + x3 + ',' + x4 + ')';
imageHolder.style.shapeOutside = value;
});
_x000D_
.container {
width: 300px;
text-align: justify;
border: 1px solid black;
}
.image-holder {
float: right;
}
_x000D_
<div class='container' style="">
<div class='image-holder' style=''>
<img class='bottom-right' style="width: 100px;" src="https://www.lwb.org.au/services/child-youth-and-family/static/b5cca79df7320248a77f6655a278190f/a6c62/img-index-banner.jpg" alt="">
</div>
<div>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Error quasi ut ipsam saepe, dignissimos, accusamus debitis ratione neque doloribus quis exercitationem iure! Harum quisquam ipsam velit distinctio tempora repudiandae eveniet.</div>
</div>
_x000D_
<input type="radio" name="radio" value="creditcard" />
<input type="radio" name="radio" value="cash"/>
<input type="radio" name="radio" value="cheque"/>
<input type="radio" name="radio" value="instore"/>
$("input[name='radio']:checked").val()
Here is the code snippet I found:
var audio = new Audio();
audio.src ='http://translate.google.com/translate_tts?ie=utf-8&tl=en&q=Hello%20World.';
audio.play();
On Angular2 (2.1.0) I use ngZone to capture the screen change event.
Take a look on the example:
import { Component, NgZone } from '@angular/core';//import ngZone library
...
//capture screen changed inside constructor
constructor(private ngZone: NgZone) {
window.onresize = (e) =>
{
ngZone.run(() => {
console.log(window.innerWidth);
console.log(window.innerHeight);
});
};
}
I hope this help!
You first have to tell Gnuplot to use a style that uses points, e.g. with points
or with linespoints
. Try for example:
plot sin(x) with points
Output:
Now try:
plot sin(x) with points pointtype 5
Output:
You may also want to look at the output from the test
command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:
I ended up using the bootstrap 3 dropdown button, I'm posting my solution here in case it helps someone in future. Adding the bootstrap 3 list-inline to the class for the ul causes it to display in a nicely compact format as well.
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
Select icon <span class="caret"></span>
</button>
<ul class="dropdown-menu list-inline" role="menu">
<li><span class="glyphicon glyphicon-cutlery"></span></li>
<li><span class="glyphicon glyphicon-fire"></span></li>
<li><span class="glyphicon glyphicon-glass"></span></li>
<li><span class="glyphicon glyphicon-heart"></span></li>
</ul>
</div>
I'm using Angular.js so this is the actual code I used:
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
Avatar <span class="caret"></span>
</button>
<ul class="dropdown-menu list-inline" role="menu">
<li ng-repeat="avatar in avatars" ng-click="avatarSelected(avatar)">
<span ng-class="getAvatar(avatar)"></span>
</li>
</ul>
</div>
And in my controller:
$scope.avatars=['cutlery','eye-open','flag','flash','glass','fire','hand-right','heart','heart-empty','leaf','music','send','star','star-empty','tint','tower','tree-conifer','tree-deciduous','usd','user','wrench','time','road','cloud'];
$scope.getAvatar=function(avatar){
return 'glyphicon glyphicon-'+avatar;
};
You should use System property instead of environment variable for this case. Edit your tomcat scripts for JAVA_OPTS and add property like:
-DAPP_MASTER_PASSWORD=foo
and in your code, write
System.getProperty("APP_MASTER_PASSWORD");
You can do this in Eclipse as well, instead of JAVA_OPTS, copy the line in VM parameters inside run configurations.
You should normally be able to run a php file (after a successful installation) just by running this command:
$ /path/to/php myfile.php // unix way
C:\php\php.exe myfile.php // windows way
You can read more about running PHP in CLI mode here.
It's worth adding that PHP from version 5.4 onwards is able to run a web server on its own. You can do it by running this code in a folder which you want to serve the pages from:
$ php -S localhost:8000
You can read more about running a PHP in a Web Server mode here.
From the command line issue
mongo --quiet --eval "printjson(db.adminCommand('listDatabases'))"
which gives output
{
"databases" : [
{
"name" : "admin",
"sizeOnDisk" : 978944,
"empty" : false
},
{
"name" : "local",
"sizeOnDisk" : 77824,
"empty" : false
},
{
"name" : "meteor",
"sizeOnDisk" : 778240,
"empty" : false
}
],
"totalSize" : 1835008,
"ok" : 1
}
Note that ng-bind-html-unsafe is no longer suppported in rc 1.2. Use ng-bind-html instead. See: With ng-bind-html-unsafe removed, how do I inject HTML?
Do this in your .profile -
export JAVA_HOME=`/usr/libexec/java_home`
(backticks make sure to execute the command and place its value in JAVA_HOME)
When running the development server - which is what you get by running app.run()
, you get a single synchronous process, which means at most 1 request is being processed at a time.
By sticking Gunicorn in front of it in its default configuration and simply increasing the number of --workers
, what you get is essentially a number of processes (managed by Gunicorn) that each behave like the app.run()
development server. 4 workers == 4 concurrent requests. This is because Gunicorn uses its included sync
worker type by default.
It is important to note that Gunicorn also includes asynchronous workers, namely eventlet
and gevent
(and also tornado
, but that's best used with the Tornado framework, it seems). By specifying one of these async workers with the --worker-class
flag, what you get is Gunicorn managing a number of async processes, each of which managing its own concurrency. These processes don't use threads, but instead coroutines. Basically, within each process, still only 1 thing can be happening at a time (1 thread), but objects can be 'paused' when they are waiting on external processes to finish (think database queries or waiting on network I/O).
This means, if you're using one of Gunicorn's async workers, each worker can handle many more than a single request at a time. Just how many workers is best depends on the nature of your app, its environment, the hardware it runs on, etc. More details can be found on Gunicorn's design page and notes on how gevent works on its intro page.
You can use fs.stat
to check if target is a file or directory and you can use fs.access
to check if you can write/read/execute the file. (remember to use path.resolve
to get full path for the target)
Documentation:
Full example (TypeScript)
import * as fs from 'fs';
import * as path from 'path';
const targetPath = path.resolve(process.argv[2]);
function statExists(checkPath): Promise<fs.Stats> {
return new Promise((resolve) => {
fs.stat(checkPath, (err, result) => {
if (err) {
return resolve(undefined);
}
return resolve(result);
});
});
}
function checkAccess(checkPath: string, mode: number = fs.constants.F_OK): Promise<boolean> {
return new Promise((resolve) => {
fs.access(checkPath, mode, (err) => {
resolve(!err);
});
});
}
(async function () {
const result = await statExists(targetPath);
const accessResult = await checkAccess(targetPath, fs.constants.F_OK);
const readResult = await checkAccess(targetPath, fs.constants.R_OK);
const writeResult = await checkAccess(targetPath, fs.constants.W_OK);
const executeResult = await checkAccess(targetPath, fs.constants.X_OK);
const allAccessResult = await checkAccess(targetPath, fs.constants.F_OK | fs.constants.R_OK | fs.constants.W_OK | fs.constants.X_OK);
if (result) {
console.group('stat');
console.log('isFile: ', result.isFile());
console.log('isDir: ', result.isDirectory());
console.groupEnd();
}
else {
console.log('file/dir does not exist');
}
console.group('access');
console.log('access:', accessResult);
console.log('read access:', readResult);
console.log('write access:', writeResult);
console.log('execute access:', executeResult);
console.log('all (combined) access:', allAccessResult);
console.groupEnd();
process.exit(0);
}());
Changing a constant type will lead to an Undefined Behavior.
However, if you have an originally non-const object which is pointed to by a pointer-to-const or referenced by a reference-to-const then you can use const_cast to get rid of that const-ness.
Casting away constness is considered evil and should not be avoided. You should consider changing the type of the pointers you use in vector to non-const if you want to modify the data through it.
There is no difference in behavior that I can find between the two (other than the obvious null-case). As for which version to prefer, I would go with the second. It is the standard way of doing this in Java.
If it confuses readers of your code (because String[] instanceof Object[]
is true), you may want to use the first to be more explicit if code reviewers keep asking about it.
To cater for the schema as well, use this format in SQL 2014
if exists(select 1 from sys.views V inner join sys.[schemas] S on v.schema_id = s.schema_id where s.name='dbo' and v.name = 'someviewname' and v.type = 'v')
drop view [dbo].[someviewname];
go
And just throwing it out there, to do stored procedures, because I needed that too:
if exists(select 1
from sys.procedures p
inner join sys.[schemas] S on p.schema_id = s.schema_id
where
s.name='dbo' and p.name = 'someprocname'
and p.type in ('p', 'pc')
drop procedure [dbo].[someprocname];
go
Inspired by yarkee, I combined it with some of the code I already got. You can also call this from another script, just by calling the function run_unit_tests()
without requiring to use the command line, or just call it from the command line with python3 my_test_file.py
.
import my_test_file
my_test_file.run_unit_tests()
Sadly this only works for Python 3.3 or above:
import unittest
class LineBalancingUnitTests(unittest.TestCase):
@classmethod
def setUp(self):
self.maxDiff = None
def test_it_is_sunny(self):
self.assertTrue("a" == "a")
def test_it_is_hot(self):
self.assertTrue("a" != "b")
Runner code:
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import unittest
from .somewhere import LineBalancingUnitTests
def create_suite(classes, unit_tests_to_run):
suite = unittest.TestSuite()
unit_tests_to_run_count = len( unit_tests_to_run )
for _class in classes:
_object = _class()
for function_name in dir( _object ):
if function_name.lower().startswith( "test" ):
if unit_tests_to_run_count > 0 \
and function_name not in unit_tests_to_run:
continue
suite.addTest( _class( function_name ) )
return suite
def run_unit_tests():
runner = unittest.TextTestRunner()
classes = [
LineBalancingUnitTests,
]
# Comment all the tests names on this list, to run all Unit Tests
unit_tests_to_run = [
"test_it_is_sunny",
# "test_it_is_hot",
]
runner.run( create_suite( classes, unit_tests_to_run ) )
if __name__ == "__main__":
print( "\n\n" )
run_unit_tests()
Editing the code a little, you can pass an array with all unit tests you would like to call:
...
def run_unit_tests(unit_tests_to_run):
runner = unittest.TextTestRunner()
classes = \
[
LineBalancingUnitTests,
]
runner.run( suite( classes, unit_tests_to_run ) )
...
And another file:
import my_test_file
# Comment all the tests names on this list, to run all unit tests
unit_tests_to_run = \
[
"test_it_is_sunny",
# "test_it_is_hot",
]
my_test_file.run_unit_tests( unit_tests_to_run )
Alternatively, you can use load_tests Protocol and define the following method in your test module/file:
def load_tests(loader, standard_tests, pattern):
suite = unittest.TestSuite()
# To add a single test from this file
suite.addTest( LineBalancingUnitTests( 'test_it_is_sunny' ) )
# To add a single test class from this file
suite.addTests( unittest.TestLoader().loadTestsFromTestCase( LineBalancingUnitTests ) )
return suite
If you want to limit the execution to one single test file, you just need to set the test discovery pattern to the only file where you defined the load_tests()
function.
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import unittest
test_pattern = 'mytest/module/name.py'
PACKAGE_ROOT_DIRECTORY = os.path.dirname( os.path.realpath( __file__ ) )
loader = unittest.TestLoader()
start_dir = os.path.join( PACKAGE_ROOT_DIRECTORY, 'testing' )
suite = loader.discover( start_dir, test_pattern )
runner = unittest.TextTestRunner( verbosity=2 )
results = runner.run( suite )
print( "results: %s" % results )
print( "results.wasSuccessful: %s" % results.wasSuccessful() )
sys.exit( not results.wasSuccessful() )
References:
Alternatively, to the last main program example, I came up with the following variation after reading the unittest.main()
method implementation:
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import unittest
PACKAGE_ROOT_DIRECTORY = os.path.dirname( os.path.realpath( __file__ ) )
start_dir = os.path.join( PACKAGE_ROOT_DIRECTORY, 'testing' )
from testing_package import main_unit_tests_module
testNames = ["TestCaseClassName.test_nameHelloWorld"]
loader = unittest.TestLoader()
suite = loader.loadTestsFromNames( testNames, main_unit_tests_module )
runner = unittest.TextTestRunner(verbosity=2)
results = runner.run( suite )
print( "results: %s" % results )
print( "results.wasSuccessful: %s" % results.wasSuccessful() )
sys.exit( not results.wasSuccessful() )
Before and BeforeClass in JUnit
The function @Before
annotation will be executed before each of test function in the class having @Test
annotation but the function with @BeforeClass
will be execute only one time before all the test functions in the class.
Similarly function with @After
annotation will be executed after each of test function in the class having @Test
annotation but the function with @AfterClass
will be execute only one time after all the test functions in the class.
SampleClass
public class SampleClass {
public String initializeData(){
return "Initialize";
}
public String processDate(){
return "Process";
}
}
SampleTest
public class SampleTest {
private SampleClass sampleClass;
@BeforeClass
public static void beforeClassFunction(){
System.out.println("Before Class");
}
@Before
public void beforeFunction(){
sampleClass=new SampleClass();
System.out.println("Before Function");
}
@After
public void afterFunction(){
System.out.println("After Function");
}
@AfterClass
public static void afterClassFunction(){
System.out.println("After Class");
}
@Test
public void initializeTest(){
Assert.assertEquals("Initailization check", "Initialize", sampleClass.initializeData() );
}
@Test
public void processTest(){
Assert.assertEquals("Process check", "Process", sampleClass.processDate() );
}
}
Output
Before Class
Before Function
After Function
Before Function
After Function
After Class
In Junit 5
@Before = @BeforeEach
@BeforeClass = @BeforeAll
@After = @AfterEach
@AfterClass = @AfterAll
This answer really helped me get started (noob) - but I encountered some weird behavior when I set a start date of 12/31/2014 and added +1 to default the end date. Instead of giving me an end date of 01/01/2015 I was getting 02/01/2015 (!!!). This version parses the components of the start date to avoid these end of year oddities.
$( "#date_start" ).datepicker({
minDate: 0,
dateFormat: "mm/dd/yy",
onSelect: function(selected) {
$("#date_end").datepicker("option","minDate", selected); // mindate on the End datepicker cannot be less than start date already selected.
var date = $(this).datepicker('getDate');
var tempStartDate = new Date(date);
var default_end = new Date(tempStartDate.getFullYear(), tempStartDate.getMonth(), tempStartDate.getDate()+1); //this parses date to overcome new year date weirdness
$('#date_end').datepicker('setDate', default_end); // Set as default
}
});
$( "#date_end" ).datepicker({
minDate: 0,
dateFormat: "mm/dd/yy",
onSelect: function(selected) {
$("#date_start").datepicker("option","maxDate", selected); // maxdate on the Start datepicker cannot be more than end date selected.
}
});
select whatever,columns,you,want from mytable
where mykey=(select max(mykey) from mytable);
You are doing mistake in "configuration_page.jsp" file. here in this file , function loadXMLDoc() 's line number 2 should be like this:
var config=document.getElementsByName('configselect').value;
because you have declared only the name
attribute in your <select>
tag. So you should get this element by name.
After correcting this, it will run without any JavaScript error
You can also remove them by adding code to your global.asax file:
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
HttpContext.Current.Response.Headers.Remove("X-Powered-By");
HttpContext.Current.Response.Headers.Remove("X-AspNet-Version");
HttpContext.Current.Response.Headers.Remove("X-AspNetMvc-Version");
HttpContext.Current.Response.Headers.Remove("Server");
}
You just have to reset the values you don't want to their defaults. No need to get into a mess by using !important
.
#zoomTarget .slikezamenjanje img {
max-height: auto;
padding-right: 0px;
}
I think the key datum you are missing is that CSS comes with default values. If you want to override a value, set it back to its default, which you can look up.
For example, all CSS height
and width
attributes default to auto
.
In Eclipse Kepler it is very easy to generate Web Service Client classes,You can achieve this by following steps .
RightClick on any Project->Create New Other ->Web Services->Web Service Client->Then paste the wsdl url(or location) in Service Definition->Next->Finish
You will see the generated classes are inside your src folder.
NOTE :Without eclipse also you can generate client classes from wsdl file by using wsimport command utility which ships with JDK.
refer this link Create Web service client using wsdl
I found my way here while trying to get filenames, last modified stamps, file sizes etc and wanted to add my code. It only took a few minutes to write a loop to parse the ftp.dir(dir_list.append)
making use of python std lib stuff like strip()
(to clean up the line of text) and split()
to create an array.
ftp = FTP('sick.domain.bro')
ftp.login()
ftp.cwd('path/to/data')
dir_list = []
ftp.dir(dir_list.append)
# main thing is identifing which char marks start of good stuff
# '-rw-r--r-- 1 ppsrt ppsrt 545498 Jul 23 12:07 FILENAME.FOO
# ^ (that is line[29])
for line in dir_list:
print line[29:].strip().split(' ') # got yerself an array there bud!
# EX ['545498', 'Jul', '23', '12:07', 'FILENAME.FOO']
I wanted to add one more point is, if you are storing a really large number like 902054990011312 then one can easily see the difference of INT(20)
and BIGINT(20)
. It is advisable to store in BIGINT
.
The first line forces a WMI console installation if required on a new build. WMI always returns a consistent string of "Version=x.x.xxxx" so the token parsing is always the same for all Windows versions.
Parsing from the VER output has variable text preceding the version info, making token positions random. Delimiters are only the '=' and '.' characters.
The batch addition allows me to easily check versions as '510' (XP) up to '10000' for Win10. I don't use the Build value.
Setlocal EnableDelayedExpansion
wmic os get version /value 1>nul 2>nul
if %errorlevel% equ 0 (
for /F "tokens=2,3,4 delims==." %%A In ('wmic os get version /value') Do (
(Set /A "_MAJ=%%A")
(Set /A "_MIN=%%B")
(Set /A "_BLD=%%C")
)
(Set /A "_OSVERSION=!_MAJ!*100")
(Set /A "_OSVERSION+=!_MIN!*10")
)
endlocal
You are on share environment and cannot find error log, always check if cPanel has option Errors on your cPanel dashboard. If you are not being able to find error log, then you can find it there .
On cPanel search bar, search Error, it will show Error Pages which are basically lists of different http error pages and other Error is where the error logs are displayed.
Other places to look on shared environment: /home/yourusername/logs /home/yourusername/public_html/error_log
Use this cp
command:
cp -Rf foo/* bar/
Create AMI -> Boot AMI on large instance.
More info http://docs.amazonwebservices.com/AmazonEC2/gsg/2006-06-26/creating-an-image.html
You can do this all from the admin console too at aws.amazon.com
Buffers are always of fixed size, there is no built in way to resize them dynamically, so your approach of copying it to a larger Buffer is the only way.
However, to be more efficient, you could make the Buffer larger than the original contents, so it contains some "free" space where you can add data without reallocating the Buffer. That way you don't need to create a new Buffer and copy the contents on each append operation.
viewPager.addOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
switch (position) {
case 0:
img_page1.setImageResource(R.drawable.dot_selected);
img_page2.setImageResource(R.drawable.dot);
img_page3.setImageResource(R.drawable.dot);
img_page4.setImageResource(R.drawable.dot);
break;
case 1:
img_page1.setImageResource(R.drawable.dot);
img_page2.setImageResource(R.drawable.dot_selected);
img_page3.setImageResource(R.drawable.dot);
img_page4.setImageResource(R.drawable.dot);
break;
case 2:
img_page1.setImageResource(R.drawable.dot);
img_page2.setImageResource(R.drawable.dot);
img_page3.setImageResource(R.drawable.dot_selected);
img_page4.setImageResource(R.drawable.dot);
break;
case 3:
img_page1.setImageResource(R.drawable.dot);
img_page2.setImageResource(R.drawable.dot);
img_page3.setImageResource(R.drawable.dot);
img_page4.setImageResource(R.drawable.dot_selected);
break;
default:
break;
}
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
This should technically be achievable using window.location.reload()
:
HTML:
<button (click)="refresh()">Refresh</button>
TS:
refresh(): void {
window.location.reload();
}
Update:
Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload()
is executed.
You could use the INDIRECT function. This takes a string and converts it into a range
More info here
=INDIRECT("K"&A2)
But it's preferable to use INDEX as it is less volatile.
=INDEX(K:K,A2)
This returns a value or the reference to a value from within a table or range
More info here
Put either function into cell B2 and fill down.
I implemented very fast Postgresq data loader with native libpq methods. Try my package https://www.nuget.org/packages/NpgsqlBulkCopy/
Without knowing the ID of the DIV I think you could select the IMG like this:
$("#"+$(this).attr("id")+" img:first")
Perhaps you're looking for the x86_64 ABI?
If that's not precisely what you're after, use 'x86_64 abi' in your preferred search engine to find alternative references.
Check & and Cross:
<span class='act-html-check'></span>
<span class='act-html-cross'><span class='act-html-cross'></span></span>
<style type="text/css">
span.act-html-check {
display: inline-block;
width: 12px;
height: 18px;
border: solid limegreen;
border-width: 0 5px 5px 0;
transform: rotate( 45deg);
}
span.act-html-cross {
display: inline-block;
width: 10px;
height: 10px;
border: solid red;
border-width: 0 5px 5px 0;
transform: rotate( 45deg);
position: relative;
}
span.act-html-cross > span { {
transform: rotate( -180deg);
position: absolute;
left: 9px;
top: 9px;
}
</style>
Seems there is another Node ng serve process running. Check it by typing this in your console (Linux/Mac):
ps aux|grep node
and quit it with:
kill -9 <NodeProcessId>
OR alternativley use
ng serve --port <AnotherFreePortNumber>
to serve your project on a free port of you choice.
char buffer [50];
unsigned long a = 5;
int n=sprintf (buffer, "%lu", a);
Ansible uses YAML syntax in its playbooks. YAML has a number of block operators:
The >
is a folding block operator. That is, it joins multiple lines together by spaces. The following syntax:
key: >
This text
has multiple
lines
Would assign the value This text has multiple lines\n
to key
.
The |
character is a literal block operator. This is probably what you want for multi-line shell scripts. The following syntax:
key: |
This text
has multiple
lines
Would assign the value This text\nhas multiple\nlines\n
to key
.
You can use this for multiline shell scripts like this:
- name: iterate user groups
shell: |
groupmod -o -g {{ item['guid'] }} {{ item['username'] }}
do_some_stuff_here
and_some_other_stuff
with_items: "{{ users }}"
There is one caveat: Ansible does some janky manipulation of arguments to the shell
command, so while the above will generally work as expected, the following won't:
- shell: |
cat <<EOF
This is a test.
EOF
Ansible will actually render that text with leading spaces, which means the shell will never find the string EOF
at the beginning of a line. You can avoid Ansible's unhelpful heuristics by using the cmd
parameter like this:
- shell:
cmd: |
cat <<EOF
This is a test.
EOF
No - there's a big prejudice in IT against web design; but in this case the "real" programmers are on pretty firm ground.
If you've done a lot of web design work you've probably done some JavaScript, so you can put that down under 'programming languages'; if you want to list HTML as well, then I agree with the answer that suggests "Technologies".
But unless you're targeting agents who're trying to tick boxes rather than find you a good job, a bare list of things you've used doesn't really look all that good. You're better off listing the projects you've worked on and detailing the technologies you used on each; that demonstrates that you've got real experience of using them rather than just that you know some buzzwords.
The no-op command in shell is :
(colon).
if [ "$a" -ge 10 ]
then
:
elif [ "$a" -le 5 ]
then
echo "1"
else
echo "2"
fi
From the bash manual:
:
(a colon)
Do nothing beyond expanding arguments and performing redirections. The return status is zero.
If your function have two vector variables and must compute itself on each value of them (as mentioned by @Ari B. Friedman) you can use mapply
as follows:
vars1<-c(1,2,3)
vars2<-c(10,20,30)
mult_one<-function(var1,var2)
{
var1*var2
}
mapply(mult_one,vars1,vars2)
which gives you:
> mapply(mult_one,vars1,vars2)
[1] 10 40 90
Based on Merrill's answer, I came up with this single line solution... it's not very pretty, but you can blame whoever maintains the code for Spinner
for neglecting to include a function that does this for that.
mySpinner.setSelection(((ArrayAdapter<String>)mySpinner.getAdapter()).getPosition(myString));
You'll get a warning about how the cast to a ArrayAdapter<String>
is unchecked... really, you could just use an ArrayAdapter
as Merrill did, but that just exchanges one warning for another.
Or if you prefer to use your own gui tool:
git difftool ./filepath
You can set your gui tool guided by this post: How do I view 'git diff' output with a visual diff program?
spark.default.parallelism is the default number of partition set by spark which is by default 200. and if you want to increase the number of partition than you can apply the property spark.sql.shuffle.partitions to set number of partition in the spark configuration or while running spark SQL.
Normally this spark.sql.shuffle.partitions it is being used when we have a memory congestion and we see below error: spark error:java.lang.IllegalArgumentException: Size exceeds Integer.MAX_VALUE
so set your can allocate a partition as 256 MB per partition and that you can use to set for your processes.
also If number of partitions is near to 2000 then increase it to more than 2000. As spark applies different logic for partition < 2000 and > 2000 which will increase your code performance by decreasing the memory footprint as data default is highly compressed if >2000.
A great way of handling this is with regular expressions.
string modifiedString = Regex.Replace(originalString, @"(\r\n)|\n|\r", "<br/>");
This will replace any of the 3 legal types of newline with the html tag.
using System.IO;
DirectoryInfo di = new DirectoryInfo(folder);
FileInfo[] files = di.GetFiles("*.xml");
Ok, I finally wanted to have a pretty complete, searchable list of those variables for reference. Here is a complete (OCR-generated, as I did not easily find something akin to a printenv
command) list of defined variables for a Visual C++ project on my machine. Probably not all macros are defined for others (e.g. OCTAVE_EXECUTABLE
), but I wanted to err on the side of inclusiveness here.
For example, this is the first time that I see $(Language)
(expanding to C++
for this project) being mentioned outside of the IDE.
$(AllowLocalNetworkLoopback)
$(ALLUSERSPROFILE)
$(AndroidTargetsPath)
$(APPDATA)
$(AppxManifestMetadataClHostArchDir)
$(AppxManifestMetadataCITargetArchDir)
$(Attach)
$(BaseIntermediateOutputPath)
$(BuildingInsideVisualStudio)
$(CharacterSet)
$(CLRSupport)
$(CommonProgramFiles)
$(CommonProgramW6432)
$(COMPUTERNAME)
$(ComSpec)
$(Configuration)
$(ConfigurationType)
$(CppWinRT_IncludePath)
$(CrtSDKReferencelnclude)
$(CrtSDKReferenceVersion)
$(CustomAfterMicrosoftCommonProps)
$(CustomBeforeMicrosoftCommonProps)
$(DebugCppRuntimeFilesPath)
$(DebuggerFlavor)
$(DebuggerLaunchApplication)
$(DebuggerRequireAuthentication)
$(DebuggerType)
$(DefaultLanguageSourceExtension)
$(DefaultPlatformToolset)
$(DefaultWindowsSDKVersion)
$(DefineExplicitDefaults)
$(DelayImplib)
$(DesignTimeBuild)
$(DevEnvDir)
$(DocumentLibraryDependencies)
$(DotNetSdk_IncludePath)
$(DotNetSdk_LibraryPath)
$(DotNetSdk_LibraryPath_arm)
$(DotNetSdk_LibraryPath_arm64)
$(DotNetSdk_LibraryPath_x64)
$(DotNetSdk_LibraryPath_x86)
$(DotNetSdkRoot)
$(DriverData)
$(EmbedManifest)
$(EnableManagedIncrementalBuild)
$(EspXtensions)
$(ExcludePath)
$(ExecutablePath)
$(ExtensionsToDeleteOnClean)
$(FPS_BROWSER_APP_PROFILE_STRING)
$(FPS_BROWSER_USER_PROFILE_STRING)
$(FrameworkDir)
$(FrameworkDir_110)
$(FrameworkSdkDir)
$(FrameworkSDKRoot)
$(FrameworkVersion)
$(GenerateManifest)
$(GPURefDebuggerBreakOnAllThreads)
$(HOMEDRIVE)
$(HOMEPATH)
$(IgnorelmportLibrary)
$(ImportByWildcardAfterMicrosoftCommonProps)
$(ImportByWildcardBeforeMicrosoftCommonProps)
$(ImportDirectoryBuildProps)
$(ImportProjectExtensionProps)
$(ImportUserLocationsByWildcardAfterMicrosoftCommonProps)
$(ImportUserLocationsByWildcardBeforeMicrosoftCommonProps)
$(IncludePath)
$(IncludeVersionInInteropName)
$(IntDir)
$(InteropOutputPath)
$(iOSTargetsPath)
$(Keyword)
$(KIT_SHARED_IncludePath)
$(LangID)
$(LangName)
$(Language)
$(LIBJABRA_TRACE_LEVEL)
$(LibraryPath)
$(LibraryWPath)
$(LinkCompiled)
$(LinkIncremental)
$(LOCALAPPDATA)
$(LocalDebuggerAttach)
$(LocalDebuggerDebuggerlType)
$(LocalDebuggerMergeEnvironment)
$(LocalDebuggerSQLDebugging)
$(LocalDebuggerWorkingDirectory)
$(LocalGPUDebuggerTargetType)
$(LOGONSERVER)
$(MicrosoftCommonPropsHasBeenImported)
$(MpiDebuggerCleanupDeployment)
$(MpiDebuggerDebuggerType)
$(MpiDebuggerDeployCommonRuntime)
$(MpiDebuggerNetworkSecurityMode)
$(MpiDebuggerSchedulerNode)
$(MpiDebuggerSchedulerTimeout)
$(MSBuild_ExecutablePath)
$(MSBuildAllProjects)
$(MSBuildAssemblyVersion)
$(MSBuildBinPath)
$(MSBuildExtensionsPath)
$(MSBuildExtensionsPath32)
$(MSBuildExtensionsPath64)
$(MSBuildFrameworkToolsPath)
$(MSBuildFrameworkToolsPath32)
$(MSBuildFrameworkToolsPath64)
$(MSBuildFrameworkToolsRoot)
$(MSBuildLoadMicrosoftTargetsReadOnly)
$(MSBuildNodeCount)
$(MSBuildProgramFiles32)
$(MSBuildProjectDefaultTargets)
$(MSBuildProjectDirectory)
$(MSBuildProjectDirectoryNoRoot)
$(MSBuildProjectExtension)
$(MSBuildProjectExtensionsPath)
$(MSBuildProjectFile)
$(MSBuildProjectFullPath)
$(MSBuildProjectName)
$(MSBuildRuntimeType)
$(MSBuildRuntimeVersion)
$(MSBuildSDKsPath)
$(MSBuildStartupDirectory)
$(MSBuildToolsPath)
$(MSBuildToolsPath32)
$(MSBuildToolsPath64)
$(MSBuildToolsRoot)
$(MSBuildToolsVersion)
$(MSBuildUserExtensionsPath)
$(MSBuildVersion)
$(MultiToolTask)
$(NETFXKitsDir)
$(NETFXSDKDir)
$(NuGetProps)
$(NUMBER_OF_PROCESSORS)
$(OCTAVE_EXECUTABLE)
$(OneDrive)
$(OneDriveCommercial)
$(OS)
$(OutDir)
$(OutDirWasSpecified)
$(OutputType)
$(Path)
$(PATHEXT)
$(PkgDefApplicationConfigFile)
$(Platform)
$(Platform_Actual)
$(PlatformArchitecture)
$(PlatformName)
$(PlatformPropsFound)
$(PlatformShortName)
$(PlatformTarget)
$(PlatformTargetsFound)
$(PlatformToolset)
$(PlatformToolsetVersion)
$(PostBuildEventUseInBuild)
$(PreBuildEventUseInBuild)
$(PreferredToolArchitecture)
$(PreLinkEventUselnBuild)
$(PROCESSOR_ARCHITECTURE)
$(PROCESSOR_ARCHITEW6432)
$(PROCESSOR_IDENTIFIER)
$(PROCESSOR_LEVEL)
$(PROCESSOR_REVISION)
$(ProgramData)
$(ProgramFiles)
$(ProgramW6432)
$(ProjectDir)
$(ProjectExt)
$(ProjectFileName)
$(ProjectGuid)
$(ProjectName)
$(ProjectPath)
$(PSExecutionPolicyPreference)
$(PSModulePath)
$(PUBLIC)
$(ReferencePath)
$(RemoteDebuggerAttach)
$(RemoteDebuggerConnection)
$(RemoteDebuggerDebuggerlype)
$(RemoteDebuggerDeployDebugCppRuntime)
$(RemoteDebuggerServerName)
$(RemoteDebuggerSQLDebugging)
$(RemoteDebuggerWorkingDirectory)
$(RemoteGPUDebuggerTargetType)
$(RetargetAlwaysSupported)
$(RootNamespace)
$(RoslynTargetsPath)
$(SDK35ToolsPath)
$(SDK40ToolsPath)
$(SDKDisplayName)
$(SDKIdentifier)
$(SDKVersion)
$(SESSIONNAME)
$(SolutionDir)
$(SolutionExt)
$(SolutionFileName)
$(SolutionName)
$(SolutionPath)
$(SourcePath)
$(SpectreMitigation)
$(SQLDebugging)
$(SystemDrive)
$(SystemRoot)
$(TargetExt)
$(TargetFrameworkVersion)
$(TargetName)
$(TargetPlatformMinVersion)
$(TargetPlatformVersion)
$(TargetPlatformWinMDLocation)
$(TargetUniversalCRTVersion)
$(TEMP)
$(TMP)
$(ToolsetPropsFound)
$(ToolsetTargetsFound)
$(UCRTContentRoot)
$(UM_IncludePath)
$(UniversalCRT_IncludePath)
$(UniversalCRT_LibraryPath_arm)
$(UniversalCRT_LibraryPath_arm64)
$(UniversalCRT_LibraryPath_x64)
$(UniversalCRT_LibraryPath_x86)
$(UniversalCRT_PropsPath)
$(UniversalCRT_SourcePath)
$(UniversalCRTSdkDir)
$(UniversalCRTSdkDir_10)
$(UseDebugLibraries)
$(UseLegacyManagedDebugger)
$(UseOfATL)
$(UseOfMfc)
$(USERDOMAIN)
$(USERDOMAIN_ROAMINGPROFILE)
$(USERNAME)
$(USERPROFILE)
$(UserRootDir)
$(VBOX_MSI_INSTALL_PATH)
$(VC_ATLMFC_IncludePath)
$(VC_ATLMFC_SourcePath)
$(VC_CRT_SourcePath)
$(VC_ExecutablePath_ARM)
$(VC_ExecutablePath_ARM64)
$(VC_ExecutablePath_x64)
$(VC_ExecutablePath_x64_ARM)
$(VC_ExecutablePath_x64_ARM64)
$(VC_ExecutablePath_x64_x64)
$(VC_ExecutablePath_x64_x86)
$(VC_ExecutablePath_x86)
$(VC_ExecutablePath_x86_ARM)
$(VC_ExecutablePath_x86_ARM64)
$(VC_ExecutablePath_x86_x64)
$(VC_ExecutablePath_x86_x86)
$(VC_IFCPath)
$(VC_IncludePath)
$(VC_LibraryPath_ARM)
$(VC_LibraryPath_ARM64)
$(VC_LibraryPath_ATL_ARM)
$(VC_LibraryPath_ATL_ARM64)
$(VC_LibraryPath_ATL_x64)
$(VC_LibraryPath_ATL_x86)
$(VC_LibraryPath_VC_ARM)
$(VC_LibraryPath_VC_ARM_Desktop)
$(VC_LibraryPath_VC_ARM_OneCore)
$(VC_LibraryPath_VC_ARM_Store)
$(VC_LibraryPath_VC_ARM64)
$(VC_LibraryPath_VC_ARM64_Desktop)
$(VC_LibraryPath_VC_ARM64_OneCore)
$(VC_LibraryPath_VC_ARM64_Store)
$(VC_LibraryPath_VC_x64)
$(VC_LibraryPath_VC_x64_Desktop)
$(VC_LibraryPath_VC_x64_OneCore)
$(VC_LibraryPath_VC_x64_Store)
$(VC_LibraryPath_VC_x86)
$(VC_LibraryPath_VC_x86_Desktop)
$(VC_LibraryPath_VC_x86_OneCore)
$(VC_LibraryPath_VC_x86_Store)
$(VC_LibraryPath_x64)
$(VC_LibraryPath_x86)
$(VC_PGO_RunTime_Dir)
$(VC_ReferencesPath_ARM)
$(VC_ReferencesPath_ARM64)
$(VC_ReferencesPath_ATL_ARM)
$(VC_ReferencesPath_ATL_ARM64)
$(VC_ReferencesPath_ATL_x64)
$(VC_ReferencesPath_ATL_x86)
$(VC_ReferencesPath_VC_ARM)
$(VC_ReferencesPath_VC_ARM64)
$(VC_ReferencesPath_VC_x64)
$(VC_ReferencesPath_VC_x86)
$(VC_ReferencesPath_x64)
$(VC_ReferencesPath_x86)
$(VC_SourcePath)
$(VC_VC_IncludePath)
$(VC_VS_IncludePath)
$(VC_VS_LibraryPath_VC_VS_ARM)
$(VC_VS_LibraryPath_VC_VS_x64)
$(VC_VS_LibraryPath_VC_VS_x86)
$(VC_VS_SourcePath)
$(VCIDEInstallDir)
$(VCIDEInstallDir_150)
$(VCInstallDir)
$(VCInstallDir_150)
$(VCLibPackagePath)
$(VCProjectVersion)
$(VCTargetsPath)
$(VCTargetsPath10)
$(VCTargetsPath11)
$(VCTargetsPath12)
$(VCTargetsPath14)
$(VCTargetsPath15)
$(VCTargetsPathActual)
$(VCTargetsPathEffective)
$(VCToolArchitecture)
$(VCToolsInstallDir)
$(VCToolsInstallDir_150)
$(VCToolsVersion)
$(VisualStudioDir)
$(VisualStudioEdition)
$(VisualStudioVersion)
$(VS_ExecutablePath)
$(VS140COMNTOOLS)
$(VSAPPIDDIR)
$(VSAPPIDNAME)
$(VSInstallDir)
$(VSInstallDir_150)
$(VsInstallRoot)
$(VSLANG)
$(VSSKUEDITION)
$(VSVersion)
$(WDKBinRoot)
$(WebBrowserDebuggerDebuggerlype)
$(WebServiceDebuggerDebuggerlype)
$(WebServiceDebuggerSQLDebugging)
$(WholeProgramOptimization)
$(WholeProgramOptimizationAvailabilityInstrument)
$(WholeProgramOptimizationAvailabilityOptimize)
$(WholeProgramOptimizationAvailabilityTrue)
$(WholeProgramOptimizationAvailabilityUpdate)
$(windir)
$(Windows81SdkInstalled)
$(WindowsAppContainer)
$(WindowsSDK_ExecutablePath)
$(WindowsSDK_ExecutablePath_arm)
$(WindowsSDK_ExecutablePath_arm64)
$(WindowsSDK_ExecutablePath_x64)
$(WindowsSDK_LibraryPath_x86)
$(WindowsSDK_MetadataFoundationPath)
$(WindowsSDK_MetadataPath)
$(WindowsSDK_MetadataPathVersioned)
$(WindowsSDK_PlatformPath)
$(WindowsSDK_SupportedAPIs_arm)
$(WindowsSDK_SupportedAPIs_x64)
$(WindowsSDK_SupportedAPIs_x86)
$(WindowsSDK_UnionMetadataPath)
$(WindowsSDK80Path)
$(WindowsSdkDir)
$(WindowsSdkDir_10)
$(WindowsSdkDir_81)
$(WindowsSdkDir_81A)
$(WindowsSDKToolArchitecture)
$(WindowsTargetPlatformVersion)
$(WinRT_IncludePath)
$(WMSISProject)
$(WMSISProjectDirectory)
Where to find this list within Visual Studio:
<Edit...>
.Macros>>
.Motivational screenshot:
Maybe the author forgot to give the font a Mac FOND name?
You could also give the "Apple" option in the export dialog a try.
DISCLAIMER: I'm not a IPhone developer!
Redirect the output to a file like this:
./a.sh > somefile 2>&1 &
This will redirect both stdout and stderr to the same file. If you want to redirect stdout and stderr to two different files use this:
./a.sh > stdoutfile 2> stderrfile &
You can use /dev/null
as one or both of the files if you don't care about the stdout and/or stderr.
See bash manpage for details about redirections.
What you should do is create an imap of a certain key to a series of commands, in this case the commands will drop you into normal mode, delete the current word and then put you back in insert:
:imap <C-d> <C-[>diwi
First, use git log
to see the log, pick the commit you want, note down the sha1 hash that is used to identify the commit. Next, run git checkout hash
. After you are done, git checkout original_branch
. This has the advantage of not moving the HEAD, it simply switches the working copy to a specific commit.
Just pressing F5 is not always working.
why?
Because your ISP is also caching web data for you.
Solution: Force Refresh.
Force refresh your browser by pressing CTRL + F5 in Firefox or Chrome to clear ISP cache too, instead of just pressing F5
You then can see 200 response instead of 304 in the browser F12 developer tools network tab.
Another trick is to add question mark ?
at the end of the URL string of the requested page:
http://localhost:52199/Customers/Create?
The question mark will ensure that the browser refresh the request without caching any previous requests.
Additionally in Visual Studio you can set the default browser to Chrome in Incognito mode to avoid cache issues while developing, by adding Chrome in Incognito mode as default browser, see the steps (self illustrated):
The other answers are correct but if you're doing numerical work, you might want to consider numpy. Using numpy, the answer is:
v = numpy.diff(t)
Don't use the word "click" as the function name. It's a reserved keyword in JavaScript. In the bellow code I’ve used "hello" function instead of "click"
<html>
<head>
<title>Space Clicker</title>
</head>
<body>
<script type="text/javascript">
var clicks = 0;
function hello() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script>
<button type="button" onclick="hello()">Click me</button>
<p>Clicks: <a id="clicks">0</a></p>
</body></html>
It's not a big deal on a small/personal scale, but it can become a bigger deal quickly on a larger scale. My employer is a large Microsoft shop, but won't/can't buy into Team System/TFS for a number of reasons. We currently use Subversion + Orcas + MBUnit + TestDriven.NET and it works well, but getting TD.NET was a huge hassle. The version sensitivity of MBUnit + TestDriven.NET is also a big hassle, and having one additional commercial thing (TD.NET) for legal to review and procurement to handle and manage, isn't trivial. My company, like a lot of companies, are fat and happy with a MSDN Subscription model, and it's just not used to handling one off procurements for hundreds of developers. In other words, the fully integrated MS offer, while definitely not always best-of-bread, is a significant value-add in my opinion.
I think we'll stay with our current step because it works and we've already gotten over the hump organizationally, but I sure do wish MS had a compelling offering in this space so we could consolidate and simplify our dev stack a bit.
In my case, was the Docker that cause problems:
In your template
template <void (*T)(int &)>
void doOperation()
The parameter T
is a non-type template parameter. This means that the behaviour of the template function changes with the value of the parameter (which must be fixed at compile time, which function pointer constants are).
If you want somthing that works with both function objects and function parameters you need a typed template. When you do this, though, you also need to provide an object instance (either function object instance or a function pointer) to the function at run time.
template <class T>
void doOperation(T t)
{
int temp=0;
t(temp);
std::cout << "Result is " << temp << std::endl;
}
There are some minor performance considerations. This new version may be less efficient with function pointer arguments as the particular function pointer is only derefenced and called at run time whereas your function pointer template can be optimized (possibly the function call inlined) based on the particular function pointer used. Function objects can often be very efficiently expanded with the typed template, though as the particular operator()
is completely determined by the type of the function object.
Use SimpleDateFormat parse method:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
String inputString = "11-11-2012";
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date inputDate = dateFormat.parse(inputString, dateFormat );
Since we have Java 8 with LocalDate I would suggest use next:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
String inputString = "11-11-2012";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate inputDate = LocalDate.parse(inputString,formatter);
They are access modifiers and help us implement Encapsulation (or information hiding). They tell the compiler which other classes should have access to the field or method being defined.
private
- Only the current class will have access to the field or method.
protected
- Only the current class and subclasses (and sometimes also same-package classes) of this class will have access to the field or method.
public
- Any class can refer to the field or call the method.
This assumes these keywords are used as part of a field or method declaration within a class definition.
You tried to paste it using
before and it didn't work so you went ahead and pasted it with classic
Sadly whenever you enter CTRL +V on terminal it adds
(at least on my machine it encoded like that).
the character that you only appears after you
(go ahead an try it on git bash).
So your link becomes ^?https://...
which is invalid.
With recent browsers you can use the HTML5 download attribute as well:
<a download="quot.pdf" href="../doc/quot.pdf">Click here to Download quotation</a>
It is supported by most of the recent browsers except MSIE11. You can use a polyfill, something like this (note that this is for data uri only, but it is a good start):
(function (){
addEvent(window, "load", function (){
if (isInternetExplorer())
polyfillDataUriDownload();
});
function polyfillDataUriDownload(){
var links = document.querySelectorAll('a[download], area[download]');
for (var index = 0, length = links.length; index<length; ++index) {
(function (link){
var dataUri = link.getAttribute("href");
var fileName = link.getAttribute("download");
if (dataUri.slice(0,5) != "data:")
throw new Error("The XHR part is not implemented here.");
addEvent(link, "click", function (event){
cancelEvent(event);
try {
var dataBlob = dataUriToBlob(dataUri);
forceBlobDownload(dataBlob, fileName);
} catch (e) {
alert(e)
}
});
})(links[index]);
}
}
function forceBlobDownload(dataBlob, fileName){
window.navigator.msSaveBlob(dataBlob, fileName);
}
function dataUriToBlob(dataUri) {
if (!(/base64/).test(dataUri))
throw new Error("Supports only base64 encoding.");
var parts = dataUri.split(/[:;,]/),
type = parts[1],
binData = atob(parts.pop()),
mx = binData.length,
uiArr = new Uint8Array(mx);
for(var i = 0; i<mx; ++i)
uiArr[i] = binData.charCodeAt(i);
return new Blob([uiArr], {type: type});
}
function addEvent(subject, type, listener){
if (window.addEventListener)
subject.addEventListener(type, listener, false);
else if (window.attachEvent)
subject.attachEvent("on" + type, listener);
}
function cancelEvent(event){
if (event.preventDefault)
event.preventDefault();
else
event.returnValue = false;
}
function isInternetExplorer(){
return /*@cc_on!@*/false || !!document.documentMode;
}
})();
This is the answer
(CASE
WHEN
(isnumeric(ts.TimeInSeconds) = 1)
THEN
CAST(ts.TimeInSeconds AS bigint)
ELSE
0
END) AS seconds
To use the java -jar selenium-server-standalone-2.45.0.jar
command-line tool you need to install a JDK.
You need to download and install the JDK and the standalone selenium server.
Unfortunately none of the above solved the problem for me.
I didn't want to edit the bootstrap-responsive.css so I went the easy way:
@media (min-width: 768px) and (max-width: 979px)
(line 461 with latest bootstrap version 2.3.1 as of today)@media (min-width: 979px)
in the place where it said @media (min-width: 768px) and (max-width: 979px)
before. This sets the from 768 to 979 style to everything above 768.That's it. It's not optimal, you will have duplicated css, but it works 100% perfect!
For me, none of these answers worked, but I finally found one that did.
I needed this for IE-
$('input:text').attr("disabled", 'disabled');
I also had to add this for Chrome and Firefox -
$('input:text').AddClass("notactive");
and this -
<style type="text/css">
.notactive {
pointer-events: none;
cursor: default;
}
</style>
You are supposed to download the jar files that contain these libraries. Libraries may be used by adding them to the classpath.
For Commons Net you need to download the binary files from Commons Net download page. Then you have to extract the file and add the commons-net-2-2.jar file to some location where you can access it from your application e.g. to /lib.
If you're running your application from the command-line you'll have to define the classpath in the java command: java -cp .;lib/commons-net-2-2.jar myapp
. More info about how to set the classpath can be found from Oracle documentation. You must specify all directories and jar files you'll need in the classpath excluding those implicitely provided by the Java runtime. Notice that there is '.' in the classpath, it is used to include the current directory in case your compiled class is located in the current directory.
For more advanced reading, you might want to read about how to define the classpath for your own jar files, or the directory structure of a war file when you're creating a web application.
If you are using an IDE, such as Eclipse, you have to remember to add the library to your build path before the IDE will recognize it and allow you to use the library.
The last place I had to unbox something was when writing some code that retrieved some data from a database (I wasn't using LINQ to SQL, just plain old ADO.NET):
int myIntValue = (int)reader["MyIntValue"];
Basically, if you're working with older APIs before generics, you'll encounter boxing. Other than that, it isn't that common.
Running an SQL query in PHPmyadmin to find and replace text in all wordpress blog posts, such as finding mysite.com/wordpress and replacing that with mysite.com/news Table in this example is tj_posts
UPDATE `tj_posts`
SET `post_content` = replace(post_content, 'mysite.com/wordpress', 'mysite.com/news')
fun isAppInForeground(): Boolean {
val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager ?: return false
val appProcesses = activityManager.runningAppProcesses ?: return false
val packageName = packageName
for (appProcess in appProcesses) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName == packageName) {
return true
}
}
return false
}
Looks like simply putting the link like this
http://dl.google.com/android/ndk/android-ndk-r7c-windows.zip
on the address bar of your browser
The revision names (r7c, r8c etc.) could be found from the ndk download page
Can someone help me with the exact syntax?
It's a three-step process, and it involves modifying the openssl.cnf
file. You might be able to do it with only command line options, but I don't do it that way.
Find your openssl.cnf
file. It is likely located in /usr/lib/ssl/openssl.cnf
:
$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf
On my Debian system, /usr/lib/ssl/openssl.cnf
is used by the built-in openssl
program. On recent Debian systems it is located at /etc/ssl/openssl.cnf
You can determine which openssl.cnf
is being used by adding a spurious XXX
to the file and see if openssl
chokes.
First, modify the req
parameters. Add an alternate_names
section to openssl.cnf
with the names you want to use. There are no existing alternate_names
sections, so it does not matter where you add it.
[ alternate_names ]
DNS.1 = example.com
DNS.2 = www.example.com
DNS.3 = mail.example.com
DNS.4 = ftp.example.com
Next, add the following to the existing [ v3_ca ]
section. Search for the exact string [ v3_ca ]
:
subjectAltName = @alternate_names
You might change keyUsage
to the following under [ v3_ca ]
:
keyUsage = digitalSignature, keyEncipherment
digitalSignature
and keyEncipherment
are standard fare for a server certificate. Don't worry about nonRepudiation
. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.
In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.
Second, modify the signing parameters. Find this line under the CA_default
section:
# Extension copying option: use with caution.
# copy_extensions = copy
And change it to:
# Extension copying option: use with caution.
copy_extensions = copy
This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.
Third, generate your self-signed certificate:
$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...
Finally, examine the certificate:
$ openssl x509 -in certificate.pem -text -noout
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 9647297427330319047 (0x85e215e5869042c7)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
Validity
Not Before: Feb 1 05:23:05 2014 GMT
Not After : Feb 1 05:23:05 2016 GMT
Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (3072 bit)
Modulus:
00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
...
d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
72:1c:45:92:2c:88:a9:be:0b:f9
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Key Identifier:
34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
X509v3 Authority Key Identifier:
keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
X509v3 Basic Constraints: critical
CA:FALSE
X509v3 Key Usage:
Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
X509v3 Subject Alternative Name:
DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
Signature Algorithm: sha256WithRSAEncryption
3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
...
71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
8b:0a:bd:65:03:d1
If you happen to be an iOS developer
:
Check how many simulators that you have downloaded as they take up a lot of space:
Go to: ~/Library/Developer/Xcode/iOS DeviceSupport
Also delete old archived apps:
Go to: ~/Library/Developer/Xcode/Archives
I cleared 100GB doing this.
You can use fork() to detach your script from the tty and have it continue to run, like so:
import os, sys
fpid = os.fork()
if fpid!=0:
# Running as daemon now. PID is fpid
sys.exit(0)
Of course you also need to implement an endless loop, like
while 1:
do_your_check()
sleep(5)
Hope this get's you started.
:before
and :after
render inside a containerand <input> can not contain other elements.
Pseudo-elements can only be defined (or better said are only supported) on container elements. Because the way they are rendered is within the container itself as a child element. input
can not contain other elements hence they're not supported. A button
on the other hand that's also a form element supports them, because it's a container of other sub-elements.
If you ask me, if some browser does display these two pseudo-elements on non-container elements, it's a bug and a non-standard conformance. Specification directly talks about element content...
If we carefully read the specification it actually says that they are inserted inside a containing element:
Authors specify the style and location of generated content with the :before and :after pseudo-elements. As their names indicate, the :before and :after pseudo-elements specify the location of content before and after an element's document tree content. The 'content' property, in conjunction with these pseudo-elements, specifies what is inserted.
See? an element's document tree content. As I understand it this means within a container.
It's worth noting, since it's confusing for people new to XML, that the root (or document node) of an XML document is not the top-level element. It's the parent of the top-level element. This is confusing because it doesn't seem like the top-level element can have a parent. Isn't it the top level?
But look at this, a well-formed XML document:
<?xml-stylesheet href="my_transform.xsl" type="text/xsl"?>
<!-- Comments and processing instructions are XML nodes too, remember. -->
<TopLevelElement/>
The root of this document has three children: a processing instruction, a comment, and an element.
So, for example, if you wanted to write a transform that got rid of that comment, but left in any comments appearing anywhere else in the document, you'd add this to the identity transform:
<xsl:template match="/comment()"/>
Even simpler (and more commonly useful), here's an XPath pattern that matches the document's top-level element irrespective of its name: /*
.
You can enter array with duplicates and below method will return array with unique elements.
function getUniqueArray(array){
var uniqueArray = [];
if (array.length > 0) {
uniqueArray[0] = array[0];
}
for(var i = 0; i < array.length; i++){
var isExist = false;
for(var j = 0; j < uniqueArray.length; j++){
if(array[i] == uniqueArray[j]){
isExist = true;
break;
}
else{
isExist = false;
}
}
if(isExist == false){
uniqueArray[uniqueArray.length] = array[i];
}
}
return uniqueArray;
}
If you don't have a modifiable lvalue of an iterator, or it is desired to get a copy of a given iterator (leaving the original one unchanged), then C++11 comes with new helper functions - std::next
/ std::prev
:
std::next(iter, 2); // returns a copy of iter incremented by 2
std::next(std::begin(v), 2); // returns a copy of begin(v) incremented by 2
std::prev(iter, 2); // returns a copy of iter decremented by 2
Let's say you're building some chairs.
The diagram that shows how to build a chair and put it together corresponds to a software class.
Let's say you build five chairs according to the pattern in that diagram. Likewise, you could construct five software objects according to the pattern in a class.
Each chair has a unique number burned into the bottom of the seat to identify each specific chair. Chair 3 is one instance of a chair pattern. Likewise, memory location 3 can contain one instance of a software pattern.
So, an instance (chair 3) is a single unique, specific manifestation of a chair pattern.
That's not how it works.
This bit ('AND' and 'OR' and 'NOT')
will evaluate as 'NOT'
. So your code is equivalent to::
while not 'NOT' in list: print 'No boolean operator'
You could try this:
while not set('AND' and 'OR' and 'NOT').union(list): print 'No boolean operator'
String 1:
$input =~ /'^\S+'/;
$s1 = $&;
String 2:
$input =~ /\(.*\)/;
$s2 = $&;
String 3:
$input =~ /\*?$/;
$s3 = $&;
This answer is very late but what I do is set a class that holds Booleans, arrays, and integer-initial values as global scope static variables. Any constant strings are defined as such.
define("myconstant", "value");
class globalVars {
static $a = false;
static $b = 0;
static $c = array('first' => 2, 'second' => 5);
}
function test($num) {
if (!globalVars::$a) {
$returnVal = 'The ' . myconstant . ' of ' . $num . ' plus ' . globalVars::$b . ' plus ' . globalVars::$c['second'] . ' is ' . ($num + globalVars::$b + globalVars::$c['second']) . '.';
globalVars::$a = true;
} else {
$returnVal = 'I forgot';
}
return $returnVal;
}
echo test(9); ---> The value of 9 + 0 + 5 is 14.
echo "<br>";
echo globalVars::$a; ----> 1
The static
keywords must be present in the class else the vars $a, $b, and $c will not be globally scoped.
I have answered this question here..Covariant virtual functions return type problem
See if it helps for some one.
this is probably a late answer but i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializer
will have to inject it to your controller
so you can simply do the following without having to use Jquery at all ,
$http.post(url,$httpParamSerializer({param:val}))
app.controller('ctrl',function($scope,$http,$httpParamSerializer){
$http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}
In bash foo
is the name of the variable, and $
is an operator which means 'get the value of'.
In perl $foo
is the name of the variable.
First off, I think mplot3D
worked a bit differently in matplotlib
version 0.99
than it does in the current version of matplotlib
.
Which version are you using? (Try running: python -c 'import matplotlib; print matplotlib."__version__")
I'm guessing you're running version 0.99
, in which case you'll need to either use a slightly different syntax or update to a more recent version of matplotlib
.
If you're running version 0.99
, try doing this instead of using using the projection
keyword argument:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D #<-- Note the capitalization!
fig = plt.figure()
ax = Axes3D(fig) #<-- Note the difference from your original code...
X, Y, Z = axes3d.get_test_data(0.05)
cset = ax.contour(X, Y, Z, 16, extend3d=True)
ax.clabel(cset, fontsize=9, inline=1)
plt.show()
This should work in matplotlib
1.0.x
, as well, not just 0.99
.
I happen to miss spaces in my query and this error comes.
Ex: $sql= "SELECT * FROM";
$sql .= "table1";
Though the example might look simple, when coding complex queries, the probability for this error is high. I was missing space before word "table1".
This question contains some useful links on headless builds, but they are mostly geared towards building plugins. I'm not sure how much of it can be applied to pure Java projects.
This problem happened for me only in special cases, when I called website from some internet providers,
I've configured only ip v4 in VirtualHost configuration of apache, but some of router use ip v6, and when I added ip v6 to apache config the problem solved.
Consider TCP over ATM. ATM uses 48 byte frames, but clearly TCP packets can be bigger than that. A frame is the chunk of data sent as a unit over the data link (Ethernet, ATM). A packet is the chunk of data sent as a unit over the layer above it (IP). If the data link is made specifically for IP, as Ethernet and WiFi are, these will be the same size and packets will correspond to frames.
I think this will help : In Controller get the list items and selected value
public ActionResult Edit(int id)
{
ItemsStore item = itemStoreRepository.FindById(id);
ViewBag.CategoryId = new SelectList(categoryRepository.Query().Get(),
"Id", "Name",item.CategoryId);
// ViewBag to pass values to View and SelectList
//(get list of items,valuefield,textfield,selectedValue)
return View(item);
}
and in View
@Html.DropDownList("CategoryId",String.Empty)
If you're looking to create an HTML document similar to how you would create an XML document in C#, you could try Microsoft's open source library, the Html Agility Pack.
It provides an HtmlDocument object that has a very similar API to the System.Xml.XmlDocument
class.
This configuration is working for me:
set termout off
set verify off
set trimspool on
set linesize 200
set longchunksize 200000
set long 200000
set pages 0
column txt format a120
The column
format definition with the linesize
option helped to avoid the truncation at 80 chars.
[2021 changelog: bugfix for option4: no total ordering on js objects (even excluding NaN!=NaN
and '5'==5
('5'===5
, '2'<3
, etc.)), so cannot use .sort
on Map.keys() (though you can on Object.keys(obj)
, since even 'numerical' keys are strings)]
Option 1
Easiest option, works in almost all cases, except that null
!==undefined
but they both are converted to JSON representation null
and considered equal:
function arraysEqual(a1,a2) {
/* WARNING: arrays must not contain {objects} or behavior may be undefined */
return JSON.stringify(a1)==JSON.stringify(a2);
}
(This might not work if your array contains objects. Whether this still works with objects depends on whether the JSON implementation sorts keys. For example, the JSON of {1:2,3:4}
may or may not be equal to {3:4,1:2}
; this depends on the implementation, and the spec makes no guarantee whatsoever. [2017 update: Actually the ES6 specification now guarantees object keys will be iterated in order of 1) integer properties, 2) properties in the order they were defined, then 3) symbol properties in the order they were defined. Thus IF the JSON.stringify implementation follows this, equal objects (in the === sense but NOT NECESSARILY in the == sense) will stringify to equal values. More research needed. So I guess you could make an evil clone of an object with properties in the reverse order, but I cannot imagine it ever happening by accident...] At least on Chrome, the JSON.stringify function tends to return keys in the order they were defined (at least that I've noticed), but this behavior is very much subject to change at any point and should not be relied upon. If you choose not to use objects in your lists, this should work fine. If you do have objects in your list that all have a unique id, you can do a1.map(function(x)}{return {id:x.uniqueId}})
. If you have arbitrary objects in your list, you can read on for option #2.)
This works for nested arrays as well.
It is, however, slightly inefficient because of the overhead of creating these strings and garbage-collecting them.
Option 2
More "proper" option, which you can override to deal with special cases (like regular objects and null/undefined and custom objects, if you so desire):
// generally useful functions
function type(x) { // does not work in general, but works on JSONable objects we care about... modify as you see fit
// e.g. type(/asdf/g) --> "[object RegExp]"
return Object.prototype.toString.call(x);
}
function zip(arrays) {
// e.g. zip([[1,2,3],[4,5,6]]) --> [[1,4],[2,5],[3,6]]
return arrays[0].map(function(_,i){
return arrays.map(function(array){return array[i]})
});
}
// helper functions
function allCompareEqual(array) {
// e.g. allCompareEqual([2,2,2,2]) --> true
// does not work with nested arrays or objects
return array.every(function(x){return x==array[0]});
}
function isArray(x){ return type(x)==type([]) }
function getLength(x){ return x.length }
function allTrue(array){ return array.reduce(function(a,b){return a&&b},true) }
// e.g. allTrue([true,true,true,true]) --> true
// or just array.every(function(x){return x});
function allDeepEqual(things) {
// works with nested arrays
if( things.every(isArray) )
return allCompareEqual(things.map(getLength)) // all arrays of same length
&& allTrue(zip(things).map(allDeepEqual)); // elements recursively equal
//else if( this.every(isObject) )
// return {all have exactly same keys, and for
// each key k, allDeepEqual([o1[k],o2[k],...])}
// e.g. ... && allTrue(objectZip(objects).map(allDeepEqual))
//else if( ... )
// extend some more
else
return allCompareEqual(things);
}
Demo:
allDeepEqual([ [], [], [] ])
true
allDeepEqual([ [1], [1], [1] ])
true
allDeepEqual([ [1,2], [1,2] ])
true
allDeepEqual([ [[1,2],[3]], [[1,2],[3]] ])
true
allDeepEqual([ [1,2,3], [1,2,3,4] ])
false
allDeepEqual([ [[1,2],[3]], [[1,2],[],3] ])
false
allDeepEqual([ [[1,2],[3]], [[1],[2,3]] ])
false
allDeepEqual([ [[1,2],3], [1,[2,3]] ])
false
To use this like a regular function, do:
function allDeepEqual2() {
return allDeepEqual([].slice.call(arguments));
}
Demo:
allDeepEqual2([[1,2],3], [[1,2],3])
true
Options 3
edit: It's 2016 and my previous overcomplicated answer was bugging me. This recursive, imperative "recursive programming 101" implementation keeps the code really simple, and furthermore fails at the earliest possible point (giving us efficiency). It also doesn't generate superfluous ephemeral datastructures (not that there's anything wrong with functional programming in general, but just keeping it clean here).
If we wanted to apply this to a non-empty arrays of arrays, we could do seriesOfArrays.reduce(arraysEqual).
This is its own function, as opposed to using Object.defineProperties to attach to Array.prototype, since that would fail with a key error if we passed in an undefined value (that is however a fine design decision if you want to do so).
This only answers OPs original question.
function arraysEqual(a,b) {
/*
Array-aware equality checker:
Returns whether arguments a and b are == to each other;
however if they are equal-lengthed arrays, returns whether their
elements are pairwise == to each other recursively under this
definition.
*/
if (a instanceof Array && b instanceof Array) {
if (a.length!=b.length) // assert same length
return false;
for(var i=0; i<a.length; i++) // assert each element equal
if (!arraysEqual(a[i],b[i]))
return false;
return true;
} else {
return a==b; // if not both arrays, should be the same
}
}
Examples:
arraysEqual([[1,2],3], [[1,2],3])
true
arraysEqual([1,2,3], [1,2,3,4])
false
arraysEqual([[1,2],[3]], [[1,2],[],3])
false
arraysEqual([[1,2],[3]], [[1],[2,3]])
false
arraysEqual([[1,2],3], undefined)
false
arraysEqual(undefined, undefined)
true
arraysEqual(1, 2)
false
arraysEqual(null, null)
true
arraysEqual(1, 1)
true
arraysEqual([], 1)
false
arraysEqual([], undefined)
false
arraysEqual([], [])
true
If you wanted to apply this to JSON-like data structures with js Objects, you could do so. Fortunately we're guaranteed that all objects keys are unique, so iterate over the objects OwnProperties and sort them by key, then assert that both the sorted key-array is equal and the value-array are equal, and just recurse. We can extend this to include Maps as well (where the keys are also unique). (However if we extend this to Sets, we run into the tree isomorphism problem http://logic.pdmi.ras.ru/~smal/files/smal_jass08_slides.pdf - fortunately it's not as hard as general graph isomorphism; there is in fact an O(#vertices) algorithm to solve it, but it can get very complicated to do it efficiently. The pathological case is if you have a set made up of lots of seemingly-indistinguishable objects, but upon further inspection some of those objects may differ as you delve deeper into them. You can also work around this by using hashing to reject almost all cases.)
Option 4: (continuation of 2016 edit)
This should work with most objects:
const STRICT_EQUALITY = (a,b)=> a===b;
function deepEquals(a,b, areEqual=STRICT_EQUALITY) {
/* compares objects hierarchically using the provided
notion of equality (defaulting to ===);
supports Arrays, Objects, Maps, ArrayBuffers */
if (a instanceof Array && b instanceof Array)
return arraysEqual(a,b, areEqual);
if (Object.getPrototypeOf(a)===Object.prototype && Object.getPrototypeOf(b)===Object.prototype)
return objectsEqual(a,b, areEqual);
if (a instanceof Map && b instanceof Map)
return mapsEqual(a,b, areEqual);
if (a instanceof Set && b instanceof Set) {
if (areEquals===STRICT_EQUALITY)
return setsEqual(a,b);
else
throw "Error: set equality by hashing not implemented because cannot guarantee custom notion of equality is transitive without programmer intervention."
}
if ((a instanceof ArrayBuffer || ArrayBuffer.isView(a)) && (b instanceof ArrayBuffer || ArrayBuffer.isView(b)))
return typedArraysEqual(a,b);
return areEqual(a,b); // see note[1] -- IMPORTANT
}
function arraysEqual(a,b, areEqual) {
if (a.length!=b.length)
return false;
for(var i=0; i<a.length; i++)
if (!deepEquals(a[i],b[i], areEqual))
return false;
return true;
}
function objectsEqual(a,b, areEqual) {
var aKeys = Object.getOwnPropertyNames(a);
var bKeys = Object.getOwnPropertyNames(b);
if (aKeys.length!=bKeys.length)
return false;
aKeys.sort();
bKeys.sort();
for(var i=0; i<aKeys.length; i++)
if (!areEqual(aKeys[i],bKeys[i])) // keys must be strings
return false;
return deepEquals(aKeys.map(k=>a[k]), aKeys.map(k=>b[k]), areEqual);
}
function mapsEqual(a,b, areEqual) { // assumes Map's keys use the '===' notion of equality, which is also the assumption of .has and .get methods in the spec; however, Map's values use our notion of the areEqual parameter
if (a.size!=b.size)
return false;
return [...a.keys()].every(k=>
b.has(k) && deepEquals(a.get(k), b.get(k), areEqual)
);
}
function setsEqual(a,b) {
// see discussion in below rest of StackOverflow answer
return a.size==b.size && [...a.keys()].every(k=>
b.has(k)
);
}
function typedArraysEqual(a,b) {
// we use the obvious notion of equality for binary data
a = new Uint8Array(a);
b = new Uint8Array(b);
if (a.length != b.length)
return false;
for(var i=0; i<a.length; i++)
if (a[i]!=b[i])
return false;
return true;
}
Demo (not extensively tested):
var nineTen = new Float32Array(2);
nineTen[0]=9; nineTen[1]=10;
> deepEquals(
[[1,[2,3]], 4, {a:5,'111':6}, new Map([['c',7],['d',8]]), nineTen],
[[1,[2,3]], 4, {111:6,a:5}, new Map([['d',8],['c',7]]), nineTen]
)
true
> deepEquals(
[[1,[2,3]], 4, {a:'5','111':6}, new Map([['c',7],['d',8]]), nineTen],
[[1,[2,3]], 4, {111:6,a:5}, new Map([['d',8],['c',7]]), nineTen],
(a,b)=>a==b
)
true
Note that if one is using the ==
notion of equality, then know that falsey values and coercion means that ==
equality is NOT TRANSITIVE. For example ''==0
and 0=='0'
but ''!='0'
. This is relevant for Sets: I do not think one can override the notion of Set equality in a meaningful way. If one is using the built-in notion of Set equality (that is, ===
), then the above should work. However if one uses a non-transitive notion of equality like ==
, you open a can of worms: Even if you forced the user to define a hash function on the domain (hash(a)!=hash(b) implies a!=b) I'm not sure that would help... Certainly one could do the O(N^2) performance thing and remove pairs of ==
items one by one like a bubble sort, and then do a second O(N^2) pass to confirm things in equivalence classes are actually ==
to each other, and also !=
to everything not thus paired, but you'd STILL have to throw a runtime error if you have some coercion going on... You'd also maybe get weird (but potentially not that weird) edge cases with https://developer.mozilla.org/en-US/docs/Glossary/Falsy and Truthy values (with the exception that NaN==NaN... but just for Sets!). This is not an issue usually with most Sets of homogenous datatype.
(sidenote: Maps are es6 dictionaries. I can't tell if they have O(1) or O(log(N)) lookup performance, but in any case they are 'ordered' in the sense that they keep track of the order in which key-value pairs were inserted into them. However, the semantic of whether two Maps should be equal if elements were inserted in a different order into them is ambiguous. I give a sample implementation below of a deepEquals that considers two maps equal even if elements were inserted into them in a different order.)
(note [1]: IMPORTANT: NOTION OF EQUALITY: You may want to override the noted line with a custom notion of equality, which you'll also have to change in the other functions anywhere it appears. For example, do you or don't you want NaN==NaN? By default this is not the case. There are even more weird things like 0=='0'. Do you consider two objects to be the same if and only if they are the same object in memory? See https://stackoverflow.com/a/5447170/711085 . You should document the notion of equality you use. )
You should be able to extend the above to WeakMaps, WeakSets. Not sure if it makes sense to extend to DataViews. Should also be able to extend to RegExps probably, etc.
As you extend it, you realize you do lots of unnecessary comparisons. This is where the type
function that I defined way earlier (solution #2) can come in handy; then you can dispatch instantly. Whether that is worth the overhead of (possibly? not sure how it works under the hood) string representing the type is up to you. You can just then rewrite the dispatcher, i.e. the function deepEquals
, to be something like:
var dispatchTypeEquals = {
number: function(a,b) {...a==b...},
array: function(a,b) {...deepEquals(x,y)...},
...
}
function deepEquals(a,b) {
var typeA = extractType(a);
var typeB = extractType(a);
return typeA==typeB && dispatchTypeEquals[typeA](a,b);
}
The following steps worked on Pop!_OS 20.10 & ubuntu 20.04
In v2.0 of the Graph API, calling /me/friends
returns the person's friends who also use the app.
In addition, in v2.0, you must request the user_friends
permission from each user. user_friends
is no longer included by default in every login. Each user must grant the user_friends
permission in order to appear in the response to /me/friends
. See the Facebook upgrade guide for more detailed information, or review the summary below.
The /me/friendlists
endpoint and user_friendlists
permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.
If you want to access a list of non-app-using friends, there are two options:
If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends
API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.
If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends
endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.
In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends
permission).
For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.
You can also make a simple function in first level derived class, to call grand base function