<TextBlock Text="{Binding Date, StringFormat='{}{0:MM/dd/yyyy a\\t h:mm tt}'}" />
will return you
04/07/2011 at 1:28 PM (-04)
try this
PictureBox picture = new PictureBox
{
Name = "pictureBox",
Size = new Size(100, 50),
Location = new Point(14, 17),
Image = Image.FromFile(@"c:\Images\test.jpg"),
SizeMode = PictureBoxSizeMode.CenterImage
};
p.Controls.Add(picture);
SelectedItem
is an object
.
SelectedValue
and SelectedValuePath
are string
s.
for example using the ListBox:
if you say give me listbox1.SelectedValue
it will return the text of the currently selected item.
string value = listbox1.SelectedValue;
if you say give me listbox1.SelectedItem
it will give you the entire object.
ListItem item = listbox1.SelectedItem;
string value = item.value;
Use Enumerable.Select<TSource, TResult> Method (IEnumerable<TSource>, Func<TSource, Int32, TResult>)
list = list.Cast<object>().Select( (v, i) => new {Value= v, Index = i});
foreach(var row in list)
{
bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row.Value)).IsChecked;
row.Index ...
}
My approach inherits StackPanel.
Usage:
<Controls:ItemSpacer Grid.Row="2" Orientation="Horizontal" Height="30" CellPadding="15,0">
<Label>Test 1</Label>
<Label>Test 2</Label>
<Label>Test 3</Label>
</Controls:ItemSpacer>
All that's needed is the following short class:
using System.Windows;
using System.Windows.Controls;
using System;
namespace Controls
{
public class ItemSpacer : StackPanel
{
public static DependencyProperty CellPaddingProperty = DependencyProperty.Register("CellPadding", typeof(Thickness), typeof(ItemSpacer), new FrameworkPropertyMetadata(default(Thickness), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnCellPaddingChanged));
public Thickness CellPadding
{
get
{
return (Thickness)GetValue(CellPaddingProperty);
}
set
{
SetValue(CellPaddingProperty, value);
}
}
private static void OnCellPaddingChanged(DependencyObject Object, DependencyPropertyChangedEventArgs e)
{
((ItemSpacer)Object).SetPadding();
}
private void SetPadding()
{
foreach (UIElement Element in Children)
{
(Element as FrameworkElement).Margin = this.CellPadding;
}
}
public ItemSpacer()
{
this.LayoutUpdated += PART_Host_LayoutUpdated;
}
private void PART_Host_LayoutUpdated(object sender, System.EventArgs e)
{
this.SetPadding();
}
}
}
In case of WSS 3.0 recently I experienced same issue. It was because of column that was accessed from code was not present in the wss list.
Hi easiest way to do this is to convert this IEnumerable into a Queryable
If it is a queryable, then performing queries becomes easy.
Please check this code:
var result = (from s in _ctx.ScannedDatas.AsQueryable()
where s.Data == scanData
select s.Id).FirstOrDefault();
return "Match Found";
Make sure you include System.Linq. This way your error will be resolved.
In App.xaml file:
<Application.Resources>
<Style TargetType="TextBox">
<EventSetter Event="GotKeyboardFocus" Handler="TextBox_GotKeyboardFocus"/>
</Style>
</Application.Resources>
In App.xaml.cs file:
private void TextBox_GotKeyboardFocus(Object sender, KeyboardFocusChangedEventArgs e)
{
((TextBox)sender).SelectAll();
}
With this code you reach all TextBox
in your application.
1) I had to do the following with my configuration: (Add BackConnectionHostNames or Disable Loopback Check) http://support.microsoft.com/kb/896861
2) I was working off a dev system on an isolated dev network. I had gotten it working using the dev system's computer name in the URL to the web service, but when I modified the URL to the URL that would be used in production (rather than the computer name), I started getting the NTLM error.
3) I noticed the security log showed that the service account failing to login with an error similar to the one in the MSDN article.
4) Adding the BackConnectionHostNames made it so I could log into the server via a browser running on the server, but the service account still had NTLM errors when trying to authenticate for the web services. I wound up disabling the loop back check and that fixed it for me.
The .NET framework actually provides an interface that you can use for notifying subscribers when a property has changed: System.ComponentModel.INotifyPropertyChanged. This interface has one event PropertyChanged. Its usually used in WPF for binding but I have found it useful in business layers as a way to standardize property change notification.
In terms of thread safety I would put a lock under in the setter so that you don't run into any race conditions.
Here are my thoughts in code :) :
public class MyClass : INotifyPropertyChanged
{
private object _lock;
public int MyProperty
{
get
{
return _myProperty;
}
set
{
lock(_lock)
{
//The property changed event will get fired whenever
//the value changes. The subscriber will do work if the value is
//1. This way you can keep your business logic outside of the setter
if(value != _myProperty)
{
_myProperty = value;
NotifyPropertyChanged("MyProperty");
}
}
}
}
private NotifyPropertyChanged(string propertyName)
{
//Raise PropertyChanged event
}
public event PropertyChangedEventHandler PropertyChanged;
}
public class MySubscriber
{
private MyClass _myClass;
void PropertyChangedInMyClass(object sender, PropertyChangedEventArgs e)
{
switch(e.PropertyName)
{
case "MyProperty":
DoWorkOnMyProperty(_myClass.MyProperty);
break;
}
}
void DoWorkOnMyProperty(int newValue)
{
if(newValue == 1)
{
//DO WORK HERE
}
}
}
Hope this is helpful :)
Try setting the models to environment and static. That fix my issue.
From the friendly Wikipedia:
The stdlib.h and stddef.h header files define a datatype called size_t which is used to represent the size of an object. Library functions that take sizes expect them to be of type size_t, and the sizeof operator evaluates to size_t.
The actual type of size_t is platform-dependent; a common mistake is to assume size_t is the same as unsigned int, which can lead to programming errors, particularly as 64-bit architectures become more prevalent.
Also, check Why size_t matters
I followed a post in this thread and got it working perfectly:
Make the bat file with the following, and save it anywhere in your PATH. I suggest C:\Program Files\Java\jdk*\bin\ to keep everything together.
@ECHO OFF
cd %~dp1
javac %~nx1
java %~n1
then edit C:\Users\your_user_name\AppData\Roaming\Sublime Text 2\Packages\Java\JavaC.sublime-build, the contents will be
{
"cmd": ["javac", "$file"],
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"selector": "source.java"
}
replace "javac" with the name of your bat file (for instance, javacexec.bat) and save it.
I just ran into this problem too, so just in case anyone needs it: The reason why it needs admin privileges is probably because of your settings on where it store the virtual device.. Go to Settings - Virtual Box - and change your virtual devices storage area. I got mine set to something like \Program Files\Genymotion, that's why it needs Admin privileges. I only blanked the field, clicked ok, and it got set to the default which is in my home directory.. After that no need to run as admin anymore..
(I need 50 reputations to comment, so had to use this answer..)
There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.
One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.
The subject is almost exhausted, I 'd like though to offer a solution to a slightly more general version where you don't know the number of output columns, a priori. So for example you have
before = data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2', 'foo_and_bar_2_and_bar_3', 'foo_and_bar'))
attr type
1 1 foo_and_bar
2 30 foo_and_bar_2
3 4 foo_and_bar_2_and_bar_3
4 6 foo_and_bar
We can't use dplyr separate()
because we don't know the number of the result columns before the split, so I have then created a function that uses stringr
to split a column, given the pattern and a name prefix for the generated columns. I hope the coding patterns used, are correct.
split_into_multiple <- function(column, pattern = ", ", into_prefix){
cols <- str_split_fixed(column, pattern, n = Inf)
# Sub out the ""'s returned by filling the matrix to the right, with NAs which are useful
cols[which(cols == "")] <- NA
cols <- as.tibble(cols)
# name the 'cols' tibble as 'into_prefix_1', 'into_prefix_2', ..., 'into_prefix_m'
# where m = # columns of 'cols'
m <- dim(cols)[2]
names(cols) <- paste(into_prefix, 1:m, sep = "_")
return(cols)
}
We can then use split_into_multiple
in a dplyr pipe as follows:
after <- before %>%
bind_cols(split_into_multiple(.$type, "_and_", "type")) %>%
# selecting those that start with 'type_' will remove the original 'type' column
select(attr, starts_with("type_"))
>after
attr type_1 type_2 type_3
1 1 foo bar <NA>
2 30 foo bar_2 <NA>
3 4 foo bar_2 bar_3
4 6 foo bar <NA>
And then we can use gather
to tidy up...
after %>%
gather(key, val, -attr, na.rm = T)
attr key val
1 1 type_1 foo
2 30 type_1 foo
3 4 type_1 foo
4 6 type_1 foo
5 1 type_2 bar
6 30 type_2 bar_2
7 4 type_2 bar_2
8 6 type_2 bar
11 4 type_3 bar_3
You can put the file "hibernate.cfg.xml" to the src folder (src\hibernate.cfg.xml) and then init the config as the code below:
Configuration configuration = new Configuration();
sessionFactory =configuration.configure().buildSessionFactory();
Use the EXECUTABLE_OUTPUT_PATH
CMake variable to set the needed path. For details, refer to the online CMake documentation:
This is how I do it.
[[[UIApplication sharedApplication] delegate] performSelector:@selector(nameofMethod)];
Dont forget to import.
#import "AppDelegate.h"
<input type="text" name="field" maxlength="8"
onkeypress="return onlyAlphabets(event,this);" />
function onlyAlphabets(e, t) {
try {
if (window.event) {
var charCode = window.event.keyCode;
}
else if (e) {
var charCode = e.which;
}
else { return true; }
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123))
return true;
else
return false;
}
catch (err) {
alert(err.Description);
}
}
If you have text inside a <div>
:
text-align: center;
vertical-align: middle;
display: table-cell;
If you want them to show up one at a time, you can do this:
import time
import sys
for i in range(20):
sys.stdout.write('a')
sys.stdout.flush()
time.sleep(0.5)
sys.stdout.flush()
is necessary to force the character to be written each time the loop is run.
I had 20.8 GB in the C:\Users\ggo\AppData\Local\Android\Sdk\system-images folder (6 android images: - android-10 - android-15 - android-21 - android-23 - android-25 - android-26 ).
I have compressed the C:\Users\ggo\AppData\Local\Android\Sdk\system-images folder.
Now it takes only 4.65 GB.
I did not encountered any problem up to now...
Compression seems to vary from 2/3 to 6, sometimes much more:
The IEnumerable<T>
interface does not include an indexer, you're probably confusing it with IList<T>
If the object really is an IList<T>
(e.g. List<T>
or an array T[]
), try making the reference to it of type IList<T>
too.
Otherwise, you can use myEnumerable.ElementAt(index)
which uses the Enumerable.ElementAt extension method. This should work for all IEnumerable<T>
s .
Note that unless the (run-time) object implements IList<T>
, this will cause all of the first index + 1
items to be enumerated, with all but the last being discarded.
EDIT:
As an explanation, IEnumerable<T>
is simply an interface that represents "that which exposes an enumerator." A concrete implementation may well be some sort of in-memory list that does allow fast-access by index, or it may not. For instance, it could be a collection that cannot efficiently satisfy such a query, such as a linked-list (as mentioned by James Curran). It may even be no sort of in-memory data-structure at all, such as an iterator, where items are generated ('yielded') on demand, or by an enumerator that fetches the items from some remote data-source. Because IEnumerable<T>
must support all these cases, indexers are excluded from its definition.
Ok found the answer. exchange()
is the best way. Oddly the HttpEntity
class doesn't have a setBody()
method (it has getBody()
), but it is still possible to set the request body, via the constructor.
// Create the request body as a MultiValueMap
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
body.add("field", "value");
// Note the body object as first parameter!
HttpEntity<?> httpEntity = new HttpEntity<Object>(body, requestHeaders);
ResponseEntity<MyModel> response = restTemplate.exchange("/api/url", HttpMethod.POST, httpEntity, MyModel.class);
isset
will return true even if the variable is "". isset
returns false only if a variable is null. What you should be doing:
if (!empty($web)) {
// foo
}
This will check that he variable is not empty.
Hope this helps
Cherry pick is to pick changes from a specific "commit". The simplest solution is to pick all changes of certain files is to use
git checkout source_branch <paths>...
In example:
$ git branch
* master
twitter_integration
$ git checkout twitter_integration app/models/avatar.rb db/migrate/20090223104419_create_avatars.rb test/unit/models/avatar_test.rb test/functional/models/avatar_test.rb
$ git status
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# new file: app/models/avatar.rb
# new file: db/migrate/20090223104419_create_avatars.rb
# new file: test/functional/models/avatar_test.rb
# new file: test/unit/models/avatar_test.rb
#
$ git commit -m "'Merge' avatar code from 'twitter_integration' branch"
[master]: created 4d3e37b: "'Merge' avatar code from 'twitter_integration' branch"
4 files changed, 72 insertions(+), 0 deletions(-)
create mode 100644 app/models/avatar.rb
create mode 100644 db/migrate/20090223104419_create_avatars.rb
create mode 100644 test/functional/models/avatar_test.rb
create mode 100644 test/unit/models/avatar_test.rb
Sources and full explanation http://jasonrudolph.com/blog/2009/02/25/git-tip-how-to-merge-specific-files-from-another-branch/
UPDATE:
With this method, git will not MERGE the file, it will just override any other change done on the destination branch. You will need to merge the changes manually:
$ git diff HEAD filename
The easiest way I've found is just
list(df.columns)
Personally I wouldn't want to change the globals, it's not that often I want to see all the columns names.
The easiest way is probably to create an std::bitset
representing the value, then stream that to cout
.
#include <bitset>
...
char a = -58;
std::bitset<8> x(a);
std::cout << x << '\n';
short c = -315;
std::bitset<16> y(c);
std::cout << y << '\n';
I agree with the previous answers, and is fine if you are ok to start in UTC. But I think it is also a common scenario for people to work with a tz aware value that has a datetime that has a non UTC local timezone.
If you were to just go by name, one would probably infer replace() will be applicable and produce the right datetime aware object. This is not the case.
the replace( tzinfo=... ) seems to be random in its behaviour. It is therefore useless. Do not use this!
localize is the correct function to use. Example:
localdatetime_aware = tz.localize(datetime_nonaware)
Or a more complete example:
import pytz
from datetime import datetime
pytz.timezone('Australia/Melbourne').localize(datetime.now())
gives me a timezone aware datetime value of the current local time:
datetime.datetime(2017, 11, 3, 7, 44, 51, 908574, tzinfo=<DstTzInfo 'Australia/Melbourne' AEDT+11:00:00 DST>)
Finding the duplicates in a String
:
public class a36 {
public static void main(String[] args) {
String a = "Gini Rani";
fix(a);
}//main
public static void fix(String a ){
Map<Character ,Integer> map = new HashMap<>();
for (int i = 0; i <a.length() ; i++ ) {
char ch = a.charAt(i);
map.put(ch , map.getOrDefault(ch,0) +1 );
}//for
List<Character> list = new ArrayList<>();
Set<Map.Entry<Character ,Integer> > entrySet = map.entrySet();
for ( Map.Entry<Character ,Integer> entry : entrySet) {
list.add( entry.getKey() );
System.out.printf( " %s : %d %n" , entry.getKey(), entry.getValue() );
}//for
System.out.println("Duplicate elements => " + list);
}//fix
}
public class a37 {
public static void main(String[] args) {
String aa = "Protijayi Gini";
String[] stringarray = aa.split("");
Map<String , Long> map = Arrays.stream(stringarray)
.collect(Collectors.groupingBy(c -> c , Collectors.counting()));
map.forEach( (k, v) -> System.out.println(k + " : "+ v) );
}
}
$("input[type=file]").wrap("<div id='fileWrapper'/>");
$("#fileWrapper").append("<div id='duplicateFile' style='display:none'>"+$("#fileWrapper").html()+"</div>");
$("#fileWrapper").html($("#duplicateFile").html());
You can use the sorted method with a key.
sorted(a, key=lambda x : x[1])
Passing data back from ViewController 2 (destination) to viewController 1 (source) is the more interesting thing. Assuming you use storyBoard, these are all the ways I found out:
Those were discussed here already.
I found there are more ways:
Using Block callbacks:
Use it in the prepareForSegue
method in the VC1
NextViewController *destinationVC = (NextViewController *) segue.destinationViewController;
[destinationVC setDidFinishUsingBlockCallback:^(NextViewController *destinationVC)
{
self.blockLabel.text = destination.blockTextField.text;
}];
Using storyboards Unwind (Exit)
Implement a method with a UIStoryboardSegue argument in VC 1,like this one:
-(IBAction)UnWindDone:(UIStoryboardSegue *)segue { }
In the storyBoard, hook the "return" button to the green Exit button (Unwind) of the vc. Now you have a segue that "goes back" so you can use the destinationViewController property in the prepareForSegue of VC2 and change any property of VC1 before it goes back.
Another option of using storyboards Undwind (Exit) - you can use the method you wrote in VC1
-(IBAction)UnWindDone:(UIStoryboardSegue *)segue {
NextViewController *nextViewController = segue.sourceViewController;
self.unwindLabel.text = nextViewController.unwindPropertyPass;
}
And in the prepareForSegue of VC1 you can change any property you want to share.
In both unwind options, you can set the tag property of the button and check it in the prepareForSegue.
These are extended operations (e.g., sort, reverse) for one dimensional and two dimensional arrays in Twig framework:
{% for key, value in array_one_dimension %}
<div>{{ key }}</div>
<div>{{ value }}</div>
{% endfor %}
{% for key, value in array_one_dimension|keys|sort %}
<div>{{ key }}</div>
<div>{{ value }}</div>
{% endfor %}
{% for key, value in array_one_dimension|keys|sort|reverse %}
<div>{{ key }}</div>
<div>{{ value }}</div>
{% endfor %}
{% for key_a, value_a in array_two_dimension %}
{% for key_b, value_b in array_two_dimension[key_a] %}
<div>{{ key_b }}</div>
<div>{{ value_b }}</div>
{% endfor %}
{% endfor %}
{% for key_a, value_a in array_two_dimension|keys|sort %}
{% for key_b, value_b in array_two_dimension[key_a] %}
<div>{{ key_b }}</div>
<div>{{ value_b }}</div>
{% endfor %}
{% endfor %}
{% for key_a, value_a in array_two_dimension|keys|sort %}
{% for key_b, value_b in array_two_dimension[key_a]|keys|sort %}
<div>{{ key_b }}</div>
<div>{{ value_b }}</div>
{% endfor %}
{% endfor %}
{% for key_a, value_a in array_two_dimension|keys|sort %}
{% for key_b, value_b in array_two_dimension[key_a]|keys|sort|reverse %}
<div>{{ key_b }}</div>
<div>{{ value_b }}</div>
{% endfor %}
{% endfor %}
{% for key_a, value_a in array_two_dimension|keys|sort|reverse %}
{% for key_b, value_b in array_two_dimension[key_a]|keys|sort %}
<div>{{ key_b }}</div>
<div>{{ value_b }}</div>
{% endfor %}
{% endfor %}
{% for key_a, value_a in array_two_dimension|keys|sort|reverse %}
{% for key_b, value_b in array_two_dimension[key_a]|keys|sort|reverse %}
<div>{{ key_b }}</div>
<div>{{ value_b }}</div>
{% endfor %}
{% endfor %}
I face similar issue while importing TensorFlow
. If you are using Tensorflow which uses Pandas library, I suggest restarting your kernel of Anaconda
. This works for me.
This is what the difference i found. Please let me know if any .
Add the jar files to your library(if using netbeans) and modify your manifest's file classpath
as follows:
Class-Path: lib/derby.jar lib/derbyclient.jar lib/derbynet.jar lib/derbytools.jar
a similar answer exists here
I had the same issue.
just removed all my worskspace:
C:\Users\<name>\.<eclipse similar name>
You can just use the -R (recursive) flag.
chmod -R 777 /Users/Test/Desktop/PATH
Because you can't count on a particular font being available, a good approach is to derive a new font from the current font. This gives you the same family, weight, etc. just larger...
Font currentFont = g.getFont();
Font newFont = currentFont.deriveFont(currentFont.getSize() * 1.4F);
g.setFont(newFont);
You can also use TextAttribute.
Map<TextAttribute, Object> attributes = new HashMap<>();
attributes.put(TextAttribute.FAMILY, currentFont.getFamily());
attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_SEMIBOLD);
attributes.put(TextAttribute.SIZE, (int) (currentFont.getSize() * 1.4));
myFont = Font.getFont(attributes);
g.setFont(myFont);
The TextAttribute method often gives one even greater flexibility. For example, you can set the weight to semi-bold, as in the example above.
One last suggestion... Because the resolution of monitors can be different and continues to increase with technology, avoid adding a specific amount (such as getSize()+2 or getSize()+4) and consider multiplying instead. This way, your new font is consistently proportional to the "current" font (getSize() * 1.4), and you won't be editing your code when you get one of those nice 4K monitors.
Maybe I'm overthinking this but..
str_l = next((k for k,v in locals().items() if id(l) == id(v)))
>>> bar = True
>>> foo = False
>>> my_dict=dict(bar=bar, foo=foo)
>>> next((k for k,v in locals().items() if id(bar) == id(v)))
'bar'
>>> next((k for k,v in locals().items() if id(foo) == id(v)))
'foo'
>>> next((k for k,v in locals().items() if id(my_dict) == id(v)))
'my_dict'
CSS doesn't really allow you to do this on a table level. Generally, I specify cellspacing="3"
when I want to achieve this effect. Obviously not a css solution, so take it for what it's worth.
for me setting the Dimensions to use % is what worked for me
width:'100%'
You can use the following method that will give you accurate result
public double CalculationByDistance(LatLng StartP, LatLng EndP) {
int Radius = 6371;// radius of earth in Km
double lat1 = StartP.latitude;
double lat2 = EndP.latitude;
double lon1 = StartP.longitude;
double lon2 = EndP.longitude;
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
+ Math.cos(Math.toRadians(lat1))
* Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2)
* Math.sin(dLon / 2);
double c = 2 * Math.asin(Math.sqrt(a));
double valueResult = Radius * c;
double km = valueResult / 1;
DecimalFormat newFormat = new DecimalFormat("####");
int kmInDec = Integer.valueOf(newFormat.format(km));
double meter = valueResult % 1000;
int meterInDec = Integer.valueOf(newFormat.format(meter));
Log.i("Radius Value", "" + valueResult + " KM " + kmInDec
+ " Meter " + meterInDec);
return Radius * c;
}
I answer to myself. As suggested by Vadzim, I must consider the jboss-logging.xml file and insert these lines:
<logger category="org.hibernate">
<level name="TRACE"/>
</logger>
Instead of DEBUG level I wrote TRACE. Now don't look only the console but open the server.log file (debug messages aren't sent to the console but you can configure this mode!).
MainActivity.java
package com.example.alarmexample;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startAlert();
} public void startAlert() {
int timeInSec = 2;
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
this.getApplicationContext(), 234, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (timeInSec * 1000), pendingIntent);
Toast.makeText(this, "Alarm set to after " + i + " seconds",Toast.LENGTH_LONG).show();
}
}
MyBroadcastReceiver.java
package com.example.alarmexample;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver {
MediaPlayer mp;
@Override
public void onReceive(Context context, Intent intent) {
mp=MediaPlayer.create(context, R.raw.alarm);
mp.start();
Toast.makeText(context, "Alarm", Toast.LENGTH_LONG).show();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alarmexample" >
<uses-permission android:name="android.permission.VIBRATE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.alarmexample.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="MyBroadcastReceiver" >
</receiver>
</application>
</manifest>
if someone still search for this, i do this:
import fs from 'fs';_x000D_
import path from 'path';_x000D_
_x000D_
const getAllFiles = dir =>_x000D_
fs.readdirSync(dir).reduce((files, file) => {_x000D_
const name = path.join(dir, file);_x000D_
const isDirectory = fs.statSync(name).isDirectory();_x000D_
return isDirectory ? [...files, ...getAllFiles(name)] : [...files, name];_x000D_
}, []);
_x000D_
and its work very good for me
Faster option:
The following code will copy your Pandas DF to postgres DB much faster than df.to_sql method and you won't need any intermediate csv file to store the df.
Create an engine based on your DB specifications.
Create a table in your postgres DB that has equal number of columns as the Dataframe (df).
Data in DF will get inserted in your postgres table.
from sqlalchemy import create_engine
import psycopg2
import io
if you want to replace the table, we can replace it with normal to_sql method using headers from our df and then load the entire big time consuming df into DB.
engine = create_engine('postgresql+psycopg2://username:password@host:port/database')
df.head(0).to_sql('table_name', engine, if_exists='replace',index=False) #drops old table and creates new empty table
conn = engine.raw_connection()
cur = conn.cursor()
output = io.StringIO()
df.to_csv(output, sep='\t', header=False, index=False)
output.seek(0)
contents = output.getvalue()
cur.copy_from(output, 'table_name', null="") # null values become ''
conn.commit()
You can compress the bitmap as an byte's array and then uncompress it in another activity, like this.
Compress!!
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();
setresult.putExtra("BMP",bytes);
Uncompress!!
byte[] bytes = data.getByteArrayExtra("BMP");
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
To bind a UDP socket when receiving multicast means to specify an address and port from which to receive data (NOT a local interface, as is the case for TCP acceptor bind). The address specified in this case has a filtering role, i.e. the socket will only receive datagrams sent to that multicast address & port, no matter what groups are subsequently joined by the socket. This explains why when binding to INADDR_ANY (0.0.0.0) I received datagrams sent to my multicast group, whereas when binding to any of the local interfaces I did not receive anything, even though the datagrams were being sent on the network to which that interface corresponded.
Quoting from UNIX® Network Programming Volume 1, Third Edition: The Sockets Networking API by W.R Stevens. 21.10. Sending and Receiving
[...] We want the receiving socket to bind the multicast group and port, say 239.255.1.2 port 8888. (Recall that we could just bind the wildcard IP address and port 8888, but binding the multicast address prevents the socket from receiving any other datagrams that might arrive destined for port 8888.) We then want the receiving socket to join the multicast group. The sending socket will send datagrams to this same multicast address and port, say 239.255.1.2 port 8888.
What's wrong with using two regexs (or three)? This makes your intentions more clear and may even improve your performance:
if ($string =~ /^(Clinton|Reagan)/i && $string !~ /Bush/i) { ... }
if (($string =~ /^Clinton/i || $string =~ /^Reagan/i)
&& $string !~ /Bush/i) {
print "$string\n"
}
I hope this is one of the basic conditional classes
Solution: 1
<section [ngClass]="(condition)? 'class1 class2 ... classN' : 'another class1 ... classN' ">
Solution 2
<section [ngClass]="(condition)? 'class1 class2 ... classN' : '(condition)? 'class1 class2 ... classN':'another class' ">
Solution 3
<section [ngClass]="'myclass': condition, 'className2': condition2">
You use jarsigner to sign APK's. You don't have to sign with the original keystore, just generate a new one. Read up on the details: http://developer.android.com/guide/publishing/app-signing.html
//1.
//Custom delegate
@protocol TB_RemovedUserCellTag <NSObject>
-(void)didRemoveCellWithTag:(NSInteger)tag;
@end
//2.
//Create a weak reference in a class where you declared the delegate
@property(weak,nonatomic)id <TB_RemovedUserCellTag> removedCellTagDelegate;
//3.
// use it in the class
[self.removedCellTagDelegate didRemoveCellWithTag:self.tag];
//4. import the header file in the class where you want to conform to the protocol
@interface MyClassUsesDelegate ()<TB_RemovedUserCellTag>
@end
//5. Implement the method in the class .m -(void)didRemoveCellWithTag:(NSInteger)tag { NSLog@("Tag %d",tag);
}
...but what about the previous round parenteses surrounding all the function declaration?
Specifically, it makes JavaScript interpret the 'function() {...}' construct as an inline anonymous function expression. If you omitted the brackets:
function() {
alert('hello');
}();
You'd get a syntax error, because the JS parser would see the 'function' keyword and assume you're starting a function statement of the form:
function doSomething() {
}
...and you can't have a function statement without a function name.
function expressions and function statements are two different constructs which are handled in very different ways. Unfortunately the syntax is almost identical, so it's not just confusing to the programmer, even the parser has difficulty telling which you mean!
Applies to Bootstrap 3 only.
Ignoring the letters (xs, sm, md, lg) for now, I'll start with just the numbers...
col-*-6
spans 6 of 12 columns (half the width), col-*-12
spans 12 of 12 columns (the entire width), etcSo, if you want two equal columns to span a div, write
<div class="col-xs-6">Column 1</div>
<div class="col-xs-6">Column 2</div>
Or, if you want three unequal columns to span that same width, you could write:
<div class="col-xs-2">Column 1</div>
<div class="col-xs-6">Column 2</div>
<div class="col-xs-4">Column 3</div>
You'll notice the # of columns always add up to 12. It can be less than twelve, but beware if more than 12, as your offending divs will bump down to the next row (not .row
, which is another story altogether).
You can also nest columns within columns, (best with a .row
wrapper around them) such as:
<div class="col-xs-6">
<div class="row">
<div class="col-xs-4">Column 1-a</div>
<div class="col-xs-8">Column 1-b</div>
</div>
</div>
<div class="col-xs-6">
<div class="row">
<div class="col-xs-2">Column 2-a</div>
<div class="col-xs-10">Column 2-b</div>
</div>
</div>
Each set of nested divs also span up to 12 columns of their parent div. NOTE: Since each .col
class has 15px padding on either side, you should usually wrap nested columns in a .row
, which has -15px margins. This avoids duplicating the padding and keeps the content lined up between nested and non-nested col classes.
-- You didn't specifically ask about the xs, sm, md, lg
usage, but they go hand-in-hand so I can't help but touch on it...
In short, they are used to define at which screen size that class should apply:
Read the "Grid Options" chapter from the official Bootstrap documentation for more details.
You should usually classify a div using multiple column classes so it behaves differently depending on the screen size (this is the heart of what makes bootstrap responsive). eg: a div with classes col-xs-6
and col-sm-4
will span half the screen on the mobile phone (xs) and 1/3 of the screen on tablets(sm).
<div class="col-xs-6 col-sm-4">Column 1</div> <!-- 1/2 width on mobile, 1/3 screen on tablet) -->
<div class="col-xs-6 col-sm-8">Column 2</div> <!-- 1/2 width on mobile, 2/3 width on tablet -->
NOTE: as per comment below, grid classes for a given screen size apply to that screen size and larger unless another declaration overrides it (i.e. col-xs-6 col-md-4
spans 6 columns on xs
and sm
, and 4 columns on md
and lg
, even though sm
and lg
were never explicitly declared)
NOTE: if you don't define xs
, it will default to col-xs-12
(i.e. col-sm-6
is half the width on sm
, md
and lg
screens, but full-width on xs
screens).
NOTE: it's actually totally fine if your .row
includes more than 12 cols, as long as you are aware of how they will react. --This is a contentious issue, and not everyone agrees.
this
is the key (vs evt.target). See example.
document.body.addEventListener("click", function (evt) {_x000D_
console.dir(this);_x000D_
//note evt.target can be a nested element, not the body element, resulting in misfires_x000D_
console.log(evt.target);_x000D_
alert("body clicked");_x000D_
});
_x000D_
<h4>This is a heading.</h4>_x000D_
<p>this is a paragraph.</p>
_x000D_
The latest build of the sublime even allows the direct command instead of double quotes. Try the below code for the build system
{
"cmd" : ["gcc $file_name -o ${file_base_name} && ./${file_base_name}"],
"selector" : "source.c",
"shell": true,
"working_dir" : "$file_path",
}
The simplest way to explain it would be to say that a data warehouse consists of more than just a database. A database is an collection of data organized in some way, but a data warehouse is organized specifically to "facilitate reporting and analysis". This however is not the entire story as data warehousing also contains "the means to retrieve and analyze data, to extract, transform and load data, and to manage the data dictionary are also considered essential components of a data warehousing system".
use the following command to install the specific version. say you want to install angular/cli version 1.6.8 then enter the following command :
sudo npm install -g @angular/[email protected]
this will install angular/cli version 1.6.8
UPDATE (Sept 4, 2020)
You can now use the ??
operator to validate null
and undefined
"values" and set a default value. For example:
const foo = null;
const bar = foo ?? 'exampleValue';
console.log(bar); // This will print 'exampleValue' due to the value condition of the foo constant, in this case, a null value
As a verbose way, if you want to compare null and undefined values ONLY, use the following example code for reference:
const incomingValue : string = undefined;
const somethingToCompare : string = incomingValue; // If the line above is not declared, TypeScript will return an excepion
if (somethingToCompare == (undefined || null)) {
console.log(`Incoming value is: ${somethingToCompare}`);
}
If incomingValue
is not declared, TypeScript should return an exception. If this is declared but not defined, the console.log()
will return "Incoming value is: undefined". Note we are not using the strict equals operator.
The "correct" way (check the other answers for details), if the incomingValue
is not a boolean
type, just evaluate if its value is true, this will be evaluated according to the constant/variable type. A true
string have to be defined explicitly as string using the = ''
assignation. If not, it will be evaluated as false
. Let's check this case using the same context:
const incomingValue : string = undefined;
const somethingToCompare0 : string = 'Trumpet';
const somethingToCompare1 : string = incomingValue;
if (somethingToCompare0) {
console.log(`somethingToCompare0 is: ${somethingToCompare0}`); // Will return "somethingToCompare0 is: Trumpet"
}
// Now, we will evaluate the second constant
if (somethingToCompare1) {
console.log(`somethingToCompare1 is: ${somethingToCompare1}`); // Launched if incomingValue is defined
} else {
console.log(`somethingToCompare1 is: ${somethingToCompare1}`); // Launched if incomingValue is undefined. Will return "somethingToCompare1 is: undefined"
}
This Works
function saveBase64AsFile(base64, fileName) {
var link = document.createElement("a");
document.body.appendChild(link);
link.setAttribute("type", "hidden");
link.href = "data:text/plain;base64," + base64;
link.download = fileName;
link.click();
document.body.removeChild(link);
}
Based on the answer above but with some changes
This is a simple reference:
// this is the id of the form
$("#idForm").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
To ignore all untracked files in any submodule use the following command to ignore those changes.
git config --global diff.ignoreSubmodules dirty
It will add the following configuration option to your local git config:
[diff]
ignoreSubmodules = dirty
Further information can be found here
Just to add, we can use array as well:
int i, array[4];
printf("Enter Four Ints: ");
for(i=0; i<4; i++) {
scanf("%d", &array[i]);
}
https://jumpcloud.com/blog/difference-between-ldap-and-active-directory/
Realistically, there are probably more differences than similarities between the two directory solutions. Microsoft’s AD is largely a directory for Windows users, devices, and applications. AD requires a Microsoft Domain Controller to be present and when it is, users are able to single sign-on to Windows resources that live within the domain structure.
LDAP, on the other hand, has largely worked outside of the Windows structure focusing on the Linux / Unix environment and with more technical applications. LDAP doesn’t have the same concepts of domains or single sign-on. LDAP is largely implemented with open source solutions and as a result has more flexibility than AD.
Another critical difference between LDAP and Active Directory is how AD and LDAP each approach device management. AD manages Windows devices through and Group Policy Objects (GPOs). A similar concept doesn’t exist within LDAP. Both LDAP and AD are highly different solutions and as a result many organization must leverage both to serve different purposes.
This is why there’s an obvious opportunity for innovation. Why leverage and manage two complete systems, when one system can effectively merge the two?
I had to change my password to the latest in the user.home/.m2/settings.xml file!
Can also see here on how to turn on MSDTC from the Control Panel's services.msc.
On the server where the trigger resides, you need to turn the MSDTC service on. You can this by clicking START > SETTINGS > CONTROL PANEL > ADMINISTRATIVE TOOLS > SERVICES. Find the service called 'Distributed Transaction Coordinator' and RIGHT CLICK (on it and select) > Start.
In 32 bit format system the hexadecimal value 0xff
represents 00000000000000000000000011111111
that is 255(15*16^1+15*16^0)
in decimal. and the bitwise & operator masks the same 8 right most bits as in first operand.
You can do it by following 3 steps:
- svn rm old_file_name
- svn add new_file_name
- svn commit
$_ is an alias for automatic variable $PSItem (introduced in PowerShell V3.0; Usage information found here) which represents the current item from the pipe.
PowerShell (v6.0) online documentation for automatic variables is here.
Within the body of a class, the class name isn't defined yet, so it is not available. Can you not simply type the name of the class? Maybe you need to say more about the problem so we can find a solution for you.
I would create a metaclass to do this work for you. It's invoked at class creation time (conceptually at the very end of the class: block), and can manipulate the class being created. I haven't tested this:
class InputAssigningMetaclass(type):
def __new__(cls, name, bases, attrs):
cls.input = get_input(name)
return super(MyType, cls).__new__(cls, name, bases, newattrs)
class MyBaseFoo(object):
__metaclass__ = InputAssigningMetaclass
class foo(MyBaseFoo):
# etc, no need to create 'input'
class foo2(MyBaseFoo):
# etc, no need to create 'input'
Generally VSCode uses the github credentials from system's credential manager, it doesn't store anywhere in the settings. As question says Changing the git user inside Visual Studio Code
, is not inside rather outside.
Search for or Go to credential manager (Windows control panel) -> Windows Credentials -> Update the GitHub password from the list.
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(function(mutations, observer) {
// fired when a mutation occurs
console.log(mutations, observer);
// ...
});
// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
subtree: true,
attributes: true
//...
});
Complete explanations: https://stackoverflow.com/a/11546242/6569224
In Rails 4.02+ according to the docs there is no method like update_all
with 2 arguments. Instead one can use this code:
# Make sure no null value exist
MyModel.where(date_column: nil).update_all(date_column: Time.now)
# Change the column to not allow null
change_column :my_models, :date_column, :datetime, null: false
Certificate must cover both www and non-www https. Some provider's certs cover both for www.xxxx.yyy, but only one for xxxx.yyy.
Turn on rewrites:
RewriteEngine On
Make all http use https:
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://xxx.yyy/$1 [L,R=301]
Make only www https use the non-www https:
RewriteCond %{SERVER_PORT} 443
RewriteCond %{HTTP_HOST} ^www[.].+$
RewriteRule ^(.*)$ https://xxxx.yyy/$1 [L,R=301]
Cannot be processing non-www https, otherwise a loop occurs.
In [L,R=301]:
More generic
A more generic approach -- not port-dependant -- is:
RewriteCond %{HTTP_HOST} ^www\.
RewriteRule ^(.*)$ https://xxxx.yyy/$1 [R=301,QSA]
to make any url with www
drop it.
RewriteCond %{HTTPS} !on
RewriteCond %{HTTPS} !1
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTP:X-Forwarded-SSL} !on
RewriteRule ^(.*)$ https://xxxx.yyy/$1 [R=301,QSA]
to force any non-https url, even for those system downstream from load-balancers that drop https, use https.
Note that I have not tested the forwarded
options, so would appreciate feedback on any issues with them. Those lines could be left out if your system is not behind a load-balancer.
TO HTTP_HOST or not
You can use ${HTTP_HOST}
to be part of the URL in the RewriteRule
, or you can use your explicit canonical domain name text (xxxx.yyy
above).
Specifying the domain name explicitly ensures that no slight-of-hand character-bending means are used in the user-supplied URL to possibly trick your site into doing something it might not be prepared for, or at least ensures that the proper domain name appears in the address bar, regardless of which URL string opened the page.
It might even help convert punycode-encoded domains to show the proper unicode characters in the address bar.
This has always worked well for me:
yAxes: [{
ticks: {
display: false;
},
Following code might be useful if someone is using React and has a different component of Marker and want to remove marker from map.
export default function useGoogleMapMarker(props) {
const [marker, setMarker] = useState();
useEffect(() => {
// ...code
const marker = new maps.Marker({ position, map, title, icon });
// ...code
setMarker(marker);
return () => marker.setMap(null); // to remove markers when unmounts
}, []);
return marker;
}
git commit -m "first commit"
git remote add origin <linkyourrepository>
git push -u origin master
will works!
A simple solution is to have your factory return an object and let your controllers work with a reference to the same object:
JS:
// declare the app with no dependencies
var myApp = angular.module('myApp', []);
// Create the factory that share the Fact
myApp.factory('Fact', function(){
return { Field: '' };
});
// Two controllers sharing an object that has a string in it
myApp.controller('FirstCtrl', function( $scope, Fact ){
$scope.Alpha = Fact;
});
myApp.controller('SecondCtrl', function( $scope, Fact ){
$scope.Beta = Fact;
});
HTML:
<div ng-controller="FirstCtrl">
<input type="text" ng-model="Alpha.Field">
First {{Alpha.Field}}
</div>
<div ng-controller="SecondCtrl">
<input type="text" ng-model="Beta.Field">
Second {{Beta.Field}}
</div>
Demo: http://jsfiddle.net/HEdJF/
When applications get larger, more complex and harder to test you might not want to expose the entire object from the factory this way, but instead give limited access for example via getters and setters:
myApp.factory('Data', function () {
var data = {
FirstName: ''
};
return {
getFirstName: function () {
return data.FirstName;
},
setFirstName: function (firstName) {
data.FirstName = firstName;
}
};
});
With this approach it is up to the consuming controllers to update the factory with new values, and to watch for changes to get them:
myApp.controller('FirstCtrl', function ($scope, Data) {
$scope.firstName = '';
$scope.$watch('firstName', function (newValue, oldValue) {
if (newValue !== oldValue) Data.setFirstName(newValue);
});
});
myApp.controller('SecondCtrl', function ($scope, Data) {
$scope.$watch(function () { return Data.getFirstName(); }, function (newValue, oldValue) {
if (newValue !== oldValue) $scope.firstName = newValue;
});
});
HTML:
<div ng-controller="FirstCtrl">
<input type="text" ng-model="firstName">
<br>Input is : <strong>{{firstName}}</strong>
</div>
<hr>
<div ng-controller="SecondCtrl">
Input should also be here: {{firstName}}
</div>
I got the same error and found the cause to be a wrong or missing foreign key. (Using JDBC)
For a more detailed answer on creating your own colormaps, I highly suggest visiting this page
If that answer is too much work, you can quickly make your own list of colors and pass them to the color
parameter. All the colormaps are in the cm
matplotlib module. Let's get a list of 30 RGB (plus alpha) color values from the reversed inferno colormap. To do so, first get the colormap and then pass it a sequence of values between 0 and 1. Here, we use np.linspace
to create 30 equally-spaced values between .4 and .8 that represent that portion of the colormap.
from matplotlib import cm
color = cm.inferno_r(np.linspace(.4, .8, 30))
color
array([[ 0.865006, 0.316822, 0.226055, 1. ],
[ 0.851384, 0.30226 , 0.239636, 1. ],
[ 0.832299, 0.283913, 0.257383, 1. ],
[ 0.817341, 0.270954, 0.27039 , 1. ],
[ 0.796607, 0.254728, 0.287264, 1. ],
[ 0.775059, 0.239667, 0.303526, 1. ],
[ 0.758422, 0.229097, 0.315266, 1. ],
[ 0.735683, 0.215906, 0.330245, 1. ],
.....
Then we can use this to plot, using the data from the original post:
import random
x = [{i: random.randint(1, 5)} for i in range(30)]
df = pd.DataFrame(x)
df.plot(kind='bar', stacked=True, color=color, legend=False, figsize=(12, 4))
I would give the requests library a try for this. Essentially just a much easier to use wrapper around the standard library modules (i.e. urllib2, httplib2, etc.) you would use for the same thing. For example, to fetch json data from a url that requires basic authentication would look like this:
import requests
response = requests.get('http://thedataishere.com',
auth=('user', 'password'))
data = response.json()
For kerberos authentication the requests project has the reqests-kerberos library which provides a kerberos authentication class that you can use with requests:
import requests
from requests_kerberos import HTTPKerberosAuth
response = requests.get('http://thedataishere.com',
auth=HTTPKerberosAuth())
data = response.json()
Implemented this way without using Jquery:
<button class="emailReplyButton" onClick="sendEmail(message)">Reply</button>
sendEmail(message) {
var email = message.emailId;
var subject = message.subject;
var emailBody = 'Hi '+message.from;
document.location = "mailto:"+email+"?subject="+subject+"&body="+emailBody;
}
In case of 2 different components (not nested components, parent\child\grandchild ) I suggest you this:
MissionService:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class MissionService {
// Observable string sources
private missionAnnouncedSource = new Subject<string>();
private missionConfirmedSource = new Subject<string>();
// Observable string streams
missionAnnounced$ = this.missionAnnouncedSource.asObservable();
missionConfirmed$ = this.missionConfirmedSource.asObservable();
// Service message commands
announceMission(mission: string) {
this.missionAnnouncedSource.next(mission);
}
confirmMission(astronaut: string) {
this.missionConfirmedSource.next(astronaut);
}
}
AstronautComponent:
import { Component, Input, OnDestroy } from '@angular/core';
import { MissionService } from './mission.service';
import { Subscription } from 'rxjs/Subscription';
@Component({
selector: 'my-astronaut',
template: `
<p>
{{astronaut}}: <strong>{{mission}}</strong>
<button
(click)="confirm()"
[disabled]="!announced || confirmed">
Confirm
</button>
</p>
`
})
export class AstronautComponent implements OnDestroy {
@Input() astronaut: string;
mission = '<no mission announced>';
confirmed = false;
announced = false;
subscription: Subscription;
constructor(private missionService: MissionService) {
this.subscription = missionService.missionAnnounced$.subscribe(
mission => {
this.mission = mission;
this.announced = true;
this.confirmed = false;
});
}
confirm() {
this.confirmed = true;
this.missionService.confirmMission(this.astronaut);
}
ngOnDestroy() {
// prevent memory leak when component destroyed
this.subscription.unsubscribe();
}
}
You can add nulls to the ArrayList
, and you will have to check for nulls in the loop:
for(Item i : itemList) {
if (i != null) {
}
}
itemsList.size();
would take the null
into account.
List<Integer> list = new ArrayList<Integer>();
list.add(null);
list.add (5);
System.out.println (list.size());
for (Integer value : list) {
if (value == null)
System.out.println ("null value");
else
System.out.println (value);
}
Output :
2
null value
5
If you see table class it has border-spacing: 2px; You could override table class in your css and set its border-spacing: 0px!important in table; I did it like
table {
border-collapse: separate;
white-space: normal;
line-height: normal;
font-weight: normal;
font-size: medium;
font-style: normal;
color: -internal-quirk-inherit;
text-align: start;
border-spacing: 0px!important;
font-variant: normal; }
It saved my day.Hope it would be of help. Thanks.
Change your default controller which is in config file.
i.e : config/routes.php
$route['default_controller'] = "Your controller name";
Hope this will help.
In my project I use this function for getting huge amount of files. It's pretty fast (put require("FS")
out to make it even faster):
var _getAllFilesFromFolder = function(dir) {
var filesystem = require("fs");
var results = [];
filesystem.readdirSync(dir).forEach(function(file) {
file = dir+'/'+file;
var stat = filesystem.statSync(file);
if (stat && stat.isDirectory()) {
results = results.concat(_getAllFilesFromFolder(file))
} else results.push(file);
});
return results;
};
usage is clear:
_getAllFilesFromFolder(__dirname + "folder");
I also had some trouble with my scrollable modals, so I did something like this:
$('.modal').on('shown.bs.modal', function () {
$('body').addClass('modal-open');
// BS adds some padding-right to acomodate the scrollbar at right
$('body').removeAttr('style');
})
$(".modal [data-toggle='modal']").click(function(){
$(this).closest(".modal").modal('hide');
});
It will serve for any modal whithin a modal that comes to appear. Note that the first its closed so the second can appear. No changes in the Bootstrap structure.
It works like this:
mpintro = MediaPlayer.create(this, Uri.parse(Environment.getExternalStorageDirectory().getPath()+ "/Music/intro.mp3"));
mpintro.setLooping(true);
mpintro.start();
It did not work properly as string filepath...
ANSWER: Read the instructions #dua
Ok the magic was in this line that I apparently missed when installing was:
$ sudo apt-get install mongodb-10gen=2.4.6
And the full process as described here http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/ is
$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
$ echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
$ sudo apt-get update
$ sudo apt-get install mongodb-10gen
$ sudo apt-get install mongodb-10gen=2.2.3
$ echo "mongodb-10gen hold" | sudo dpkg --set-selections
$ sudo service mongodb start
$ mongod --version
db version v2.4.6
Wed Oct 16 12:21:39.938 git version: b9925db5eac369d77a3a5f5d98a145eaaacd9673
IMPORTANT: Make sure you change 2.4.6 to the latest version (or whatever you want to install). Find the latest version number here http://www.mongodb.org/downloads
Don't forget
apt-get install libaio1 libaio-dev
or
yum install libaio
I resolved it by adding below code to my application.
// enter code here this is error I was getting when I run build.gradle. main class name has not been configured and it could not be resolved
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
the solution to the typescript:
Step1:
npm install jquery
npm install --save-dev @types/jquery
step2: in Angular.json add:
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
]
or in index.html add:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
step3: in *.component.ts where you want to use jquery
import * as $ from 'jquery'; // dont need "declare let $"
Then you can use jquery the same as javaScript. This way, VScode supports auto-suggestion by Typescript
i use this
$i = 1;
$last_time = $_SERVER['REQUEST_TIME'];
while($i > 0){
$total = $_SERVER['REQUEST_TIME'] - $last_time;
if($total >= 2){
// Code Here
$i = -1;
}
}
you can use
function WaitForSec($sec){
$i = 1;
$last_time = $_SERVER['REQUEST_TIME'];
while($i > 0){
$total = $_SERVER['REQUEST_TIME'] - $last_time;
if($total >= 2){
return 1;
$i = -1;
}
}
}
and run code =>
WaitForSec(your_sec);
Example :
WaitForSec(5);
OR you can use sleep
Example :
sleep(5);
Just add a break after your ArrayList.remove(A) statement
Example: Getting app_name string:
Resources.getSystem().getString( R.string.app_name )
for WPF: (where lblInfo is a label, chkRun is a checkBox)
this.Topmost is just to keep my app on the top of other windows, you will also need to add a using statement " using Microsoft.Win32; ", StartupWithWindows is my application's name
public partial class MainWindow : Window
{
// The path to the key where Windows looks for startup applications
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
public MainWindow()
{
InitializeComponent();
if (this.IsFocused)
{
this.Topmost = true;
}
else
{
this.Topmost = false;
}
// Check to see the current state (running at startup or not)
if (rkApp.GetValue("StartupWithWindows") == null)
{
// The value doesn't exist, the application is not set to run at startup, Check box
chkRun.IsChecked = false;
lblInfo.Content = "The application doesn't run at startup";
}
else
{
// The value exists, the application is set to run at startup
chkRun.IsChecked = true;
lblInfo.Content = "The application runs at startup";
}
//Run at startup
//rkApp.SetValue("StartupWithWindows",System.Reflection.Assembly.GetExecutingAssembly().Location);
// Remove the value from the registry so that the application doesn't start
//rkApp.DeleteValue("StartupWithWindows", false);
}
private void btnConfirm_Click(object sender, RoutedEventArgs e)
{
if ((bool)chkRun.IsChecked)
{
// Add the value in the registry so that the application runs at startup
rkApp.SetValue("StartupWithWindows", System.Reflection.Assembly.GetExecutingAssembly().Location);
lblInfo.Content = "The application will run at startup";
}
else
{
// Remove the value from the registry so that the application doesn't start
rkApp.DeleteValue("StartupWithWindows", false);
lblInfo.Content = "The application will not run at startup";
}
}
}
Here is a Extension implemented in Swift based on Jakob Egger's most excellent answer:
import UIKit
extension UIResponder {
// Swift 1.2 finally supports static vars!. If you use 1.1 see:
// http://stackoverflow.com/a/24924535/385979
private weak static var _currentFirstResponder: UIResponder? = nil
public class func currentFirstResponder() -> UIResponder? {
UIResponder._currentFirstResponder = nil
UIApplication.sharedApplication().sendAction("findFirstResponder:", to: nil, from: nil, forEvent: nil)
return UIResponder._currentFirstResponder
}
internal func findFirstResponder(sender: AnyObject) {
UIResponder._currentFirstResponder = self
}
}
import UIKit
extension UIResponder {
private weak static var _currentFirstResponder: UIResponder? = nil
public static var current: UIResponder? {
UIResponder._currentFirstResponder = nil
UIApplication.shared.sendAction(#selector(findFirstResponder(sender:)), to: nil, from: nil, for: nil)
return UIResponder._currentFirstResponder
}
@objc internal func findFirstResponder(sender: AnyObject) {
UIResponder._currentFirstResponder = self
}
}
You can use, pathlib also
from pathlib import Path
fl = Path("file_name")
fl.chmod(0o444)
If you are using MacOS use:
sudo cp /usr/local/etc/openssl/cert.pem /etc/ssl/certs
after this Trust anchor not found error disappears
Example:
create table longtable(id number,text long);
insert into longtable values(1,'hello world');
insert into longtable values(2,'say hello!');
commit;
create or replace function search_long(r rowid) return varchar2 is
temporary_varchar varchar2(4000);
begin
select text into temporary_varchar from longtable where rowid=r;
return temporary_varchar;
end;
/
SQL> select text from longtable where search_long(rowid) like '%hello%';
TEXT
--------------------------------------------------------------------------------
hello world
say hello!
But be careful. A PL/SQL function will only search the first 32K of LONG.
py2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation.
var empty = true;
$('input[type="text"]').each(function() {
if ($(this).val() != "") {
empty = false;
return false;
}
});
This should look all the input and set the empty var to false, if at least one is not empty.
EDIT:
To match the OP edit request, this can be used to filter input based on name substring.
$('input[name*="denominationcomune_"]').each(...
You need to add a return to the index.html file.
app.use(express.static(path.join(__dirname, 'build')));
app.get('*', function(req, res) {res.sendFile(path.join(__dirname + '/build/index.html')); });
Short answer: Don't do it.
Longer answer: Use WCF. It's here to replace Asmx.
see this answer for example, or the first comment on this one.
John Saunders: ASMX is a legacy technology, and should not be used for new development. WCF or ASP.NET Web API should be used for all new development of web service clients and servers. One hint: Microsoft has retired the ASMX Forum on MSDN.
As for comment ... well, if you have to, you have to. I'll leave you in the competent hands of the other answers then. (Even though it's funny it has issues, and if it does, why are you doing it in VS2013 to begin with ?)
It is possible you are using zsh instead of bash then you have to enter the above mentioned commands in .zshenv instead of .bash_profile
Does the column allow null?
Seems to work. Just tested with phpMyAdmin, the column is of type int that allows nulls:
INSERT INTO `database`.`table` (`column`) VALUES (NULL);
Why would the first way not work. Canvas object is created and the size is set and the grahpics are set. I always find this strange. Also if a class extends JComponent you can override the
paintComponent(){
super...
}
and then shouldn't you be able to create and instance of the class inside of another class and then just call NewlycreateinstanceOfAnyClass.repaint();
I have tried this approach for some game programming I have been working and it doesn't seem to work the way I think that it should be.
Doug Hauf
Check the trees.config file which located in config folder... sometimes (I don't know why) this file became to be empty like someone delete the content inside... keep backup up of this file in your local pc then when this error appear - replace the server file with your local file. This is what i do when this error happened.
check the available space on the server. sometimes this is the problem.
Good luck.
substring().
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html
You should probably use the ngHref directive along with the ngClick:
<a ng-href='#here' ng-click='go()' >click me</a>
Here is an example: http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
{{msg}}
<a ng-href='#here' ng-click='go()' >click me</a>
<div style='height:1000px'>
<a id='here'></a>
</div>
<h1>here</h1>
</body>
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.go = function() {
$scope.msg = 'clicked';
}
});
I don't know if this will work with the library you are using but it will at least let you link and use the ngClick function.
** Update **
Here is a demo of the set and get working fine with a service.
http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, sharedProperties) {
$scope.name = 'World';
$scope.go = function(item) {
sharedProperties.setListName(item);
}
$scope.getItem = function() {
$scope.msg = sharedProperties.getListName();
}
});
app.service('sharedProperties', function () {
var list_name = '';
return {
getListName: function() {
return list_name;
},
setListName: function(name) {
list_name = name;
}
};
});
* Edit *
Please review https://github.com/centralway/lungo-angular-bridge which talks about how to use lungo and angular. Also note that if your page is completely reloading when browsing to another link, you will need to persist your shared properties into localstorage and/or a cookie.
Just use this code as the basis of a simple JQuery plugin.
$.extend({
distinct : function(anArray) {
var result = [];
$.each(anArray, function(i,v){
if ($.inArray(v, result) == -1) result.push(v);
});
return result;
}
});
Use as so:
$.distinct([0,1,2,2,3]);
The tf.exe command line is included in the VSTS agent package in folder externals\vstsom.
CSS has different pseudo selector by which you can achieve such effect. In your case you can use
:active : if you want background color only when the button is clicked and don't want to persist.
:focus: if you want background color untill the focus is on the button.
button:active{
background:olive;
}
and
button:focus{
background:olive;
}
P.S.: Please don't give the number in Id
attribute of html elements.
Best solution is to use
DELETE FROM table WHERE id NOT IN ( 2 )
Instead of using a custom RecyclerView
, extending an AdapterDataObserver
is a simpler solution that allows setting a custom View
that is displayed when there are no items in the list:
Example Usage:
RVEmptyObserver observer = new RVEmptyObserver(recyclerView, emptyView)
rvAdapter.registerAdapterDataObserver(observer);
Class:
public class RVEmptyObserver extends RecyclerView.AdapterDataObserver {
private View emptyView;
private RecyclerView recyclerView;
public RVEmptyObserver(RecyclerView rv, View ev) {
this.recyclerView = rv;
this.emptyView = ev;
checkIfEmpty();
}
private void checkIfEmpty() {
if (emptyView != null && recyclerView.getAdapter() != null) {
boolean emptyViewVisible = recyclerView.getAdapter().getItemCount() == 0;
emptyView.setVisibility(emptyViewVisible ? View.VISIBLE : View.GONE);
recyclerView.setVisibility(emptyViewVisible ? View.GONE : View.VISIBLE);
}
}
public void onChanged() { checkIfEmpty(); }
public void onItemRangeInserted(int positionStart, int itemCount) { checkIfEmpty(); }
public void onItemRangeRemoved(int positionStart, int itemCount) { checkIfEmpty(); }
}
http://www.gnu.org/software/make/manual/make.html#Recursion
subsystem:
cd subdir && $(MAKE)
or, equivalently, this :
subsystem:
$(MAKE) -C subdir
The following answer could be helpful for the first part of your question:
Use the affix
component included with Bootstrap. Start with a 'navbar-static-top' and this will change it to fixed
when the height of your header (content above the navbar) is reached...
$('#nav').affix({
offset: {
top: $('header').height()
}
});
Instantiate a new ArrayList:
List<String> myList = new ArrayList<String>();
Iterate over your data structure (with a for loop, for instance, more details on your code would help.) and for each element (yourElement):
myList.add(yourElement);
Consider if instead it was:
class RectangularRoom(object):
def __init__(self, width, height):
pass
def cleanTileAtPosition(self, pos):
pass
def isTileCleaned(self, m, n):
pass
and you subclass and forget to tell it how to isTileCleaned()
or, perhaps more likely, typo it as isTileCLeaned()
. Then in your code, you'll get a None
when you call it.
None
valid output? Who knows. raise NotImplmentedError
forces you to implement it, as it will throw an exception when you try to run it until you do so. This removes a lot of silent errors. It's similar to why a bare except is almost never a good idea: because people make mistakes and this makes sure they aren't swept under the rug.
Note: Using an abstract base class, as other answers have mentioned, is better still, as then the errors are frontloaded and the program won't run until you implement them (with NotImplementedError, it will only throw an exception if actually called).
If you have a built-in command of GridView like insert, update or delete, on row command you can use the following code to get the index:
int index = Convert.ToInt32(e.CommandArgument);
In a custom command, you can set the command argument to yourRow.RowIndex.ToString()
and then get it back in the RowCommand event handler. Unless, of course, you need the command argument for another purpose.
Here is another solution for adding class definitions to the widgets after declaring the fields in the class.
def __init__(self, *args, **kwargs):
super(SampleClass, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs['class'] = 'my_class'
??
should be preferred to ||
because it checks only for nulls and undefined.
All The expressions below are true:
(null || 'x') === 'x' ;
(undefined || 'x') === 'x' ;
//Most of the times you don't want the result below
('' || 'x') === 'x' ;
(0 || 'x') === 'x' ;
(false || 'x') === 'x' ;
//-----
//Using ?? is preferred
(null ?? 'x') === 'x' ;
(undefined ?? 'x') === 'x' ;
//?? works only for null and undefined, which is in general safer
('' ?? 'x') === '' ;
(0 ?? 'x') === 0 ;
(false ?? 'x') === false ;
Bottom line:
int j=i ?? 10;
is perfectly fine to use in javascript also. Just replace int
with let
.
Asterisk: Check browser compatibility and if you really need to support these other browsers use babel.
Use pylint
it will give you a detailed report about how many spaces you need and where.
You can view the error-output of your test runner by opening the Output panel (view-->output) and choosing "tests" from the "Show output from" dropdown
Additionally, if you have Resharper installed you can open a test file and hover over the test-circle next to a test to get additional error info
Clicking that will bring you to a window with more detailed information. Alternatively, you can open that window by going to Extensions --> Reshaper --> Windows --> Unit Test Exploration Results
Something like:
SELECT id, email, IF(active = 1, 'enabled', 'disabled') AS account_status FROM users
This allows you to make operations and show it as columns.
EDIT:
you can also use joins and show operations as columns:
SELECT u.id, e.email, IF(c.id IS NULL, 'no selected', c.name) AS country
FROM users u LEFT JOIN countries c ON u.country_id = c.id
Sounds like you have a utility class similar to java.lang.Math.
The approach there is final class with private constructor and static methods.
But beware of what this does for testability, I recommend reading this article
Static Methods are Death to Testability
For what purpose?
IF EXISTS (SELECT * FROM Table)...
SELECT TOP 1 1 FROM Table
returns either zero or one rowsSELECT COUNT(*) FROM Table
If you add the boolean true to the reload
window.location.reload(true)
it will load from server.
It is not clear how supported this boolean is, W3Org mentions that NS used to support it
There MIGHT be a difference between the content of window.location.href and document.URL - there at least used to be a difference between location.href and the non-standard and deprecated document.location that had to do with redirection, but that is really last millennium.
For documentation purposes I would use window.location.reload() because that is what you want to do.
visibility:hidden is the proper syntax, but another way to 'hide' the table is with display:none or dynamically with JQuery:
$('#myTable').hide()
Here's an example that let's you set the color of the background. If you don't want to use float, then you might need to set the width and height manually. But even that really depends on the surrounding CSS/HTML.
<style>
#color {
background-color: red;
float: left;
}#opacity {
opacity : 0.4;
filter: alpha(opacity=40);
}
</style>
<div id="color">
<div id="opacity">
<img src="image.jpg" />
</div>
</div>
For me, it was a String value Resource not being defined … after I added it by hand to Strings.xml, the R class was automagically regenerated!
Node.js was created explicitly as an experiment in async processing. The theory was that doing async processing on a single thread could provide more performance and scalability under typical web loads than the typical thread-based implementation.
And you know what? In my opinion that theory's been borne out. A node.js app that isn't doing CPU intensive stuff can run thousands more concurrent connections than Apache or IIS or other thread-based servers.
The single threaded, async nature does make things complicated. But do you honestly think it's more complicated than threading? One race condition can ruin your entire month! Or empty out your thread pool due to some setting somewhere and watch your response time slow to a crawl! Not to mention deadlocks, priority inversions, and all the other gyrations that go with multithreading.
In the end, I don't think it's universally better or worse; it's different, and sometimes it's better and sometimes it's not. Use the right tool for the job.
This will probably have some performance costs when creating the connection but as connections are pooled, they are created only once and then reused, so it won't make any difference to your application. But as always: measure it.
UPDATE:
There are two authentication modes:
This is a feature of C# 4.0, but was not possible without using function overload prior to that version.
$route.reload()
will reinitialise the controllers but not the services. If you want to reset the whole state of your application you can use:
$window.location.reload();
This is a standard DOM method which you can access injecting the $window service.
If you want to be sure to reload the page from the server, for example when you are using Django or another web framework and you want a fresh server side render, pass true
as a parameter to reload
, as explained in the docs. Since that requires interaction with the server, it will be slower so do it only if necessary
The above applies to Angular 1. I am not using Angular 2, looks like the services are different there, there is Router
, Location
, and the DOCUMENT
. I did not test different behaviors there
Make sure you import MaterialModule as well since you are using md-input which does not belong to FormsModule
Yet another cause of this error is when you are calling the stored procedure from code, and the parameter type in code does not match the type on the stored procedure.
I'm using version 2(supports both bootstrap v2 and v3) and for me this works:
$("#datepicker").datepicker( {
format: "mm/yyyy",
startView: "year",
minView: "year"
});
Depends what it is that you're trying to do it with. You could use something like this:
echo "<a href=\"javascript:history.go(-1)\">GO BACK</a>";
That's the simplest option. The other poster is right about having a proper flow of history but this is an example for you.
Just edited, orig version wasn't indented and looked like nothing. ;)
var input=950000; _x000D_
var output=parseInt(input).toLocaleString(); _x000D_
alert(output);
_x000D_
No, you can just write the function as:
$(document).ready(function() {
MyBlah("hello");
});
function MyBlah(blah) {
alert(blah);
}
This calls the function MyBlah
on content ready.
You are not creating datetime index properly,
format = '%Y-%m-%d %H:%M:%S'
df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'], format=format)
df = df.set_index(pd.DatetimeIndex(df['Datetime']))
The OSHI
project provides platform-independent hardware utilities.
Maven dependency:
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
<version>LATEST</version>
</dependency>
For instance, you could use something like the following code to identify a machine uniquely:
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.ComputerSystem;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.OperatingSystem;
class ComputerIdentifier
{
static String generateLicenseKey()
{
SystemInfo systemInfo = new SystemInfo();
OperatingSystem operatingSystem = systemInfo.getOperatingSystem();
HardwareAbstractionLayer hardwareAbstractionLayer = systemInfo.getHardware();
CentralProcessor centralProcessor = hardwareAbstractionLayer.getProcessor();
ComputerSystem computerSystem = hardwareAbstractionLayer.getComputerSystem();
String vendor = operatingSystem.getManufacturer();
String processorSerialNumber = computerSystem.getSerialNumber();
String processorIdentifier = centralProcessor.getIdentifier();
int processors = centralProcessor.getLogicalProcessorCount();
String delimiter = "#";
return vendor +
delimiter +
processorSerialNumber +
delimiter +
processorIdentifier +
delimiter +
processors;
}
public static void main(String[] arguments)
{
String identifier = generateLicenseKey();
System.out.println(identifier);
}
}
Output for my machine:
Microsoft#57YRD12#Intel64 Family 6 Model 60 Stepping 3#8
Your output will be different since at least the processor serial number will differ.
a simple code snippet that i prepared, hope it will be usefull for you;
$ages = array("Kerem"=>"35","Ahmet"=>"65","Talip"=>"62","Kamil"=>"60");
reset($ages);
for ($i=0; $i < count($ages); $i++){
echo "Key : " . key($ages) . " Value : " . current($ages) . "<br>";
next($ages);
}
reset($ages);
Without the 0x prefix, you need to specify the base explicitly, otherwise there's no way to tell:
x = int("deadbeef", 16)
With the 0x prefix, Python can distinguish hex and decimal automatically.
>>> print(int("0xdeadbeef", 0))
3735928559
>>> print(int("10", 0))
10
(You must specify 0
as the base in order to invoke this prefix-guessing behavior; if you omit the second parameter int()
will assume base-10.)
This worked for me (macOS v10.13 (High Sierra)):
sudo -u postgres /Library/PostgreSQL/9.6/bin/pg_ctl start -D /Library/PostgreSQL/9.6/data
Or first
cd /Library/PostgreSQL/9.6/bin/
Part One - Polyfill
For browsers that haven't implemented it, a polyfill for array.find
. Courtesy of MDN.
if (!Array.prototype.find) {
Array.prototype.find = function(predicate) {
if (this == null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
return undefined;
};
}
Part Two - Interface
You need to extend the open Array interface to include the find
method.
interface Array<T> {
find(predicate: (search: T) => boolean) : T;
}
When this arrives in TypeScript, you'll get a warning from the compiler that will remind you to delete this.
Part Three - Use it
The variable x
will have the expected type... { id: number }
var x = [{ "id": 1 }, { "id": -2 }, { "id": 3 }].find(myObj => myObj.id < 0);
On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.
Source: Reading and Writing Files
text-align: center
will center it horizontally as for vertically put it in a span and give it a css of margin:auto 0;
(you will probably also have to give the span a display: block
property)
If using Bash, just switch into the folder that has your package.json file and run the following:
for package in `ls node_modules`; do npm uninstall $package; done;
In the case of globally-installed packages, switch into your %appdata%/npm
folder (if on Windows) and run the same command.
EDIT: This command breaks with npm 3.3.6 (Node 5.0). I'm now using the following Bash command, which I've mapped to npm_uninstall_all in my .bashrc file:
npm uninstall `ls -1 node_modules | tr '/\n' ' '`
Added bonus? it's way faster!
Just because you don't know what two things are, does not mean they're equal. If when you think of NULL
you think of “NULL” (string) then you probably want a different test of equality like Postgresql's IS DISTINCT FROM
AND IS NOT DISTINCT FROM
From the PostgreSQL docs on "Comparison Functions and Operators"
expression
IS DISTINCT FROM
expressionexpression
IS NOT DISTINCT FROM
expressionFor non-null inputs,
IS DISTINCT FROM
is the same as the<>
operator. However, if both inputs are null it returns false, and if only one input is null it returns true. Similarly,IS NOT DISTINCT FROM
is identical to=
for non-null inputs, but it returns true when both inputs are null, and false when only one input is null. Thus, these constructs effectively act as though null were a normal data value, rather than "unknown".
You have it almost done. Just explicitly say where to create the file
@echo off
echo.>"d:\testing\dblank.txt"
This creates a file containing a blank line (CR + LF = 2 bytes).
If you want the file empty (0 bytes)
@echo off
break>"d:\testing\dblank.txt"
can use html5 mark tag within paragraph and heading tag.
<p>lorem ipsum <mark>Highlighted Text</mark> dolor sit.</p>
_x000D_
I managed to find a solution using css/jQuery that I'm comfortable with. The original issue: I had to force the visibility to be shown while animating as I have elements hanging outside the area. Doing so, made large blocks of text now hang outside the content area during animation as well.
The solution was to start the main text elements with an opacity of 0 and use addClass
to inject and transition to an opacity of 1. Then removeClass
when clicked on again.
I'm sure there's an all jQquery way to do this. I'm just not the guy to do it. :)
So in it's most basic form...
.slideDown().addClass("load");
.slideUp().removeClass("load");
Thanks for the help everyone.
No. While the definition from w3c for HTML 4 doesn't seem to explicitly cover your question, the definition of the name and id attribute says no spaces in the identifier:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
$("input").datepicker({ dateFormat: 'dd, mm, yy' });
later in your code when the date is set you could get it by
dateVariable = $("input").val();
dateString = $.datepicker.formatDate('dd, MM, yy', new Date("20 April 2012"));
I've updated the jsfiddle for experimenting with this
Loop AutoFilter columns, if column is activated(on) then reset a column filter, you may insert a new criteria after a loop. This code does not remove AutoFilter banner.
Dim iCol as Long
Dim ws as Worksheet
...
For iCol = 1 To ws.AutoFilter.Filters.count
If ws.AutoFilter.Filters(iCol).On Then ws.AutoFilter.Range.AutoFilter Field:=iCol
Next
...
ws.AutoFilter.Range.AutoFilter Field:=4, Criteria1:="AABBCC"
You should in fact do both, so that all browsers will find the icon.
Naming the file "favicon.ico" and putting it in the root of your website is the method "discouraged" by W3C:
Method 2 (Discouraged): Putting the favicon at a predefined URI
A second method for specifying a favicon relies on using a predefined URI to identify the image: "/favicon", which is relative to the server root. This method works because some browsers have been programmed to look for favicons using that URI.
W3C - How to add a favicon to your site
So, to cover all situations, I always do that in addition to the recommended method of adding a "rel" attribute and pointing it to the same .ico file.
S.Lott inserted a comment, but it should be an answer: see the same question.
Since it wasn't as obvious as I intended it to be, here follows a verbatim copy of S.Lott's answer in the other question:
I'm a big fan of ARGO UML from Tigris.org. Draws nice pictures using standard UML notation. It does some code generation, but mostly Java classes, which isn't SQL DDL, so that may not be close enough to what you want to do.
You can look at the Data Modelling Tools list and see if anything there is better than Argo UML. Many of the items on this list are free or cheap.
Also, if you're using Eclipse or NetBeans, there are many design plug-ins, some of which may have the features you're looking for.
Today I had this problem in a project and I had to change this parameter to false (or remove the lines, by default is disabled):
ini_set( 'session.cookie_secure', 1 );
This happened because the actual project works over http and not https only. Found more info in the docs http://php.net/manual/en/session.security.ini.php
Easy. Use a bitwise AND to compare your number with the value 2^bitNumber, which can be cheaply calculated by bit-shifting.
//your black magic
var bit = (b & (1 << bitNumber-1)) != 0;
EDIT: To add a little more detail because there are a lot of similar answers with no explanation:
A bitwise AND compares each number, bit-by-bit, using an AND join to produce a number that is the combination of bits where both the first bit and second bit in that place were set. Here's the logic matrix of AND logic in a "nibble" that shows the operation of a bitwise AND:
0101
& 0011
----
0001 //Only the last bit is set, because only the last bit of both summands were set
In your case, we compare the number you passed with a number that has only the bit you want to look for set. Let's say you're looking for the fourth bit:
11010010
& 00001000
--------
00000000 //== 0, so the bit is not set
11011010
& 00001000
--------
00001000 //!= 0, so the bit is set
Bit-shifting, to produce the number we want to compare against, is exactly what it sounds like: take the number, represented as a set of bits, and shift those bits left or right by a certain number of places. Because these are binary numbers and so each bit is one greater power-of-two than the one to its right, bit-shifting to the left is equivalent to doubling the number once for each place that is shifted, equivalent to multiplying the number by 2^x. In your example, looking for the fourth bit, we perform:
1 (2^0) << (4-1) == 8 (2^3)
00000001 << (4-1) == 00001000
Now you know how it's done, what's going on at the low level, and why it works.
Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:
Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:
Rory Gallagher Guitar
Gerry McAvoy Bass
Rod de'Ath Drums
Lou Martin Keyboards
Donkey Kong Sioux Self-Appointed Semi-official Stomper
Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)
Save the file as a CSV file.
Copy the contents of the CSV file to the clipboard
Verify that the "First row is column names" checkbox is checked
Paste the CSV data into the content area
Mash the "Convert CSV to JSON" button
With the data shown above, you will now have:
[
{
"MUSICIAN":"Rory Gallagher",
"INSTRUMENT":"Guitar"
},
{
"MUSICIAN":"Gerry McAvoy",
"INSTRUMENT":"Bass"
},
{
"MUSICIAN":"Rod D'Ath",
"INSTRUMENT":"Drums"
},
{
"MUSICIAN":"Lou Martin",
"INSTRUMENT":"Keyboards"
}
{
"MUSICIAN":"Donkey Kong Sioux",
"INSTRUMENT":"Self-Appointed Semi-Official Stomper"
}
]
With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.
Go here: http://jsonlint.com/
Paste the JSON into the content area
Pres the "Validate" button.
If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.
LIBRARY_PATH
is used by gcc before compilation to search directories containing static and shared libraries that need to be linked to your program.
LD_LIBRARY_PATH
is used by your program to search directories containing shared libraries after it has been successfully compiled and linked.
EDIT:
As pointed below, your libraries can be static or shared. If it is static then the code is copied over into your program and you don't need to search for the library after your program is compiled and linked. If your library is shared then it needs to be dynamically linked to your program and that's when LD_LIBRARY_PATH
comes into play.
.showme {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.showhim:hover .showme {_x000D_
display: block;_x000D_
}
_x000D_
<div class="showhim">HOVER ME_x000D_
<div class="showme">hai</div>_x000D_
</div>
_x000D_
Since this answer is popular I think a small explanation is needed. Using this method when you hover on the internal element, it wont disappear. Because the .showme is inside .showhim it will not disappear when you move your mouse between the two lines of text (or whatever it is).
These are example of quirqs you need to take care of when implementing such behavior.
It all depends what you need this for. This method is better for a menu style scenario, while Yi Jiang's is better for tooltips.
The whole idea behind Parallel.ForEach()
is that you have a set of threads and each thread processes part of the collection. As you noticed, this doesn't work with async
-await
, where you want to release the thread for the duration of the async call.
You could “fix” that by blocking the ForEach()
threads, but that defeats the whole point of async
-await
.
What you could do is to use TPL Dataflow instead of Parallel.ForEach()
, which supports asynchronous Task
s well.
Specifically, your code could be written using a TransformBlock
that transforms each id into a Customer
using the async
lambda. This block can be configured to execute in parallel. You would link that block to an ActionBlock
that writes each Customer
to the console.
After you set up the block network, you can Post()
each id to the TransformBlock
.
In code:
var ids = new List<string> { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
var getCustomerBlock = new TransformBlock<string, Customer>(
async i =>
{
ICustomerRepo repo = new CustomerRepo();
return await repo.GetCustomer(i);
}, new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded
});
var writeCustomerBlock = new ActionBlock<Customer>(c => Console.WriteLine(c.ID));
getCustomerBlock.LinkTo(
writeCustomerBlock, new DataflowLinkOptions
{
PropagateCompletion = true
});
foreach (var id in ids)
getCustomerBlock.Post(id);
getCustomerBlock.Complete();
writeCustomerBlock.Completion.Wait();
Although you probably want to limit the parallelism of the TransformBlock
to some small constant. Also, you could limit the capacity of the TransformBlock
and add the items to it asynchronously using SendAsync()
, for example if the collection is too big.
As an added benefit when compared to your code (if it worked) is that the writing will start as soon as a single item is finished, and not wait until all of the processing is finished.
The most trivial way to upload a file over SFTP with JSch is:
JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");
Similarly for a download:
sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");
You may need to deal with UnknownHostKey
exception.
Received SQLSTATE 01000 in the following error message below:
SQL Agent - Jobs Failed: The SQL Agent Job "LiteSpeed Backup Full" has failed with the message "The job failed. The Job was invoked by User X. The last step to run was step 1 (Step1). NOTE: Failed to notify via email. - Executed as user: X. LiteSpeed(R) for SQL Server Version 6.5.0.1460 Copyright 2011 Quest Software, Inc. [SQLSTATE 01000] (Message 1) LiteSpeed for SQL Server could not open backup file: (N:\BACKUP2\filename.BAK). The previous system message is the reason for the failure. [SQLSTATE 42000] (Error 60405). The step failed."
In my case this was related to permission on drive N following an SQL Server failover on an Active/Passive SQL cluster.
All SQL resources where failed over to the seconary resouce and back to the preferred node following maintenance. When the Quest LiteSpeed job then executed on the preferred node it was clear the previous permissions for SQL server user X had been lost on drive N and SQLSTATE 10100 was reported.
Simply added the permissions again to the backup destination drive and the issue was resolved.
Hope that helps someone.
Windows 2008 Enterprise
SQL Server 2008 Active/Passive cluster.
For those of us who found this and are not using Azure SQL Database:
STRING_AGG()
in PostgreSQL, SQL Server 2017 and Azure SQL
https://www.postgresql.org/docs/current/static/functions-aggregate.html
https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql
GROUP_CONCAT()
in MySQL
http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat
(Thanks to @Brianjorden and @milanio for Azure update)
select Id
, STRING_AGG(Name, ', ') Names
from Demo
group by Id
SQL Fiddle: http://sqlfiddle.com/#!18/89251/1
In my case, I was careless while merging the application.yml file, and I've unnecessary indented my properties to the right.
I've indented it like this:
spring:
application:
name: applicationName
............................
myProperties:
property1: property1value
While the code expected it to be like this:
spring:
application:
name: applicationName
.............................
myProperties:
property1: property1value
Look on my solution. I suppose that you should set selected position in holder and pass it as Tag of View. The view should be set in the onCreateViewHolder(...) method. There is also correct place to set listener for view such as OnClickListener or LongClickListener.
Please look on the example below and read comments to code.
public class MyListAdapter extends RecyclerView.Adapter<MyListAdapter.ViewHolder> {
//Here is current selection position
private int mSelectedPosition = 0;
private OnMyListItemClick mOnMainMenuClickListener = OnMyListItemClick.NULL;
...
// constructor, method which allow to set list yourObjectList
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//here you prepare your view
// inflate it
// set listener for it
final ViewHolder result = new ViewHolder(view);
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.your_view_layout, parent, false);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//here you set your current position from holder of clicked view
mSelectedPosition = result.getAdapterPosition();
//here you pass object from your list - item value which you clicked
mOnMainMenuClickListener.onMyListItemClick(yourObjectList.get(mSelectedPosition));
//here you inform view that something was change - view will be invalidated
notifyDataSetChanged();
}
});
return result;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
final YourObject yourObject = yourObjectList.get(position);
holder.bind(yourObject);
if(mSelectedPosition == position)
holder.itemView.setBackgroundColor(Color.CYAN);
else
holder.itemView.setBackgroundColor(Color.RED);
}
// you can create your own listener which you set for adapter
public void setOnMainMenuClickListener(OnMyListItemClick onMyListItemClick) {
mOnMainMenuClickListener = onMyListItemClick == null ? OnMyListItemClick.NULL : onMyListItemClick;
}
static class ViewHolder extends RecyclerView.ViewHolder {
ViewHolder(View view) {
super(view);
}
private void bind(YourObject object){
//bind view with yourObject
}
}
public interface OnMyListItemClick {
OnMyListItemClick NULL = new OnMyListItemClick() {
@Override
public void onMyListItemClick(YourObject item) {
}
};
void onMyListItemClick(YourObject item);
}
}
Well, the _id is an object in your example, so you just need to pass an object
'db.test_users.remove({"_id": { "$oid" : "4d513345cc9374271b02ec6c" }})'
This should work
Edit: Added trailing paren to ensure that it compiled.
You need to pass an array of element to jsx
. The problem is that forEach
does not return anything (i.e it returns undefined
). So it's better to use map
because map
returns an array:
class QuestionSet extends Component {
render(){
<div className="container">
<h1>{this.props.question.text}</h1>
{this.props.question.answers.map((answer, i) => {
console.log("Entered");
// Return the element. Also pass key
return (<Answer key={answer} answer={answer} />)
})}
}
export default QuestionSet;
The answer to this simple questions is unfortunately not a simple one, but working in 100% of all systems, and even extendable to the numerous .net frameworks.
The complexity comes from the fact that there are (and were) many VC runtimes revisions which could lead to the case that although VC10 runtimes were installed, their build number was not recent enough so your EXE wouldn't start unless you either installed the very exact runtimes you required or one of the newer runtimes which enable this and previous versions for the same major version to run with it (the side-by-side hell). Also, if you have a 64 bit EXE, you will have to check for both, the 32 AND 64 bit runtimes.
That said, the only reliable way to determine whether the runtimes for your EXE are installed is to attempt to run the EXE - or a another EXE which is built with the same settings as your main EXE and whose only purpose is to do - nothing. Just run (which means the runtimes are installed) or fail to run (when not installed).
I did the following for an installer which required the VC10 32 and 64 bit runtimes installed: The installer attempts to launch all dummy EXEs and if it succeeds, the corresponding runtime is considered to be installed. This also resolves the 32/64 bit scenario.
This, by the way, works also to determine if the proper .net framework is installed, which is very tricky in Windows 8 and 10, as the downloadable built-in .net 3.5 support also supports the .net versions 3.0 and 2.0 - there are no registry entries for these. (And worse, you cannot even use the standard framework installers here, you must use the built-in support and download it via Windows, or rebuild your app with .net 4, but that's another story).
The C++ dummy EXE can be built using a project with the following code (and another one in a 64 bit configuration if necessary):
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
Remember to set the project's properties Use of MFC to Use MFC in a shared DLL. The executables will be around 4KB in size - a small price to pay for a sure result.
To give your users a nice installation experience, you could do the following (sample code is for NSIS):
Function TryLaunchApplication
Pop $1 ; pathname
nsExec::Exec $1
Pop $0
${If} $0 == "error"
${OrIf} $0 != 0
Push 0
${Else}
Push 1
${EndIf}
FunctionEnd
and call it in a function, e.g. CheckRuntimes
Function CheckRuntimes
; Try to execute VC++ 10 application (32 bit)
Push "Vc10RuntimeCheckerApp.exe"
Call TryLaunchApplication
Pop $Vc10RuntimesFound
; Add 64 bit check if required.
; Remember to try running the 64 bit EXE only on a 64 bit OS,
; which requires further checks.
; Try to execute .net application
Push "DotNetRuntimeCheckerApp.exe"
Call TryLaunchApplication
Pop $DotNetFrameworkFound
FunctionEnd
Then launch the runtime check e.g. when leaving the Welcome page and cache the result, so you don't have to re-check every time the user clicks on the "Back" and "Next" button.
Next, make a read-only section in the install tree and pre-select or unselect it on the a function which is executed before the Components page is shown.
This will make sure that the installation of each missing runtime component is mandatory, and is skipped if it is already present.
This is a message for me in the future:
Just use: (unsigned)!((int)0)
It creates the largest possible number in any machine by assigning all bits to 1s (ones) and then casts it to unsigned
Even better
#define INF (unsigned)!((int)0)
And then just use INF in your code
check if the object exists or not in DB, if it exists get the object and refresh it:
if (getEntityManager().contains(instance)) {
getEntityManager().refresh(instance);
return instance;
}
if it fails the above if condition... find the Object with Id in DB, do the operation which you need, in this case exactly changes will reflects.
if (....) {
} else if (null != identity) {
E dbInstance = (E) getEntityManager().find(instance.getClass(), identity);
return dbInstance;
}
from django.http import JsonResponse
def SomeFunction(): dict1 = {}
obj = list( Mymodel.objects.values() )
dict1['data']=obj
return JsonResponse(dict1)
Try this code for Django
There are a couple of things to check:
proceedToSecond
" into the FireBug console to see if the function gets definedscript
tag: it should be <script type="text/javascript">
instead of <script type = "text/javascript">
From JavaEE docs ServletResponse#setContentType
Sets the content type of the response being sent to the client, if the response has not been committed yet.
The given content type may include a character encoding specification, for example,
response.setContentType("text/html;charset=UTF-8");
The response's character encoding is only set from the given content type if this method is called before getWriter
is called.
This method may be called repeatedly to change content type and character encoding.
This method has no effect if called after the response has been committed. It does not set the response's character encoding if it is called after getWriter
has been called or after the response has been committed.
Containers must communicate the content type and the character encoding used for the servlet response's writer to the client if the protocol provides a way for doing so. In the case of HTTP, the Content-Type header is used.
If you only want to return a blank when B2 is blank you can use an additional IF function for that scenario specifically, i.e.
=IF(B2="","",VLOOKUP(B2,Index!A1:B12,2,FALSE))
or to return a blank with any error from the VLOOKUP (e.g. including if B2 is populated but that value isn't found by the VLOOKUP) you can use IFERROR function if you have Excel 2007 or later, i.e.
=IFERROR(VLOOKUP(B2,Index!A1:B12,2,FALSE),"")
in earlier versions you need to repeat the VLOOKUP, e.g.
=IF(ISNA(VLOOKUP(B2,Index!A1:B12,2,FALSE)),"",VLOOKUP(B2,Index!A1:B12,2,FALSE))
You can use Newtonsoft.Json
, it's a dependency of Microsoft.AspNet.Mvc.ModelBinding
which is a dependency of Microsoft.AspNet.Mvc
. So, you don't need to add a dependency in your project.json.
#using Newtonsoft.Json
....
JsonConvert.DeserializeObject(json);
Note, using a WebAPI controller you don't need to deal with JSON.
Json.NET has been removed from the ASP.NET Core 3.0 shared framework.
You can use the new JSON serializer layers on top of the high-performance Utf8JsonReader
and Utf8JsonWriter
. It deserializes objects from JSON and serializes objects to JSON. Memory allocations are kept minimal and includes support for reading and writing JSON with Stream asynchronously.
To get started, use the JsonSerializer
class in the System.Text.Json.Serialization
namespace. See the documentation for information and samples.
To use Json.NET in an ASP.NET Core 3.0 project:
services.AddMvc()
.AddNewtonsoftJson();
Read Json.NET support in Migrate from ASP.NET Core 2.2 to 3.0 Preview 2 for more information.
When the JVM
tries to run your application, it calls your main method statically; something like this:
LinkedList.main();
That means there is no instance of your LinkedList
class. In order to call your toString()
method, you can create a new instance of your LinkedList
class.
So the body of your main
method should be like this:
public static void main(String[] args){
// creating an instance of LinkedList class
LinkedList ll = new LinkedList();
// adding some data to the list
ll.insertFront(1);
ll.insertFront(2);
ll.insertFront(3);
ll.insertBack(4);
System.out.println(ll.toString());
}
I want to start by saying by saying that I realize this question is old and already has an accepted answer; but, as an unfortunate internet user that used this question as a means to end only to be proven wrong shortly after (but not before I upset my client a little) I want to add my thoughts and suggestions.
While @DSG and @Giona are correct, and there is nothing wrong with their answers, there is a creative mechanism you can employ to "get around," so to speak, this limitation. That is not say that I'm condoning circumvention of this feature, quite the contrary, but just some mechanisms so that a user still "feels" as if a video or audio file is "auto playing."
The quick work around is hide a video tag somewhere on the mobile page, since I built a responsive site I only do this for smaller screens. The video tag (HTML and jQuery examples):
HTML
<video id="dummyVideo" src="" preload="none" width="1" height="2"></video>
jQuery
var $dummyVideo = $("<video />", {
id: "dummyVideo",
src: "",
preload: "none",
width: "1",
height: "2"
});
With that hidden on the page, when a user "clicks" to watch a movie (still user interaction, there is no way to get around that requirement) instead of navigating to a secondary watch page I load the hidden video. This mainly works because the media tag isn't really used but instead promoted to a Quicktime instance so having a visible video element isn't necessary at all. In the handler for "click" (or "touchend" on mobile).
$(".movie-container").on("click", function() {
var url = $(this).data("stream-url");
$dummyVideo.attr("src", url);
$dummyVideo.get(0).load(); // required if src changed after page load
$dummyVideo.get(0).play();
});
And viola. As far as UX goes, a user clicks on a video to play and Quicktime opens playing the video they chose. This remains within the limitation that videos can only be played via user action so I'm not forcing data on anyone who isn't deciding to watch a video with this service. I discovered this when trying to figure out how exactly Youtube pulled this off with their mobile which is essentially some really nice Javascript page building and fancy element hiding like in the case of the video tag.
tl;dr Here is a somewhat "workaround" to try and create an "autoplay" UX feature on iOS devices without going above and beyond Apple's limitations and still having users decide if they want to watch a video (or audio most likey, though I've not tested) themselves without having one just loaded without their permission.
Also, to the person who commented that is from sleep.fm, this still unfortunately would not have been a solution to your issues which is time based audio play back.
I hope someone finds this information useful, it would have saved me a week of bad news delivery to a client that was adamant that they have this feature and I was glad to find a way to deliver it in the end.
EDIT
Further finding indicate the above workaround is for iPhone/iPod devices only. The iPad plays video in Safari before it's been full screened so you'll need some mechanism to resize the video on click before playing or else you'll end up with audio and no video.
I used fontWithSize
for a label with light system font, but it changes back to normal system font.
If you want to keep the font's traits, better to include the descriptors.
label.font = UIFont(descriptor: label.font.fontDescriptor(), size: 16.0)
all multy key's probably fail, cause the put([key1, key2], val) and the get([null, key2]) end up using the equals of [key1, key2] and [null, key2]. If the backing map doesnt contains hash buckets per key then lookups are real slow to.
i think the way to go is using a index decorator (see the key1, key2 examples above) and if the extra index key's are properties of the stored value you can use the property name's and reflection to build the secondairy maps when you put(key, val) and add an extra method get(propertyname, propertyvalue) to use that index.
the return type of the get(propertyname, propertyvalue) could be a Collection so even none unique key's are indexed....
You just have to use your local IP address:using the cmd command "ipconfig" and your server port number like this:
String webServiceUrl = "http://192.168.X.X:your_local_server_port/your_web_service_name.php"
And make sure you did set the internet permission in your project manifest
It's working perfectly for me
Good Luck
A PDOStatement
(which you have in $users
) is a forward-cursor. That means, once consumed (the first foreach
iteration), it won't rewind to the beginning of the resultset.
You can close the cursor after the foreach
and execute the statement again:
$users = $dbh->query($sql);
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
$users->execute();
foreach ($users as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
Or you could cache using tailored CachingIterator
with a fullcache:
$users = $dbh->query($sql);
$usersCached = new CachedPDOStatement($users);
foreach ($usersCached as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($usersCached as $row) {
print $row["name"] . "-" . $row["sex"] ."<br/>";
}
You find the CachedPDOStatement
class as a gist. The caching itertor is probably more sane than storing the resultset into an array because it still offers all properties and methods of the PDOStatement
object it has wrapped.
I was getting the same error even after adding no-arg constructor,Then I figured out that I was missing several JARs.I am posting this so that if anyone gets the error like I got, make sure you have added these JARs in your lib folder :
activation-1.0.2.jar
antlr-2.7.6.jar
aopalliance.jar
asm-1.5.3.jar
asm-attrs-1.5.3.jar
cglib-2.1_3.jar
commons-beanutils-1.7.0.jar
commons-collections-2.1.1.jar
commons-digester-1.8.jar
commons-email-1.0.jar
commons-fileupload-1.1.1.jar
commons-io-1.1.jar
commons-lang-2.5.jar
commons-logging-1.1.3.jar
dom4j-1.6.1.jar
dumbster-1.6.jar
ehcache-1.2.3.jar
ejb3-persistence-3.3.1.jar
hibernate-commons-annotations-4.0.4.Final.jar
hibernate-core-4.2.8.Final.jar
icu4j-2.6.1.jar
javassist-3.4.GA.jar
javax.persistence_2.0.3.v201010191057.jar
javax.servlet.jsp.jstl-1.2.1.jar
jaxb-api-2.1.jar
jaxb-impl-2.1.3.jar
jaxen-1.1.1.jar
jboss-logging-3.1.3.GA.jar
jdom-1.0.jar
jstl-1.2.jar
jta-1.1.jar
lucene-core-2.3.2.jar
lucene-highlighter-2.0.0.jar
mail-1.4.jar
mysql-connector-java-5.0.8-bin.jar
org.springframework.orm.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.5.6.jar
spring-aop-4.0.0.RELEASE.jar
spring-aspects-4.0.0.RELEASE-javadoc.jar
spring-beans-4.0.0.RELEASE.jar
spring-build-src-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
spring-framework-bom-4.0.0.RELEASE.jar
spring-jdbc-4.0.0.RELEASE.jar
spring-orm-4.0.0.RELEASE.jar
spring-tx-4.0.0.RELEASE.jar
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar
stax-api-1.0-2.jar
validation-api-1.0.0.GA.jar
xalan-2.6.0.jar
xercesImpl-2.6.2.jar
xml-apis-1.3.02.jar
xmlParserAPIs-2.6.2.jar
xom-1.0.jar
In my case, this causes error:
return response->json(["message" => "Model status successfully updated!", "data" => $model], 200);
but this not:
return response->json(["message" => "Model status successfully updated!", "data" => $model->toJson()], 200);
If i go by Grodriguez's answer
System.out.println("" + value);
value = value.setScale(0, BigDecimal.ROUND_HALF_UP);
System.out.println("" + value);
This is the output
100.23 -> 100
100.77 -> 101
Which isn't quite what i want, so i ended up doing this..
System.out.println("" + value);
value = value.setScale(0, BigDecimal.ROUND_HALF_UP);
value = value.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("" + value);
This is what i get
100.23 -> 100.00
100.77 -> 101.00
This solves my problem for now .. : ) Thank you all.
try this if you need to convert black image into white:
.classname{
filter: brightness(0) invert(1);
}
Generic methods to compare a char at a position between 2 strings with ignore case.
public static boolean isEqualIngoreCase(char one, char two){
return Character.toLowerCase(one)==Character .toLowerCase(two);
}
public static boolean isEqualStringCharIgnoreCase(String one, String two, int position){
char oneChar = one.charAt(position);
char twoChar = two.charAt(position);
return isEqualIngoreCase(oneChar, twoChar);
}
Function call
boolean isFirstCharEqual = isEqualStringCharIgnoreCase("abc", "ABC", 0)
This occurred for me due to changing the names of certain dataset fields within BIDS that were being referenced by parameters. I forgot to go into the parameters and reassign a default value (the default value of the parameter didn't automatically change to the newly renamed dataset field. Instead .
You can try this:
/// <summary>
/// Remove all extra spaces and tabs between words in the specified string!
/// </summary>
/// <param name="str">The specified string.</param>
public static string RemoveExtraSpaces(string str)
{
str = str.Trim();
StringBuilder sb = new StringBuilder();
bool space = false;
foreach (char c in str)
{
if (char.IsWhiteSpace(c) || c == (char)9) { space = true; }
else { if (space) { sb.Append(' '); }; sb.Append(c); space = false; };
}
return sb.ToString();
}
A slightly simplified version of Oglester's solution (the sequence doesn't require a select from DUAL:
INSERT INTO account_type_standard
(account_type_Standard_id, tax_status_id, recipient_id)
VALUES(
account_type_standard_seq.nextval,
(SELECT tax_status_id FROM tax_status WHERE tax_status_code = ?),
(SELECT recipient_id FROM recipient WHERE recipient_code = ?)
)
When git push [$there]
does not say what to push, we have used the
traditional "matching" semantics so far (all your branches were sent
to the remote as long as there already are branches of the same name
over there). In Git 2.0, the default is now the "simple" semantics,
which pushes:
only the current branch to the branch with the same name, and only when the current branch is set to integrate with that remote branch, if you are pushing to the same remote as you fetch from; or
only the current branch to the branch with the same name, if you are pushing to a remote that is not where you usually fetch from.
You can use the configuration variable "push.default" to change this. If you are an old-timer who wants to keep using the "matching" semantics, you can set the variable to "matching", for example. Read the documentation for other possibilities.
When git add -u
and git add -A
are run inside a subdirectory
without specifying which paths to add on the command line, they
operate on the entire tree for consistency with git commit -a
and
other commands (these commands used to operate only on the current
subdirectory). Say git add -u .
or git add -A .
if you want to
limit the operation to the current directory.
git add <path>
is the same as git add -A <path>
now, so that
git add dir/
will notice paths you removed from the directory and
record the removal. In older versions of Git, git add <path>
used
to ignore removals. You can say git add --ignore-removal <path>
to
add only added or modified paths in <path>
, if you really want to.
This is going to be something to do with character encodings.
Are you sure the mirrored site has the same properties with regards to character encodings as your main server?
Depending on what sort of server you have, this may be a property of the server process itself, or it could be an environment variable.
For example, if this is a UNIX environment, perhaps try comparing LANG or LC_ALL?
See also here
You should learn the raise statement of python for that. It should be kept inside the try block. Example -
try:
raise TypeError #remove TypeError by any other error if you want
except TypeError:
print('TypeError raised')
Keep in mind that there are processes on the database which may not currently support a session.
If you're interested in all processes you'll want to look to v$process (or gv$process on RAC)
You can simplify this code to:
DirectorySearcher searcher = new DirectorySearcher();
searcher.Filter = "(&(objectCategory=user)(cn=steve.evans))";
SearchResultCollection results = searcher.FindAll();
if (results.Count == 1)
{
//do what you want to do
}
else if (results.Count == 0)
{
//user does not exist
}
else
{
//found more than one user
//something is wrong
}
If you can narrow down where the user is you can set searcher.SearchRoot to a specific OU that you know the user is under.
You should also use objectCategory instead of objectClass since objectCategory is indexed by default.
You should also consider searching on an attribute other than CN. For example it might make more sense to search on the username (sAMAccountName) since it's guaranteed to be unique.
Hash code is used for hash-based collections like Dictionary, Hashtable, HashSet etc. The purpose of this code is to very quickly pre-sort specific object by putting it into specific group (bucket). This pre-sorting helps tremendously in finding this object when you need to retrieve it back from hash-collection because code has to search for your object in just one bucket instead of in all objects it contains. The better distribution of hash codes (better uniqueness) the faster retrieval. In ideal situation where each object has a unique hash code, finding it is an O(1) operation. In most cases it approaches O(1).
I ran into this error also. For whatever reason I had originally coded
var table = $('#myTable').DataTable({
"paging": false,
"order": [[ 4, "asc" ]]
});
This would not throw the error sometimes and other times it would. By changing code to
$('#myTable').DataTable({
"paging": false,
"order": [[ 4, "asc" ]]
});
Error appears to have stopped
var Str_txt = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';
If you want to add at last position then use this:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].push({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"
If you want to add at first position then use the following code:
var parse_obj = JSON.parse(Str_txt);
parse_obj['theTeam'].unshift({"teamId":"4","status":"pending"});
Str_txt = JSON.stringify(parse_obj);
Output //"{"theTeam":[{"teamId":"4","status":"pending"},{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}"
Anyone who wants to add at a certain position of an array try this:
parse_obj['theTeam'].splice(2, 0, {"teamId":"4","status":"pending"});
Output //"{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"4","status":"pending"},{"teamId":"3","status":"member"}]}"
Above code block adds an element after the second element.
I found this code where date is compared in a format to compare with date field in database...may be this might be helpful to you...
When you convert the string to date using simpledateformat, it is hard to compare with the Date field in mysql databases.
So convert the java string date in the format using select STR_to_DATE('yourdate','%m/%d/%Y') --> in this format, then you will get the exact date format of mysql date field.
http://javainfinite.com/java/java-convert-string-to-date-and-compare/