Are you thinking about something like this?
$('ul li').each(function(i)
{
$(this).attr('rel'); // This is your rel value
});
Try this:
string text = "My text that I want to display";
MessageBox.Show(text);
Try Catch exists via workaround in VBScript:
Class CFunc1
Private Sub Class_Initialize
WScript.Echo "Starting"
Dim i : i = 65535 ^ 65535
MsgBox "Should not see this"
End Sub
Private Sub CatchErr
If Err.Number = 0 Then Exit Sub
Select Case Err.Number
Case 6 WScript.Echo "Overflow handled!"
Case Else WScript.Echo "Unhandled error " & Err.Number & " occurred."
End Select
Err.Clear
End Sub
Private Sub Class_Terminate
CatchErr
WScript.Echo "Exiting"
End Sub
End Class
Dim Func1 : Set Func1 = New CFunc1 : Set Func1 = Nothing
In fragments, you can use
getActivity().getString(R.id.whatever);
The problem seems to relate to the way Windows handles non-native resolutions on monitors and can be avoided in several ways
The problem can be a complete nightmare when it happens, but it only happens intermittently.
We have been testing recently an excel worksheet used by a few dozen people and have developed a good idea of the cause and some possible fixes.
The cause seems to relate to any setup where screens are used in something other than their native resolution. This can happen easily if a user plugs an external monitor into a laptop and doesn't choose the resulting screen configuration carefully. For example, if a laptop is plugged into a projector (perhaps an old one with a native 1024 by 768 display) but the laptop is a 1280 by 800 and the user chooses to duplicate the display rather than extending it (settings in "connect to a projector" or "displays" control panel in Windows 7), the result is an unpredictable and usually unsatisfactory image on both screens with both in non-native resolutions. We have found that these settings almost always cause serious problems with Excel buttons, especially ActiveX controls. Sometimes, on repeated clicks, they shrink to unreadability; other times they expand to cover the whole screen.
Mostly, when we instruct users to use the extend display setting and the result is two screens both using native resolutions, we don't see the problem.
There are also code-based ways to minimize the problem. We tried resetting the location and size of buttons and controls when they were clicked (which adds a lot of tedious code if you have a lot of buttons). This sometimes worked. We also tried toggling the autosize property from true to false and back (this works manually in developer mode) and this fixes more instances, but not apparently all.
git pull origin master
will fetch all the changes from the remote's master branch and will merge it into your local.We generally don't use git pull origin/master.We can do the same thing by git merge origin/master
.It will merge all the changes from "cached copy" of origin's master branch into your local branch.In my case git pull origin/master
is throwing the error.
Technically you don't need to install it globally if the node_modules
folder in your local installation is in your PATH
. Generally this isn't a good idea.
Alternatively if npm test
references gulp
then you can just type npm test
and it'll run the local gulp.
I've never installed gulp globally -- I think it's bad form.
This can be used to get the first two characters as hours and last two as minutes. Same logic may be applied to seconds.
/**_x000D_
* PT1H30M -> 0130_x000D_
* @param {ISO String} isoString_x000D_
* @return {string} absolute 4 digit number HH:mm_x000D_
*/_x000D_
_x000D_
const parseIsoToAbsolute = (isoString) => {_x000D_
_x000D_
const durations = moment.duration(isoString).as('seconds');_x000D_
const momentInSeconds = moment.duration(durations, 'seconds');_x000D_
_x000D_
let hours = momentInSeconds.asHours().toString().length < 2_x000D_
? momentInSeconds.asHours().toString().padStart(2, '0') : momentInSeconds.asHours().toString();_x000D_
_x000D_
if (!Number.isInteger(Number(hours))) hours = '0'+ Math.floor(hours);_x000D_
_x000D_
const minutes = momentInSeconds.minutes().toString().length < 2_x000D_
? momentInSeconds.minutes().toString().padEnd(2, '0') : momentInSeconds.minutes().toString();_x000D_
_x000D_
const absolute = hours + minutes;_x000D_
return absolute;_x000D_
};_x000D_
_x000D_
console.log(parseIsoToAbsolute('PT1H30M'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
_x000D_
I was trying to use Feign, while I encounter same issue, As I understood HTTP message converter will help but wanted to understand how to achieve this.
@FeignClient(name = "mobilesearch", url = "${mobile.search.uri}" ,
fallbackFactory = MobileSearchFallbackFactory.class,
configuration = MobileSearchFeignConfig.class)
public interface MobileSearchClient {
@RequestMapping(method = RequestMethod.GET)
List<MobileSearchResponse> getPhones();
}
You have to use Customer Configuration for the decoder, MobileSearchFeignConfig,
public class MobileSearchFeignConfig {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
@Bean
public Decoder feignDecoder() {
return new ResponseEntityDecoder(new SpringDecoder(feignHttpMessageConverter()));
}
public ObjectFactory<HttpMessageConverters> feignHttpMessageConverter() {
final HttpMessageConverters httpMessageConverters = new HttpMessageConverters(new MappingJackson2HttpMessageConverter());
return new ObjectFactory<HttpMessageConverters>() {
@Override
public HttpMessageConverters getObject() throws BeansException {
return httpMessageConverters;
}
};
}
public class MappingJackson2HttpMessageConverter extends org.springframework.http.converter.json.MappingJackson2HttpMessageConverter {
MappingJackson2HttpMessageConverter() {
List<MediaType> mediaTypes = new ArrayList<>();
mediaTypes.add(MediaType.valueOf(MediaType.TEXT_HTML_VALUE + ";charset=UTF-8"));
setSupportedMediaTypes(mediaTypes);
}
}
}
Automatically fill all form fields from an array
http://jsfiddle.net/brynner/wf0rk7tz/2/
JS
function fill(a){
for(var k in a){
$('[name="'+k+'"]').val(a[k]);
}
}
array_example = {"God":"Jesus","Holy":"Spirit"};
fill(array_example);
HTML
<form>
<input name="God">
<input name="Holy">
</form>
For strings, you can use string.c_str()
which will return you a const char*, which can be treated as an array, example:
const char* strdata = str.c_str();
for (int i = 0; i < str.length(); ++i)
cout << i << strdata[i];
In Apache, you can add the woff2
mime type via your .htaccess
file as stated by this link.
AddType application/font-woff2 .woff2
In IIS, simply add the following mimeMap
tag into your web.config
file inside the staticContent
tag.
<configuration>
<system.webServer>
<staticContent>
<mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
To install the latest stable version:
nvm install stable
To set default to the stable version (instead of a specific version):
nvm alias default stable
To list installed versions:
nvm list
As of v6.2.0
, it will look something like:
$ nvm list
v4.4.2
-> v6.2.0
default -> stable (-> v6.2.0)
node -> stable (-> v6.2.0) (default)
stable -> 6.2 (-> v6.2.0) (default)
iojs -> N/A (default)
This solution is what we are using:
def test_date_invalidformat():
"""
Test if input incorrect data will raises ValueError exception
"""
date = "06/21/2018 00:00:00"
with pytest.raises(ValueError):
app.func(date) #my function to be tested
Please refer to pytest, https://docs.pytest.org/en/latest/reference.html#pytest-raises
Another possible option would be to use Datejs
Then you can do
Date.getDaysInMonth(2009, 9)
Although adding a library just for this function is overkill, it's always nice to know all the options you have available to you :)
By default, an image is rendered inline, like a letter so it sits on the same line that a, b, c and d sit on.
There is space below that line for the descenders you find on letters like g, j, p and q.
You can:
vertical-align
of the image to position it elsewhere (e.g. the middle
) ordisplay
so it isn't inline.div {_x000D_
border: solid black 1px;_x000D_
margin-bottom: 10px;_x000D_
}_x000D_
_x000D_
#align-middle img {_x000D_
vertical-align: middle;_x000D_
}_x000D_
_x000D_
#align-base img {_x000D_
vertical-align: bottom;_x000D_
}_x000D_
_x000D_
#display img {_x000D_
display: block;_x000D_
}
_x000D_
<div id="default">_x000D_
<h1>Default</h1>_x000D_
The quick brown fox jumps over the lazy dog <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f2/VangoghStarry-night2.jpg/300px-VangoghStarry-night2.jpg" alt="">_x000D_
</div>_x000D_
_x000D_
<div id="align-middle">_x000D_
<h1>vertical-align: middle</h1>_x000D_
The quick brown fox jumps over the lazy dog <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f2/VangoghStarry-night2.jpg/300px-VangoghStarry-night2.jpg" alt=""> </div>_x000D_
_x000D_
<div id="align-base">_x000D_
<h1>vertical-align: bottom</h1>_x000D_
The quick brown fox jumps over the lazy dog <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f2/VangoghStarry-night2.jpg/300px-VangoghStarry-night2.jpg" alt=""> </div>_x000D_
_x000D_
<div id="display">_x000D_
<h1>display: block</h1>_x000D_
The quick brown fox jumps over the lazy dog <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f2/VangoghStarry-night2.jpg/300px-VangoghStarry-night2.jpg" alt="">_x000D_
</div>
_x000D_
The included image is public domain and sourced from Wikimedia Commons
@SamMonk your technique is great. But you can use laravel form helper to do so. I have a customer and dogs relationship.
On your controller
$dogs = Dog::lists('name', 'id');
On customer create view you can use.
{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, null, ['id' => 'dogs', 'multiple' => 'multiple']) }}
Third parameter accepts a list of array a well. If you define a relationship on your model you can do this:
{{ Form::label('dogs', 'Dogs') }}
{{ Form::select('dogs[]', $dogs, $customer->dogs->lists('id'), ['id' => 'dogs', 'multiple' => 'multiple']) }}
Update For Laravel 5.1
The lists method now returns a Collection. Upgrading To 5.1.0
{!! Form::label('dogs', 'Dogs') !!}
{!! Form::select('dogs[]', $dogs, $customer->dogs->lists('id')->all(), ['id' => 'dogs', 'multiple' => 'multiple']) !!}
Using dis
to look at the bytecode generated for the two versions:
not ==
4 0 LOAD_FAST 0 (foo)
3 LOAD_FAST 1 (bar)
6 COMPARE_OP 2 (==)
9 UNARY_NOT
10 RETURN_VALUE
!=
4 0 LOAD_FAST 0 (foo)
3 LOAD_FAST 1 (bar)
6 COMPARE_OP 3 (!=)
9 RETURN_VALUE
The latter has fewer operations, and is therefore likely to be slightly more efficient.
It was pointed out in the commments (thanks, @Quincunx) that where you have if foo != bar
vs. if not foo == bar
the number of operations is exactly the same, it's just that the COMPARE_OP
changes and POP_JUMP_IF_TRUE
switches to POP_JUMP_IF_FALSE
:
not ==
:
2 0 LOAD_FAST 0 (foo)
3 LOAD_FAST 1 (bar)
6 COMPARE_OP 2 (==)
9 POP_JUMP_IF_TRUE 16
!=
2 0 LOAD_FAST 0 (foo)
3 LOAD_FAST 1 (bar)
6 COMPARE_OP 3 (!=)
9 POP_JUMP_IF_FALSE 16
In this case, unless there was a difference in the amount of work required for each comparison, it's unlikely you'd see any performance difference at all.
However, note that the two versions won't always be logically identical, as it will depend on the implementations of __eq__
and __ne__
for the objects in question. Per the data model documentation:
There are no implied relationships among the comparison operators. The truth of
x==y
does not imply thatx!=y
is false.
For example:
>>> class Dummy(object):
def __eq__(self, other):
return True
def __ne__(self, other):
return True
>>> not Dummy() == Dummy()
False
>>> Dummy() != Dummy()
True
Finally, and perhaps most importantly: in general, where the two are logically identical, x != y
is much more readable than not x == y
.
Another answer for the first question is to use one for loop and perform linear indexing into the array using the function NUMEL to get the total number of elements:
total = 0;
for i = 1:numel(A)
total = total+A(i);
end
One thing want to add is that if a property is declared as @dynamic it will not occupy memory (I confirmed with allocation instrument). A consequence is that you can declare property in class category.
rem set defaults:
set filename1="c:\file1.txt"
set filename2="c:\file2.txt"
set filename3="c:\file3.txt"
rem set parameters:
IF NOT "a%1"=="a" (set filename1="%1")
IF NOT "a%2"=="a" (set filename2="%2")
IF NOT "a%3"=="a" (set filename1="%3")
echo %filename1%, %filename2%, %filename3%
Be careful with quotation characters though, you may or may not need them in your variables.
r := strings(byteData)
This also works to turn []byte
into io.Reader
With Angular Universal, you can generate landing pages for the app that look like the complete app and then load your Angular app behind it.
Angular Universal generates pure HTML means no-javascript pages in server-side and serve them to users without delaying. So you can deal with any crawler, bot and user (who already have low cpu and network speed).Then you can redirect them by links/buttons to your actual angular app that already loaded behind it. This solution is recommended by official site. -More info about SEO and Angular Universal-
There can be one more reason for such behavior - you delete current working directory.
For example:
# in terminal #1
cd /home/user/myJavaApp
# in terminal #2
rm -rf /home/user/myJavaApp
# in terminal #1
java -jar myJar.jar
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.
I used SOAP UI for functional and automated testing. SOAP UI allows you to run the tests on the click of a button. There is also a spring controllers testing page created by Ted Young. I used this article to create Rest unit tests in our application.
Use align-items: flex-start
on the container, or align-self: flex-start
on the flex items.
No need for display: inline-flex
.
An initial setting of a flex container is align-items: stretch
. This means that flex items will expand to cover the full length of the container along the cross axis.
The align-self
property does the same thing as align-items
, except that align-self
applies to flex items while align-items
applies to the flex container.
By default, align-self
inherits the value of align-items
.
Since your container is flex-direction: column
, the cross axis is horizontal, and align-items: stretch
is expanding the child element's width as much as it can.
You can override the default with align-items: flex-start
on the container (which is inherited by all flex items) or align-self: flex-start
on the item (which is confined to the single item).
Learn more about flex alignment along the cross axis here:
Learn more about flex alignment along the main axis here:
Simply use the base transpose function t
, wrapped with as.data.frame
:
final_df <- as.data.frame(t(starting_df))
final_df
A B C D
a 1 2 3 4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd
Above updated. As docendo discimus pointed out, t
returns a matrix. As Mark suggested wrapping it with as.data.frame
gets back a data frame instead of a matrix. Thanks!
After hours of struggle with no solution here, this worked for me then I found a youtube video where it says the password column is now called authentication_string . So I was able to change my password as follows: First get into mysql from terminal
sudo mysql
then inside mysql type whatever after mysql>
mysql> use mysql
mysql> update user set authentication_string=PASSWORD("mypass") where user='root';
mysql> flush privileges;
mysql> quit;
at this point you are out of mysql back to your normal terminal place. You need to restart mysql for this to take effect. for that type the following:
sudo service mysql restart
Refer to this video link for better understanding
Just use the constructor for the vector that takes iterators:
std::set<T> s;
//...
std::vector v( s.begin(), s.end() );
Assumes you just want the content of s in v, and there's nothing in v prior to copying the data to it.
If anyone is interested in getting the localized string from the property with DisplayAttribute and ResourceType like this:
[Display(Name = "Year", ResourceType = typeof(ArrivalsResource))]
public int Year { get; set; }
Use the following after displayAttribute != null
(as shown above by @alex' answer):
ResourceManager resourceManager = new ResourceManager(displayAttribute.ResourceType);
var entry = resourceManager.GetResourceSet(Thread.CurrentThread.CurrentUICulture, true, true)
.OfType<DictionaryEntry>()
.FirstOrDefault(p => p.Key.ToString() == displayAttribute.Name);
return entry.Value.ToString();
Promise returned from $http
can not be binded directly (I dont exactly know why).
I'm using wrapping service that works perfectly for me:
.factory('DocumentsList', function($http, $q){
var d = $q.defer();
$http.get('/DocumentsList').success(function(data){
d.resolve(data);
});
return d.promise;
});
and bind to it in controller:
function Ctrl($scope, DocumentsList) {
$scope.Documents = DocumentsList;
...
}
UPDATE!:
In Angular 1.2 auto-unwrap promises was removed. See http://docs.angularjs.org/guide/migration#templates-no-longer-automatically-unwrap-promises
I had the same problem and came across this post. Nothing worked. After randomly playing around, I found that <embed ........ play="false">
stopped it from playing automatically. I now have the problem that I can't get a controller to appear, so can't start the movie! :S
A better approach is to have something "steal" first responder status.
Since UIApplication is a subclass of UIResponder, you could try:
[[UIApplication sharedApplication] becomeFirstResponder]
[[UIApplication sharedApplication] resignFirstResponder]
Failing that, create a new UITextField with a zero sized frame, add it to a view somewhere and do something similar (become followed by resign).
EDIT: As of 2019, e.metaKey
is supported on all major browsers as per the MDN.
Note that on Windows, although the ? Windows key is considered to be the "meta" key, it is not going to be captured by browsers as such.
This is only for the command key on MacOS/keyboards.
Unlike Shift/Alt/Ctrl, the Cmd (“Apple”) key is not considered a modifier key—instead, you should listen on keydown
/keyup
and record when a key is pressed and then depressed based on event.keyCode
.
Unfortunately, these key codes are browser-dependent:
224
17
91
(Left Command) or 93
(Right Command)You might be interested in reading the article JavaScript Madness: Keyboard Events, from which I learned that knowledge.
Try this
public class NetworkUtil {
public static final int TYPE_WIFI = 1;
public static final int TYPE_MOBILE = 2;
public static final int TYPE_NOT_CONNECTED = 0;
public static final int NETWORK_STATUS_NOT_CONNECTED = 0;
public static final int NETWORK_STATUS_WIFI = 1;
public static final int NETWORK_STATUS_MOBILE = 2;
public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}
public static int getConnectivityStatusString(Context context) {
int conn = NetworkUtil.getConnectivityStatus(context);
int status = 0;
if (conn == NetworkUtil.TYPE_WIFI) {
status = NETWORK_STATUS_WIFI;
} else if (conn == NetworkUtil.TYPE_MOBILE) {
status = NETWORK_STATUS_MOBILE;
} else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
status = NETWORK_STATUS_NOT_CONNECTED;
}
return status;
}
}
And for the BroadcastReceiver
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
int status = NetworkUtil.getConnectivityStatusString(context);
Log.e("Sulod sa network reciever", "Sulod sa network reciever");
if ("android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction())) {
if (status == NetworkUtil.NETWORK_STATUS_NOT_CONNECTED) {
new ForceExitPause(context).execute();
} else {
new ResumeForceExitPause(context).execute();
}
}
}
}
Don't forget to put this into your AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<receiver
android:name="NetworkChangeReceiver"
android:label="NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
Hope this will help you Cheers!
CGRect screenBounds = [[UIScreen mainScreen] bounds];
That will give you the entire screen's resolution in points, so it would most typically be 320x480 for iPhones. Even though the iPhone4 has a much larger screen size iOS still gives back 320x480 instead of 640x960. This is mostly because of older applications breaking.
CGFloat screenScale = [[UIScreen mainScreen] scale];
This will give you the scale of the screen. For all devices that do not have Retina Displays this will return a 1.0f, while Retina Display devices will give a 2.0f and the iPhone 6 Plus (Retina HD) will give a 3.0f.
Now if you want to get the pixel width & height of the iOS device screen you just need to do one simple thing.
CGSize screenSize = CGSizeMake(screenBounds.size.width * screenScale, screenBounds.size.height * screenScale);
By multiplying by the screen's scale you get the actual pixel resolution.
A good read on the difference between points and pixels in iOS can be read here.
EDIT: (Version for Swift)
let screenBounds = UIScreen.main.bounds
let screenScale = UIScreen.main.scale
let screenSize = CGSize(width: screenBounds.size.width * screenScale, height: screenBounds.size.height * screenScale)
Have you tried mode 'a+'?
with open(filename, 'a+') as f:
f.write(...)
Note however that f.tell()
will return 0 in Python 2.x. See https://bugs.python.org/issue22651 for details.
solution is easy:
replace
mask = (50 < df['heart rate'] < 101 &
140 < df['systolic blood pressure'] < 160 &
90 < df['dyastolic blood pressure'] < 100 &
35 < df['temperature'] < 39 &
11 < df['respiratory rate'] < 19 &
95 < df['pulse oximetry'] < 100
, "excellent", "critical")
by
mask = ((50 < df['heart rate'] < 101) &
(140 < df['systolic blood pressure'] < 160) &
(90 < df['dyastolic blood pressure'] < 100) &
(35 < df['temperature'] < 39) &
(11 < df['respiratory rate'] < 19) &
(95 < df['pulse oximetry'] < 100)
, "excellent", "critical")
NOTE: You may want to remove duplicate items (eg duplicate entries in the same column) before doing these steps to prevent false positives.
split
slice
concentrate
This is a good workout for beginners and it's easy to achieve.
Another advanced method is a function like this:
def trim(s):
return trim(s[slice])
And for this question, you just want to remove the last characters, so you can write like this:
def trim(s):
return s[ : -3]
I think you are over to care about what those three characters are, so you lost. You just want to remove last three, nevertheless who they are!
If you want to remove some specific characters, you can add some if judgements:
def trim(s):
if [conditions]: ### for some cases, I recommend using isinstance().
return trim(s[slice])
Your class has a base class, and this base class also has a property (which is not virtual or abstract) called Events which is being overridden by your class. If you intend to override it put the "new" keyword after the public modifier. E.G.
public new EventsDataTable Events
{
..
}
If you don't wish to override it change your properties' name to something else.
using Android KTX library u can parse easily
val uri = myUriString.toUri()
PuTTY's plink has a command-line argument for a password. Some other suggestions have been made in the answers to this question: using Expect (which is available for Windows), or writing a launcher in Python with Paramiko.
It is worth noting that when a .CSV file has fields wrapped in double quotes which contain line breaks, Excel will not import the .CSV file properly if the .CSV file is written in UTF-8 format. Excel treats the line break as if it were CR/LF and begins a new line. The spreadsheet is garbled. That seems to be true even if semi-colons are used as field delimiters (instead of commas).
The problem can be resolved by using Windows Notepad to edit the .CSV file, using File > Save As... to save the file, and before saving the file, changing the file encoding from UTF-8 to ANSI. Once the file is saved in ANSI format, then I find that Microsoft Excel 2013 running on Windows 7 Professional will import the file properly.
well... with 5.3 on the horizon, all will be better, because with 5.3, we'll get closures and with them anonymous functions
Decides when the route should be stored return false to
this.router.routeReuseStrategy.shouldReuseRoute = function () {
return false;
};
and set the navigated value of router to false, that show that this route never routed
this.mySubscription = this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
this.router.navigated = false;
}
});
SELECT CONVERT(DATE,DATEADD(MM, DATEDIFF(MM, 0, GETDATE())-1, 0)) AS FirstDayOfPrevMonth
SELECT CONVERT(DATE,DATEADD(MS, -3, DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) , 0))) AS LastDayOfPrevMonth
You get the integer limits in <limits.h>
or <climits>
. Floating point characteristics are defined in <float.h>
for C. In C++, the preferred version is usually std::numeric_limits<double>::max()
(for which you #include <limits>
).
As to your original question, if you want a larger integer type than long
, you should probably consider long long
. This isn't officially included in C++98 or C++03, but is part of C99 and C++11, so all reasonably current compilers support it.
Style the td
and th
instead
td, th {
border: 1px solid black;
}
And also to make it so there is no spacing between cells use:
table {
border-collapse: collapse;
}
(also note, you have border-style: none;
which should be border-style: solid;
)
See an example here: http://jsfiddle.net/KbjNr/
Update from @MrEngineer13's answer: to align title center in any cases, including Hamburger icon, option menus, you can add a FrameLayout
in toolbar like this:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_top"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="@color/action_bar_bkgnd"
app:theme="@style/ToolBarTheme" >
<FrameLayout android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toolbar Title"
android:layout_gravity="center"
style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title"
android:id="@+id/toolbar_title" />
</FrameLayout>
</android.support.v7.widget.Toolbar>
Here’s some code you can use to get a list of all the open windows. Actually, you get a dictionary where each item is a KeyValuePair where the key is the handle (hWnd) of the window and the value is its title. It also finds pop-up windows, such as those created by MessageBox.Show
.
using System.Runtime.InteropServices;
using HWND = System.IntPtr;
/// <summary>Contains functionality to get all the open windows.</summary>
public static class OpenWindowGetter
{
/// <summary>Returns a dictionary that contains the handle and title of all the open windows.</summary>
/// <returns>A dictionary that contains the handle and title of all the open windows.</returns>
public static IDictionary<HWND, string> GetOpenWindows()
{
HWND shellWindow = GetShellWindow();
Dictionary<HWND, string> windows = new Dictionary<HWND, string>();
EnumWindows(delegate(HWND hWnd, int lParam)
{
if (hWnd == shellWindow) return true;
if (!IsWindowVisible(hWnd)) return true;
int length = GetWindowTextLength(hWnd);
if (length == 0) return true;
StringBuilder builder = new StringBuilder(length);
GetWindowText(hWnd, builder, length + 1);
windows[hWnd] = builder.ToString();
return true;
}, 0);
return windows;
}
private delegate bool EnumWindowsProc(HWND hWnd, int lParam);
[DllImport("USER32.DLL")]
private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);
[DllImport("USER32.DLL")]
private static extern int GetWindowText(HWND hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("USER32.DLL")]
private static extern int GetWindowTextLength(HWND hWnd);
[DllImport("USER32.DLL")]
private static extern bool IsWindowVisible(HWND hWnd);
[DllImport("USER32.DLL")]
private static extern IntPtr GetShellWindow();
}
And here’s some code that uses it:
foreach(KeyValuePair<IntPtr, string> window in OpenWindowGetter.GetOpenWindows())
{
IntPtr handle = window.Key;
string title = window.Value;
Console.WriteLine("{0}: {1}", handle, title);
}
There is two simples ways to do that :
1-
select("users.birthdate",
DB::raw("FLOOR(DATEDIFF(CURRENT_DATE, STR_TO_DATE(users.birthdate, '%Y-%m-%d'))/365) AS age_way_one"),
2-
select("users.birthdate",DB::raw("(YEAR(CURDATE())-YEAR(users.birthdate)) AS age_way_two"))
tabControl1.SelectedTab = MyTab;
Thanks so much everyone for all these input!
I quoted that sentence from a lecture note online: http://www.cs.cornell.edu/courses/cs213/2002fa/lectures/Lecture02/Lecture02.pdf
the first page the 6th slide
" Pass by VALUE The value of a variable is passed along to the function If the function modifies that value, the modifications stay within the scope of that function.
Pass by REFERENCE A reference to the variable is passed along to the function If the function modifies that value, the modifications appear also within the scope of the calling function.
"
Thanks so much again!
As other commenters correctly noted, you should never use floating-point arithmetic when exact values are required, such as for monetary values. The main reason is indeed the rounding behaviour inherent in floating-points, but let's not forget that dealing with floating-points means also having to deal with infinite and NaN values.
As an illustration that your approach simply doesn't work, here is some simple test code. I simply add your EPSILON
to 10.0
and look whether the result is equal to 10.0
-- which it shouldn't be, as the difference is clearly not less than EPSILON
:
double a = 10.0;
double b = 10.0 + EPSILON;
if (!equals(a, b)) {
System.out.println("OK: " + a + " != " + b);
} else {
System.out.println("ERROR: " + a + " == " + b);
}
Surprise:
ERROR: 10.0 == 10.00001
The errors occurs because of the loss if significant bits on subtraction if two floating-point values have different exponents.
If you think of applying a more advanced "relative difference" approach as suggested by other commenters, you should read Bruce Dawson's excellent article Comparing Floating Point Numbers, 2012 Edition, which shows that this approach has similar shortcomings and that there is actually no fail-safe approximate floating-point comparison that works for all ranges of floating-point numbers.
To make things short: Abstain from double
s for monetary values, and use exact number representations such as BigDecimal
. For the sake of efficiency, you could also use longs
interpreted as "millis" (tenths of cents), as long as you reliably prevent over- and underflows. This yields a maximum representable values of 9'223'372'036'854'775.807
, which should be enough for most real-world applications.
I imagine this forum posting, which I quote fully below, should answer the question.
Inside a procedure, function, or trigger definition, or in a dynamic SQL statement (embedded in a host program):
BEGIN ATOMIC
DECLARE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
END
or (in any environment):
WITH t(example) AS (VALUES('welcome'))
SELECT *
FROM tablename, t
WHERE column1 = example
or (although this is probably not what you want, since the variable needs to be created just once, but can be used thereafter by everybody although its content will be private on a per-user basis):
CREATE VARIABLE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
Use COALESCE()
instead:
SELECT COALESCE(Field,'Empty') from Table;
It functions much like ISNULL
, although provides more functionality. Coalesce will return the first non null value in the list. Thus:
SELECT COALESCE(null, null, 5);
returns 5, while
SELECT COALESCE(null, 2, 5);
returns 2
Coalesce will take a large number of arguments. There is no documented maximum. I tested it will 100 arguments and it succeeded. This should be plenty for the vast majority of situations.
document.getElementById()
only supports one name at a time and only returns a single node not an array of nodes. You have several different options:
document.querySelectorAll()
that allows you to specify multiple ids in a CSS selector string .document.getElementsByClassName()
with a single class name.Examples of each option:
doStuff(document.querySelectorAll("#myCircle1, #myCircle2, #myCircle3, #myCircle4"));
or:
// put a common class on each object
doStuff(document.getElementsByClassName("circles"));
or:
function getElementsById(ids) {
var idList = ids.split(" ");
var results = [], item;
for (var i = 0; i < idList.length; i++) {
item = document.getElementById(idList[i]);
if (item) {
results.push(item);
}
}
return(results);
}
doStuff(getElementsById("myCircle1 myCircle2 myCircle3 myCircle4"));
Yes using Option Explicit
is a good habit. Using .Select
however is not :) it reduces the speed of the code. Also fully justify sheet names else the code will always run for the Activesheet
which might not be what you actually wanted.
Is this what you are trying?
Option Explicit
Sub Sample()
Dim lastRow As Long, i As Long
Dim CopyRange As Range
'~~> Change Sheet1 to relevant sheet name
With Sheets("Sheet1")
lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 2 To lastRow
If Len(Trim(.Range("A" & i).Value)) <> 0 Then
If CopyRange Is Nothing Then
Set CopyRange = .Rows(i)
Else
Set CopyRange = Union(CopyRange, .Rows(i))
End If
Else
Exit For
End If
Next
If Not CopyRange Is Nothing Then
'~~> Change Sheet2 to relevant sheet name
CopyRange.Copy Sheets("Sheet2").Rows(1)
End If
End With
End Sub
NOTE
If if you have data from Row 2 till Row 10 and row 11 is blank and then you have data again from Row 12 then the above code will only copy data from Row 2 till Row 10
If you want to copy all rows which have data then use this code.
Option Explicit
Sub Sample()
Dim lastRow As Long, i As Long
Dim CopyRange As Range
'~~> Change Sheet1 to relevant sheet name
With Sheets("Sheet1")
lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 2 To lastRow
If Len(Trim(.Range("A" & i).Value)) <> 0 Then
If CopyRange Is Nothing Then
Set CopyRange = .Rows(i)
Else
Set CopyRange = Union(CopyRange, .Rows(i))
End If
End If
Next
If Not CopyRange Is Nothing Then
'~~> Change Sheet2 to relevant sheet name
CopyRange.Copy Sheets("Sheet2").Rows(1)
End If
End With
End Sub
Hope this is what you wanted?
Sid
(ansible 2.9.6 ansible-lint 4.2.0)
See ansible-lint default rules. The condition below causes E602 Don’t compare to empty string
when: test_myscript.stderr != ""
Correct syntax and also "Ansible Galaxy Warning-Free" option is
when: test_myscript.stderr | length > 0
Quoting from source code
"Use
when: var|length > 0
rather thanwhen: var != ""
(or ' 'converselywhen: var|length == 0
rather thanwhen: var == ""
)"
Notes
- debug:
msg: "Empty string '{{ var }}' evaluates to False"
when: not var
vars:
var: ''
- debug:
msg: "Empty list {{ var }} evaluates to False"
when: not var
vars:
var: []
give
"msg": "Empty string '' evaluates to False"
"msg": "Empty list [] evaluates to False"
ANSIBLE_CONDITIONAL_BARE_VARS=false
the condition works fine but setting ANSIBLE_CONDITIONAL_BARE_VARS=true
the condition will fail - debug:
msg: "String '{{ var }}' evaluates to True"
when: var
vars:
var: 'abc'
gives
fatal: [localhost]: FAILED! =>
msg: |-
The conditional check 'var' failed. The error was: error while
evaluating conditional (var): 'abc' is undefined
Explicit cast to Boolean prevents the error but evaluates to False i.e. will be always skipped (unless var='True'
). When the filter bool
is used the options ANSIBLE_CONDITIONAL_BARE_VARS=true
and ANSIBLE_CONDITIONAL_BARE_VARS=false
have no effect
- debug:
msg: "String '{{ var }}' evaluates to True"
when: var|bool
vars:
var: 'abc'
gives
skipping: [localhost]
- include_tasks: teardown.yml
when: teardown
- include_tasks: provision.yml
when: not teardown
" based on a variable you define as a string (with quotation marks around it):"
In Ansible 2.7 and earlier, the two conditions above evaluated as True and False respectively if teardown: 'true'
In Ansible 2.7 and earlier, both conditions evaluated as False if teardown: 'false'
In Ansible 2.8 and later, you have the option of disabling conditional bare variables, so when: teardown always evaluates as True and when: not teardown always evaluates as False when teardown is a non-empty string (including 'true' or 'false')
"Expect that this setting eventually will be deprecated after 2.12"
The Magic
field of the IMAGE_OPTIONAL_HEADER
(though there is nothing optional about the header in Windows executable images (DLL/EXE files)) will tell you the architecture of the PE.
Here's an example of grabbing the architecture from a file.
public static ushort GetImageArchitecture(string filepath) {
using (var stream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
using (var reader = new System.IO.BinaryReader(stream)) {
//check the MZ signature to ensure it's a valid Portable Executable image
if (reader.ReadUInt16() != 23117)
throw new BadImageFormatException("Not a valid Portable Executable image", filepath);
// seek to, and read, e_lfanew then advance the stream to there (start of NT header)
stream.Seek(0x3A, System.IO.SeekOrigin.Current);
stream.Seek(reader.ReadUInt32(), System.IO.SeekOrigin.Begin);
// Ensure the NT header is valid by checking the "PE\0\0" signature
if (reader.ReadUInt32() != 17744)
throw new BadImageFormatException("Not a valid Portable Executable image", filepath);
// seek past the file header, then read the magic number from the optional header
stream.Seek(20, System.IO.SeekOrigin.Current);
return reader.ReadUInt16();
}
}
The only two architecture constants at the moment are:
0x10b - PE32
0x20b - PE32+
Cheers
UPDATE
It's been a while since I posted this answer, yet I still see that it gets a few upvotes now and again so I figured it was worth updating. I wrote a way to get the architecture of a Portable Executable
image, which also checks to see if it was compiled as AnyCPU
. Unfortunately the answer is in C++, but it shouldn't be too hard to port to C# if you have a few minutes to look up the structures in WinNT.h
. If people are interested I'll write a port in C#, but unless people actually want it I wont spend much time stressing about it.
#include <Windows.h>
#define MKPTR(p1,p2) ((DWORD_PTR)(p1) + (DWORD_PTR)(p2))
typedef enum _pe_architecture {
PE_ARCHITECTURE_UNKNOWN = 0x0000,
PE_ARCHITECTURE_ANYCPU = 0x0001,
PE_ARCHITECTURE_X86 = 0x010B,
PE_ARCHITECTURE_x64 = 0x020B
} PE_ARCHITECTURE;
LPVOID GetOffsetFromRva(IMAGE_DOS_HEADER *pDos, IMAGE_NT_HEADERS *pNt, DWORD rva) {
IMAGE_SECTION_HEADER *pSecHd = IMAGE_FIRST_SECTION(pNt);
for(unsigned long i = 0; i < pNt->FileHeader.NumberOfSections; ++i, ++pSecHd) {
// Lookup which section contains this RVA so we can translate the VA to a file offset
if (rva >= pSecHd->VirtualAddress && rva < (pSecHd->VirtualAddress + pSecHd->Misc.VirtualSize)) {
DWORD delta = pSecHd->VirtualAddress - pSecHd->PointerToRawData;
return (LPVOID)MKPTR(pDos, rva - delta);
}
}
return NULL;
}
PE_ARCHITECTURE GetImageArchitecture(void *pImageBase) {
// Parse and validate the DOS header
IMAGE_DOS_HEADER *pDosHd = (IMAGE_DOS_HEADER*)pImageBase;
if (IsBadReadPtr(pDosHd, sizeof(pDosHd->e_magic)) || pDosHd->e_magic != IMAGE_DOS_SIGNATURE)
return PE_ARCHITECTURE_UNKNOWN;
// Parse and validate the NT header
IMAGE_NT_HEADERS *pNtHd = (IMAGE_NT_HEADERS*)MKPTR(pDosHd, pDosHd->e_lfanew);
if (IsBadReadPtr(pNtHd, sizeof(pNtHd->Signature)) || pNtHd->Signature != IMAGE_NT_SIGNATURE)
return PE_ARCHITECTURE_UNKNOWN;
// First, naive, check based on the 'Magic' number in the Optional Header.
PE_ARCHITECTURE architecture = (PE_ARCHITECTURE)pNtHd->OptionalHeader.Magic;
// If the architecture is x86, there is still a possibility that the image is 'AnyCPU'
if (architecture == PE_ARCHITECTURE_X86) {
IMAGE_DATA_DIRECTORY comDirectory = pNtHd->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR];
if (comDirectory.Size) {
IMAGE_COR20_HEADER *pClrHd = (IMAGE_COR20_HEADER*)GetOffsetFromRva(pDosHd, pNtHd, comDirectory.VirtualAddress);
// Check to see if the CLR header contains the 32BITONLY flag, if not then the image is actually AnyCpu
if ((pClrHd->Flags & COMIMAGE_FLAGS_32BITREQUIRED) == 0)
architecture = PE_ARCHITECTURE_ANYCPU;
}
}
return architecture;
}
The function accepts a pointer to an in-memory PE image (so you can choose your poison on how to get it their; memory-mapping or reading the whole thing into memory...whatever).
This is very tricky in Python.
I'll first comment on why you're having that problem and then I will mention two possible solutions.
You must take this paragraph from the Python documentation into consideration:
Note that relative imports are based on the name of the current module. Since the name of the main module is always "main", modules intended for use as the main module of a Python application must always use absolute imports.
And also the following from PEP 328:
Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.
Relative imports work from the filename (__name__
attribute), which can take two values:
package.test_A.test
Here Python knows the parent directories: before test
comes test_A
and then package
.
So you can use the dot notation for relative import.# package.test_A/test.py
from ..A import foo
You can then have like a root file in the root directory which calls test.py
:
# root.py
from package.test_A import test
test.py
) directly, it becomes the entry point to the program , so __name__
== __main__
. The filename has no indication of the directory structure, so Python doesn't know how to go up in the directory. For Python, test.py
becomes the top-level script, there is nothing above it. That's why you cannot use relative import.A) One way to solve this is to have a root file (in the root directory) which calls the modules/packages, like this:
root.py
imports test.py
. (entry point, __name__ == __main__
).test.py
(relative) imports foo.py
.foo.py
says the module has been imported.The output is:
package.A.foo has been imported
Module's name is: package.test_A.test
B) If you want to execute the code as a module and not as a top-level script, you can try this from the command line:
python -m package.test_A.test
Any suggestions are welcomed.
You should also check: Relative imports for the billionth time , specially BrenBarn's answer.
If you want device ID information use TelephonyManager. Here is the link for that :
http://facinatingandroid.blogspot.in/2011/09/android-device-information.html
and also check this :
http://sree.cc/google/android/reading-phone-device-details-in-android
Remove the files ib_logfileN (N being the number) from the MAMP/db/mysql56 folder.
Then restart MAMP.
Should Work!
This is a fairly trivial effect to accomplish. One way to achieve this is to simply place floated div
elements within a common parent container, and set their width and height. In order to clear the floated elements, we set the overflow
property of the parent.
<div class="container">
<div class="cube">do</div>
<div class="cube">ray</div>
<div class="cube">me</div>
<div class="cube">fa</div>
<div class="cube">so</div>
<div class="cube">la</div>
<div class="cube">te</div>
<div class="cube">do</div>
</div>
The CSS resembles the strategy outlined in the first paragraph above:
.container {
width: 450px;
overflow: auto;
}
.cube {
float: left;
width: 150px;
height: 150px;
}
You can see the end result here: http://jsfiddle.net/Qjum2/2/
Browsers that support pseudo elements provide an alternative way to clear:
.container::after {
content: "";
clear: both;
display: block;
}
You can see the results here: http://jsfiddle.net/Qjum2/3/
I hope this helps.
SQL Server uses the TCP port 1433. This is probably blocked either by the VPN tunnel or by a firewall on the server.
It has nothing to do with append
. tuple(3, 4)
all by itself raises that error.
The reason is that, as the error message says, tuple
expects an iterable argument. You can make a tuple of the contents of a single object by passing that single object to tuple. You can't make a tuple of two things by passing them as separate arguments.
Just do (3, 4)
to make a tuple, as in your first example. There's no reason not to use that simple syntax for writing a tuple.
This works quite nicely for IOS
, but should also work for cocoa
.
NSString *bundleRoot = [[NSBundle mainBundle] bundlePath];
NSFileManager *manager = [NSFileManager defaultManager];
NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:bundleRoot];
NSString *filename;
while ((filename = [direnum nextObject] )) {
//change the suffix to what you are looking for
if ([filename hasSuffix:@".data"]) {
// Do work here
NSLog(@"Files in resource folder: %@", filename);
}
}
Best answer of that question I've seen is:
list(, $caller) = debug_backtrace(false);
Short and clean
I needed a C# API and after spending hours looking for it (all I found was outdated and non-working) and unsuccessfully trying to port the PHP/Python/Java versions listed here (none worked either) I decided to create my own. It's SMS-only for now...
For the simple case of just copying the last commit from branch wss to v2.1, you can simply grab the commit id (git log --oneline | head -n 1
) and do:
git checkout v2.1
git merge <commit>
I generally try to keep all of my packages in one library, but if you want to add a library why not append the new library (which must already exist in your filesystem) to the existing library path?
.libPaths( c( .libPaths(), "~/userLibrary") )
# obviously this would need to be a valid file directory in your OS
# min just happened to be on a Mac that day
Or (and this will make the userLibrary the first place to put new packages):
.libPaths( c( "~/userLibrary" , .libPaths() ) )
Then I get (at least back when I wrote this originally):
> .libPaths()
[1] "/Library/Frameworks/R.framework/Versions/2.15/Resources/library"
[2] "/Users/user_name/userLibrary"
The .libPaths
function is a bit different than most other nongraphics functions. It works via side-effect. The functions Sys.getenv
and Sys.setenv
that report and alter the R environment variables have been split apart but .libPaths
can either report or alter its target.
The information about the R startup process can be read at ?Startup
help page and there is RStudio material at: https://support.rstudio.com/hc/en-us/articles/200549016-Customizing-RStudio
In your case it appears that RStudio is not respecting the Rprofile.site settings or perhaps is overriding them by reading an .Rprofile setting from one of the RStudio defaults. It should also be mentioned that the result from this operation also appends the contents of calls to .Library
and .Library.site
, which is further reason why an RStudio- (or any other IDE or network installed-) hosted R might exhibit different behavior.
Since Sys.getenv()
returns the current system environment for the R process, you can see the library and other paths with:
Sys.getenv()[ grep("LIB|PATH", names(Sys.getenv())) ]
The two that matter for storing and accessing packages are (now different on a Linux box):
R_LIBS_SITE /usr/local/lib/R/site-library:/usr/lib/R/site-library:/usr/lib/R/library
R_LIBS_USER /home/david/R/x86_64-pc-linux-gnu-library/3.5.1/
There are three options, that you can use. -I
is to exclude binary files in grep. Other are for line numbers and file names.
grep -I -n -H
-I -- process a binary file as if it did not contain matching data;
-n -- prefix each line of output with the 1-based line number within its input file
-H -- print the file name for each match
So this might be a way to run grep:
grep -InH your-word *
The plugin manager is currently unavailable (does not come with the distribution) for Notepad++. You must install it manually (https://github.com/bruderstein/nppPluginManager/releases) and even if you do, a lot of the plugins are not available anymore (no TextFX) plugin.
Maybe there is another plugin which contains the required functionality. Other than that, the only way to do it in Notepad++ is to use some special regex for matching and then replacing (Ctrl + F → Replace tab).
Although there are many functionalities available via Edit menu item (trimming, removing empty lines, sorting, converting EOL) there is no "unique" operation available.
If you have Windows 10 then you can enable Bash (just type Ubuntu in Microsoft Store and follow the instructions in the description to install it) and use cat your_file.txt | sort | uniq > your_file_edited.txt
. Of course you must be in the same working directory as "your_file.txt" or refer to it via its path.
In cases where you just want to inject some styles from a stylesheet into a component without bundling in the whole stylesheet I recommend https://github.com/glortho/styled-import. For example:
const btnStyle = styledImport.react('../App.css', '.button')
// btnStyle is now { color: 'blue' } or whatever other rules you have in `.button`.
NOTE: I am the author of this lib, and I built it for cases where mass imports of styles and CSS modules are not the best or most viable solution.
There's also workaround doing disjunction of your array, worked for me as other solutions were hard to implement using some old framework.
select * from tableA where id = 1 or id = 2 or id = 3 ...
But for better perfo, I would use Nikolai Nechai's solution with unions, if possible.
It boils down to adding android:stretchColumns="*"
to your TableLayout
root and setting android:layout_width="0dp"
to all the children in your TableRow
s.
<TableLayout
android:stretchColumns="*" // Optionally use numbered list "0,1,2,3,..."
>
<TableRow
android:layout_width="0dp"
>
The answer by MadProgrammer is correct, especially the tip about Joda-Time. The successor to Joda-Time is now built into Java 8 as the new java.time package. Here's example code in Java 8.
When working with date-time (as opposed to local date), the time zone in critical. The day-of-month depends on the time zone. For example, the India time zone is +05:30
(five and a half hours ahead of UTC), while France is only one hour ahead. So a moment in a new day in India has one date while the same moment in France has “yesterday’s” date. Creating string output lacking any time zone or offset information is creating ambiguity. You asked for YYYY-MM-DD output so I provided, but I don't recommend it. Instead of ISO_LOCAL_DATE
I would have used ISO_DATE
to get this output: 2014-02-25+05:30
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zonedDateTime = ZonedDateTime.now( zoneId );
DateTimeFormatter formatterOutput = DateTimeFormatter.ISO_LOCAL_DATE; // Caution: The "LOCAL" part means we are losing time zone information, creating ambiguity.
String output = formatterOutput.format( zonedDateTime );
Dump to console…
System.out.println( "zonedDateTime: " + zonedDateTime );
System.out.println( "output: " + output );
When run…
zonedDateTime: 2014-02-25T14:22:20.919+05:30[Asia/Kolkata]
output: 2014-02-25
Similar code using the Joda-Time library, the precursor to java.time.
DateTimeZone zone = new DateTimeZone( "Asia/Kolkata" );
DateTime dateTime = DateTime.now( zone );
DateTimeFormatter formatter = ISODateTimeFormat.date();
String output = formatter.print( dateTime );
By the way, that format of your input string is a standard format, one of several handy date-time string formats defined by ISO 8601.
Both Joda-Time and java.time use ISO 8601 formats by default when parsing and generating string representations of various date-time values.
This looks like a behavior difference in the handling of \s
between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).
Note:
GNU grep 2.5.4
echo "foo bar" | grep "\s"
(doesn't match)
whereas
GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar
Probably less trouble (as \s
is not documented):
Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar
My advice is to avoid using \s
... use [ \t]*
or [[:space:]]
or something like it instead.
A variation on the answer by @tallgirltaadaa , draw your own button in the shape of a caret:
var a = $('.MyCarouselContainer').slick({
prevArrow: '<canvas class="prevArrowCanvas a-left control-c prev slick-prev" width="15" height="50"></canvas>',
nextArrow: '<canvas class="nextArrowCanvas a-right control-c next slick-next" width="15" height="50"></canvas>'
});
function drawNextPreviousArrows(strokeColor) {
var c = $(".prevArrowCanvas")[0];
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, c.width, c.height);
ctx.moveTo(15, 0);
ctx.lineTo(0, 25);
ctx.lineTo(15, 50);
ctx.lineWidth = 2;
ctx.strokeStyle = strokeColor;
ctx.stroke();
var c = $(".nextArrowCanvas")[0];
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, c.width, c.height);
ctx.moveTo(0, 0);
ctx.lineTo(15, 25);
ctx.lineTo(0, 50);
ctx.lineWidth = 2;
ctx.strokeStyle = strokeColor;
ctx.stroke();
}
drawNextPreviousArrows("#cccccc");
then add the css
.slick-prev, .slick-next
height: 50px;s
}
A little late but I was having this problem too and running studio as root just created more problems (using OSX here).
I fixed it by manually installing what was failing to install using the Android SDK manager. Just run android sdk
in a terminal (probably the same on Windows but don't quote me). Let it install all the updates it wants, then if you can't make it through the setup, manually find the packages that are failing to install and install them.
Got me through a very frustrating problem and back to work.....
Check out this link (Running react-native run-ios occurs an error?). It appears to be a problem with the location of Command line tools
.
In Xcode, select Xcode menu, then Preferences, then Locations tab. Select your Xcode version from the dropdown and exit Xcode.
Every derived table (AKA sub-query) must indeed have an alias. I.e. each query in brackets must be given an alias (AS whatever
), which can the be used to refer to it in the rest of the outer query.
SELECT ID FROM (
SELECT ID, msisdn FROM (
SELECT * FROM TT2
) AS T
) AS T
In your case, of course, the entire query could be replaced with:
SELECT ID FROM TT2
I don't see any margin
or margin-left
declarations for #footer-wrap li
.
This ought to do the trick:
#footer-wrap ul,
#footer-wrap li {
margin-left: 0;
list-style-type: none;
}
In my solution (Kotlin);
I'm using onBackAlternative function as a parameter on BaseActivity.
BaseActivity
abstract class BaseActivity {
var onBackPressAlternative: (() -> Unit)? = null
override fun onBackPressed() {
if (onBackPressAlternative != null) {
onBackPressAlternative!!()
} else {
super.onBackPressed()
}
}
}
I have a function for set onBackPressAlternative on BaseFragment.
BaseFragment
abstract class BaseFragment {
override fun onStart() {
super.onStart()
...
setOnBackPressed(null) // Add this
}
//Method must be declared as open, for overriding in child class
open fun setOnBackPressed(onBackAlternative: (() -> Unit)?) {
(activity as BaseActivity<*, *>).onBackPressAlternative = onBackAlternative
}
}
Then my onBackPressAlternative is ready to use on fragments.
Sub Fragments
override fun setOnBackPressed(onBackAlternative: (() -> Unit)?) {
(activity as BaseActivity<*, *>).onBackPressAlternative = {
// TODO Your own custom onback function
}
}
The best precision you can possibly get is through the use of the x86-only "rdtsc" instruction, which can provide clock-level resolution (ne must of course take into account the cost of the rdtsc call itself, which can be measured easily on application startup).
The main catch here is measuring the number of clocks per second, which shouldn't be too hard.
Your string is wider than your format width of 2. So there's no padding to be done.
I had same issue when first start Android Studio in Window 10, with java jdk 1.8.0_66. The solution that worked is:
Step 1: Close Android Studio
Step 2: Delete Folder C:\Users\Anna\.gradle (Anna is my username)
Step 3: Open Android Studio as Administrator
Step 4: If you are currently in an opened project, close current project by select File > Close Project.
Step 5: Now you seeing this Quick Start GUI:
Wait for gradle to build again (it would download all the dependency in your build.gradle for every module in your project)
If it has not worked till now, you could restart your computer. Do step 1 again.
This happens sometime when I changed Android Studio version or recently upgrade Window. Hope that helps !
when you use \\b(\\w+)+\\b
that means exact match with a word containing only word characters ([a-zA-Z0-9])
in your case for example setting \\b
at the begining of regex will accept -12
(with space) but again it won't accept -12
(without space)
for reference to support my words: https://docs.oracle.com/javase/tutorial/essential/regex/bounds.html
Based on Daniel's answer, I wrote this SASS mixin with interpolation (#{}
) for a youtube video's iframe that is inside a Bootstrap modal dialog:
@mixin responsive-modal-wiframe($height: 9, $width: 16.5,
$max-w-allowed: 90, $max-h-allowed: 60) {
$sides-adjustment: 1.7;
iframe {
width: #{$width / $height * ($max-h-allowed - $sides-adjustment)}vh;
height: #{$height / $width * $max-w-allowed}vw;
max-width: #{$max-w-allowed - $sides-adjustment}vw;
max-height: #{$max-h-allowed}vh;
}
@media only screen and (max-height: 480px) {
margin-top: 5px;
.modal-header {
padding: 5px;
.modal-title {font-size: 16px}
}
.modal-footer {display: none}
}
}
Usage:
.modal-dialog {
width: 95vw; // the modal should occupy most of the screen's available space
text-align: center; // this will center the titles and the iframe
@include responsive-modal-wiframe();
}
HTML:
<div class="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Video</h4>
</div>
<div class="modal-body">
<iframe src="https://www.youtube-nocookie.com/embed/<?= $video_id ?>?rel=0" frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>
</div>
<div class="modal-footer">
<button class="btn btn-danger waves-effect waves-light"
data-dismiss="modal" type="button">Close</button>
</div>
</div>
</div>
</div>
This will always display the video without those black parts that youtube adds to the iframe when the width or height is not proportional to the video. Notes:
$sides-adjustment
is a slight adjustment to compensate a tiny part of these black parts showing up on the sides;.modal-footer
;.modal-dialog
;.modal-header
.After a lot of testing, this is working flawlessly for me now.
So, perhaps this is a bit clunky but so far so good. Im working in angular 9.
file .ts
scroll(el: HTMLElement) {
el.scrollIntoView({ block: 'start', behavior: 'smooth' });
}
file .html
<button (click)="scroll(target)"></button>
<div #target style="margin-top:-50px;padding-top: 50px;" ></div>
I adjust the offset with margin and padding top.
Saludos!
If it's a new project, I'd just drop the database, and create a new one with a proper charset:
CREATE DATABASE <dbname> CHARACTER SET utf8;
You can use the variables name itself to check if a value is an integer. for example:
#include <iostream>
using namespace std;
int main (){
int firstvariable;
int secondvariable;
float float1;
float float2;
cout << "Please enter two integers and then press Enter:" << endl;
cin >> firstvariable;
cin >> secondvariable;
if(firstvariable && secondvariable){
cout << "Time for some simple mathematical operations:\n" << endl;
cout << "The sum:\n " << firstvariable << "+" << secondvariable
<<"="<< firstvariable + secondvariable << "\n " << endl;
}else{
cout << "\n[ERROR\tINVALID INPUT]\n";
return 1;
}
return 0;
}
you can write a stored procedure like this:
CREATE PROCEDURE sanitize_TABLE()
BEGIN
#replace space with underscore
UPDATE Table SET FieldName = REPLACE(FieldName," ","_") WHERE FieldName is not NULL;
#delete dot
UPDATE Table SET FieldName = REPLACE(FieldName,".","") WHERE FieldName is not NULL;
#delete (
UPDATE Table SET FieldName = REPLACE(FieldName,"(","") WHERE FieldName is not NULL;
#delete )
UPDATE Table SET FieldName = REPLACE(FieldName,")","") WHERE FieldName is not NULL;
#raplace or delete any char you want
#..........................
END
In this way you have modularized control over table.
You can also generalize stored procedure making it, parametric with table to sanitoze input parameter
In my case install angular cli
npm install -g @angular/cli@latest
update Nodejs to latest, then all should work fine.
...and if you still have that problem, it maybe because you run the command in shell and not in cmd (you need to run command in cmd), check this out and maybe it helps...
Permitting a nested object :
params.permit( {:school => [:id , :name]},
{:student => [:id,
:name,
:address,
:city]},
{:records => [:marks, :subject]})
You can do something like this:
a = [1,2,3,4,5]
b = [i**2 for i in a]
It's called a list comprehension, to make it easier for you to loop inside a list.
You might need to turn on virtualization in your BIOS, most manufacturers disable it by default. Intel HAX requires CPU virtualization to be enabled.
You can also call the "host" command from the PowerShell commandline. It should give you the value of the $host
variable.
From the now unavailable internet archive:
Go to Edit -> Preferences -> SQL Editor and set to a higher value this parameter: DBMS connection read time out (in seconds). For instance: 86400.
Close and reopen MySQL Workbench. Kill your previously query that probably is running and run the query again.
1- update your local meta-data using : git fetch --all
2- show your remote and local branches using : git branch -a , see the following Screenshot
3- switch to target branch , that you want to linked with the remote: using
git checkout branchName
example :
4- Link your local branch to a remote branch using:
git branch --set-upstream-to nameOfRemoteBranch
N.B : nameOfRemoteBranch : to copy from the output of step 2 " git branch -r "
Example of use:
your http service file:
import { Injectable } from "@angular/core";
import { ActivatedRoute, Router } from '@angular/router';
import { Http, Headers, Response, Request, RequestMethod, URLSearchParams, RequestOptions } from "@angular/http";
import {Observable} from 'rxjs/Rx';
import { Constants } from './constants';
declare var $: any;
@Injectable()
export class HttpClient {
requestUrl: string;
responseData: any;
handleError: any;
constructor(private router: Router,
private http: Http,
private constants: Constants,
) {
this.http = http;
}
postWithFile (url: string, postData: any, files: File[]) {
let headers = new Headers();
let formData:FormData = new FormData();
formData.append('files', files[0], files[0].name);
// For multiple files
// for (let i = 0; i < files.length; i++) {
// formData.append(`files[]`, files[i], files[i].name);
// }
if(postData !=="" && postData !== undefined && postData !==null){
for (var property in postData) {
if (postData.hasOwnProperty(property)) {
formData.append(property, postData[property]);
}
}
}
var returnReponse = new Promise((resolve, reject) => {
this.http.post(this.constants.root_dir + url, formData, {
headers: headers
}).subscribe(
res => {
this.responseData = res.json();
resolve(this.responseData);
},
error => {
this.router.navigate(['/login']);
reject(error);
}
);
});
return returnReponse;
}
}
call your function (Component file):
onChange(event) {
let file = event.srcElement.files;
let postData = {field1:"field1", field2:"field2"}; // Put your form data variable. This is only example.
this._service.postWithFile(this.baseUrl + "add-update",postData,file).then(result => {
console.log(result);
});
}
your html code:
<input type="file" class="form-control" name="documents" (change)="onChange($event)" [(ngModel)]="stock.documents" #documents="ngModel">
I had the same problem when using bootstrap-datewidget and i loaded jquery in the header instead of loading it at the end of the body and it worked.
Perhaps 0
or '\u0000'
would do?
Yes, you just forgot the quotes ...
$('<form/>').attr('action','form2.html').submit();
Create an XML-file in a res/drawable
folder. For instance, "btn_image.xml":
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/bg_state_1"
android:state_pressed="true"
android:state_selected="true"/>
<item android:drawable="@drawable/bg_state_2"
android:state_pressed="true"
android:state_selected="false"/>
<item android:drawable="@drawable/bg_state_selected"
android:state_selected="true"/>
<item android:drawable="@drawable/bg_state_deselected"/>
</selector>
You can combine those files you like, for instance, change "bg_state_1" to "bg_state_deselected" and "bg_state_2" to "bg_state_selected".
In any of those files you can write something like:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#ccdd00"/>
<corners android:radius="5dp"/>
</shape>
Create in a layout file an ImageView or ImageButton with the following attributes:
<ImageView
android:id="@+id/image"
android:layout_width="50dp"
android:layout_height="50dp"
android:adjustViewBounds="true"
android:background="@drawable/btn_image"
android:padding="10dp"
android:scaleType="fitCenter"
android:src="@drawable/star"/>
Later in code:
image.setSelected(!image.isSelected());
I have some hacky answers that are likely to be terrible... but I have very little experience at this point.
a way:
class myClass():
myInstances = []
def __init__(self, myStr01, myStr02):
self.myStr01 = myStr01
self.myStr02 = myStr02
self.__class__.myInstances.append(self)
myObj01 = myClass("Foo", "Bar")
myObj02 = myClass("FooBar", "Baz")
for thisObj in myClass.myInstances:
print(thisObj.myStr01)
print(thisObj.myStr02)
A hack way to get this done:
import sys
class myClass():
def __init__(self, myStr01, myStr02):
self.myStr01 = myStr01
self.myStr02 = myStr02
myObj01 = myClass("Foo", "Bar")
myObj02 = myClass("FooBar", "Baz")
myInstances = []
myLocals = str(locals()).split("'")
thisStep = 0
for thisLocalsLine in myLocals:
thisStep += 1
if "myClass object at" in thisLocalsLine:
print(thisLocalsLine)
print(myLocals[(thisStep - 2)])
#myInstances.append(myLocals[(thisStep - 2)])
print(myInstances)
myInstances.append(getattr(sys.modules[__name__], myLocals[(thisStep - 2)]))
for thisObj in myInstances:
print(thisObj.myStr01)
print(thisObj.myStr02)
Another more 'clever' hack:
import sys
class myClass():
def __init__(self, myStr01, myStr02):
self.myStr01 = myStr01
self.myStr02 = myStr02
myInstances = []
myClasses = {
"myObj01": ["Foo", "Bar"],
"myObj02": ["FooBar", "Baz"]
}
for thisClass in myClasses.keys():
exec("%s = myClass('%s', '%s')" % (thisClass, myClasses[thisClass][0], myClasses[thisClass][1]))
myInstances.append(getattr(sys.modules[__name__], thisClass))
for thisObj in myInstances:
print(thisObj.myStr01)
print(thisObj.myStr02)
Update your cordova to the latest version and the issue should be resolved. In case the issue not resolved please set the path in the environment variable (in case of Windows). Example: System Variable Value name GRADLE_HOME Value D:\Android\Android Studio\gradle\gradle-4.3.1 (please replace with your path)
use the arguments -Xms<memory>
-Xmx<memory>
. Use M
or G
after the numbers for indicating Megs and Gigs of bytes respectively. -Xms
indicates the minimum and -Xmx
the maximum.
Typically one uses an abstract class to provide some incomplete functionality that will be fleshed out by concrete subclasses. It may provide methods that are used by its subclasses; it may also represent an intermediate node in the class hierarchy, to represent a common grouping of concrete subclasses, distinguishing them in some way from other subclasses of its superclass. Since an interface can't derive from a class, this is another situation where a class (abstract or otherwise) would be necessary, versus an interface.
A good rule of thumb is that only leaf nodes of a class hierarchy should ever be instantiated. Making non-leaf nodes abstract is an easy way of ensuring that.
in my.cnf file , please change the following
## Instead of skip-networking the default is now to listen only on ## localhost which is more compatible and is not less secure. ## bind-address = 127.0.0.1
if one wants to use .post() then this will set headers for all future request made with jquery
$.ajaxSetup({
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
then make your .post() calls as normal.
All your controls are belong to us!
Fionnuala answered this correctly but skimmers like me would find it easy to miss the point.
You don't refresh the subFORM you refresh the subform CONTROL. In fact, if you check with allforms() the subForm isn't even loaded as far as access is concerned.
On the main form look at the label the subform wizard provided or select the subform by clicking once or on the border around it and look at the "caption" in the "Other" tab in properties. That's the name you use for requerying, not the name of the form that appears in the navigation panel.
In my case I had a subform called frmInvProdSub and I tried for many hours to figure out why Access didn't think it existed. I gave up, deleted the form and re-created it. The very last step is telling it what you want to call the control so I called it frmInvProdSub and finished the wizard. Then I tried and voila, it worked!
When I looked at the form name in the navigation window I realized I'd forgotten to put "Sub" in the name! That's when it clicked. The CONTROL is called frmInvProdSub, not the form and using the control name works.
Of course if both names are identical then you didn't have this problem lol.
1. Create .bat File with backup sqlcmd command
for backup
SqlCmd -E -S Server_Name –Q “BACKUP DATABASE [Name_of_Database] TO DISK=’X:PathToBackupLocation[Name_of_Database].bak'”
for restore
SqlCmd -E -S Server_Name –Q “RESTORE DATABASE [Name_of_Database] FROM DISK=’X:PathToBackupFile[File_Name].bak'”
2. Run the the bat file with WPF/C# code
FileInfo file = new FileInfo("DB\\batfile.bat");
Process process = new Process();
process.StartInfo.FileName = file.FullName;
process.StartInfo.Arguments = @"-X";
process.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
process.StartInfo.UseShellExecute = false; //Changed Line
process.StartInfo.RedirectStandardOutput = true; //Changed Line
process.Start();
string output = process.StandardOutput.ReadToEnd(); //Changed Line
process.WaitForExit(); //Moved Line
In SQL server, a cursor is used when you need Instead of the T-SQL commands that operate on all the rows in the result set one at a time, we use a cursor when we need to update records in a database table in a singleton fashion, in other words row by row.to fetch one row at a time or row by row.
Working with cursors consists of several steps:
Declare - Declare is used to define a new cursor. Open - A Cursor is opened and populated by executing the SQL statement defined by the cursor. Fetch - When the cursor is opened, rows can be retrieved from the cursor one by one. Close - After data operations, we should close the cursor explicitly. Deallocate - Finally, we need to delete the cursor definition and release all the system resources associated with the cursor. Syntax
DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ] [ FORWARD_ONLY | SCROLL ] [ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ] [ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ] [ TYPE_WARNING] FOR select_statement [FOR UPDATE [ OF column_name [ ,...n ] ] ] [;]
open the console as a administrator. Right Click on the command prompt or bash -> more and select "run as administrator"
@Transactional
@RequestMapping(value = { "/getDatabaseTables" }, method = RequestMethod.GET)
public @ResponseBody String getDatabaseTables() throws Exception{
Connection con = ((SessionImpl) sessionFactory.getCurrentSession()).connection();
DatabaseMetaData md = con.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
HashMap<String,List<String>> databaseTables = new HashMap<String,List<String>>();
List<String> tables = new ArrayList<String>();
String db = "";
while (rs.next()) {
tables.add(rs.getString(3));
db = rs.getString(1);
}
List<String> database = new ArrayList<String>();
database.add(db);
databaseTables.put("database", database);
Collections.reverse(tables);
databaseTables.put("tables", tables);
return new ObjectMapper().writeValueAsString(databaseTables);
}
@Transactional
@RequestMapping(value = { "/getTableDetails" }, method = RequestMethod.GET)
public @ResponseBody String getTableDetails(@RequestParam(value="tablename")String tablename) throws Exception{
System.out.println("...tablename......"+tablename);
Connection con = ((SessionImpl) sessionFactory.getCurrentSession()).connection();
Statement st = con.createStatement();
String sql = "select * from "+tablename;
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metaData = rs.getMetaData();
int rowCount = metaData.getColumnCount();
List<HashMap<String,String>> databaseColumns = new ArrayList<HashMap<String,String>>();
HashMap<String,String> columnDetails = new HashMap<String,String>();
for (int i = 0; i < rowCount; i++) {
columnDetails = new HashMap<String,String>();
Method method = com.mysql.jdbc.ResultSetMetaData.class.getDeclaredMethod("getField", int.class);
method.setAccessible(true);
com.mysql.jdbc.Field field = (com.mysql.jdbc.Field) method.invoke(metaData, i+1);
columnDetails.put("columnName", field.getName());//metaData.getColumnName(i + 1));
columnDetails.put("columnType", metaData.getColumnTypeName(i + 1));
columnDetails.put("columnSize", field.getLength()+"");//metaData.getColumnDisplaySize(i + 1)+"");
columnDetails.put("columnColl", field.getCollation());
columnDetails.put("columnNull", ((metaData.isNullable(i + 1)==0)?"NO":"YES"));
if (field.isPrimaryKey()) {
columnDetails.put("columnKEY", "PRI");
} else if(field.isMultipleKey()) {
columnDetails.put("columnKEY", "MUL");
} else if(field.isUniqueKey()) {
columnDetails.put("columnKEY", "UNI");
} else {
columnDetails.put("columnKEY", "");
}
columnDetails.put("columnAINC", (field.isAutoIncrement()?"AUTO_INC":""));
databaseColumns.add(columnDetails);
}
HashMap<String,List<HashMap<String,String>>> tableColumns = new HashMap<String,List<HashMap<String,String>>>();
Collections.reverse(databaseColumns);
tableColumns.put("columns", databaseColumns);
return new ObjectMapper().writeValueAsString(tableColumns);
}
Can you use simply the SVG <title>
element and the default browser rendering it conveys? (Note: this is not the same as the title
attribute you can use on div/img/spans in html, it needs to be a child element named title
)
rect {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
fill: #69c;_x000D_
stroke: #069;_x000D_
stroke-width: 5px;_x000D_
opacity: 0.5_x000D_
}
_x000D_
<p>Mouseover the rect to see the tooltip on supporting browsers.</p>_x000D_
_x000D_
<svg xmlns="http://www.w3.org/2000/svg">_x000D_
<rect>_x000D_
<title>Hello, World!</title>_x000D_
</rect>_x000D_
</svg>
_x000D_
Alternatively, if you really want to show HTML in your SVG, you can embed HTML directly:
rect {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
fill: #69c;_x000D_
stroke: #069;_x000D_
stroke-width: 5px;_x000D_
opacity: 0.5_x000D_
}_x000D_
_x000D_
foreignObject {_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
svg div {_x000D_
text-align: center;_x000D_
line-height: 150px;_x000D_
}
_x000D_
<svg xmlns="http://www.w3.org/2000/svg">_x000D_
<rect/>_x000D_
<foreignObject>_x000D_
<body xmlns="http://www.w3.org/1999/xhtml">_x000D_
<div>_x000D_
Hello, <b>World</b>!_x000D_
</div>_x000D_
</body> _x000D_
</foreignObject>_x000D_
</svg>
_x000D_
…but then you'd need JS to turn the display on and off. As shown above, one way to make the label appear at the right spot is to wrap the rect and HTML in the same <g>
that positions them both together.
To use JS to find where an SVG element is on screen, you can use getBoundingClientRect()
, e.g. http://phrogz.net/svg/html_location_in_svg_in_html.xhtml
Instead of getting the frame from the document, try getting the frame from the window object.
in the above example change this:
if (typeof (document.all.resultFrame.Reset) == "function")
document.all.resultFrame.Reset();
else
alert("resultFrame.Reset NOT found");
to
if (typeof (window.frames[0].Reset) == "function")
window.frames[0].Reset();
else
alert("resultFrame.Reset NOT found");
the problem is that the scope of the javascript inside the iframe is not exposed through the DOM element for the iframe. only window objects contain the javascript scoping information for the frames.
CNCopySupportedInterfaces is no longer deprecated in iOS 10. (API Reference)
You need to import SystemConfiguration/CaptiveNetwork.h and add SystemConfiguration.framework to your target's Linked Libraries (under build phases).
Here is a code snippet in swift (RikiRiocma's Answer):
import Foundation
import SystemConfiguration.CaptiveNetwork
public class SSID {
class func fetchSSIDInfo() -> String {
var currentSSID = ""
if let interfaces = CNCopySupportedInterfaces() {
for i in 0..<CFArrayGetCount(interfaces) {
let interfaceName: UnsafePointer<Void> = CFArrayGetValueAtIndex(interfaces, i)
let rec = unsafeBitCast(interfaceName, AnyObject.self)
let unsafeInterfaceData = CNCopyCurrentNetworkInfo("\(rec)")
if unsafeInterfaceData != nil {
let interfaceData = unsafeInterfaceData! as Dictionary!
currentSSID = interfaceData["SSID"] as! String
}
}
}
return currentSSID
}
}
(Important: CNCopySupportedInterfaces returns nil on simulator.)
For Objective-c, see Esad's answer here and below
+ (NSString *)GetCurrentWifiHotSpotName {
NSString *wifiName = nil;
NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
for (NSString *ifnam in ifs) {
NSDictionary *info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
if (info[@"SSID"]) {
wifiName = info[@"SSID"];
}
}
return wifiName;
}
As of iOS 9 Captive Network is deprecated*. (source)
*No longer deprecated in iOS 10, see above.
It's recommended you use NEHotspotHelper (source)
You will need to email apple at [email protected] and request entitlements. (source)
Sample Code (Not my code. See Pablo A's answer):
for(NEHotspotNetwork *hotspotNetwork in [NEHotspotHelper supportedNetworkInterfaces]) {
NSString *ssid = hotspotNetwork.SSID;
NSString *bssid = hotspotNetwork.BSSID;
BOOL secure = hotspotNetwork.secure;
BOOL autoJoined = hotspotNetwork.autoJoined;
double signalStrength = hotspotNetwork.signalStrength;
}
Side note: Yup, they deprecated CNCopySupportedInterfaces in iOS 9 and reversed their position in iOS 10. I spoke with an Apple networking engineer and the reversal came after so many people filed Radars and spoke out about the issue on the Apple Developer forums.
Adding a bit to use Gokhan's solution for using:
--allow-file-access-from-files
Now you just need to append above text in Target text followed by a space. make sure you close all the instances of chrome browser after adding above property. Now restart chrome by the icon where you added this property. It should work for all.
Matt's approach above is fine, but please be aware that you will run into problems if you use it to differentiate between dates of the format y/M/d
and d/M/y
. For instance, a formatter initialised with y/M/d
will accept a date like 01/01/2009
and give you back a date which is clearly not what you wanted. I fixed the issue as follows, but I have limited time and I'm not happy with the solution for 2 main reasons:
getDateFormat()
method becoming a bit of a nightmare if you needed it to handle lots of other date formats.If I had to make something that could handle lots and lots of different date formats and needed to be highly performant, then I think I would use the approach of creating an enum which linked each different date regex to its format. Then use MyEnum.values()
to loop through the enum and test with if(myEnum.getPattern().matches(date))
rather than catching a dateformatexception.
Anway, that being said, the following can handle dates of the formats 'y/M/d' 'y-M-d' 'y M d' 'd/M/y' 'd-M-y' 'd M y'
and all other variations of those which include time formats as well:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtil {
private static final String[] timeFormats = {"HH:mm:ss","HH:mm"};
private static final String[] dateSeparators = {"/","-"," "};
private static final String DMY_FORMAT = "dd{sep}MM{sep}yyyy";
private static final String YMD_FORMAT = "yyyy{sep}MM{sep}dd";
private static final String ymd_template = "\\d{4}{sep}\\d{2}{sep}\\d{2}.*";
private static final String dmy_template = "\\d{2}{sep}\\d{2}{sep}\\d{4}.*";
public static Date stringToDate(String input){
Date date = null;
String dateFormat = getDateFormat(input);
if(dateFormat == null){
throw new IllegalArgumentException("Date is not in an accepted format " + input);
}
for(String sep : dateSeparators){
String actualDateFormat = patternForSeparator(dateFormat, sep);
//try first with the time
for(String time : timeFormats){
date = tryParse(input,actualDateFormat + " " + time);
if(date != null){
return date;
}
}
//didn't work, try without the time formats
date = tryParse(input,actualDateFormat);
if(date != null){
return date;
}
}
return date;
}
private static String getDateFormat(String date){
for(String sep : dateSeparators){
String ymdPattern = patternForSeparator(ymd_template, sep);
String dmyPattern = patternForSeparator(dmy_template, sep);
if(date.matches(ymdPattern)){
return YMD_FORMAT;
}
if(date.matches(dmyPattern)){
return DMY_FORMAT;
}
}
return null;
}
private static String patternForSeparator(String template, String sep){
return template.replace("{sep}", sep);
}
private static Date tryParse(String input, String pattern){
try{
return new SimpleDateFormat(pattern).parse(input);
}
catch (ParseException e) {}
return null;
}
}
I think the simplest way to use the newest version of Node.js is to get the newest Node.js pkg file in the website https://nodejs.org/en/download/current/ if you want to use different version of Node.js you can use nvm or n to manage it.
Edit: I have just explained logic to pair here. If anybody want to go with the complete code then see my another answer. I have answered here for logic only but I was not able to explain properly, So I have added another answer in the same thread.
Try this to do pairing:
If you are able to search the devices then this would be your next step
ArrayList<BluetoothDevice> arrayListBluetoothDevices = NEW ArrayList<BluetoothDevice>;
I am assuming that you have the list of Bluetooth devices added in the arrayListBluetoothDevices
:
BluetoothDevice bdDevice;
bdDevice = arrayListBluetoothDevices.get(PASS_THE_POSITION_TO_GET_THE_BLUETOOTH_DEVICE);
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
Log.i("Log","Paired");
}
} catch (Exception e)
{
e.printStackTrace();
}
The createBond()
method:
public boolean createBond(BluetoothDevice btDevice)
throws Exception
{
Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = class1.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
Add this line into your Receiver in the ACTION_FOUND
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
arrayListBluetoothDevices.add(device);
}
https://dev.mysql.com/doc/refman/8.0/en/insert-optimization.html
The time required for inserting a row is determined by the following factors, where the numbers indicate approximate proportions:
- Connecting: (3)
- Sending query to server: (2)
- Parsing query: (2)
- Inserting row: (1 × size of row)
- Inserting indexes: (1 × number of indexes)
- Closing: (1)
From this it should be obvious, that sending one large statement will save you an overhead of 7 per insert statement, which in further reading the text also says:
If you are inserting many rows from the same client at the same time, use INSERT statements with multiple VALUES lists to insert several rows at a time. This is considerably faster (many times faster in some cases) than using separate single-row INSERT statements.
Python's advanced slicing operation has a barely known syntax element, the ellipsis:
>>> class C(object):
... def __getitem__(self, item):
... return item
...
>>> C()[1:2, ..., 3]
(slice(1, 2, None), Ellipsis, 3)
Unfortunately it's barely useful as the ellipsis is only supported if tuples are involved.
I'll try and break it down (example from documention)
/*
* The cellForRowAtIndexPath takes for argument the tableView (so if the same object
* is delegate for several tableViews it can identify which one is asking for a cell),
* and an indexPath which determines which row and section the cell is returned for.
*/
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
/*
* This is an important bit, it asks the table view if it has any available cells
* already created which it is not using (if they are offScreen), so that it can
* reuse them (saving the time of alloc/init/load from xib a new cell ).
* The identifier is there to differentiate between different types of cells
* (you can display different types of cells in the same table view)
*/
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];
/*
* If the cell is nil it means no cell was available for reuse and that we should
* create a new one.
*/
if (cell == nil) {
/*
* Actually create a new cell (with an identifier so that it can be dequeued).
*/
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
/*
* Now that we have a cell we can configure it to display the data corresponding to
* this row/section
*/
NSDictionary *item = (NSDictionary *)[self.content objectAtIndex:indexPath.row];
cell.textLabel.text = [item objectForKey:@"mainTitleKey"];
cell.detailTextLabel.text = [item objectForKey:@"secondaryTitleKey"];
NSString *path = [[NSBundle mainBundle] pathForResource:[item objectForKey:@"imageKey"] ofType:@"png"];
UIImage *theImage = [UIImage imageWithContentsOfFile:path];
cell.imageView.image = theImage;
/* Now that the cell is configured we return it to the table view so that it can display it */
return cell;
}
This is a DataSource
method so it will be called on whichever object has declared itself as the DataSource
of the UITableView
. It is called when the table view actually needs to display the cell onscreen, based on the number of rows and sections (which you specify in other DataSource methods).
Inserting 'test' to name will lead to inserting NULL
values to other columns of the base table which wont be correct as Id is a PRIMARY KEY
and it cannot have NULL
value.
This worked for me:
ActiveWorkbook.refreshall
ActiveWorkbook.Save
When you save the workbook it's necessary to complete the refresh.
This SO question is missing the following approach :
-- List down all columns of table 'Logging'
select * from sys.all_columns where object_id = OBJECT_ID('Logging')
If your HTML is well formed, I think this is a better solution:
create function dbo.StripHTML( @text varchar(max) ) returns varchar(max) as
begin
declare @textXML xml
declare @result varchar(max)
set @textXML = REPLACE( @text, '&', '' );
with doc(contents) as
(
select chunks.chunk.query('.') from @textXML.nodes('/') as chunks(chunk)
)
select @result = contents.value('.', 'varchar(max)') from doc
return @result
end
go
select dbo.StripHTML('This <i>is</i> an <b>html</b> test')
Try:
g = pd.DataFrame(['A','B','A','C','D','D','E'])
# Group by the contents of column 0
gg = g.groupby(0)
# Create a DataFrame with the counts of each letter
histo = gg.apply(lambda x: x.count())
# Add a new column that is the count / total number of elements
histo[1] = histo.astype(np.float)/len(g)
print histo
Output:
0 1
0
A 2 0.285714
B 1 0.142857
C 1 0.142857
D 2 0.285714
E 1 0.142857
You can pivot your DataFrame after creating:
>>> df = pd.DataFrame(data)
>>> df.pivot(index=0, columns=1, values=2)
# avg DataFrame
1 c1 c2
0
r1 avg11 avg12
r2 avg21 avg22
>>> df.pivot(index=0, columns=1, values=3)
# stdev DataFrame
1 c1 c2
0
r1 stdev11 stdev12
r2 stdev21 stdev22
There are newer beta versions of Xampp that come with newer PHP upgrades.
you should check at http://www.apachefriends.org
Edit If you are asking about security, see my addendum at the bottom Edit
PHP has a serialize function provided for this specific purpose. Pass it an array, and it will give you a string representation of it. When you want to convert it back to an array, you just use the unserialize function.
$data = array('one'=>1, 'two'=>2, 'three'=>33);
$dataString = serialize($data);
//send elsewhere
$data = unserialize($dataString);
This is often used by lazy coders to save data to a database. Not recommended, but works as a quick/dirty solution.
Addendum
I was under the impression that you were looking for a way to send the data reliably, not "securely". No matter how you pass the data, if it is going through the users system, you cannot trust it at all. Generally, you should store it somewhere on the server & use a credential (cookie, session, password, etc) to look it up.
d = DateTime.Now;
int dayofweek =(int) d.DayOfWeek;
if (dayofweek != 0)
{
d = d.AddDays(1 - dayofweek);
}
else { d = d.AddDays(-6); }
I think your professor is trying to stop a bad habit before it even starts.
Global variables have their place and like many people said knowing where and when to use them can be complicated. So I think rather than get into the nitty gritty of the why, how, when, and where of global variables your professor decided to just ban. Who knows, he might un-ban them in the future.
This is improvement of simpleigh answer (omit length)
s.slice(0, 4) + s.slice(5)
let s = "crt/r2002_2";
let o = s.slice(0, 4) + s.slice(5);
let delAtIdx = (s, i) => s.slice(0, i) + s.slice(i + 1); // this function remove letter at index i
console.log(o);
console.log(delAtIdx(s, 4));
_x000D_
Just another approach:
SELECT col1 * 1.0 / col2 FROM tbl1
Multiplying by 1.0 turns an integer into a float numeric(13,1) and so works like a typecast, but most probably it is slower than that.
A slightly shorter variation suggested by Aleksandr Fedorenko in a comment:
SELECT col1 * 1. / col2 FROM tbl1
The effect would be basically the same. The only difference is that the multiplication result in this case would be numeric(12,0).
Principal advantage: less wordy than other approaches.
The difference is subtle but important. The MOV instruction is a 'MOVe' effectively a copy of the address that the TABLE-ADDR label stands for. The LEA instruction is a 'Load Effective Address' which is an indirected instruction, which means that TABLE-ADDR points to a memory location at which the address to load is found.
Effectively using LEA is equivalent to using pointers in languages such as C, as such it is a powerful instruction.
Vavr (formerly called Javaslang) (http://www.vavr.io) provides tuples (til size of 8) as well. Here is the javadoc: https://static.javadoc.io/io.vavr/vavr/0.9.0/io/vavr/Tuple.html.
This is a simple example:
Tuple2<Integer, String> entry = Tuple.of(1, "A");
Integer key = entry._1;
String value = entry._2;
Why JDK itself did not come with a simple kind of tuples til now is a mystery to me. Writing wrapper classes seems to be an every day business.
Try list(newdict.keys())
.
This will convert the dict_keys
object to a list.
On the other hand, you should ask yourself whether or not it matters. The Pythonic way to code is to assume duck typing (if it looks like a duck and it quacks like a duck, it's a duck). The dict_keys
object will act like a list for most purposes. For instance:
for key in newdict.keys():
print(key)
Obviously, insertion operators may not work, but that doesn't make much sense for a list of dictionary keys anyway.
You will have to look through the various locations depending on your version of MySQL.
mysqld --help -verbose | grep my.cnf
For Homebrew:
/usr/local/Cellar/mysql/8.0.11/bin/mysqld (mysqld 8.0.11)
Default possible locations:
/etc/my.cnf
/etc/mysql/my.cnf
~/.my.cnf
Found mine here:
/usr/local/etc/my.cnf
You need
test.split("\\|");
split
uses regular expression and in regex |
is a metacharacter representing the OR
operator. You need to escape that character using \
(written in String as "\\"
since \
is also a metacharacter in String literals and require another \
to escape it).
You can also use
test.split(Pattern.quote("|"));
and let Pattern.quote
create the escaped version of the regex representing |
.
I'm using this without any additional settings:
if (!$st->execute()) {
print_r($st->errorInfo());
}
Open package.json and look under dependencies. You should see:
"dependencies": {
...
"bootstrap-less": "^3.8.8"
...
}
for angular 5 and over
In Controller i have specified the below code with ActionResult which is a base class that can have 11 subtypes in MVC like: ViewResult, PartialViewResult, EmptyResult, RedirectResult, RedirectToRouteResult, JsonResult, JavaScriptResult, ContentResult, FileContentResult, FileStreamResult, FilePathResult.
public ActionResult Index()
{
if (HttpContext.Session["LoggedInUser"] == null)
{
return RedirectToAction("Login", "Home");
}
else
{
return View(); // returns ViewResult
}
}
//More Examples
[HttpPost]
public ActionResult Index(string Name)
{
ViewBag.Message = "Hello";
return Redirect("Account/Login"); //returns RedirectResult
}
[HttpPost]
public ActionResult Index(string Name)
{
return RedirectToRoute("RouteName"); // returns RedirectToRouteResult
}
Likewise we can return all these 11 subtypes by using ActionResult() without specifying every subtype method explicitly. ActionResult is the best thing if you are returning different types of views.
This is a Kotlin based version, assuming that the parent view is an instance of LinearLayout
.
someView.layoutParams = LinearLayout.LayoutParams(100, 200)
This allows to set the width and height (100
and 200
) in a single line.
I claim that the obvious way to see whether casting a value changed the value would be to cast and check the result. I would, however, remove the unnecessary cast when comparing. I'm also not too keen on one letter variable names (exception x
and y
, but not when they mean row and column (sometimes respectively)).
public static int intValue(long value) {
int valueInt = (int)value;
if (valueInt != value) {
throw new IllegalArgumentException(
"The long value "+value+" is not within range of the int type"
);
}
return valueInt;
}
However, really I would want to avoid this conversion if at all possible. Obviously sometimes it's not possible, but in those cases IllegalArgumentException
is almost certainly the wrong exception to be throwing as far as client code is concerned.
This works fine if you want the http protocol also since it could be http or https.
$domainURL = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'];
Your question contains the string literal "\b[A-Z]{2,}\b"
,
but that \b
will mean backspace, because there is no r-modifier.
Try: r"\b[A-Z]{2,}\b"
.
There is a gem called active_record_union that might be what you are looking for.
It's example usages is the following:
current_user.posts.union(Post.published)
current_user.posts.union(Post.published).where(id: [6, 7])
current_user.posts.union("published_at < ?", Time.now)
user_1.posts.union(user_2.posts).union(Post.published)
user_1.posts.union_all(user_2.posts)
sprintf(mystring, "%05d", myInt);
Here, "05" says "use 5 digits with leading zeros".
The command you have typed is /startup.sh
, if you have to start a shell script you have to fire the command as shown below:
$ cd /home/mpatil/softwares/apache-tomcat-7.0.47/bin
$ sh startup.sh
or
$ ./startup.sh
Please try that, you also have to go to your tomcat's bin-folder (by using the cd-command) to execute this shell script. In your case this is /home/mpatil/softwares/apache-tomcat-7.0.47/bin
.
import { Component, ElementRef, OnInit } from '@angular/core';
@Component({
selector:'display',
template:`
<input (input)="updateName($event.target.value)">
<p> My name : {{ myName }}</p>
`
})
class DisplayComponent implements OnInit {
constructor(public element: ElementRef) {
this.element.nativeElement // <- your direct element reference
}
ngOnInit() {
var el = this.element.nativeElement;
console.log(el);
}
updateName(value) {
// ...
}
}
Example updated to work with the latest version
For more details on native element, here
This has nothing to do with the MULTILINE flag; what you're seeing is the difference between the find()
and matches()
methods. find()
succeeds if a match can be found anywhere in the target string, while matches()
expects the regex to match the entire string.
Pattern p = Pattern.compile("xyz");
Matcher m = p.matcher("123xyzabc");
System.out.println(m.find()); // true
System.out.println(m.matches()); // false
Matcher m = p.matcher("xyz");
System.out.println(m.matches()); // true
Furthermore, MULTILINE
doesn't mean what you think it does. Many people seem to jump to the conclusion that you have to use that flag if your target string contains newlines--that is, if it contains multiple logical lines. I've seen several answers here on SO to that effect, but in fact, all that flag does is change the behavior of the anchors, ^
and $
.
Normally ^
matches the very beginning of the target string, and $
matches the very end (or before a newline at the end, but we'll leave that aside for now). But if the string contains newlines, you can choose for ^
and $
to match at the start and end of any logical line, not just the start and end of the whole string, by setting the MULTILINE flag.
So forget about what MULTILINE
means and just remember what it does: changes the behavior of the ^
and $
anchors. DOTALL
mode was originally called "single-line" (and still is in some flavors, including Perl and .NET), and it has always caused similar confusion. We're fortunate that the Java devs went with the more descriptive name in that case, but there was no reasonable alternative for "multiline" mode.
In Perl, where all this madness started, they've admitted their mistake and gotten rid of both "multiline" and "single-line" modes in Perl 6 regexes. In another twenty years, maybe the rest of the world will have followed suit.
And there's a Google library available.
Really, command-line parsing is "solved." Just pick one.
I know this has been answered, but here's mine just because I think case is an under-appreciated tool. (Maybe because people think it is slow, but it's at least as fast as an if, sometimes faster.)
case "$1" in
0|1) xinput set-prop 12 "Device Enabled" $1 ;;
*) echo "This script requires a 1 or 0 as first parameter." ;;
esac
From SQL Server 2016 you can just use
DROP TABLE IF EXISTS ##CLIENTS_KEYWORD
On previous versions you can use
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
/*Then it exists*/
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD
(
client_id INT
)
You could also consider truncating the table instead rather than dropping and recreating.
IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
TRUNCATE TABLE ##CLIENTS_KEYWORD
ELSE
CREATE TABLE ##CLIENTS_KEYWORD
(
client_id INT
)
With mysql v5.7.20, here is how I was able to get the row count from a table using PHP v7.0.22:
$query = "select count(*) from bigtable";
$qresult = mysqli_query($this->conn, $query);
$row = mysqli_fetch_assoc($qresult);
$count = $row["count(*)"];
echo $count;
The third line will return a structure that looks like this:
array(1) {
["count(*)"]=>string(4) "1570"
}
In which case the ending echo statement will return:
1570
For me the problem was in that I had not yet ran composer update
for this new project/fork. The command failed silently, nothing happened.
After running composer update
it worked.
You can use the "User-Defined Language" option available at the notepad++. You do not need to do the xml-based hacks, where the formatting would be available only in the searched window, with the formatting rules.
Sample for your reference here.
For me.. the problem was that the anchor needs a title, and that was missing!
It's weird that the Swing toolkit doesn't include this functionality, but here's the best answer to your question:
textField = new JTextField();
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
if (txtGuess.getText().length() >= 3 ) // limit to 3 characters
e.consume();
}
});
I use this in a fun guessing game example in my Udemy.com course "Learn Java Like a Kid". Cheers - Bryson
Echoing justanotherdev's comment:
Mind-blowing and useful:
CTRL
+ SHIFT
+ p
(Mac: CMD
+ SHIFT
+ p
)>transform
pick upper/lower case and press enterIts a combination from other answers with a plus
After you malloc
a node
make sure to set node->next = NULL
.
int addNodeBottom(int val, node *head)
{
node *current = head;
node *newNode = (node *) malloc(sizeof(node));
if (newNode == NULL) {
printf("malloc failed\n");
exit(-1);
}
newNode->value = val;
newNode->next = NULL;
while (current->next) {
current = current->next;
}
current->next = newNode;
return 0;
}
I should point out that with this version the head
is still used as a dummy, not used for storing a value. This lets you represent an empty list by having just a head
node.
Basic Authentication use base 64 Encoding for generating cryptographic string which contains the information of username and password.
Digest Access Authentication uses the hashing methodologies to generate the cryptographic result
With the Apache 2 change KeepAliveTimeout
set it to 60 or above
i have tried this one for more projects and it worked for me. note that solution can configure your app for multidex:
android {
compileSdkVersion 25
buildToolsVersion "25.0.1"
defaultConfig {
...
minSdkVersion 9
targetSdkVersion 25
}
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}}
dependencies {
compile 'com.android.support:support-v4:25.1.0'
compile 'com.google.android.gms:play-services:8.3.0'
...
}
Global variables and static variables are automatically initialized to zero. If you have simply
char ZEROARRAY[1024];
at global scope it will be all zeros at runtime. But actually there is a shorthand syntax if you had a local array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. You could write:
char ZEROARRAY[1024] = {0};
The compiler would fill the unwritten entries with zeros. Alternatively you could use memset
to initialize the array at program startup:
memset(ZEROARRAY, 0, 1024);
That would be useful if you had changed it and wanted to reset it back to all zeros.
Create python module test.py
import sys
sys.path.append("<project-path>/lib/")
from tes1 import Client1
from tes2 import Client2
import tes3
Create python module test_check.py
from test import Client1
from test import Client2
from test import test3
We can import the imported module from module.
Before creating a file, it's needed to create all the parent's directories.
Use yourFile.getParentFile().mkdirs()
Knibb High football rules!
This should be relatively fast and accurate but I admit I didn't put it through a thorough test, just a few.
It avoids expensive exceptions, regex, and also avoids looping through a character set, instead using ascii ranges for validation.
public static bool IsBase64String(string s)
{
s = s.Trim();
int mod4 = s.Length % 4;
if(mod4!=0){
return false;
}
int i=0;
bool checkPadding = false;
int paddingCount = 1;//only applies when the first is encountered.
for(i=0;i<s.Length;i++){
char c = s[i];
if (checkPadding)
{
if (c != '=')
{
return false;
}
paddingCount++;
if (paddingCount > 3)
{
return false;
}
continue;
}
if(c>='A' && c<='z' || c>='0' && c<='9'){
continue;
}
switch(c){
case '+':
case '/':
continue;
case '=':
checkPadding = true;
continue;
}
return false;
}
//if here
//, length was correct
//, there were no invalid characters
//, padding was correct
return true;
}
You can use SELECT
as lambacck said
or add parentheses:
SET @times = (SELECT COUNT(DidWin)as "I Win"
FROM thetable
WHERE DidWin = 1 AND Playername='Me');
For example, in selenium automation, you have a PageObject which can use its parent's constructor like this:
public class DeveloperSteps extends ScenarioSteps {
public DeveloperSteps(Pages pages) {
super(pages);
}........
The Set statement is only used for object variables (like Range
, Cell
or Worksheet
in Excel), while the simple equal sign '=' is used for elementary datatypes like Integer
. You can find a good explanation for when to use set here.
The other problem is, that your variable g1val
isn't actually declared as Integer
, but has the type Variant
. This is because the Dim statement doesn't work the way you would expect it, here (see example below). The variable has to be followed by its type right away, otherwise its type will default to Variant
. You can only shorten your Dim statement this way:
Dim intColumn As Integer, intRow As Integer 'This creates two integers
For this reason, you will see the "Empty" instead of the expected "0" in the Watches window.
Try this example to understand the difference:
Sub Dimming()
Dim thisBecomesVariant, thisIsAnInteger As Integer
Dim integerOne As Integer, integerTwo As Integer
MsgBox TypeName(thisBecomesVariant) 'Will display "Empty"
MsgBox TypeName(thisIsAnInteger ) 'Will display "Integer"
MsgBox TypeName(integerOne ) 'Will display "Integer"
MsgBox TypeName(integerTwo ) 'Will display "Integer"
'By assigning an Integer value to a Variant it becomes Integer, too
thisBecomesVariant = 0
MsgBox TypeName(thisBecomesVariant) 'Will display "Integer"
End Sub
Two further notices on your code:
First remark: Instead of writing
'If g1val is bigger than the value in the current cell
If g1val > Cells(33, i).Value Then
g1val = g1val 'Don't change g1val
Else
g1val = Cells(33, i).Value 'Otherwise set g1val to the cell's value
End If
you could simply write
'If g1val is smaller or equal than the value in the current cell
If g1val <= Cells(33, i).Value Then
g1val = Cells(33, i).Value 'Set g1val to the cell's value
End If
Since you don't want to change g1val
in the other case.
Second remark: I encourage you to use Option Explicit when programming, to prevent typos in your program. You will then have to declare all variables and the compiler will give you a warning if a variable is unknown.
add KexAlgorithms diffie-hellman-group1-sha1,diffie-hellman-group-exchange-sha??1 to your sshd_config on the server.
This worked, but make sure you restart sshd: sudo service sshd restart
This one is very interesting,
HTML and CSS only
.help-tip {_x000D_
position: absolute;_x000D_
top: 18px;_x000D_
left: 18px;_x000D_
text-align: center;_x000D_
background-color: #BCDBEA;_x000D_
border-radius: 50%;_x000D_
width: 24px;_x000D_
height: 24px;_x000D_
font-size: 14px;_x000D_
line-height: 26px;_x000D_
cursor: default;_x000D_
}_x000D_
_x000D_
.help-tip:before {_x000D_
content: '?';_x000D_
font-weight: bold;_x000D_
color: #fff;_x000D_
}_x000D_
_x000D_
.help-tip:hover span {_x000D_
display: block;_x000D_
transform-origin: 100% 0%;_x000D_
-webkit-animation: fadeIn 0.3s ease-in-out;_x000D_
animation: fadeIn 0.3s ease-in-out;_x000D_
}_x000D_
_x000D_
.help-tip span {_x000D_
display: none;_x000D_
text-align: left;_x000D_
background-color: #1E2021;_x000D_
padding: 5px;_x000D_
width: 200px;_x000D_
position: absolute;_x000D_
border-radius: 3px;_x000D_
box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.2);_x000D_
left: -4px;_x000D_
color: #FFF;_x000D_
font-size: 13px;_x000D_
line-height: 1.4;_x000D_
}_x000D_
_x000D_
.help-tip span:before {_x000D_
position: absolute;_x000D_
content: '';_x000D_
width: 0;_x000D_
height: 0;_x000D_
border: 6px solid transparent;_x000D_
border-bottom-color: #1E2021;_x000D_
left: 10px;_x000D_
top: -12px;_x000D_
}_x000D_
_x000D_
.help-tip span:after {_x000D_
width: 100%;_x000D_
height: 40px;_x000D_
content: '';_x000D_
position: absolute;_x000D_
top: -40px;_x000D_
left: 0;_x000D_
}
_x000D_
<span class="help-tip">_x000D_
<span > This is the inline help tip! </span>_x000D_
</span>
_x000D_
There is no such functionality in jQuery. Use JSON.stringify
or alternatively any jQuery plugin with similar functionality (e.g jquery-json).
I am using this method to read Contacts
public static List<ContactItem> readPhoneContacts(Context context) {
List<ContactItem> contactItems = new ArrayList<ContactItem>();
try {
Cursor cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, "upper("+ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + ") ASC");
/*context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?",
new String[] { id },
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" ASC");*/
Integer contactsCount = cursor.getCount(); // get how many contacts you have in your contacts list
if (contactsCount > 0) {
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
ContactItem contactItem = new ContactItem();
contactItem.setContactName(contactName);
//the below cursor will give you details for multiple contacts
Cursor pCursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{id}, null);
// continue till this cursor reaches to all phone numbers which are associated with a contact in the contact list
while (pCursor.moveToNext()) {
int phoneType = pCursor.getInt(pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
//String isStarred = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.STARRED));
String phoneNo = pCursor.getString(pCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//you will get all phone numbers according to it's type as below switch case.
//Logs.e will print the phone number along with the name in DDMS. you can use these details where ever you want.
switch (phoneType) {
case Phone.TYPE_MOBILE:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_MOBILE", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_HOME", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_WORK", " " + phoneNo);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_WORK_MOBILE", " " + phoneNo);
break;
case Phone.TYPE_OTHER:
contactItem.setContactNumberMobile(phoneNo);
Log.e(contactName + ": TYPE_OTHER", " " + phoneNo);
break;
default:
break;
}
}
contactItem.setSelectedAddress(getContactPostalAddress(pCursor));
pCursor.close();
contactItems.add(contactItem);
}
}
cursor.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return contactItems;
}//loadContacts
The same thing happened to me as I had changed something in the /etc/hosts
file. After changing it back to 127.0.0.1 localhost
it worked for me.
You'd need to be careful as onBlur
has some caveats in IE11 (How to use relatedTarget (or equivalent) in IE?, https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget).
There is, however, no way to use onFocusOut
in React as far as I can tell. See the issue on their github https://github.com/facebook/react/issues/6410 if you need more information.
Just use valueOf() method. If the value doesn't exist, it throws IllegalArgumentException and you can catch it like that:
boolean isSettingCodeValid = true;
try {
SettingCode.valueOf(settingCode.toUpperCase());
} catch (IllegalArgumentException e) {
// throw custom exception or change the isSettingCodeValid value
isSettingCodeValid = false;
}
For arrays you can use:
Array.FindIndex<T>
:
int keyIndex = Array.FindIndex(words, w => w.IsKey);
For lists you can use List<T>.FindIndex
:
int keyIndex = words.FindIndex(w => w.IsKey);
You can also write a generic extension method that works for any Enumerable<T>
:
///<summary>Finds the index of the first item matching an expression in an enumerable.</summary>
///<param name="items">The enumerable to search.</param>
///<param name="predicate">The expression to test the items against.</param>
///<returns>The index of the first matching item, or -1 if no items match.</returns>
public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate) {
if (items == null) throw new ArgumentNullException("items");
if (predicate == null) throw new ArgumentNullException("predicate");
int retVal = 0;
foreach (var item in items) {
if (predicate(item)) return retVal;
retVal++;
}
return -1;
}
And you can use LINQ as well:
int keyIndex = words
.Select((v, i) => new {Word = v, Index = i})
.FirstOrDefault(x => x.Word.IsKey)?.Index ?? -1;
Only checked
and checked="checked"
are valid. Your other options depend on error recovery in browsers.
checked="yes"
and checked="true"
are particularly bad as they imply that checked="no"
and checked="false"
will set the default state to be unchecked … which they will not.
if you execute
mvn eclipse:clean
followed by
mvn eclipse:eclipse
if will prepare the eclipse .classpath
file for you. That is, these commands are run against maven from the command line i.e. outside of eclipse.
You should be able to choose the SQL Server Database file option to get the right kind of database (the system.data.SqlClient
provider), and then manually correct the connection string to point to your db.
I think the reasoning behind those db choices probably goes something like this:
However, this logic doesn't quite hold. Even if each of those 4 points is true 90% of the time, by the time you apply all four of them it only applies to ~65% of your audience, which means up to 35% of the express market might legitimately want to talk to a server-class db, and that's a significant group. And so, the simplified (greedy) version:
Using detach is magnitudes faster than any of the other answers here:
$('#mytable').find('tbody').detach();
Don't forget to put the tbody element back into the table since detach removed it:
$('#mytable').append($('<tbody>'));
Also note that when talking efficiency $(target).find(child)
syntax is faster than $(target > child)
. Why? Sizzle!
Elapsed Time to Empty 3,161 Table Rows
Using the Detach() method (as shown in my example above):
Using the empty() method:
It will merger two array and remove duplicate
<?php
$first = 'your first array';
$second = 'your second array';
$result = array_merge($first,$second);
print_r($result);
$result1= array_unique($result);
print_r($result1);
?>
Try this link link1
It's ok to pass an array - in fact it amounts to the same thing
String.format("%s %s", "hello", "world!");
is the same as
String.format("%s %s", new Object[] { "hello", "world!"});
It's just syntactic sugar - the compiler converts the first one into the second, since the underlying method is expecting an array for the vararg parameter.
See
If you want to push commit on git repository, plz make sure you have merged all commit from other branches.
After merging if you are unable to push commit, Use the push command with -f
git push -f origin branch-name
Where origin is the name of your remote repo.
The simplest (and best) way to change the color of the back/up-arrow. Best part is that there are no side-effects (unlike the other answers)!
Widget.AppCompat.DrawerArrowToggle
, define the color
and any other attributes you'd like.drawerArrowStyle
attribute in the apps Theme.Create style:
<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
<!-- Set that the nav buttons will animate-->
<item name="spinBars">true</item>
<!-- Set the color of the up arrow / hamburger button-->
<item name="color">@color/white</item>
</style>
Set the style in App Theme:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<!-- Change global up-arrow color with no side-effects -->
<item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>
To change the ToolBar
text color (and other attributes), create this style
:
<style name="ToolbarStyle" parent="Widget.AppCompat.Toolbar">
<item name="android:textColor">@color/white</item>
<item name="titleTextColor">@color/white</item>
<item name="colorControlNormal">@color/white</item> <!-- colorControlNormal is Probably not necessary -->
</style>
Then set that style on the AppTheme:
<!-- Base application theme. -->
<style name="AppTheme.MyProduceApp" parent="Theme.MaterialComponents.Light.NoActionBar.Bridge">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<!-- Style the toolbar (mostly the color of the text) -->
<item name="toolbarStyle">@style/ToolbarStyle</item>
<!-- Change color of up-arrow -->
<item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>
The .net framework supports JSON through JavaScriptSerializer. Here is a good example to get you started.
using System.Collections.Generic;
using System.Web.Script.Serialization;
namespace GoogleTranslator.GoogleJSON
{
public class FooTest
{
public void Test()
{
const string json = @"{
""DisplayFieldName"" : ""ObjectName"",
""FieldAliases"" : {
""ObjectName"" : ""ObjectName"",
""ObjectType"" : ""ObjectType""
},
""PositionType"" : ""Point"",
""Reference"" : {
""Id"" : 1111
},
""Objects"" : [
{
""Attributes"" : {
""ObjectName"" : ""test name"",
""ObjectType"" : ""test type""
},
""Position"" :
{
""X"" : 5,
""Y"" : 7
}
}
]
}";
var ser = new JavaScriptSerializer();
ser.Deserialize<Foo>(json);
}
}
public class Foo
{
public Foo() { Objects = new List<SubObject>(); }
public string DisplayFieldName { get; set; }
public NameTypePair FieldAliases { get; set; }
public PositionType PositionType { get; set; }
public Ref Reference { get; set; }
public List<SubObject> Objects { get; set; }
}
public class NameTypePair
{
public string ObjectName { get; set; }
public string ObjectType { get; set; }
}
public enum PositionType { None, Point }
public class Ref
{
public int Id { get; set; }
}
public class SubObject
{
public NameTypePair Attributes { get; set; }
public Position Position { get; set; }
}
public class Position
{
public int X { get; set; }
public int Y { get; set; }
}
}
I am not 100% sure if this works all the time, but in my application this gives me the expected behavior.
Lets say you are on ABOUT page and you have the following route:
yourApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/about', {
templateUrl: 'about.html',
controller: 'AboutCtrl'
}).
otherwise({
redirectTo: '/'
});
}
]);
Now, in you HTML
<ul>
<li><a href="#/about#tab1">First Part</a></li>
<li><a href="#/about#tab2">Second Part</a></li>
<li><a href="#/about#tab3">Third Part</a></li>
</ul>
<div id="tab1">1</div>
<div id="tab2">2</div>
<div id="tab3">3</div>
In conclusion
Including the page name before the anchor did the trick for me. Let me know about your thoughts.
Downside
This will re-render the page and then scroll to the anchor.
UPDATE
A better way is to add the following:
<a href="#tab1" onclick="return false;">First Part</a>
There's an error in your code. You're using a mix of full syntax and shorthand notation on the background-image property.This is causing the no-repeat to be ignored, since it's not a valid value for the background-image property.
body{
background-position:center;
background-image:url(../images/images2.jpg) no-repeat;
}
Should become one of the following:
body{
background:url(../images/images2.jpg) center center no-repeat;
}
or
body
{
background-image: url(path-to-file/img.jpg);
background-repeat:no-repeat;
background-position: center center;
}
EDIT: For your image 'scaling' issue, you might want to look at this question's answer.
Put it in a JScrollPane
Edit: Here is a link for you: http://java.sun.com/docs/books/tutorial/uiswing/components/textarea.html