0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.
There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.
I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException
and Application.ThreadException
, as appropriate.
I hate to point out the obvious, but System.IO.FileNotFoundException means the program did not find the file you specified. So what you need to do is check what file your code is looking for in production.
To see what file your program is looking for in production (look at the FileName property of the exception), try these techniques:
Then look at the file system on the machine and see if the file exists. Most likely the case is that it doesn't exist.
In regards to PowerShell 5.1 (this is so much easier in PowerShell 7)...
Operating off the assumption that we have a file named jsonConfigFile.json
with the following content from your post:
{
"Stuffs": [
{
"Name": "Darts",
"Type": "Fun Stuff"
},
{
"Name": "Clean Toilet",
"Type": "Boring Stuff"
}
]
}
This will create an ordered hashtable from a JSON file to help make retrieval easier:
$json = [ordered]@{}
(Get-Content "jsonConfigFile.json" -Raw | ConvertFrom-Json).PSObject.Properties |
ForEach-Object { $json[$_.Name] = $_.Value }
$json.Stuffs
will list a nice hashtable, but it gets a little more complicated from here. Say you want the Type
key's value associated with the Clean Toilet
key, you would retrieve it like this:
$json.Stuffs.Where({$_.Name -eq "Clean Toilet"}).Type
It's a pain in the ass, but if your goal is to use JSON on a barebones Windows 10 installation, this is the best way to do it as far as I've found.
by default <UL/>
contains default padding
therefore try adding style to padding:0px
in css class or inline css
You want the php function "asort":
http://php.net/manual/en/function.asort.php
it sorts the array, maintaining the index associations.
Edit: I've just noticed you're using a standard array (non-associative). if you're not fussed about preserving index associations, use sort():
Include this code somewhere when you slide to your 'section' called blog.
$("#myLink").click(function() {
setTimeout(function() {
window.navigate("the url of the page you want to navigate back to");
}, 2000);
});
Where myLink
is the id of your href.
Rectangle
will have to be a template, otherwise it is just one type. It cannot be a non-template whilst its base magically is. (Its base may be a template instantiation, though you seem to want to maintain the base's functionality as a template.)
Another common option is gradle.
http://www.gradle.org/docs/current/userguide/application_plugin.html
To build your war file in a web app:
In build.gradle, add:
apply plugin: 'war'
Then:
./gradlew war
Use the layout from accepted answer above.
We have noticed that using the MediaQuery
class can be a bit cumbersome, and it’s also missing a couple of key pieces of information.
Here We have a small Screen helper class, that we use across all our new projects:
class Screen {
static double get _ppi => (Platform.isAndroid || Platform.isIOS)? 150 : 96;
static bool isLandscape(BuildContext c) => MediaQuery.of(c).orientation == Orientation.landscape;
//PIXELS
static Size size(BuildContext c) => MediaQuery.of(c).size;
static double width(BuildContext c) => size(c).width;
static double height(BuildContext c) => size(c).height;
static double diagonal(BuildContext c) {
Size s = size(c);
return sqrt((s.width * s.width) + (s.height * s.height));
}
//INCHES
static Size inches(BuildContext c) {
Size pxSize = size(c);
return Size(pxSize.width / _ppi, pxSize.height/ _ppi);
}
static double widthInches(BuildContext c) => inches(c).width;
static double heightInches(BuildContext c) => inches(c).height;
static double diagonalInches(BuildContext c) => diagonal(c) / _ppi;
}
To use
bool isLandscape = Screen.isLandscape(context)
bool isLargePhone = Screen.diagonal(context) > 720;
bool isTablet = Screen.diagonalInches(context) >= 7;
bool isNarrow = Screen.widthInches(context) < 3.5;
To More, See: https://blog.gskinner.com/archives/2020/03/flutter-simplify-platform-detection-responsive-sizing.html
I believe this line in the web.config will set the max upload size:
<system.web>
<httpRuntime maxRequestLength="600000"/>
</system.web>
It is the equivalent to \n -> LF (Line Feed).
Sometimes it is used in HTML and JavaScript. Otherwise in .NET environments, use Environment.NewLine
.
To update one column here are some syntax options:
Option 1
var ls=new int[]{2,3,4};
using (var db=new SomeDatabaseContext())
{
var some= db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList();
some.ForEach(a=>a.status=true);
db.SubmitChanges();
}
Option 2
using (var db=new SomeDatabaseContext())
{
db.SomeTable
.Where(x=>ls.Contains(x.friendid))
.ToList()
.ForEach(a=>a.status=true);
db.SubmitChanges();
}
Option 3
using (var db=new SomeDatabaseContext())
{
foreach (var some in db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList())
{
some.status=true;
}
db.SubmitChanges();
}
Update
As requested in the comment it might make sense to show how to update multiple columns. So let's say for the purpose of this exercise that we want not just to update the status
at ones. We want to update name
and status
where the friendid
is matching. Here are some syntax options for that:
Option 1
var ls=new int[]{2,3,4};
var name="Foo";
using (var db=new SomeDatabaseContext())
{
var some= db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList();
some.ForEach(a=>
{
a.status=true;
a.name=name;
}
);
db.SubmitChanges();
}
Option 2
using (var db=new SomeDatabaseContext())
{
db.SomeTable
.Where(x=>ls.Contains(x.friendid))
.ToList()
.ForEach(a=>
{
a.status=true;
a.name=name;
}
);
db.SubmitChanges();
}
Option 3
using (var db=new SomeDatabaseContext())
{
foreach (var some in db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList())
{
some.status=true;
some.name=name;
}
db.SubmitChanges();
}
Update 2
In the answer I was using LINQ to SQL and in that case to commit to the database the usage is:
db.SubmitChanges();
But for Entity Framework to commit the changes it is:
db.SaveChanges()
XML Copy Editor is perfect for this type of thing.
A Runnable is basically a type of class (Runnable is an Interface) that can be put into a thread, describing what the thread is supposed to do.
The Runnable Interface requires of the class to implement the method run()
like so:
public class MyRunnableTask implements Runnable {
public void run() {
// do stuff here
}
}
And then use it like this:
Thread t = new Thread(new MyRunnableTask());
t.start();
If you did not have the Runnable
interface, the Thread class, which is responsible to execute your stuff in the other thread, would not have the promise to find a run()
method in your class, so you could get errors. That is why you need to implement the interface.
Note that you do not need to define a class as usual, you can do all of that inline:
Thread t = new Thread(new Runnable() {
public void run() {
// stuff here
}
});
t.start();
This is similar to the above, only you don't create another named class.
Here is my take on s soosh's and 0xA3's answers. It can update the console with user messages while updating the spinner and has an elapsed time indicator aswell.
public class ConsoleSpiner : IDisposable
{
private static readonly string INDICATOR = "/-\\|";
private static readonly string MASK = "\r{0} {1:c} {2}";
int counter;
Timer timer;
string message;
public ConsoleSpiner() {
counter = 0;
timer = new Timer(200);
timer.Elapsed += TimerTick;
}
public void Start() {
timer.Start();
}
public void Stop() {
timer.Stop();
counter = 0;
}
public string Message {
get { return message; }
set { message = value; }
}
private void TimerTick(object sender, ElapsedEventArgs e) {
Turn();
}
private void Turn() {
counter++;
var elapsed = TimeSpan.FromMilliseconds(counter * 200);
Console.Write(MASK, INDICATOR[counter % 4], elapsed, this.Message);
}
public void Dispose() {
Stop();
timer.Elapsed -= TimerTick;
this.timer.Dispose();
}
}
usage is something like this:
class Program
{
static void Main(string[] args)
{
using (var spinner = new ConsoleSpiner())
{
spinner.Start();
spinner.Message = "About to do some heavy staff :-)"
DoWork();
spinner.Message = "Now processing other staff".
OtherWork();
spinner.Stop();
}
Console.WriteLine("COMPLETED!!!!!\nPress any key to exit.");
}
}
If you are using Bootstrap 3, you can use Florin's method, or use a custom CSS file.
If you use Bootstrap less source instead of processed css files, you can directly change it in bootstrap/less/variables.less
.
Find something like:
//** Background color used for `.table-striped`.
@table-bg-accent: #f9f9f9;
Fix: Running scripts is disabled on this system
Open Powershell
Set-ExecutionPolicy RemoteSigned A
(A: YES TO ALL)
Done!
I tried the first solution and it works but the end user can easily identify that the div's are refreshing as it is fadeIn(), without fade in i tried .toggle().toggle() and it works perfect. you can try like this
$("#panel").toggle().toggle();
_x000D_
it works perfectly for me as i'm developing a messenger and need to minimize and maximize the chat box's and this does it best rather than the above code.
char = split_string_to_char(text)(index)
------
Function split_string_to_char(text) As String()
Dim chars() As String
For char_count = 1 To Len(text)
ReDim Preserve chars(char_count - 1)
chars(char_count - 1) = Mid(text, char_count, 1)
Next
split_string_to_char = chars
End Function
Error with Uncaught SyntaxError: Unexpected token <
using @Mario answer but that was only part of my problem. Another problem is, javascript doesn't get any data from PHP file. That was solved using this code, inside PHP file: header("Content-Type: text/javascript; charset=utf-8");
This answer is found on this link, where I opened another question to solve this issue: Can't receive json data from PHP in Chrome and Opera
None of the other answers worked for me but this did:
SELECT CONCAT(Cust_First, ' ', Cust_Last) AS CustName FROM customer
You could probably use an inheritance structure although the more I played with this the dirtier I felt.
class AnimalEnum:
@classmethod
def verify(cls, other):
return issubclass(other.__class__, cls)
class Dog(AnimalEnum):
pass
def do_something(thing_that_should_be_an_enum):
if not AnimalEnum.verify(thing_that_should_be_an_enum):
raise OhGodWhy
I tried changing value="true"
to ng-value="true"
, and it seems to work.
<input type="radio" name="response2" data-ng-model="choice.isUserAnswer" ng-value="true" />
Also, to get both inputs to work in your example, you'd have to give different name to each input -- e.g. response
should become response1
and response2
.
Decode it with the unicode-escape
codec:
>>> a="Hello\u2026"
>>> a.decode('unicode-escape')
u'Hello\u2026'
>>> print _
Hello…
This is because for a non-unicode string the \u2026
is not recognised but is instead treated as a literal series of characters (to put it more clearly, 'Hello\\u2026'
). You need to decode the escapes, and the unicode-escape
codec can do that for you.
Note that you can get unicode
to recognise it in the same way by specifying the codec argument:
>>> unicode(a, 'unicode-escape')
u'Hello\u2026'
But the a.decode()
way is nicer.
You need to add a name to your <select>
element:
<select id="testSelect" name="testSelect">
It will be posted to the server, and you can see it using:
Request.Form["testSelect"]
You need to set Transaction for every Account.
foreach(Account account : accounts){
account.setTransaction(transactionObj);
}
Or it colud be enough (if appropriate) to set ids to null on many side.
// list of existing accounts
List<Account> accounts = new ArrayList<>(transactionObj.getAccounts());
foreach(Account account : accounts){
account.setId(null);
}
transactionObj.setAccounts(accounts);
// just persist transactionObj using EntityManager merge() method.
Angular has several timepoints to start executing functions. If you seek for something like jQuery's
$(document).ready();
You may find this analog in angular to be very useful:
$scope.$watch('$viewContentLoaded', function(){
//do something
});
This one is helpful when you want to manipulate the DOM elements. It will start executing only after all te elements are loaded.
UPD: What is said above works when you want to change css properties. However, sometimes it doesn't work when you want to measure the element properties, such as width, height, etc. In this case you may want to try this:
$scope.$watch('$viewContentLoaded',
function() {
$timeout(function() {
//do something
},0);
});
Define a property of the form like, then use this in other places it would be available with the form instance
public string SetText
{
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
I personally use the very good http://www.datejs.com/ library.
Docco here: http://code.google.com/p/datejs/wiki/APIDocumentation
You can use the following to get your Australian format and will validate the leap day 29/02/2012 and not 29/02/2011:
jQuery.validator.addMethod("australianDate", function(value, element) {
return Date.parseExact(value, "d/M/yyyy");
});
$("#myForm").validate({
rules : {
birth_date : { australianDate : true }
}
});
I also use the masked input plugin to standardise the data http://digitalbush.com/projects/masked-input-plugin/
$("#birth_date").mask("99/99/9999");
Its simple matter of setting adjustViewBounds="true"
and scaleType="fitCenter"
in the XML file for the ImageView!
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/image"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
/>
Note: layout_width
is set to match_parent
Yes, JavaScript variables will exist in the scope they are created.
var bannerID = 55;
<input id="EditBanner" type="button"
value="Edit Image" onclick="EditBanner(bannerID);"/>
function EditBanner(id) {
//Do something with id
}
If you use event handlers and jQuery it is simple also
$("#EditBanner").click(function() {
EditBanner(bannerID);
});
IValueConverter implementation can be used. Converter class which takes inheritance from IValueConverter takes some parameters like value
(percentage) and parameter
(parent's width) and returns desired width value. In XAML file, component's width is set with the desired value:
public class SizePercentageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (parameter == null)
return 0.7 * value.ToDouble();
string[] split = parameter.ToString().Split('.');
double parameterDouble = split[0].ToDouble() + split[1].ToDouble() / (Math.Pow(10, split[1].Length));
return value.ToDouble() * parameterDouble;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
// Don't need to implement this
return null;
}
}
XAML:
<UserControl.Resources>
<m:SizePercentageConverter x:Key="PercentageConverter" />
</UserControl.Resources>
<ScrollViewer VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Disabled"
Width="{Binding Converter={StaticResource PercentageConverter}, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Border}},Path=ActualWidth}"
Height="{Binding Converter={StaticResource PercentageConverter}, ConverterParameter=0.6, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Border}},Path=ActualHeight}">
....
</ScrollViewer>
Not necessary to give 160 . 141 will also work. For the value field provide value="" .
Maybe join
+split
:
>>> a=12345
>>> list(map(int,' '.join(str(a)).split()))
[1, 2, 3, 4, 5]
>>> [int(i) for i in ' '.join(str(a)).split()]
[1, 2, 3, 4, 5]
>>>
str.join
+ str.split
is your friend, also we use map
or list comprehension
to get a list, (split what we join :-)).
Maybe, e.g.,
SAVE_IFS="$IFS"
IFS=","
FOOJOIN="${FOO[*]}"
IFS="$SAVE_IFS"
echo "$FOOJOIN"
The constructor of PetStore
will call a constructor of Farm
; there's
no way you can prevent it. If you do nothing (as you've done), it will
call the default constructor (Farm()
); if you need to pass arguments,
you'll have to specify the base class in the initializer list:
PetStore::PetStore()
: Farm( neededArgument )
, idF( 0 )
{
}
(Similarly, the constructor of PetStore
will call the constructor of
nameF
. The constructor of a class always calls the constructors of
all of its base classes and all of its members.)
Here's the function I use.
function trim(s){
return ( s || '' ).replace( /^\s+|\s+$/g, '' );
}
How about you just pull the layout params from the view itself if you created it.
$((RelativeLayout)findViewById(R.id.imageButton1)).getLayoutParams();
You can redirect the regular stdin through unit 3 to keep the get it inside the pipeline:
{ cat notify-finished | while read line; do
read -u 3 input
echo "$input"
done; } 3<&0
BTW, if you really are using cat
this way, replace it with a redirect and things become even easier:
while read line; do
read -u 3 input
echo "$input"
done 3<&0 <notify-finished
Or, you can swap stdin and unit 3 in that version -- read the file with unit 3, and just leave stdin alone:
while read line <&3; do
# read & use stdin normally inside the loop
read input
echo "$input"
done 3<notify-finished
Representation is the same, the meaning is different. e.g, 0xFF, it both represented as "FF". When it is treated as "char", it is negative number -1; but it is 255 as unsigned. When it comes to bit shifting, it is a big difference since the sign bit is not shifted. e.g, if you shift 255 right 1 bit, it will get 127; shifting "-1" right will be no effect.
For the case where the TextView
is inside a TableLayout
, the solution is to set android:shrinkColumns="1"
on the TableLayout
. (Replace 1
with the column number the TextView you want to wrap is in. (0-indexed))
AFAICT, no other attributes are needed on the TextView
.
For other cases, see the other answers here.
FWIW, I had initially gotten it to sort of work with
<TextView
android:id="@+id/inventory_text"
android:layout_width="fill_parent"
android:layout_weight="1"
android:width="0dp"
but that resulted in some extra empty space at the bottom of the Dialog it was all in.
Very interesting question.
I don't see any difference w.r.t safety or versatility, since you can do the same thing with pointer or reference. I also don't think there is any visible difference in performance since references are implemented by pointers.
But I think using reference is better because it is consistent with the standard library. For example, chaining in iostream is done by reference rather than pointer.
using str.splitines()
and str.split()
:
In [126]: strs="""A1023 CRT
.....: A1029 Regulator
.....: A1030 Therm"""
In [127]: dict(x.split() for x in strs.splitlines())
Out[127]: {'A1023': 'CRT', 'A1029': 'Regulator', 'A1030': 'Therm'}
str.splitlines([keepends]) -> list of strings
Return a list of the lines in S, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.
str.split([sep [,maxsplit]]) -> list of strings
Return a list of the words in the string S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.
OpenSSL is quite difficult. It's easy to accidentally throw away all your security by not doing negotiation exactly right. (Heck, I've been personally bitten by a bug where curl wasn't reading the OpenSSL alerts exactly right, and couldn't talk to some sites.)
If you really want quick and simple, put stud in front of your program an call it a day. Having SSL in a different process won't slow you down: http://vincent.bernat.im/en/blog/2011-ssl-benchmark.html
As of SQL Server 2012 you can use the eomonth
built-in function, which is intended for getting the end of the month but can also be used to get the start as so:
select dateadd(day, 1, eomonth(<date>, -1))
If you need the result as a datetime
etc., just cast
it:
select cast(dateadd(day, 1, eomonth(<date>, -1)) as datetime)
My Hosting server block requesting URL And code site getting the same error
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
After a lot of time spent and apply the following step to resolve this issue
Added line before the call web URL
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
still issue not resolve then I upgrade .net version to 4.7.2 but I think it's optional
Last change I have checked my hosting server security level which causes to TLS handshaking for this used "https://www.ssllabs.com/ssltest/index.html" site
and also check to request URL security level then I find the difference is requested URL have to enable a weak level Cipher Suites you can see in the below image
Now here are my hosting server supporting Cipher Suites
here is called if you have control over requesting URL host server then you can sync this both server Cipher Suites. but in my case, it's not possible so I have applied the following script in Windows PowerShell on my hosting server for enabling required weak level Cipher Suites.
Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"
Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"
Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_GCM_SHA384"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_128_GCM_SHA256"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_CBC_SHA256"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_128_CBC_SHA256"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_CBC_SHA"
Enable-TlsCipherSuite -Name "TLS_RSA_WITH_AES_256_CBC_SHA"
after applying the above script my hosting server Cipher Suites level look like
Then my issue resolved.
Note: server security level downgrade is not a recommended option.
I came up with the following spider code. I adapted it a bit from the following: PHP - Is the there a safe way to perform deep recursion? it seems fairly rapid....
<?php
function spider( $base_url , $search_urls=array() ) {
$queue[] = $base_url;
$done = array();
$found_urls = array();
while($queue) {
$link = array_shift($queue);
if(!is_array($link)) {
$done[] = $link;
foreach( $search_urls as $s) { if (strstr( $link , $s )) { $found_urls[] = $link; } }
if( empty($search_urls)) { $found_urls[] = $link; }
if(!empty($link )) {
echo 'LINK:::'.$link;
$content = file_get_contents( $link );
//echo 'P:::'.$content;
preg_match_all('~<a.*?href="(.*?)".*?>~', $content, $sublink);
if (!in_array($sublink , $done) && !in_array($sublink , $queue) ) {
$queue[] = $sublink;
}
}
} else {
$result=array();
$return = array();
// flatten multi dimensional array of URLs to one dimensional.
while(count($link)) {
$value = array_shift($link);
if(is_array($value))
foreach($value as $sub)
$link[] = $sub;
else
$return[] = $value;
}
// now loop over one dimensional array.
foreach($return as $link) {
// echo 'L::'.$link;
// url may be in form <a href.. so extract what's in the href bit.
preg_match_all('/<a[^>]+href=([\'"])(?<href>.+?)\1[^>]*>/i', $link, $result);
if ( isset( $result['href'][0] )) { $link = $result['href'][0]; }
// add the new URL to the queue.
if( (!strstr( $link , "http")) && (!in_array($base_url.$link , $done)) && (!in_array($base_url.$link , $queue)) ) {
$queue[]=$base_url.$link;
} else {
if ( (strstr( $link , $base_url )) && (!in_array($base_url.$link , $done)) && (!in_array($base_url.$link , $queue)) ) {
$queue[] = $link;
}
}
}
}
}
return $found_urls;
}
$base_url = 'https://www.houseofcheese.co.uk/';
$search_urls = array( $base_url.'acatalog/' );
$done = spider( $base_url , $search_urls );
//
// RESULT
//
//
echo '<br /><br />';
echo 'RESULT:::';
foreach( $done as $r ) {
echo 'URL:::'.$r.'<br />';
}
I'm using EF6, and I find something strange,
Suppose Customer has constructor with parameter ,
if I use new Customer(id, "name")
, and do
using (var db = new EfContext("name=EfSample"))
{
db.Customers.Add( new Customer(id, "name") );
db.SaveChanges();
}
It run through without error, but when I look into the DataBase, I find in fact that the data Is NOT be Inserted,
But if I add the curly brackets, use new Customer(id, "name"){}
and do
using (var db = new EfContext("name=EfSample"))
{
db.Customers.Add( new Customer(id, "name"){} );
db.SaveChanges();
}
the data will then actually BE Inserted,
seems the Curly Brackets make the difference, I guess that only when add Curly Brackets, entity framework will recognize this is a real concrete data.
As the previous posts didn't work for me because of some permissions issues, I found that creating a separate crontab file and adding it to the user's crontab with the -u parameter while root worked for me.
sudo crontab -u {USERNAME} ~/{PATH_TO_CRONTAB_FILE}
If u want to tweak the spacing without touching the actual cell size, this is the solution that worked best for me. #xcode 9 #tvOS11 #iOS11 #swift
So in UICollectionViewDelegateFlowLayout, change implement the next methods, the trick is u have to use both of them, and the documentation was not really pointing me to think in that direction. :D
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return cellSpacing
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return cellSpacing
}
select * from incidentsnew1
where BINARY_CHECKSUM(CloseBy) = BINARY_CHECKSUM(Upper(CloseBy))
Yes, #id
selectors combined with a multiple selector (comma) is perfectly valid in both jQuery and CSS.
However, for your example, since <script>
comes before the elements, you need a document.ready
handler, so it waits until the elements are in the DOM to go looking for them, like this:
<script>
$(function() {
$("#segement1,#segement2,#segement3").hide()
});
</script>
<div id="segement1"></div>
<div id="segement2"></div>
<div id="segement3"></div>
I needed same thing and this solution work fine, hope it can help someone also
Enumeration[] array = Enumeration.values();
List<Enumeration> list = Arrays.asList(array);
then you can get the .name() of your enumeration.
Set ${COMMAND}
to g++
on Linux
Under "Preprocessor Include Paths, Macros, etc." and "CDT GCC Built-in Compiler Settings" there is an undefined ${COMMAND}
variable if you imported the sources from an existing Makefile project.
Eclipse tries to run that command to parse its stdout to find headers, but ${COMMAND}
is not set by default, and so it is not able to do so.
I have explained this in more detail at: How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?
This works for me.
private OnClickListener mDisconnectListener;
mDisconnectListener = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
};
...
... onCreateView(...){
mButtonDisconnect = (Button) rootView.findViewById(R.id.button_disconnect);
mButtonDisconnect.setOnClickListener(mDisconnectListener);
...
}
The easiest way to get rid of this is to:
Ex :
<script>
function loadUrl(location)
{
this.document.location.href = location;
}</script>
<div onclick="loadUrl('company_page.jsp')">Abc</div>
This worked very well for me. Cheers
One way is to set the the div to position:absolute
and give it a top of 50px and bottom of 0px;
#div2
{
position:absolute;
bottom:0px;
top:50px
}
I had a similar issue but I was missing the (@Service or @Component) from the implementation of com.example.my.services.myUser.MyUserServiceImpl
As previously mentioned - in case of a project, Makefile
or otherwise, this is a project configuration issue, where you'll likely need to specify other flags too.
But what about one-off programs, where you would normally just write g++ file.cpp && ./a.out
?
Well, I would much like to have some #pragma
to turn in on at source level, or maybe a default extension - say .cxx
or .C11
or whatever, trigger it by default. But as of today, there is no such feature.
But, as you probably are working in a manual environment (i.e. shell), you can just have an alias in you .bashrc
(or whatever):
alias g++11="g++ -std=c++0x"
or, for newer G++ (and when you want to feel "real C++11")
alias g++11="g++ -std=c++11"
You can even alias to g++
itself, if you hate C++03 that much ;)
I assume you are using windows. Open the command prompt and type ipconfig
and find out your local address (on your pc) it should look something like 192.168.1.13
or 192.168.0.5
where the end digit is the one that changes. It should be next to IPv4 Address.
If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13
If you have a virtual host then you will need root to edit the hosts file.
If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.
See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.
Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).
If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow
to allow,deny
in the httpd.conf
file. You can access this by the WAMP menu.
To eliminate possible causes of the issue for now set your config file to
<Directory />
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
<RequireAll>
Require all granted
</RequireAll>
</Directory>
As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.
Config file that fixed the problem:
https://gist.github.com/samvaughton/6790739
Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.
For me its easier to use arrays than objects,
So, I convert an Xml-Object,
$xml = simplexml_load_file('xml_file.xml');
$json_string = json_encode($xml);
$result_array = json_decode($json_string, TRUE);
document.getElementById('mybox').style.display = "block";
Shortest way to get all dictionary/object values:
Object.keys(dict).map(k => dict[k]);
if (date.isBefore(endDate)
&& date.isAfter(startDate)
|| (date.isSame(startDate) || date.isSame(endDate))
is logically the same as
if (!(date.isBefore(startDate) || date.isAfter(endDate)))
which saves you a couple of lines of code and (in some cases) method calls.
Might be easier than pulling in a whole plugin if you only want to do this once or twice.
As Homebrew is my favorite for macOS although it is possible to have apt-get
on macOS using Fink.
In the second .c
file use extern
keyword with the same variable name.
Change:
struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
delcare a variable with
no name. */
to:
struct timeval tvalBefore, tvalAfter;
It is less likely (IMO) to make this mistake if there is a single declaration per line:
struct timeval tvalBefore;
struct timeval tvalAfter;
It becomes more error prone when declaring pointers to types on a single line:
struct timeval* tvalBefore, tvalAfter;
tvalBefore
is a struct timeval*
but tvalAfter
is a struct timeval
.
Rather give names of the column on which you want to merge:
exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)
'opts' is deprecated.
in ggplot2 >= 0.9.2
use
p + theme(legend.position = "none")
Add a key in your info.plist
file UIViewControllerBasedStatusBarAppearance
and set it to YES
.
In viewDidLoad method of your ViewController add a method call:
[self setNeedsStatusBarAppearanceUpdate];
Then paste the following method in viewController
file:
- (UIStatusBarStyle)preferredStatusBarStyle
{
return UIStatusBarStyleLightContent;
}
Use the below where x is the variable which holds the markup in question.
$(x).find("div").html();
As addition to the other answers, in a cpanel installation, the mysql root password is stored in a file named /root/.my.cnf
. (and the cpanel service resets it back on change, so the other answers here won't help)
I have crafted this piece of code that worked for me to detect when I scroll to the end of an element!
let element = $('.element');
if ($(document).scrollTop() > element.offset().top + element.height()) {
/// do something ///
}
It's already 2019, I can't believe still no easiest and conveniencest way to convert the most popular Micro$oft Word document to Adobe PDF format in Java world.
I almost tried every method the above answers mentioned, and I found the best and the only way can satisfy my requirement is by using OpenOffice or LibreOffice. Actually I am not exactly know the difference between them, seems both of them provide soffice
command line.
My requirement is:
First thing came in mind is doc-to-pdf-converter
, but it lacks of maintenance, last update happened 4 years ago, I will not use a nobody-maintain-solution. Xdocreport
seems a promising choice, but it can only convert docx
, but not doc
binary file which is mandatory for me. Using Java to call OpenOffice API seems good, but too complicated for such a simple requirement.
Finally I found the best solution: use OpenOffice command line to finish the job:
Runtime.getRuntime().exec("soffice --convert-to pdf -outdir . /path/some.doc");
I always believe the shortest code is the best code (of course it should be understandable), that's it.
Try vterm, which is a pretty much full feature shell inside vim. It is slightly buggy with its history and clear functions, and still in development, but it still is pretty good
I had to do something similar but I was generating a Date
object so I ended up making a function like this:
function convertTo24Hour(time) {
var hours = parseInt(time.substr(0, 2));
if(time.indexOf('am') != -1 && hours == 12) {
time = time.replace('12', '0');
}
if(time.indexOf('pm') != -1 && hours < 12) {
time = time.replace(hours, (hours + 12));
}
return time.replace(/(am|pm)/, '');
}
I think this reads a little easier. You feed a string in the format h:mm am/pm.
var time = convertTo24Hour($("#starttime").val().toLowerCase());
var date = new Date($("#startday").val() + ' ' + time);
Examples:
$("#startday").val('7/10/2013');
$("#starttime").val('12:00am');
new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
Wed Jul 10 2013 00:00:00 GMT-0700 (PDT)
$("#starttime").val('12:00pm');
new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
Wed Jul 10 2013 12:00:00 GMT-0700 (PDT)
$("#starttime").val('1:00am');
new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
Wed Jul 10 2013 01:00:00 GMT-0700 (PDT)
$("#starttime").val('12:12am');
new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
Wed Jul 10 2013 00:12:00 GMT-0700 (PDT)
$("#starttime").val('3:12am');
new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
Wed Jul 10 2013 03:12:00 GMT-0700 (PDT)
$("#starttime").val('9:12pm');
new Date($("#startday").val() + ' ' + convertTo24Hour($("#starttime").val().toLowerCase()));
Wed Jul 10 2013 21:12:00 GMT-0700 (PDT)
return car.GetType().GetProperty(propertyName).GetValue(car, null);
In C++
Any variable at file scope and that is not nested inside a class or function, is visible throughout all translation units in a program. This is called external linkage because at link time the name is visible to the linker everywhere, external to that translation unit.
Global variables and ordinary functions have external linkage.
Static object or function name at file scope is local to translation unit. That is called as Internal Linkage
Linkage refers only to elements that have addresses at link/load time; thus, class declarations and local variables have no linkage.
You can check undefined object using below code.
ReactObject === 'undefined'
Adding on to superM's and Jeff's answer,
If there are 2 views in the LinearLayout, the first with a layout_weight of 1, the second with a layout_weight of 2 and no weightSum is specified, by default, the weightSum is calculated to be 3 (sum of the weights of the children) and the first view takes 1/3 of the space while the second takes 2/3.
However, if we were to specify the weightSum as 5, the first would take 1/5th of the space while the second would take 2/5th. So a total of 3/5th of the space would be occupied by the layout keeping the rest empty.
The difference between an operating system and a kernel:
The kernel is a part of an operating system. The operating system is the software package that communicates directly to the hardware and our application. The kernel is the lowest level of the operating system. The kernel is the main part of the operating system and is responsible for translating the command into something that can be understood by the computer. The main functions of the kernel are:
On Macs, (assuming you have the right version installed)
JAVA_HOME=`/usr/libexec/java_home -v 1.8` mvn clean install -DskipTests
DateTime birthDate = new DateTime(1981, 8, 9);
Console.WriteLine ("I was born on the {0}. of {1}, {2}.", birthDate.Day, birthDate.ToString("MMMM"), birthDate.Year);
/* The above code will say:
"I was born on the 9. of august, 1981."
"dd" converts to the day (01 thru 31).
"ddd" converts to 3-letter name of day (e.g. mon).
"dddd" converts to full name of day (e.g. monday).
"MMM" converts to 3-letter name of month (e.g. aug).
"MMMM" converts to full name of month (e.g. august).
"yyyy" converts to year.
*/
When you want to use an anchor tag simply as a link without the added styling (such as the underline on hover or blue color) add class="no-style"
to the anchor tag. Then in your global stylesheet create the class "no-style".
.no-style {
text-decoration: none !important;
}
This has two advantages.
If anyone wants to enable dark mode, you may follow the below steps
Operators Overloadability
+, -, *, /, %, &, |, <<, >> All C# binary operators can be overloaded.
+, -, !, ~, ++, --, true, false All C# unary operators can be overloaded.
==, !=, <, >, <= , >= All relational operators can be overloaded,
but only as pairs.
&&, || They can't be overloaded
() (Conversion operator) They can't be overloaded
+=, -=, *=, /=, %= These compound assignment operators can be
overloaded. But in C#, these operators are
automatically overloaded when the respective
binary operator is overloaded.
=, . , ?:, ->, new, is, as, sizeof These operators can't be overloaded
[ ] Can be overloaded but not always!
For bracket:
public Object this[int index]
{
}
The array indexing operator cannot be overloaded; however, types can define indexers, properties that take one or more parameters. Indexer parameters are enclosed in square brackets, just like array indices, but indexer parameters can be declared to be of any type (unlike array indices, which must be integral).
From MSDN
For centos users:
yum install -y mysql-devel python-devel python-setuptools
then
pip install MySQL-python
If this solution doesn't work, and print gcc compile error like:
_mysql.c:29:20: error: Python.h: No such file or directory
You need to specify the path of Python.h
, like this:
pip install --global-option=build_ext --global-option="-I/usr/include/python2.6" MySQL-python
Offical Bitmapdrawable documentation
This is sample on how to convert bitmap to drawable
Bitmap bitmap;
//Convert bitmap to drawable
Drawable drawable = new BitmapDrawable(getResources(), bitmap);
imageView.setImageDrawable(drawable);
Use below query and it works
SELECT column_name FROM table_name where isnull(column_name,'') <> ''
Add external js file in index.html.
<script src="./assets/vendors/myjs.js"></script>
Here's myjs.js file :
var myExtObject = (function() {
return {
func1: function() {
alert('function 1 called');
},
func2: function() {
alert('function 2 called');
}
}
})(myExtObject||{})
var webGlObject = (function() {
return {
init: function() {
alert('webGlObject initialized');
}
}
})(webGlObject||{})
Then declare it is in component like below
demo.component.ts
declare var myExtObject: any;
declare var webGlObject: any;
constructor(){
webGlObject.init();
}
callFunction1() {
myExtObject.func1();
}
callFunction2() {
myExtObject.func2();
}
demo.component.html
<div>
<p>click below buttons for function call</p>
<button (click)="callFunction1()">Call Function 1</button>
<button (click)="callFunction2()">Call Function 2</button>
</div>
It's working for me...
There are now multiple ways to mimic this same effect but further tailor the properties based on the use case. As stated above, this works:
.product__specfield_8_arrow { display: inline-block }
but also
.product__specfield_8_arrow { display: inline-flex } // flex container will be inline
.product__specfield_8_arrow { display: inline-grid } // grid container will be inline
.product__specfield_8_arrow { display: inline-table } // table will be inline-level table
This JSFiddle shows how similar these display properties are in this case.
For a relevant discussion please see this SO post.
Tried the given example, but over VPN and with 400k+ keys it was too slow for me. Also it did not give me the key objects.
I wrote a small Python called tool redis-mass-get to combine KEYS
and MGET
requests against Redis:
# installation:
pip install redis-mass-get
# pipeline example CSV:
redis-mass-get -f csv -och redis://my.redis.url product:* | less
# write to json-file example with progress indicator:
redis-mass-get -d results.json -jd redis://my.redis.url product:*
It supports JSON, CSV and TXT output to file or stdout
for usage in pipes. More info can be found at: Reading multiple key/values from Redis.
create a batch-file with the following code:
dir %1 /b /a-d > list.txt
Then drag & drop a directory on it and the files inside the directory will be listed in list.txt
It works with params if you capture an array with one element, that holds the current index.
int[] idx = { 0 };
params.forEach(e -> query.bind(idx[0]++, e));
The above code assumes, that the method forEach iterates through the elements in encounter order. The interface Iterable specifies this behaviour for all classes unless otherwise documented. Apparently it works for all implementations of Iterable from the standard library, and changing this behaviour in the future would break backward-compatibility.
If you are working with Streams instead of Collections/Iterables, you should use forEachOrdered, because forEach can be executed concurrently and the elements can occur in different order. The following code works for both sequential and parallel streams:
int[] idx = { 0 };
params.stream().forEachOrdered(e -> query.bind(idx[0]++, e));
You can write your query like so:
SELECT * FROM MyTable WHERE (A LIKE '%text1%' OR A LIKE '%text2%')
The %
is a wildcard, meaning that it searches for all rows where column A contains either text1 or text2
FYI, in case you need to add attributes to your dictionary (things that are attached to the dictionary, but are not one of the keys), then you'll need the second form. In that case, you can initialize your dictionary with keys having arbitrary characters, one at a time, like so:
class mydict(dict): pass
a = mydict()
a["b=c"] = 'value'
a.test = False
JavaScript stores strings as UTF-16
(double byte) so if you want to ignore the second byte just strip it out with a bitwise &
operator on 0000000011111111
(ie 255):
'a'.charCodeAt(0) & 255 === 97; // because 'a' = 97 0
'b'.charCodeAt(0) & 255 === 98; // because 'b' = 98 0
'?'.charCodeAt(0) & 255 === 19; // because '?' = 19 39
It really depends on what you're trying to accomplish in your code. I've heard that it's just stuff of urban legend that there is any performance difference between VB.NET, C# and managed C++. However, I've found, at least in string comparisons, that managed C++ beats the pants off of C#, which in turn beats the pants off of VB.NET.
I've by no means done any exhaustive comparisons in algorithmic complexity between the languages. I'm also just using the default settings in each of the languages. In VB.NET I'm using settings to require declaration of variables, etc. Here is the code I'm using for managed C++: (As you can see, this code is quite simple). I'm running the same in the other languages in Visual Studio 2013 with .NET 4.6.2.
#include "stdafx.h"
using namespace System;
using namespace System::Diagnostics;
bool EqualMe(String^ first, String^ second)
{
return first->Equals(second);
}
int main(array<String ^> ^args)
{
Stopwatch^ sw = gcnew Stopwatch();
sw->Start();
for (int i = 0; i < 100000; i++)
{
EqualMe(L"one", L"two");
}
sw->Stop();
Console::WriteLine(sw->ElapsedTicks);
return 0;
}
You can use coalesce(column_name,0)
instead of just column_name
. The coalesce
function returns the first non-NULL value in the list.
I should mention that per-row functions like this are usually problematic for scalability. If you think your database may get to be a decent size, it's often better to use extra columns and triggers to move the cost from the select
to the insert/update
.
This amortises the cost assuming your database is read more often than written (and most of them are).
You can use the .Clear method:
Sheets("Zeros").UsedRange.Clear
Using this you can remove the contents and the formatting of a cell or range without affecting the rest of the worksheet.
Within your app in the Android Emulator press Command + M on macOS or Ctrl + M on Linux and Windows.
You need to use the files
parameter to send a multipart form POST request even when you do not need to upload any files.
From the original requests source:
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
...
:param files: (optional) Dictionary of ``'name': file-like-objects``
(or ``{'name': file-tuple}``) for multipart encoding upload.
``file-tuple`` can be a 2-tuple ``('filename', fileobj)``,
3-tuple ``('filename', fileobj, 'content_type')``
or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``,
where ``'content-type'`` is a string
defining the content type of the given file
and ``custom_headers`` a dict-like object
containing additional headers to add for the file.
The relevant part is: file-tuple can be a
2-tuple
, 3-tuple
or a
4-tuple
.
Based on the above, the simplest multipart form request that includes both files to upload and form fields will look like this:
multipart_form_data = {
'file2': ('custom_file_name.zip', open('myfile.zip', 'rb')),
'action': (None, 'store'),
'path': (None, '/path1')
}
response = requests.post('https://httpbin.org/post', files=multipart_form_data)
print(response.content)
☝ Note the None
as the first argument in the tuple for plain text fields — this is a placeholder for the filename field which is only used for file uploads, but for text fields passing None
as the first parameter is required in order for the data to be submitted.
If you need to post multiple fields with the same name then instead of a dictionary you can define your payload as a list (or a tuple) of tuples:
multipart_form_data = (
('file2', ('custom_file_name.zip', open('myfile.zip', 'rb'))),
('action', (None, 'store')),
('path', (None, '/path1')),
('path', (None, '/path2')),
('path', (None, '/path3')),
)
If the above API is not pythonic enough for you, then consider using requests toolbelt (pip install requests_toolbelt
) which is an extension of the core requests module that provides support for file upload streaming as well as the MultipartEncoder which can be used instead of files
, and which also lets you define the payload as a dictionary, tuple or list.
MultipartEncoder
can be used both for multipart requests with or without actual upload fields. It must be assigned to the data
parameter.
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
multipart_data = MultipartEncoder(
fields={
# a file upload field
'file': ('file.zip', open('file.zip', 'rb'), 'text/plain')
# plain text fields
'field0': 'value0',
'field1': 'value1',
}
)
response = requests.post('http://httpbin.org/post', data=multipart_data,
headers={'Content-Type': multipart_data.content_type})
If you need to send multiple fields with the same name, or if the order of form fields is important, then a tuple or a list can be used instead of a dictionary:
multipart_data = MultipartEncoder(
fields=(
('action', 'ingest'),
('item', 'spam'),
('item', 'sausage'),
('item', 'eggs'),
)
)
Create a URI like this one:
https://maps.google.com/?q=[lat],[long]
For example:
https://maps.google.com/?q=-37.866963,144.980615
or, if you are using the javascript API
map.setCenter(new GLatLng(0,0))
This, and other helpful info comes from here:
https://developers.google.com/maps/documentation/javascript/reference/?csw=1#Map
you may try the following code:
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration:false,
}
});
Delete package-lock.json file and then try to install
You can use many different queries to check if a table exists. Below is a comparison between several:
mysql_query('select 1 from `table_name` group by 1'); or
mysql_query('select count(*) from `table_name`');
mysql_query("DESCRIBE `table_name`");
70000 rows: 24ms
1000000 rows: 24ms
5000000 rows: 24ms
mysql_query('select 1 from `table_name`');
70000 rows: 19ms
1000000 rows: 23ms
5000000 rows: 29ms
mysql_query('select 1 from `table_name` group by 1'); or
mysql_query('select count(*) from `table_name`');
70000 rows: 18ms
1000000 rows: 18ms
5000000 rows: 18ms
These benchmarks are only averages:
In MVVM (wich makes a lot of things a lot easier - you should try it) you would have two properties in your ViewModel Text
that is bound to your TextBox and you would have an ICommand
property Apply
(or similar) that is bound to the button:
<Button Command="Apply">Apply</Button>
The ICommand
interface has a Method CanExecute
that is where you return true
if (!string.IsNullOrWhiteSpace(this.Text)
. The rest is done by WPF for you (enabling/disabling, executing the actual command on click).
The linked article explains it in detail.
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(year, month, date);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy MM dd");
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
}
3 Steps you can follow
chmod -R 775 <repo path>
---> change permissions of repository
chown -R apache:apache <repo path>
---> change owner of svn repository
chcon -R -t httpd_sys_content_t <repo path>
----> change SELinux security context of the svn repository
For anyone looking for an Azure solution
SET NOCOUNT ON
CREATE TABLE Numbers (n bigint PRIMARY KEY)
GO
DECLARE @numbers table(number int);
WITH numbers(number) as (
SELECT 1 AS number
UNION all
SELECT number+1 FROM numbers WHERE number<10000
)
INSERT INTO @numbers(number)
SELECT number FROM numbers OPTION(maxrecursion 10000)
INSERT INTO Numbers(n) SELECT number FROM @numbers
Sourced from the sql azure team blog http://azure.microsoft.com/blog/2010/09/16/create-a-numbers-table-in-sql-azure/
Hashing is a one-way process but using a password-list you can regenerate the hashes and compare to the stored hash to 'crack' the password.
This site https://crackstation.net/ attempts to do this for you - run through passwords lists and tell you the cleartext password based on your hash.
Setting the slice to nil
is the best way to clear a slice. nil
slices in go are perfectly well behaved and setting the slice to nil
will release the underlying memory to the garbage collector.
package main
import (
"fmt"
)
func dump(letters []string) {
fmt.Println("letters = ", letters)
fmt.Println(cap(letters))
fmt.Println(len(letters))
for i := range letters {
fmt.Println(i, letters[i])
}
}
func main() {
letters := []string{"a", "b", "c", "d"}
dump(letters)
// clear the slice
letters = nil
dump(letters)
// add stuff back to it
letters = append(letters, "e")
dump(letters)
}
Prints
letters = [a b c d]
4
4
0 a
1 b
2 c
3 d
letters = []
0
0
letters = [e]
1
1
0 e
Note that slices can easily be aliased so that two slices point to the same underlying memory. The setting to nil
will remove that aliasing.
This method changes the capacity to zero though.
In some cases this also occurs if you have table hints and you have spaces between WITH clause and your hint, so best to type it like:
SELECT Column1 FROM Table1 t1 WITH(NOLOCK)
INNER JOIN Table2 t2 WITH(NOLOCK) ON t1.Column1 = t2.Column1
And not:
SELECT Column1 FROM Table1 t1 WITH (NOLOCK)
INNER JOIN Table2 t2 WITH (NOLOCK) ON t1.Column1 = t2.Column1
As we know jQuery validate plugin invalidates Select field when it has blank value. Why don't we set its value to blank when required.
Yes, you can validate select field with some predefined value.
$("#everything").validate({
rules: {
select_field:{
required: {
depends: function(element){
if('none' == $('#select_field').val()){
//Set predefined value to blank.
$('#select_field').val('');
}
return true;
}
}
}
}
});
We can set blank value for select field but in some case we can't. For Ex: using a function that generates Dropdown field for you and you don't have control over it.
I hope it helps as it helps me.
You can't "add" values to an array as the array length is immutable. You can set values at specific array positions.
If you know how to do it with one-dimensional arrays then you know how to do it with n-dimensional arrays: There are no n-dimensional arrays in Java, only arrays of arrays (of arrays...).
But you can chain the index operator for array element access.
String[][] x = new String[2][];
x[0] = new String[1];
x[1] = new String[2];
x[0][0] = "a1";
// No x[0][1] available
x[1][0] = "b1";
x[1][1] = "b2";
Note the dimensions of the child arrays don't need to match.
Regarding Diadistis response. This worked for me, except I had to use Floor to remove the fractional part of the division before the multiplication. So,
d = new DateTime((d.Ticks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond);
becomes
d = new DateTime(Math.Floor(d.Ticks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond);
I would have expected the division of two Long values to result in a Long, thus removing the decimal part, but it resolves it as a Double leaving the exact same value after the multiplication.
Eppsy
select get_something('NAME', sys.diutil.int_to_bool(1)) from dual;
How to get the last N rows of a pandas DataFrame?
If you are slicing by position, __getitem__
(i.e., slicing with[]
) works well, and is the most succinct solution I've found for this problem.
pd.__version__
# '0.24.2'
df = pd.DataFrame({'A': list('aaabbbbc'), 'B': np.arange(1, 9)})
df
A B
0 a 1
1 a 2
2 a 3
3 b 4
4 b 5
5 b 6
6 b 7
7 c 8
df[-3:]
A B
5 b 6
6 b 7
7 c 8
This is the same as calling df.iloc[-3:]
, for instance (iloc
internally delegates to __getitem__
).
As an aside, if you want to find the last N rows for each group, use groupby
and GroupBy.tail
:
df.groupby('A').tail(2)
A B
1 a 2
2 a 3
5 b 6
6 b 7
7 c 8
There are probably less than 20 entries in your xml.
change the code to this
for ($i=0;$i< sizeof($xml->entry); $i++)
...
It's work for me
private void showForgotDialog(Context c) {
final EditText taskEditText = new EditText(c);
AlertDialog dialog = new AlertDialog.Builder(c)
.setTitle("Forgot Password")
.setMessage("Enter your mobile number?")
.setView(taskEditText)
.setPositiveButton("Reset", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String task = String.valueOf(taskEditText.getText());
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
}
How to call? (Current activity name)
showForgotDialog(current_activity_name.this);
I don't know if there's an easier way to do it without using an external library, but I personally love underscore.js which has tons of utilities for dealing with arrays, collections etc.
With underscore you could do this easily with one line of code:
_.pluck(arr, 'name').join(', ')
Update: This answer may be incorrect or out of date. Please see comments for details.
I switched from @Inject
to @EJB
because @EJB
allows circular injection whereas @Inject
pukes on it.
Details: I needed @PostConstruct
to call an @Asynchronous
method but it would do so synchronously. The only way to make the asynchronous call was to have the original call a method of another bean and have it call back the method of the original bean. To do this each bean needed a reference to the other -- thus circular. @Inject
failed for this task whereas @EJB
worked.
import os.path
os.path.abspath(os.pardir)
Embedded option:
Wrap python code in a bash function.
#!/bin/bash
function current_datetime {
python - <<END
import datetime
print datetime.datetime.now()
END
}
# Call it
current_datetime
# Call it and capture the output
DT=$(current_datetime)
echo Current date and time: $DT
Use environment variables, to pass data into to your embedded python script.
#!/bin/bash
function line {
PYTHON_ARG="$1" python - <<END
import os
line_len = int(os.environ['PYTHON_ARG'])
print '-' * line_len
END
}
# Do it one way
line 80
# Do it another way
echo $(line 80)
http://bhfsteve.blogspot.se/2014/07/embedding-python-in-bash-scripts.html
For second accuracy, yyyy-MM-dd HH:mm:ss should do the trick.
I believe Excel is not very good with fractions of a second (loses them when interacting with COM object IIRC).
Note: do not mix GitLab SSL settings and GitLab SSH keys.
If what you have configured in your GitLab profile is an SSH public key, then your HTTPS URL would not use it.
Regarding your HTTPS credentials, double-check:
git config credential.helper
.Because $xml->xpath
always return an array, and strlen
expects a string.
You need to modify the method GetData()
and add your "experimental" code there, and return t1
.
Appears to be a duplicate of https://askubuntu.com/questions/21131/how-to-correctly-remove-openjdk-and-jre-and-set-the-system-use-only-and-only-sun#answer-21137 assuming that you are using Ubuntu.
The key is to use the command sudo update-java-alternatives -s java-6-sun
. Any commands that rely on javac
will be affected and not just Maven.
Similar to @Dominykas's answer, this is a decorator that converts multiargument-accepting functions into tuple-accepting functions:
apply_tuple = lambda f: lambda args: f(*args)
Example 1:
def add(a, b):
return a + b
three = apply_tuple(add)((1, 2))
Example 2:
@apply_tuple
def add(a, b):
return a + b
three = add((1, 2))
Use Json
class instead of Content
as shown following:
// When I want to return an error:
if (!isFileSupported)
{
Response.StatusCode = (int) HttpStatusCode.BadRequest;
return Json("The attached file is not supported", MediaTypeNames.Text.Plain);
}
else
{
// When I want to return sucess:
Response.StatusCode = (int)HttpStatusCode.OK;
return Json("Message sent!", MediaTypeNames.Text.Plain);
}
Also set contentType:
contentType: 'application/json; charset=utf-8',
You can also try using runuser
(as root) to run a command as a different user
*/1 * * * * runuser php5 \
--command="/var/www/web/includes/crontab/queue_process.php \
>> /var/www/web/includes/crontab/queue.log 2>&1"
See also: man runuser
In my case I exported Drupal instance from server to localhost on XAMPP. It obviously did not do justice to the file and directory ownership and Apache was throwing the above error.
This is the ownership of files and directories initially:
To give read permissions to my files and execute permission to my directories I could do so that all users can read, write and execute:
sudo chmod 777 -R
but that would not be the ideal solution coz this would be migrated back to server and might end up with a security loophole.
A script is given in this blog: https://www.drupal.org/node/244924
#!/bin/bash
# Help menu
print_help() {
cat <<-HELP
This script is used to fix permissions of a Drupal installation
you need to provide the following arguments:
1) Path to your Drupal installation.
2) Username of the user that you want to give files/directories ownership.
3) HTTPD group name (defaults to www-data for Apache).
Usage: (sudo) bash ${0##*/} --drupal_path=PATH --drupal_user=USER --httpd_group=GROUP
Example: (sudo) bash ${0##*/} --drupal_path=/usr/local/apache2/htdocs --drupal_user=john --httpd_group=www-data
HELP
exit 0
}
if [ $(id -u) != 0 ]; then
printf "**************************************\n"
printf "* Error: You must run this with sudo or root*\n"
printf "**************************************\n"
print_help
exit 1
fi
drupal_path=${1%/}
drupal_user=${2}
httpd_group="${3:-www-data}"
# Parse Command Line Arguments
while [ "$#" -gt 0 ]; do
case "$1" in
--drupal_path=*)
drupal_path="${1#*=}"
;;
--drupal_user=*)
drupal_user="${1#*=}"
;;
--httpd_group=*)
httpd_group="${1#*=}"
;;
--help) print_help;;
*)
printf "***********************************************************\n"
printf "* Error: Invalid argument, run --help for valid arguments. *\n"
printf "***********************************************************\n"
exit 1
esac
shift
done
if [ -z "${drupal_path}" ] || [ ! -d "${drupal_path}/sites" ] || [ ! -f "${drupal_path}/core/modules/system/system.module" ] && [ ! -f "${drupal_path}/modules/system/system.module" ]; then
printf "*********************************************\n"
printf "* Error: Please provide a valid Drupal path. *\n"
printf "*********************************************\n"
print_help
exit 1
fi
if [ -z "${drupal_user}" ] || [[ $(id -un "${drupal_user}" 2> /dev/null) != "${drupal_user}" ]]; then
printf "*************************************\n"
printf "* Error: Please provide a valid user. *\n"
printf "*************************************\n"
print_help
exit 1
fi
cd $drupal_path
printf "Changing ownership of all contents of "${drupal_path}":\n user => "${drupal_user}" \t group => "${httpd_group}"\n"
chown -R ${drupal_user}:${httpd_group} .
printf "Changing permissions of all directories inside "${drupal_path}" to "rwxr-x---"...\n"
find . -type d -exec chmod u=rwx,g=rx,o= '{}' \;
printf "Changing permissions of all files inside "${drupal_path}" to "rw-r-----"...\n"
find . -type f -exec chmod u=rw,g=r,o= '{}' \;
printf "Changing permissions of "files" directories in "${drupal_path}/sites" to "rwxrwx---"...\n"
cd sites
find . -type d -name files -exec chmod ug=rwx,o= '{}' \;
printf "Changing permissions of all files inside all "files" directories in "${drupal_path}/sites" to "rw-rw----"...\n"
printf "Changing permissions of all directories inside all "files" directories in "${drupal_path}/sites" to "rwxrwx---"...\n"
for x in ./*/files; do
find ${x} -type d -exec chmod ug=rwx,o= '{}' \;
find ${x} -type f -exec chmod ug=rw,o= '{}' \;
done
echo "Done setting proper permissions on files and directories"
And need to invoke the command:
sudo bash /Applications/XAMPP/xamppfiles/htdocs/fix-permissions.sh --drupal_path=/Applications/XAMPP/xamppfiles/htdocs/rkmission --drupal_user=daemon --httpd_group=admin
In my case the user on which Apache is running is 'daemon'. You can identify the user by just running this php script in a php file through localhost:
<?php echo exec('whoami');?>
Below is the right user with right file permissions for Drupal:
You might have to change it back once it is transported back to server!
Careful:
$array = (array) $object;
does a shallow conversion ($object->innerObject = new stdClass() remains an object) and converting back and forth using json works but it's not a good idea if performance is an issue.
If you need all objects to be converted to associative arrays here is a better way to do that (code ripped from I don't remember where):
function toArray($obj)
{
if (is_object($obj)) $obj = (array)$obj;
if (is_array($obj)) {
$new = array();
foreach ($obj as $key => $val) {
$new[$key] = toArray($val);
}
} else {
$new = $obj;
}
return $new;
}
buf.delete(0, buf.length());
For Sql server try this
SELECT T.name,
I.rows AS [ROWCOUNT]
FROM sys.tables AS T
INNER JOIN sys.sysindexes AS I
ON T.object_id = I.id AND I.indid < 2
WHERE T.name = 'Your_Table_Name'
ORDER BY I.rows DESC
Sample Ubuntu-based build for ccache:
sudo apt-get update
sudo apt-get build-dep ccache
apt-get -b source ccache
sudo dpkg -i ccache*.deb
More details: http://blog.aplikacja.info/2011/11/building-packages-from-sources-in-debianubuntu/
Not sure if you have solved the problem. For this issue, you can use the "filter" function in the dplyr package. The idea is to filter the observations/rows whose values of the variable of your interest is not NA. Next, you make the graph with these filtered observations. You can find my codes below, and note that all the name of the data frame and variable is copied from the prompt of your question. Also, I assume you know the pipe operators.
library(tidyverse)
MyDate %>%
filter(!is.na(the_variable)) %>%
ggplot(aes(x= the_variable, fill=the_variable)) +
geom_bar(stat="bin")
You should be able to remove the annoying NAs on your plot. Hope this works :)
Run the command java -X
and you will get a list of all -X
options:
C:\Users\Admin>java -X
-Xmixed mixed mode execution (default)
-Xint interpreted mode execution only
-Xbootclasspath:<directories and zip/jar files separated by ;>
set search path for bootstrap classes and resources
-Xbootclasspath/a:<directories and zip/jar files separated by ;>
append to end of bootstrap class path
-Xbootclasspath/p:<directories and zip/jar files separated by ;>
prepend in front of bootstrap class path
-Xdiag show additional diagnostic messages
-Xnoclassgc disable class garbage collection
-Xincgc enable incremental garbage collection
-Xloggc:<file> log GC status to a file with time stamps
-Xbatch disable background compilation
-Xms<size> set initial Java heap size.........................
-Xmx<size> set maximum Java heap size.........................
-Xss<size> set java thread stack size
-Xprof output cpu profiling data
-Xfuture enable strictest checks, anticipating future default
-Xrs reduce use of OS signals by Java/VM (see documentation)
-Xcheck:jni perform additional checks for JNI functions
-Xshare:off do not attempt to use shared class data
-Xshare:auto use shared class data if possible (default)
-Xshare:on require using shared class data, otherwise fail.
-XshowSettings show all settings and continue
-XshowSettings:all show all settings and continue
-XshowSettings:vm show all vm related settings and continue
-XshowSettings:properties show all property settings and continue
-XshowSettings:locale show all locale related settings and continue
The -X options are non-standard and subject to change without notice.
I hope this will help you understand Xms
, Xmx
as well as many other things that matters the most. :)
Inci framework you can do download like so:
function clubDownload($clubname)
{
$this->load->library("excel");
$object = new PHPExcel();
$object->setActiveSheetIndex(0);
$this->load->model('Members_student_model');
$query = $this->db->query("SELECT * FROM student WHERE $clubname!='' order by id desc");
$resultdatanew=$query->result_array();
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 1;
$object->getActiveSheet()->getStyle("A1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("B1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("C1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("D1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("E1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("F1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("G1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("H1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$object->getActiveSheet()->getStyle("I1")->getFont()->setBold(true)
->setName('Verdana')
->setSize(10)
->getColor()->setRGB('330000');
$headerStyle = array(
'fill' => array(
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb'=>'CCE5FF'),
),
'font' => array(
'bold' => true,
)
);
$object->getActiveSheet()->getStyle('A1:'.'I1')->applyFromArray($headerStyle);
$table_columns = array("id", "studentid", "passport", "lastname", "firstname","university","commencing",$clubname,"added_date");
$column = 0;
foreach($table_columns as $field)
{
$object->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field);
$column++;
}
$excel_row = 2;
foreach($resultdatanew as $row)
{
$id=$row['id'];
$studentid=$row['studentid'];
$passport=$row['passport'];
$lastname=$row['last_name'];
$firstname=$row['first_name'];
$passport=$row['university'];
$commencing=$row['commencing'];
$email_id=$row['email_id'];
$added_date=$row['added_date'];
$object->getActiveSheet()->setCellValueByColumnAndRow(0, $excel_row,$id);
$object->getActiveSheet()->setCellValueByColumnAndRow(1, $excel_row, $studentid);
$object->getActiveSheet()->setCellValueByColumnAndRow(2, $excel_row, $passport);
$object->getActiveSheet()->setCellValueByColumnAndRow(3, $excel_row, $lastname);
$object->getActiveSheet()->setCellValueByColumnAndRow(4, $excel_row, $firstname);
$object->getActiveSheet()->setCellValueByColumnAndRow(5, $excel_row, $passport);
$object->getActiveSheet()->setCellValueByColumnAndRow(6, $excel_row, $commencing);
$object->getActiveSheet()->setCellValueByColumnAndRow(7, $excel_row, $email_id);
$object->getActiveSheet()->setCellValueByColumnAndRow(8, $excel_row, $added_date);
$excel_row++;
}
$object_writer = PHPExcel_IOFactory::createWriter($object, 'Excel5');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="club' .$clubname.'-'.date('Y-m-d') . '.xls');
$object_writer->save('php://output');
I suggest you do it a different way.
In the following code I set as a Range
the column with the sports name F and loop through each cell of it, check if it is "hockey" and if yes I insert the values in the other sheet one by one, by using Offset.
I do not think it is very complicated and even if you are just learning VBA, you should probably be able to understand every step. Please let me know if you need some clarification
Sub TestThat()
'Declare the variables
Dim DataSh As Worksheet
Dim HokySh As Worksheet
Dim SportsRange As Range
Dim rCell As Range
Dim i As Long
'Set the variables
Set DataSh = ThisWorkbook.Sheets("Data")
Set HokySh = ThisWorkbook.Sheets("Hoky")
Set SportsRange = DataSh.Range(DataSh.Cells(3, 6), DataSh.Cells(Rows.Count, 6).End(xlUp))
'I went from the cell row3/column6 (or F3) and go down until the last non empty cell
i = 2
For Each rCell In SportsRange 'loop through each cell in the range
If rCell = "hockey" Then 'check if the cell is equal to "hockey"
i = i + 1 'Row number (+1 everytime I found another "hockey")
HokySh.Cells(i, 2) = i - 2 'S No.
HokySh.Cells(i, 3) = rCell.Offset(0, -1) 'School
HokySh.Cells(i, 4) = rCell.Offset(0, -2) 'Background
HokySh.Cells(i, 5) = rCell.Offset(0, -3) 'Age
End If
Next rCell
End Sub
Once you clear the interval using clearInterval
you could setInterval
once again. And to avoid repeating the callback externalize it as a separate function:
var ticker = function() {
console.log('idle');
};
then:
var myTimer = window.setInterval(ticker, 4000);
then when you decide to restart:
window.clearInterval(myTimer);
myTimer = window.setInterval(ticker, 4000);
What about this:
var txt="";
var nyc = {
fullName: "New York City",
mayor: "Michael Bloomberg",
population: 8000000,
boroughs: 5
};
for (var x in nyc){
txt += nyc[x];
}
For Eclipse, you can use TPTP (Test and Performance Tools Platform) for analyse memory usage and etc. more information
I am using mongoose version 5.x for my project. After requiring the mongoose package, set the value globally as below.
const mongoose = require('mongoose');
// Set the global useNewUrlParser option to turn on useNewUrlParser for every connection by default.
mongoose.set('useNewUrlParser', true);
Maybe you can try traversing upwards from __filename
until you find a package.json
, and decide that's the main directory your current file belongs to.
If you're using long lists, it appears the list comprehension's faster, not to mention more readable.
~$ python -mtimeit -s"mylist = ['a','b','c','d']" "list(enumerate(mylist))"
1000000 loops, best of 3: 1.61 usec per loop
~$ python -mtimeit -s"mylist = ['a','b','c','d']" "[(i, j) for i, j in enumerate(mylist)]"
1000000 loops, best of 3: 0.978 usec per loop
~$ python -mtimeit -s"mylist = ['a','b','c','d']" "[t for t in enumerate(mylist)]"
1000000 loops, best of 3: 0.767 usec per loop
I have to find distinct rows with the following details
class : Scountry
columns: countryID, countryName,isactive
There is no primary key in this. I have succeeded with the followin queries
public DbSet<SCountry> country { get; set; }
public List<SCountry> DoDistinct()
{
var query = (from m in country group m by new { m.CountryID, m.CountryName, m.isactive } into mygroup select mygroup.FirstOrDefault()).Distinct();
var Countries = query.ToList().Select(m => new SCountry { CountryID = m.CountryID, CountryName = m.CountryName, isactive = m.isactive }).ToList();
return Countries;
}
I have come to point out the answer nobody seems to see here. You can fullfill all requests you have made with pure CSS and it's very simple. Just use Media Queries. Media queries can check the orientation of the user's screen, or viewport. Then you can style your images depending on the orientation.
Just set your default CSS on your images like so:
img {
width:auto;
height:auto;
max-width:100%;
max-height:100%;
}
Then use some media queries to check your orientation and that's it!
@media (orientation: landscape) { img { height:100%; } }
@media (orientation: portrait) { img { width:100%; } }
You will always get an image that scales to fit the screen, never loses aspect ratio, never scales larger than the screen, never clips or overflows.
To learn more about these media queries, you can read MDN's specs.
To center your image horizontally and vertically, just use the flex box model. Use a parent div
set to 100% width and height, like so:
div.parent {
display:flex;
position:fixed;
left:0px;
top:0px;
width:100%;
height:100%;
justify-content:center;
align-items:center;
}
With the parent div's display
set to flex
, the element is now ready to use the flex box model. The justify-content
property sets the horizontal alignment of the flex items. The align-items
property sets the vertical alignment of the flex items.
I too had wanted these exact requirements and had scoured the web for a pure CSS solution. Since none of the answers here fulfilled all of your requirements, either with workarounds or settling upon sacrificing a requirement or two, this solution really is the most straightforward for your goals; as it fulfills all of your requirements with pure CSS.
EDIT: The accepted answer will only appear to work if your images are large. Try using small images and you will see that they can never be larger than their original size.
I was stuck for a very long time at this problem but after sometime I found a solution:
If the function is from a source file available on the filesystem, then inspect.getsource(foo)
might be of help:
If foo
is defined as:
def foo(arg1,arg2):
#do something with args
a = arg1 + arg2
return a
Then:
import inspect
lines = inspect.getsource(foo)
print(lines)
Returns:
def foo(arg1,arg2):
#do something with args
a = arg1 + arg2
return a
But I believe that if the function is compiled from a string, stream or imported from a compiled file, then you cannot retrieve its source code.
if (obj === undefined)
{
// Create obj
}
If you are doing extensive javascript programming you should get in the habit of using === and !== when you want to make a type specific check.
Also if you are going to be doing a fair amount of javascript, I suggest running code through JSLint http://www.jslint.com it might seem a bit draconian at first, but most of the things JSLint warns you about will eventually come back to bite you.
the lines
account.withdraw(balance, 2500);
account.deposit(balance, 3000);
you might want to make withdraw and deposit non-static and let it modify the balance
public void withdraw(double withdrawAmount) {
balance = balance - withdrawAmount;
}
public void deposit(double depositAmount) {
balance = balance + depositAmount;
}
and remove the balance parameter from the call
DateTime dt = DateTime.Parse("01:00 pm"); //Time in string formate
TimeSpan time = new TimeSpan();
time = dt.TimeOfDay;
Console.WriteLine(time);
Result : 13:00:00
Apart from answering OP's queries, Let me throw some insights on Apache Solr from simple introduction to detailed installation and implementation.
Simple Introduction
Anyone who has had experience with the search engines above, or other engines not in the list -- I would love to hear your opinions.
Solr shouldn't be used to solve real-time problems. For search engines, Solr is pretty much game and works flawlessly.
Solr works fine on High Traffic web-applications (I read somewhere that it is not suited for this, but I am backing up that statement). It utilizes the RAM, not the CPU.
- result relevance and ranking
The boost helps you rank your results show up on top. Say, you're trying to search for a name john in the fields firstname and lastname, and you want to give relevancy to the firstname field, then you need to boost up the firstname field as shown.
http://localhost:8983/solr/collection1/select?q=firstname:john^2&lastname:john
As you can see, firstname field is boosted up with a score of 2.
More on SolrRelevancy
- searching and indexing speed
The speed is unbelievably fast and no compromise on that. The reason I moved to Solr.
Regarding the indexing speed, Solr can also handle JOINS from your database tables. A higher and complex JOIN do affect the indexing speed. However, an enormous RAM config can easily tackle this situation.
The higher the RAM, The faster the indexing speed of Solr is.
- ease of use and ease of integration with Django
Never attempted to integrate Solr and Django, however you can achieve to do that with Haystack. I found some interesting article on the same and here's the github for it.
- resource requirements - site will be hosted on a VPS, so ideally the search engine wouldn't require a lot of RAM and CPU
Solr breeds on RAM, so if the RAM is high, you don't to have to worry about Solr.
Solr's RAM usage shoots up on full-indexing if you have some billion records, you could smartly make use of Delta imports to tackle this situation. As explained, Solr is only a near real-time solution.
- scalability
Solr is highly scalable. Have a look on SolrCloud. Some key features of it.
- extra features such as "did you mean?", related searches, etc
For the above scenario, you could use the SpellCheckComponent that is packed up with Solr. There are a lot other features, The SnowballPorterFilterFactory helps to retrieve records say if you typed, books instead of book, you will be presented with results related to book.
This answer broadly focuses on Apache Solr & MySQL. Django is out of scope.
Assuming that you are under LINUX environment, you could proceed to this article further. (mine was an Ubuntu 14.04 version)
Detailed Installation
Download Apache Solr from here. That would be version is 4.8.1. You could download new versions, I found this stable.
After downloading the archive , extract it to a folder of your choice.
Say .. Downloads
or whatever.. So it will look like Downloads/solr-4.8.1/
On your prompt.. Navigate inside the directory
shankar@shankar-lenovo: cd Downloads/solr-4.8.1
So now you are here ..
shankar@shankar-lenovo: ~/Downloads/solr-4.8.1$
Jetty is available inside the examples folder of the solr-4.8.1
directory , so navigate inside that and start the Jetty Application Server.
shankar@shankar-lenovo:~/Downloads/solr-4.8.1/example$ java -jar start.jar
Now , do not close the terminal , minimize it and let it stay aside.
( TIP : Use & after start.jar to make the Jetty Server run in the background )
To check if Apache Solr runs successfully, visit this URL on the browser. http://localhost:8983/solr
It runs on the port 8983 as default. You could change the port either here or directly inside the jetty.xml
file.
java -Djetty.port=9091 -jar start.jar
This JAR file acts as a bridge between MySQL and JDBC , Download the Platform Independent Version here
After downloading it, extract the folder and copy themysql-connector-java-5.1.31-bin.jar
and paste it to the lib directory.
shankar@shankar-lenovo:~/Downloads/solr-4.8.1/contrib/dataimporthandler/lib
To put Solr to use, You need to have some tables and data to search for. For that, we will use MySQL for creating a table and pushing some random names and then we could use Solr to connect to MySQL and index that table and it's entries.
CREATE TABLE test_solr_mysql
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(45) NULL,
created TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
);
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jean');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jack');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jason');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Vego');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Grunt');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jasper');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Fred');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Jenna');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Rebecca');
INSERT INTO `test_solr_mysql` (`name`) VALUES ('Roland');
shankar@shankar-lenovo: ~/Downloads/solr-4.8.1/example/solr/collection1/conf
Add these two directives to this file..
<lib dir="../../../contrib/dataimporthandler/lib/" regex=".*\.jar" />
<lib dir="../../../dist/" regex="solr-dataimporthandler-\d.*\.jar" />
Now add the DIH (Data Import Handler)
<requestHandler name="/dataimport"
class="org.apache.solr.handler.dataimport.DataImportHandler" >
<lst name="defaults">
<str name="config">db-data-config.xml</str>
</lst>
</requestHandler>
If the file exists then ignore, add these lines to that file. As you can see the first line, you need to provide the credentials of your MySQL database. The Database name, username and password.
<dataConfig>
<dataSource type="JdbcDataSource" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/yourdbname" user="dbuser" password="dbpass"/>
<document>
<entity name="test_solr" query="select CONCAT('test_solr-',id) as rid,name from test_solr_mysql WHERE '${dataimporter.request.clean}' != 'false'
OR `created` > '${dataimporter.last_index_time}'" >
<field name="id" column="rid" />
<field name="solr_name" column="name" />
</entity>
</document>
</dataConfig>
( TIP : You can have any number of entities but watch out for id field, if they are same then indexing will skipped. )
Add this to your schema.xml as shown..
<uniqueKey>id</uniqueKey>
<field name="solr_name" type="string" indexed="true" stored="true" />
Implementation
This is where the real deal is. You need to do the indexing of data from MySQL to Solr inorder to make use of Solr Queries.
Hit the URL http://localhost:8983/solr on your browser. The screen opens like this.
As the marker indicates, go to Logging inorder to check if any of the above configuration has led to errors.
Ok so now you are here, As you can there are a lot of yellow messages (WARNINGS). Make sure you don't have error messages marked in red. Earlier, on our configuration we had added a select query on our db-data-config.xml, say if there were any errors on that query, it would have shown up here.
Fine, no errors. We are good to go. Let's choose collection1 from the list as depicted and select Dataimport
Using the DIH, you will be connecting to MySQL from Solr through the configuration file db-data-config.xml from the Solr interface and retrieve the 10 records from the database which gets indexed onto Solr.
To do that, Choose full-import , and check the options Clean and Commit. Now click Execute as shown.
Alternatively, you could use a direct full-import query like this too..
http://localhost:8983/solr/collection1/dataimport?command=full-import&commit=true
After you clicked Execute, Solr begins to index the records, if there were any errors, it would say Indexing Failed and you have to go back to the Logging section to see what has gone wrong.
Assuming there are no errors with this configuration and if the indexing is successfully complete., you would get this notification.
Seems like everything went well, now you could use Solr Queries to query the data that was indexed. Click the Query on the left and then press Execute button on the bottom.
You will see the indexed records as shown.
The corresponding Solr query for listing all the records is
http://localhost:8983/solr/collection1/select?q=*:*&wt=json&indent=true
Well, there goes all 10 indexed records. Say, we need only names starting with Ja , in this case, you need to target the column name solr_name
, Hence your query goes like this.
http://localhost:8983/solr/collection1/select?q=solr_name:Ja*&wt=json&indent=true
That's how you write Solr Queries. To read more about it, Check this beautiful article.
var app = angular.module('myApp', []);_x000D_
app.controller('myCtrl', function($scope) {_x000D_
_x000D_
$scope.minus = function() { _x000D_
_x000D_
var a = Number($scope.a || 0);_x000D_
var b = Number($scope.b || 0);_x000D_
$scope.sum1 = a-b;_x000D_
// $scope.sum = $scope.sum1+1; _x000D_
alert($scope.sum1);_x000D_
}_x000D_
_x000D_
$scope.add = function() { _x000D_
_x000D_
var c = Number($scope.c || 0);_x000D_
var d = Number($scope.d || 0);_x000D_
$scope.sum2 = c+d;_x000D_
alert($scope.sum2);_x000D_
}_x000D_
});
_x000D_
<head>_x000D_
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="myCtrl">_x000D_
<h3>Using Double Negation</h3>_x000D_
_x000D_
<p>First Number:_x000D_
<input type="text" ng-model="a" />_x000D_
</p>_x000D_
<p>Second Number:_x000D_
<input type="text" ng-model="b" />_x000D_
</p>_x000D_
<button id="minus" ng-click="minus()">Minus</button>_x000D_
<!-- <p>Sum: {{ a - b }}</p> -->_x000D_
<p>Sum: {{ sum1 }}</p>_x000D_
_x000D_
<p>First Number:_x000D_
<input type="number" ng-model="c" />_x000D_
</p>_x000D_
<p>Second Number:_x000D_
<input type="number" ng-model="d" />_x000D_
</p>_x000D_
<button id="minus" ng-click="add()">Add</button>_x000D_
<p>Sum: {{ sum2 }}</p>_x000D_
</div>
_x000D_
If you want to use the back button, check this out. https://stackoverflow.com/questions/116446/what-is-the-best-back-button-jquery-plugin
Use document.location.href to change the page location, place it in the function on a successful ajax run.
curl: command not found
is a big hint, you have to install it with :
apt-get update; apt-get install curl
Your CAST() looks correct.
Your CONVERT() is not correct. You are quoting the column as a string. You will want something like
CONVERT(INT, A.my_NvarcharColumn)
** notice without the quotes **
The only other reason why this could fail is if you have a non-numeric character in the field value or if it's out of range.
You can try something like the following to verify it's numeric and return a NULL if it's not:
SELECT
CASE
WHEN ISNUMERIC(A.my_NvarcharColumn) = 1 THEN CONVERT(INT, A.my_NvarcharColumn)
ELSE NULL
END AS my_NvarcharColumn
I searched for multiple options to get my git reset to specific commit, but most of them aren't so satisfactory.
I generally use this to reset the git to the specific commit in source tree.
select commit to reset on sourcetree.
In dropdowns select the active branch , first Parent Only
And right click on "Reset branch to this commit" and select hard reset option (soft, mixed and hard)
and then go to terminal git push -f
You should be all set!
I use this:
var myapp = angular.module('myApp', [])
// allow DI for use in controllers, unit tests
.constant('_', window._)
// use in views, ng-repeat="x in _.range(3)"
.run(function ($rootScope) {
$rootScope._ = window._;
});
See https://github.com/angular/angular.js/wiki/Understanding-Dependency-Injection about halfway for some more info on run
.
It sounds like you want to control whether components published in your manifest are active, not dynamically register a receiver (via Context.registerReceiver()) while running.
If so, you can use PackageManager.setComponentEnabledSetting() to control whether these components are active:
Note if you are only interested in receiving a broadcast while you are running, it is better to use registerReceiver(). A receiver component is primarily useful for when you need to make sure your app is launched every time the broadcast is sent.
Unwind segues are used to "go back" to some view controller from which, through a number of segues, you got to the "current" view controller.
Imagine you have something a MyNavController
with A
as its root view controller. Now you use a push segue to B
. Now the navigation controller has A and B in its viewControllers
array, and B is visible. Now you present C
modally.
With unwind segues, you could now unwind "back" from C
to B
(i.e. dismissing the modally presented view controller), basically "undoing" the modal segue. You could even unwind all the way back to the root view controller A
, undoing both the modal segue and the push segue.
Unwind segues make it easy to backtrack. For example, before iOS 6, the best practice for dismissing presented view controllers was to set the presenting view controller as the presented view controller’s delegate, then call your custom delegate method, which then dismisses the presentedViewController. Sound cumbersome and complicated? It was. That’s why unwind segues are nice.
UPDATE MyTable SET MyDate = CONVERT(datetime, '2009/07/16 08:28:01', 120)
For a full discussion of CAST and CONVERT, including the different date formatting options, see the MSDN Library Link below:
https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql
Try this code:
SELECT XMLAGG(XMLELEMENT(E,fieldname||',')).EXTRACT('//text()') "FieldNames"
FROM FIELD_MASTER
WHERE FIELD_ID > 10 AND FIELD_AREA != 'NEBRASKA';
Use "E"
See the section on Date and Time Patterns:
So things have changed ever since @Luke Bennett answered this question. Here is an update.
jQuery since version 1.4(?) automatically detects if the element you are trying to insert (using any of the append()
, prepend()
, before()
, or after()
methods) is a <tr>
and inserts it into the first <tbody>
in your table or wraps it into a new <tbody>
if one doesn't exist.
So yes your example code is acceptable and will work fine with jQuery 1.4+. ;)
$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');
Judging from other answers, it seems this might be find's fault.
However you can do it this way instead:
find . * | grep -P "[a-f0-9\-]{36}\.jpg"
You might have to tweak the grep a bit and use different options depending on what you want but it works.
$("#myframe").load(function() {
alert("loaded");
});
You can get clean and clear solutions by building the appropriate predicates as helper functions. In other words, use the Python set-builder notation the same way you would write the answer with regular mathematics set-notation.
The whole idea behind set comprehensions is to let us write and reason in code the same way we do mathematics by hand.
With an appropriate predicate in hand, problem 1 simplifies to:
low_primes = {x for x in range(1, 100) if is_prime(x)}
And problem 2 simplifies to:
low_prime_pairs = {(x, x+2) for x in range(1,100,2) if is_prime(x) and is_prime(x+2)}
Note how this code is a direct translation of the problem specification, "A Prime Pair is a pair of consecutive odd numbers that are both prime."
P.S. I'm trying to give you the correct problem solving technique without actually giving away the answer to the homework problem.
using System.ComponentModel;
private readonly BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
// run all background tasks here
}
private void worker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
//update ui once worker complete his work
}
worker.RunWorkerAsync();
Track progress (optional, but often useful)
a) subscribe to ProgressChanged
event and use ReportProgress(Int32)
in DoWork
b) set worker.WorkerReportsProgress = true;
(credits to @zagy)
Use setInterval
:
$(function(){
setInterval(oneSecondFunction, 1000);
});
function oneSecondFunction() {
// stuff you want to do every second
}
Here's an article on the difference between setTimeout
and setInterval
. Both will provide the functionality you need, they just require different implementations.
You can get all tables that has column "Product" from information_Schema.columns
SELECT DISTINCT table_name FROM information_schema.columns WHERE column_name ="Product";
Nor create a procedure
delimiter //
CREATE PROCEDURE curdemo()
BEGIN
DECLARE a varchar(100);
DECLARE cur1 CURSOR FOR SELECT DISTINCT table_name FROM information_schema.columns WHERE column_name ="Product";
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO a;
SELECT * FROM a;
END LOOP;
CLOSE cur1;
END;
delimiter ;
call curdemo();
If you go into the source code of an SVG file you can change the color fill by modifying the fill property.
<svg fill="#3F6078" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
</svg>
Use your favorite text editor, open the SVG file and play around with it.
There is a problem with pylint, which I do not completely understood yet.
You can just import OpenCV with:
from cv2 import cv2
A foreign key always requires an index. Without an index enforcing the constraint would require a full table scan on the referenced table for every inserted or updated key in the referencing table. And that would have an unacceptable performance impact. This has the following 2 consequences:
For an instance
Character.Gorgon gor = new Character.Gorgon();
Then do
gor instanceof Monster
For a Class instance do
Class<?> clazz = Character.Gorgon.class;
Monster.class.isAssignableFrom(clazz);
This is an array of the command line switches pass to the program. E.g. if you start the program with the command "myapp.exe -c -d
" then string[] args[]
will contain the strings "-c" and "-d".
Convert your x-axis data from text to datetime.datetime
, use datetime.strptime
:
>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
datetime.datetime(2012, 5, 31, 19, 0)
This is an example of how to plot data once you have an array of datetimes:
import matplotlib.pyplot as plt
import datetime
import numpy as np
x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)
plt.plot(x,y)
plt.show()
Try sgrep. It's not clear exactly what you are trying to do, but I surely would not attempt writing an XML parser in bash.
div { background: none !important }
div { background: red; }
Is transparent.
div { background: none !important }
div { background: red !important; }
Is red.
An !important can override another !important.
If you can't edit the CSS file you can still add another one, or a style tag in the head tag.
try to clean the eclipse project
You're making a mistake here. Oh, no, you've picked the right PHP functions to make your data a bit safer. That's fine. Your mistake is in the order of operations, and how and where to use these functions.
It's important to understand the difference between sanitizing and validating user data, escaping data for storage, and escaping data for presentation.
When users submit data, you need to make sure that they've provided something you expect.
For example, if you expect a number, make sure the submitted data is a number. You can also cast user data into other types. Everything submitted is initially treated like a string, so forcing known-numeric data into being an integer or float makes sanitization fast and painless.
What about free-form text fields and textareas? You need to make sure that there's nothing unexpected in those fields. Mainly, you need to make sure that fields that should not have any HTML content do not actually contain HTML. There are two ways you can deal with this problem.
First, you can try escaping HTML input with htmlspecialchars
. You should not use htmlentities
to neutralize HTML, as it will also perform encoding of accented and other characters that it thinks also need to be encoded.
Second, you can try removing any possible HTML. strip_tags
is quick and easy, but also sloppy. HTML Purifier does a much more thorough job of both stripping out all HTML and also allowing a selective whitelist of tags and attributes through.
Modern PHP versions ship with the filter extension, which provides a comprehensive way to sanitize user input.
Making sure that submitted data is free from unexpected content is only half of the job. You also need to try and make sure that the data submitted contains values you can actually work with.
If you're expecting a number between 1 and 10, you need to check that value. If you're using one of those new fancy HTML5-era numeric inputs with a spinner and steps, make sure that the submitted data is in line with the step.
If that data came from what should be a drop-down menu, make sure that the submitted value is one that appeared in the menu.
What about text inputs that fulfill other needs? For example, date inputs should be validated through strtotime
or the DateTime class. The given date should be between the ranges you expect. What about email addresses? The previously mentioned filter extension can check that an address is well-formed, though I'm a fan of the is_email library.
The same is true for all other form controls. Have radio buttons? Validate against the list. Have checkboxes? Validate against the list. Have a file upload? Make sure the file is of an expected type, and treat the filename like unfiltered user data.
Every modern browser comes with a complete set of developer tools built right in, which makes it trivial for anyone to manipulate your form. Your code should assume that the user has completely removed all client-side restrictions on form content!
Now that you've made sure that your data is in the expected format and contains only expected values, you need to worry about persisting that data to storage.
Every single data storage mechanism has a specific way to make sure data is properly escaped and encoded. If you're building SQL, then the accepted way to pass data in queries is through prepared statements with placeholders.
One of the better ways to work with most SQL databases in PHP is the PDO extension. It follows the common pattern of preparing a statement, binding variables to the statement, then sending the statement and variables to the server. If you haven't worked with PDO before here's a pretty good MySQL-oriented tutorial.
Some SQL databases have their own specialty extensions in PHP, including SQL Server, PostgreSQL and SQLite 3. Each of those extensions has prepared statement support that operates in the same prepare-bind-execute fashion as PDO. Sometimes you may need to use these extensions instead of PDO to support non-standard features or behavior.
MySQL also has its own PHP extensions. Two of them, in fact. You only want to ever use the one called mysqli. The old "mysql" extension has been deprecated and is not safe or sane to use in the modern era.
I'm personally not a fan of mysqli. The way it performs variable binding on prepared statements is inflexible and can be a pain to use. When in doubt, use PDO instead.
If you are not using an SQL database to store your data, check the documentation for the database interface you're using to determine how to safely pass data through it.
When possible, make sure that your database stores your data in an appropriate format. Store numbers in numeric fields. Store dates in date fields. Store money in a decimal field, not a floating point field. Review the documentation provided by your database on how to properly store different data types.
Every time you show data to users, you must make sure that the data is safely escaped, unless you know that it shouldn't be escaped.
When emitting HTML, you should almost always pass any data that was originally user-supplied through htmlspecialchars
. In fact, the only time you shouldn't do this is when you know that the user provided HTML, and that you know that it's already been sanitized it using a whitelist.
Sometimes you need to generate some Javascript using PHP. Javascript does not have the same escaping rules as HTML! A safe way to provide user-supplied values to Javascript via PHP is through json_encode
.
There are many more nuances to data validation.
For example, character set encoding can be a huge trap. Your application should follow the practices outlined in "UTF-8 all the way through". There are hypothetical attacks that can occur when you treat string data as the wrong character set.
Earlier I mentioned browser debug tools. These tools can also be used to manipulate cookie data. Cookies should be treated as untrusted user input.
Data validation and escaping are only one aspect of web application security. You should make yourself aware of web application attack methodologies so that you can build defenses against them.
Create custom context initializer:
public class MyDbContextInitializer : MigrateDatabaseToLatestVersion<MyDbContext, Migrations.Configuration>
{
public override void InitializeDatabase(MyDbContext context)
{
bool exists = context.Database.Exists();
base.InitializeDatabase(context);
if (!exists)
{
MyDbSeed.Seed(context);
}
}
}
Note that Migrations.Configuration is a class generating by migration command line in Package Manager Console. You may need to change internal to public modifier of the Migrations.Configuration class.
And register it from your OmModelCreating:
public partial class MyDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<MyDbContext>(new MyDbContextInitializer());
//other code for creating model
}
}
1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,
2) AbstractTableModel should be useful, where is in the JTable
required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel
,
3) consider using DefaultTableModel
, (if you are not sure about how to works) instead of AbstractTableModel
,
could be generated from simple code:
import javax.swing.*;
import javax.swing.table.*;
public class TableCheckBox extends JFrame {
private static final long serialVersionUID = 1L;
private JTable table;
public TableCheckBox() {
Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
Object[][] data = {
{"Buy", "IBM", new Integer(1000), new Double(80.50), false},
{"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
{"Sell", "Apple", new Integer(3000), new Double(7.35), true},
{"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model) {
private static final long serialVersionUID = 1L;
/*@Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}*/
@Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return Integer.class;
case 3:
return Double.class;
default:
return Boolean.class;
}
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TableCheckBox frame = new TableCheckBox();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
}
});
}
}
I pasted the contents of your example into a file named so.txt
.
$ cat so.txt | awk '{ print $7 }' | cut -f2 -d"="
9
10
Explanation:
cat so.txt
will print the contents of the file to stdout
. awk '{ print $7 }'
will print the seventh column, i.e. the one containing id=n
cut -f2 -d"="
will cut the output of step #2 using =
as the delimiter and get the second column (-f2
)If you'd rather get id=
also, then:
$ cat so.txt | awk '{ print $7 }'
id=9
id=10
Yes, PHP supports arrays as session variables. See this page for an example.
As for your second question: once you set the session variable, it will remain the same until you either change it or unset
it. So if the 3rd page doesn't change the session variable, it will stay the same until the 2nd page changes it again.
As an addition and observation to the other useful answers, it's worth noticing that actually doing [:10]
as slicing will return the first 10 elements of the list, not the last 10...
To get the last 10 you should do [-10:]
instead (see here). This will help you avoid using order_by('-id')
with the -
to reverse the elements.
I think the tutorial passed by @emdhie will help a lot. How install maven
But, i followed and still getting mvn: command not found
I found this solution to know what was wrong in my configuration:
I opened the command line and called this command:
../apache-maven-3.5.3/bin/mvn --version
After that i got the correct JAVA_HOME and saw that my JAVA_HOME was wrong.
Hope this helps.
I have published a WPF Auto Complete Text Box in WPF at CodePlex.com. You can download and try it from https://wpfautocomplete.codeplex.com/.
Just this:
// assuming "cloud" is:
// int cloud[10];
// or any other fixed size
#define countof(x) (sizeof(x)/sizeof((x)[0]))
int* pMax = std::max_element(cloud, cloud + countof(cloud));
When you use QDir.mkpath() it returns true if the path already exists, in the other hand QDir.mkdir() returns false if the path already exists. So depending on your program you have to choose which fits better.
You can see more on Qt Documentation
If you just want to remove single character and If you know index of a character you want to remove, you can use following function:
/**
* Remove single character at particular index from string
* @param {*} index index of character you want to remove
* @param {*} str string from which character should be removed
*/
function removeCharAtIndex(index, str) {
var maxIndex=index==0?0:index;
return str.substring(0, maxIndex) + str.substring(index, str.length)
}
I realize this is a very old post, but I have had success using the JUCE library, which builds projects for the major IDE's like Xcode, VS, and Codeblocks and automatically builds VST/3, AU/v3, RTAS, and AAX.
declare @testVal varchar(20)
set @testVal = '?t/es?ti/n*g 1*2?3*'
select @testVal = REPLACE(@testVal, item, '') from (select '?' item union select '*' union select '/') list
select @testVal;
try this code. then 'formId' div can set the image.
$('#formId').append('<iframe style="width: 100%;height: 500px" src="/document_path/name.jpg"' +
'title="description"> </iframe> ');
When you call diff
, moment.js calculates the difference in milliseconds.
If the milliseconds is passed to duration
, it is used to calculate duration which is correct.
However. when you pass the same milliseconds to the moment()
, it calculates the date that is milliseconds from(after) epoch/unix time that is January 1, 1970 (midnight UTC/GMT).
That is why you get 1969 as the year together with wrong hour.
duration.get("hours") +":"+ duration.get("minutes") +":"+ duration.get("seconds")
So, I think this is how you should do it since moment.js does not offer format
function for duration. Or you can write a simple wrapper to make it easier/prettier.
open http://localhost:8080/ in browser, if you get tomcat home page. it means tomcat is running
The problem is that simple console can't edit the registry. No need to edit the registry by hand, just launch the groovysh
once with administrative priveleges. All subsequent launches work without error.
Since you are using jQuery, you might as well use the each method... Also, it seems like everything is a value of the property 'd' in this JS Object [Notation].
$.each(result.d,function(i) {
// In case there are several values in the array 'd'
$.each(this,function(j) {
// Apparently doesn't work...
alert(this.EmployeeName);
// What about this?
alert(result.d[i][j]['EmployeeName']);
// Or this?
alert(result.d[i][j].EmployeeName);
});
});
That should work. if not, then maybe you can give us a longer example of the JSON.
Edit: If none of this stuff works then I'm starting to think there might be something wrong with the syntax of your JSON.
Try this:
window.location.href = "http://PlaceYourUrl.com";
I feel that I need to extend my comment a bit...
About paradigm\style
That's probably the most notable aspect. FP became popular due to what you can get avoiding side-effects. I won't delve deep into what pros\cons you can get from this, since this is not related to the question.
However, I will say that the iteration using Iterable.forEach is inspired by FP and rather result of bringing more FP to Java (ironically, I'd say that there is no much use for forEach in pure FP, since it does nothing except introducing side-effects).
In the end I would say that it is rather a matter of taste\style\paradigm you are currently writing in.
About parallelism.
From performance point of view there is no promised notable benefits from using Iterable.forEach over foreach(...).
According to official docs on Iterable.forEach :
Performs the given action on the contents of the Iterable, in the order elements occur when iterating, until all elements have been processed or the action throws an exception.
... i.e. docs pretty much clear that there will be no implicit parallelism. Adding one would be LSP violation.
Now, there are "parallell collections" that are promised in Java 8, but to work with those you need to me more explicit and put some extra care to use them (see mschenk74's answer for example).
BTW: in this case Stream.forEach will be used, and it doesn't guarantee that actual work will be done in parallell (depends on underlying collection).
UPDATE: might be not that obvious and a little stretched at a glance but there is another facet of style and readability perspective.
First of all - plain old forloops are plain and old. Everybody already knows them.
Second, and more important - you probably want to use Iterable.forEach only with one-liner lambdas. If "body" gets heavier - they tend to be not-that readable. You have 2 options from here - use inner classes (yuck) or use plain old forloop. People often gets annoyed when they see the same things (iteratins over collections) being done various vays/styles in the same codebase, and this seems to be the case.
Again, this might or might not be an issue. Depends on people working on code.
Did you declare the jobparameters as map properly as bean?
Or did you perhaps accidently instantiate a JobParameters object, which has no getter for the filename?
For more on expression language you can find information in Spring documentation here.
You can use it like this: http://plnkr.co/edit/vtNjEgmpItqxX5fdwtPi?p=preview
Like you found, filter
accepts predicate function which accepts item
by item from the array.
So, you just have to create an predicate function based on the given criteria
.
In this example, criteriaMatch
is a function which returns a predicate
function which matches the given criteria
.
template:
<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
{{ item }}
</div>
scope:
$scope.criteriaMatch = function( criteria ) {
return function( item ) {
return item.name === criteria.name;
};
};