Other answers have already covered profiling to avoid premature optimization and overhead cost in parallel processing. This answer explains the ideal choice of data structures for parallel streaming.
As a rule, performance gains from parallelism are best on streams over
ArrayList
,HashMap
,HashSet
, andConcurrentHashMap
instances; arrays;int
ranges; andlong
ranges. What these data structures have in common is that they can all be accurately and cheaply split into subranges of any desired sizes, which makes it easy to divide work among parallel threads. The abstraction used by the streams library to perform this task is the spliterator , which is returned by thespliterator
method onStream
andIterable
.Another important factor that all of these data structures have in common is that they provide good-to-excellent locality of reference when processed sequentially: sequential element references are stored together in memory. The objects referred to by those references may not be close to one another in memory, which reduces locality-of-reference. Locality-of-reference turns out to be critically important for parallelizing bulk operations: without it, threads spend much of their time idle, waiting for data to be transferred from memory into the processor’s cache. The data structures with the best locality of reference are primitive arrays because the data itself is stored contiguously in memory.
Source: Item #48 Use Caution When Making Streams Parallel, Effective Java 3e by Joshua Bloch
I think that a good idea is to use mb_stpos
:
$haystack = 'How are you?';
$needle = 'are';
if (mb_strpos($haystack, $needle) !== false) {
echo 'true';
}
Because this solution is case sensitive and safe for all Unicode characters.
But you can also do it like this (sauch response was not yet):
if (count(explode($needle, $haystack)) > 1) {
echo 'true';
}
This solution is also case sensitive and safe for Unicode characters.
In addition you do not use the negation in the expression, which increases the readability of the code.
Here is other solution using function:
function isContainsStr($haystack, $needle) {
return count(explode($needle, $haystack)) > 1;
}
if (isContainsStr($haystack, $needle)) {
echo 'true';
}
Completely reset?
Delete the .git
directory locally.
Recreate the git repostory:
$ cd (project-directory)
$ git init
$ (add some files)
$ git add .
$ git commit -m 'Initial commit'
Push to remote server, overwriting. Remember you're going to mess everyone else up doing this … you better be the only client.
$ git remote add origin <url>
$ git push --force --set-upstream origin master
body {
position: fixed;
height: 100%;
}
class Calculate(object):
# Your instance method to be executed
def f(self, x, y):
return x*y
if __name__ == '__main__':
inp_list = [1,2,3]
y = 2
cal_obj = Calculate()
pool = Pool(2)
results = pool.map(lambda x: cal_obj.f(x, y), inp_list)
There is a possibility that you would want to apply this function for each different instance of the class. Then here is the solution for that also
class Calculate(object):
# Your instance method to be executed
def __init__(self, x):
self.x = x
def f(self, y):
return self.x*y
if __name__ == '__main__':
inp_list = [Calculate(i) for i in range(3)]
y = 2
pool = Pool(2)
results = pool.map(lambda x: x.f(y), inp_list)
Generally you can't have constant time look up and log time deletions/insertions, but if you're happy with log time look ups then you can use a SortedList.
Not sure if you'll trust my coding but I recently wrote a SortedList implementation in Java, which you can download from http://www.scottlogic.co.uk/2010/12/sorted_lists_in_java/. This implementation allows you to look up the i-th element of the list in log time.
It seems wrong to me to set up an if/else statement just to use the else portion...
Just negate your condition, and you'll get the else
logic inside the if
:
if (!(id in tutorTimes)) { ... }
You can try with the following:
new_string = your_string.split(',').pop().trim();
This is how it works:
split(',')
creates an array made of the different parts of your_string
(e.g. if the string is "'SELECT___100E___7',24"
, the array would be ["'SELECT___100E___7'", "24"]
).
pop()
gets the last element of the array(in the example, it would be "24"
).
This would already be enough, but in case there might be some spaces (not in the case of the OP, but more in general), we could have:
trim()
that would remove the spaces around the string (in case it would be " 24 "
, it would become simply "24"
)It's a simple solution and surely easier than a regexp.
I was searching for a deep find for dictionaries and didn't find one. Based on this article I was able to create the following. Thanks and Enjoy!!
def deapFind( theList, key, value ):
result = False
for x in theList:
if( value == x[key] ):
return True
return result
theList = [{ "n": "aaa", "d": "bbb" }, { "n": "ccc", "d": "ddd" }]
print 'Result: ' + str (deapFind( theList, 'n', 'aaa'))
I'm using == instead of the in operator since in returns true for partial matches. IOW: searching aa on the n key returns true. I don't think that would be desired.
HTH
select from_unixtime(column,'%Y-%m-%d') from myTable;
In your Android Manifest file make sure that the activity is using this (or a) theme (that is based on) @style/Theme.AppCompat.NoActionBar
This removes the ActionBar completely, but won't make your activity fullscreen.
If you want to make your activity fullscreen only use this theme
@android:style/Theme.NoTitleBar.Fullscreen
Or you could change
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
to
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
This is what I use to get fullscreen at runtime
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mDecorView = getWindow().getDecorView();
mDecorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
| View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
| View.SYSTEM_UI_FLAG_IMMERSIVE);
}
To exit fullscreen I use this
mDecorView = getWindow().getDecorView();
mDecorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
I know this was asked awhile back, but I found a comprehensive list of the virtual keyboard key codes right in MSDN, for use in C/C++. This also includes the mouse events. Note it is different than the javascript key codes (I noticed it around the VK_OEM section).
Here's the link:
http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
This one worked for me:
PGPASSWORD=postgres psql -h localhost -p 3307 -U postgres -d postgres
Use the above to load an initial script as:
PGPASSWORD=postgres psql -h localhost -p 3307 -U postgres -d postgres < src/sql/local/blabla.sql
Do not that i remap my ports as:
docker run -p3307:5432 --name postgres -e POSTGRES_PASSWORD=postgres -d postgres
Edit your /etc/postgresql/9.3/main/postgresql.conf
, and change the lines as follows.
Note: If you didn't find the postgresql.conf
file, then just type $locate postgresql.conf
in a terminal
#log_directory = 'pg_log'
to log_directory = 'pg_log'
#log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'
to log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log'
#log_statement = 'none'
to log_statement = 'all'
#logging_collector = off
to logging_collector = on
Optional: SELECT set_config('log_statement', 'all', true);
sudo /etc/init.d/postgresql restart
or sudo service postgresql restart
Fire query in postgresql select 2+2
Find current log in /var/lib/pgsql/9.2/data/pg_log/
The log files tend to grow a lot over a time, and might kill your machine. For your safety, write a bash script that'll delete logs and restart postgresql server.
Thanks @paul , @Jarret Hardie , @Zoltán , @Rix Beck , @Latif Premani
Custom domain SSL certs were just added today for $600/cert/month. Sign up for your invite below: http://aws.amazon.com/cloudfront/custom-ssl-domains/
Update: SNI customer provided certs are now available for no additional charge. Much cheaper than $600/mo, and with XP nearly killed off, it should work well for most use cases.
@skalee AWS has a mechanism for achieving what the poster asks for, "implement SSL for an Amazon s3 bucket", it's called CloudFront
. I'm reading "implement" as "use my SSL certs," not "just put an S on the HTTP URL which I'm sure the OP could have surmised.
Since CloudFront costs exactly the same as S3 ($0.12/GB), but has a ton of additional features around SSL AND allows you to add your own SNI cert at no additional cost, it's the obvious fix for "implementing SSL" on your domain.
Another way to extend (specifically meaning, add new methods, not change existing ones) classes, even built-in ones, is to use a preprocessor that adds the ability to extend out of/above the scope of Python itself, converting the extension to normal Python syntax before Python actually gets to see it.
I've done this to extend Python 2's str()
class, for instance. str()
is a particularly interesting target because of the implicit linkage to quoted data such as 'this'
and 'that'
.
Here's some extending code, where the only added non-Python syntax is the extend:testDottedQuad
bit:
extend:testDottedQuad
def testDottedQuad(strObject):
if not isinstance(strObject, basestring): return False
listStrings = strObject.split('.')
if len(listStrings) != 4: return False
for strNum in listStrings:
try: val = int(strNum)
except: return False
if val < 0: return False
if val > 255: return False
return True
After which I can write in the code fed to the preprocessor:
if '192.168.1.100'.testDottedQuad():
doSomething()
dq = '216.126.621.5'
if not dq.testDottedQuad():
throwWarning();
dqt = ''.join(['127','.','0','.','0','.','1']).testDottedQuad()
if dqt:
print 'well, that was fun'
The preprocessor eats that, spits out normal Python without monkeypatching, and Python does what I intended it to do.
Just as a c preprocessor adds functionality to c, so too can a Python preprocessor add functionality to Python.
My preprocessor implementation is too large for a stack overflow answer, but for those who might be interested, it is here on GitHub.
I know, I am late but here is the correct way of doing it. using base64. This technique will convert the array to string.
import base64
import numpy as np
random_array = np.random.randn(32,32)
string_repr = base64.binascii.b2a_base64(random_array).decode("ascii")
array = np.frombuffer(base64.binascii.a2b_base64(string_repr.encode("ascii")))
For array to string
Convert binary data to a line of ASCII characters in base64 coding and decode to ASCII to get string repr.
For string to array
First, encode the string in ASCII format then Convert a block of base64 data back to binary and return the binary data.
I somehow absolutely missed the actual command in the accepted answer, so here it is again, bit more visible in its own paragraph, to see how many people are like me
$ docker history --no-trunc <IMAGE_ID>
Based on Ray Nicholus's answer :
inputElement.onchange = function(event) {
var fileList = inputElement.files;
//TODO do something with fileList.
}
using this will also work :
inputElement.onchange = function(event) {
var fileList = event.target.files;
//TODO do something with fileList.
}
One of the ways to get around login issues with ssh
, scp
, and sftp
(all use the same protocol and sshd
server) is to create public/private key pairings.
Some servers may disallow this, but most sites don't. These directions are for Unix/Linux/Mac. As always, Windows is a wee bit different although the cygwin environment on Windows does follow these steps.
ssh-keygen
. This can vary from system to system, but the program should lead you through this.ssh-keygen
is finished, you will have a $HOME/.ssh
directory on your machine. This directory will contain a public key and a private key. There will be two more files that are generated as you go along. One is known_hosts
which contains the fingerprints of all known hosts you've logged into. The second will be called either authorized_keys
or authorized_keys2
depending upon your implementation.ssh-keygen
there too. This will generate a $HOME/.ssh
directory there as well as a private/public key pair. Don't do this if the $HOME/.ssh
directory already exists and has a public and private key file. You don't want to regenerate it.$HOME/.ssh
directory, create a file called authorized_keys
. In this file, put your public key. This public key is found on your $HOME/.ssh
directory on your local machine. It will end with *.pub
. Paste the contents of that into authorized_keys
. If authorized_keys
already exists, paste your public key in the next line.Now, when you log in using ssh
, or you use scp
or sftp
, you will not be required to enter a password. By the way, the user IDs on the two machines do not have to agree. I've logged into many remote servers as a different user and setup my public key in authorized_keys
and have no problems logging directly into that user.
If you use Windows, you will need something that can do ssh
. Most people I know use PuTTY which can generate public/private keys, and do the key pairing when you login remotely. I can't remember all of the steps, but you generate two files (one contains the public key, one contains the private key), and configure PuTTY to use both of those when logging into a remote site. If that remote site is Linux/Unix/Mac, you can copy your public key and put it into the authorized_keys
file.
If you can use SSH Public/Private keys, you can eliminate the need for passwords in your scripts. Otherwise, you will have to use something like Expect or Perl with Net::SSH which can watch the remote host and enter the password when prompted.
A stack in principle is quite simple: imagine a rifle's clip - You can only access the topmost bullet - taking it out is called "pop", inserting a new one is called "push".
A very useful example for that is for applications that allow you to "undo".
Imagine you save each state of the application in a stack. e.g. the state of the application after every type the user makes.
Now when the user presses "undo" you just "pop" the previous state from the stack. For every action the user does - you "push" the new state to the stack (that's of course simplified).
About what your lecturer specifically was doing - in order to explain it some more information would be helpful..
We should have the projects which include (at least) all the filtered tags, or said in a different way, exclude the ones which doesn't include all those filtered tags.
So we can use Linq Except
to get those tags which are not included. Then we can use Count() == 0
to have only those which excluded no tags:
var res = projects.Where(p => filteredTags.Except(p.Tags).Count() == 0);
Or we can make it slightly faster with by replacing Count() == 0
with !Any()
:
var res = projects.Where(p => !filteredTags.Except(p.Tags).Any());
As far as I can tell from the question, the amount of padding you want will vary according to the data you have. Accordingly, the only solution to this is to scan the data before printing, to figure out the widest datum, and so find a width value you can pass to printf using the asterix operator, e.g.
loop over data - get correct padding, put into width
printf( "%*d\n", width, datum );
Adding to corroded answer from the same referenced page is a PowerShell version http://blogs.msdn.com/b/oldnewthing/archive/2008/04/17/8399914.aspx#8408736
Get-ChildItem -Recurse . | where { $_.PSISContainer -and @( $_ | Get-ChildItem ).Count -eq 0 } | Remove-Item
or, more tersely,
gci -R . | where { $_.PSISContainer -and @( $_ | gci ).Count -eq 0 } | ri
credit goes to the posting author
As others said, it's a time change in 1927 in Shanghai.
It was 23:54:07
in Shanghai, in the local standard time, but then after 5 minutes and 52 seconds, it turned to the next day at 00:00:00
, and then local standard time changed back to 23:54:08
. So, that's why the difference between the two times is 343 seconds, not 1 second, as you would have expected.
The time can also mess up in other places like the US. The US has Daylight Saving Time. When the Daylight Saving Time starts the time goes forward 1 hour. But after a while, the Daylight Saving Time ends, and it goes backward 1 hour back to the standard time zone. So sometimes when comparing times in the US the difference is about 3600
seconds not 1 second.
But there is something different about these two-time changes. The latter changes continuously and the former was just a change. It didn't change back or change again by the same amount.
It's better to use UTC unless if needed to use non-UTC time like in display.
$("input").click(function(){
var name = $(this).attr("name");
$('input[name="' + name + '"]').hide();
});
Also works with ID:
var id = $(this).attr("id");
$('input[id="' + id + '"]').hide();
when, (sometimes)
$('input#' + id).hide();
does not work, as it should.
You can even do both:
$('input[name="' + name + '"][id="' + id + '"]').hide();
Another possibility is to use separate lines to set up Make variables when a rule fires.
For example, here is a makefile with two rules. If a rule fires, it creates a temp dir and sets TMP to the temp dir name.
PHONY = ruleA ruleB display
all: ruleA
ruleA: TMP = $(shell mktemp -d testruleA_XXXX)
ruleA: display
ruleB: TMP = $(shell mktemp -d testruleB_XXXX)
ruleB: display
display:
echo ${TMP}
Running the code produces the expected result:
$ ls
Makefile
$ make ruleB
echo testruleB_Y4Ow
testruleB_Y4Ow
$ ls
Makefile testruleB_Y4Ow
Just another example where the value of a column from table 1 is inserted into a column in table 2:
UPDATE Address
SET Phone1 = sp.Phone
FROM Address ad LEFT JOIN Speaker sp
ON sp.AddressID = ad.ID
WHERE sp.Phone <> ''
if jQuery is available, you could use jQuery BBQ
If you use Eclipse Collections you can use the collectIf()
method.
MutableList<Integer> source =
Lists.mutable.with(1, null, 2, null, 3, null, 4, null, 5);
MutableList<String> result = source.collectIf(Objects::nonNull, String::valueOf);
Assert.assertEquals(Lists.immutable.with("1", "2", "3", "4", "5"), result);
It evaluates eagerly and should be a bit faster than using a Stream.
Note: I am a committer for Eclipse Collections.
With postgres 9.3 use -> for object access. 4 example
seed.rb
se = SmartElement.new
se.data =
{
params:
[
{
type: 1,
code: 1,
value: 2012,
description: 'year of producction'
},
{
type: 1,
code: 2,
value: 30,
description: 'length'
}
]
}
se.save
rails c
SELECT data->'params'->0 as data FROM smart_elements;
returns
data
----------------------------------------------------------------------
{"type":1,"code":1,"value":2012,"description":"year of producction"}
(1 row)
You can continue nesting
SELECT data->'params'->0->'type' as data FROM smart_elements;
return
data
------
1
(1 row)
Taking DWins example.
What I often do, particularly when I use many, many different plots with the same colours or size information, is I store them in variables I otherwise never use. This helps me keep my code a little cleaner AND I can change it "globally".
E.g.
clab = 1.5
cmain = 2
caxis = 1.2
plot(1, 1 ,xlab="x axis", ylab="y axis", pch=19,
col.lab="red", cex.lab=clab,
col="green", main = "Testing scatterplots", cex.main =cmain, cex.axis=caxis)
You can also write a function, doing something similar. But for a quick shot this is ideal. You can also store that kind of information in an extra script, so you don't have a messy plot script:
which you then call with setwd("") source("plotcolours.r")
in a file say called plotcolours.r you then store all the e.g. colour or size variables
clab = 1.5
cmain = 2
caxis = 1.2
for colours could use
darkred<-rgb(113,28,47,maxColorValue=255)
as your variable 'darkred' now has the colour information stored, you can access it in your actual plotting script.
plot(1,1,col=darkred)
The posted answer is fine but didn't directly answer the same question I had about reading in a connection string. Through much searching I found a slightly simpler way of doing this.
In Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
// Add the whole configuration object here.
services.AddSingleton<IConfiguration>(Configuration);
}
In your controller add a field for the configuration and a parameter for it on a constructor
private readonly IConfiguration configuration;
public HomeController(IConfiguration config)
{
configuration = config;
}
Now later in your view code you can access it like:
connectionString = configuration.GetConnectionString("DefaultConnection");
Please follow below steps :
1.Open Your project.
2.Go to the Left side of the Gradle button.
3.Look at below image.
4.Click button above image show.
5.if this type of view you are not in offline mode.
6.Go to Build and rebuild the project.
All above point is work for me.
For the benefit of others, I though I'd include what I did.
Since you cannot get Visual Studio (2010 in my case) to ignore the LNK4204 warnings, my approach was to give it what it wanted: the pdb files. As I was using open source libraries in my case, I have the code building the pdb files already.
BUT, the default is to name all of the PDF files the same thing: vc100.pdb in my case. As you need a .pdb for each and every .lib, this creates a problem, especially if you are using something like ImageMagik, which creates about 20 static .lib files. You cannot have 20 lib files in one directory (which your application's linker references to link in the libraries from) and have all the 20 .pdb files called the same thing.
My solution was to go and rebuild my static library files, and configure VS2010 to name the .pdb file with respect to the PROJECT. This way, each .lib gets a similarly named .pdb, and you can put all of the LIBs and PDBs in one directory for your project to use.
So for the "Debug" configuraton, I edited:
Properties->Configuration Properties -> C/C++ -> Output Files -> Program Database File Name from
$(IntDir)vc$(PlatformToolsetVersion).pdb
to be the following value:
$(OutDir)vc$(PlatformToolsetVersion)D$(ProjectName).pdb
Now rather than somewhere in the intermediate directory, the .pdb files are written to the output directory, where the .lib files are also being written, AND most importantly, they are named with a suffix of D+project name. This means each library project produduces a project .lib and a project specific .pdb.
I'm now able to copy all of my release .lib files, my debug .lib files and the debug .pdb files into one place on my development system, and the project that uses that 3rd party library in debug mode, has the pdb files it needs in debug mode.
try like this
= IIF( MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ) ) = -1, "", FormatNumber( MAX( iif( IsNothing(Fields!.Reading.Value ), -1, Fields!.Reading.Value ), "CellReading_Reading"),3)) )
Here is an example:
MySqlConnection con = new MySqlConnection(
"Server=ServerName;Database=DataBaseName;UID=username;Password=password");
MySqlCommand cmd = new MySqlCommand(
" INSERT Into Test (lat, long) VALUES ('"+OSGconv.deciLat+"','"+
OSGconv.deciLon+"')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
In Internet Explorer 9 (and 8), the console
object is only exposed when the developer tools are opened for a particular tab. If you hide the developer tools window for that tab, the console
object remains exposed for each page you navigate to. If you open a new tab, you must also open the developer tools for that tab in order for the console
object to be exposed.
The console
object is not part of any standard and is an extension to the Document Object Model. Like other DOM objects, it is considered a host object and is not required to inherit from Object
, nor its methods from Function
, like native ECMAScript functions and objects do. This is the reason apply
and call
are undefined on those methods. In IE 9, most DOM objects were improved to inherit from native ECMAScript types. As the developer tools are considered an extension to IE (albeit, a built-in extension), they clearly didn't receive the same improvements as the rest of the DOM.
For what it's worth, you can still use some Function.prototype
methods on console
methods with a little bind()
magic:
var log = Function.prototype.bind.call(console.log, console);
log.apply(console, ["this", "is", "a", "test"]);
//-> "thisisatest"
i remember this from reading some articles about performance in unity from internet which awaring javascript users from using it in unity about really massive issues of using javascript in unity instead of C#, it says that C# is almost 4x faster than javascript!
i really appreciate that article b/c it saved my ass when i was about to start gaming, i dont mean that javascript it bad for unity developers , it is good but my advice could be that if you like using javascript, you should use it for simple small gamesNOT FOR BIG PROJECTS because it really can be a damn problem!
From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.
This is an old post, but given the title of this question, the END option should be described in more detail. This can be used to stop ALL PROCEDURES (not just the subroutine running). It can also be used within a function to stop other Subroutines (which I find useful for some add-ins I work with).
Terminates execution immediately. Never required by itself but may be placed anywhere in a procedure to end code execution, close files opened with the Open statement, and to clear variables*. I noticed that the END method is not described in much detail. This can be used to stop ALL PROCEDURES (not just the subroutine running).
Here is an illustrative example:
Sub RunSomeMacros()
Call FirstPart
Call SecondPart
'the below code will not be executed if user clicks yes during SecondPart.
Call ThirdPart
MsgBox "All of the macros have been run."
End Sub
Private Sub FirstPart()
MsgBox "This is the first macro"
End Sub
Private Sub SecondPart()
Dim answer As Long
answer = MsgBox("Do you want to stop the macros?", vbYesNo)
If answer = vbYes Then
'Stops All macros!
End
End If
MsgBox "You clicked ""NO"" so the macros are still rolling..."
End Sub
Private Sub ThirdPart()
MsgBox "Final Macro was run."
End Sub
This has to be dependent on what phase of your application development lifecycle you are in.
If you've been at development for a while and have a lot of implemented code already and are just now realizing that you need to think about code coverage then you have to check your current coverage (if it exists) and then use that baseline to set milestones each sprint (or an average rise over a period of sprints), which means taking on code debt while continuing to deliver end user value (at least in my experience the end user doesn't care one bit if you've increased test coverage if they don't see new features).
Depending on your domain it's not unreasonable to shoot for 95%, but I'd have to say on average your going to be looking at an average case of 85% to 90%.
In a navigation based application you can change color
NSArray *ver = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
if ([[ver objectAtIndex:0] intValue] >= 7) {
self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:19.0/255.0 green:86.0/255.0 blue:138.0/255.0 alpha:1];
self.navigationController.navigationBar.translucent = NO;
} else {
self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:19.0/255.0 green:86.0/255.0 blue:138.0/255.0 alpha:1];
}
You can use the dplyr
package to easily remove those particular rows.
library(dplyr)
df <- filter(df, C != "Foo")
In this model, you have publishers who will do some logic and publish an "event."
Publishers will then send out their event only to subscribers who have subscribed to receive the specific event.
In C#, any object can publish a set of events to which other applications can subscribe.
When the publishing class raises an event, all the subscribed applications are notified.
The following figure shows this mechanism.
Simplest Example possible on Events and Delegates in C#:
code is self explanatory, Also I've added the comments to clear out the code.
using System;
public class Publisher //main publisher class which will invoke methods of all subscriber classes
{
public delegate void TickHandler(Publisher m, EventArgs e); //declaring a delegate
public TickHandler Tick; //creating an object of delegate
public EventArgs e = null; //set 2nd paramter empty
public void Start() //starting point of thread
{
while (true)
{
System.Threading.Thread.Sleep(300);
if (Tick != null) //check if delegate object points to any listener classes method
{
Tick(this, e); //if it points i.e. not null then invoke that method!
}
}
}
}
public class Subscriber1 //1st subscriber class
{
public void Subscribe(Publisher m) //get the object of pubisher class
{
m.Tick += HeardIt; //attach listener class method to publisher class delegate object
}
private void HeardIt(Publisher m, EventArgs e) //subscriber class method
{
System.Console.WriteLine("Heard It by Listener");
}
}
public class Subscriber2 //2nd subscriber class
{
public void Subscribe2(Publisher m) //get the object of pubisher class
{
m.Tick += HeardIt; //attach listener class method to publisher class delegate object
}
private void HeardIt(Publisher m, EventArgs e) //subscriber class method
{
System.Console.WriteLine("Heard It by Listener2");
}
}
class Test
{
static void Main()
{
Publisher m = new Publisher(); //create an object of publisher class which will later be passed on subscriber classes
Subscriber1 l = new Subscriber1(); //create object of 1st subscriber class
Subscriber2 l2 = new Subscriber2(); //create object of 2nd subscriber class
l.Subscribe(m); //we pass object of publisher class to access delegate of publisher class
l2.Subscribe2(m); //we pass object of publisher class to access delegate of publisher class
m.Start(); //starting point of publisher class
}
}
Output:
Heard It by Listener
Heard It by Listener2
Heard It by Listener
Heard It by Listener2
Heard It by Listener . . . (infinite times)
The best way to check for a null values is
if ( testVar !== null )
{
// do action here
}
and for undefined
if ( testVar !== undefined )
{
// do action here
}
You can assign a avariable with undefined.
testVar = undefined;
//typeof(testVar) will be equal to undefined.
I think you want Any
:
if (myList.Any(str => str.Contains("Mdd LH")))
It's well worth becoming familiar with the LINQ standard query operators; I would usually use those rather than implementation-specific methods (such as List<T>.ConvertAll
) unless I was really bothered by the performance of a specific operator. (The implementation-specific methods can sometimes be more efficient by knowing the size of the result etc.)
From ggplot2 2.0.0
you can use the margin =
argument of element_text()
to change the distance between the axis title and the numbers. Set the values of the margin
on t
op, r
ight, b
ottom, and l
eft side of the element.
ggplot(mpg, aes(cty, hwy)) + geom_point()+
theme(axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)))
margin
can also be used for other element_text
elements (see ?theme
), such as axis.text.x
, axis.text.y
and title
.
addition
in order to set the margin for axis titles when the axis has a different position (e.g., with scale_x_...(position = "top")
, you'll need a different theme setting - e.g. axis.title.x.top
. See https://github.com/tidyverse/ggplot2/issues/4343.
Diffuse is my favourite but of course I am biased. :-) It is very easy to use:
$ diffuse "mine" "output" "theirs"
Diffuse is a small and simple text merge tool written in Python. With Diffuse, you can easily merge, edit, and review changes to your code. Diffuse is free software.
Use JSON.stringify()
and JSON.parse()
as suggested by no! This prevents the maybe rare but possible problem of a member name which includes the delimiter (e.g. member name three|||bars
).
Primary key does not allow NULL
values, but unique key allows NULL
values.
We can declare only one primary key in a table, but a table can have multiple unique keys (column assign).
You should be able to parse the SQL file into statements. And run a single statement a time. If you know that your file consists of simple insert/update/delete statements you can use a semicolon as statement delimiter. In common case you have a task to create your specific SQL-dialect parser.
Try
echo -en "`date` User `whoami` started the script.\n" >> output.log
Try issuing this multiple times. I hope you are looking for the same output.
Define your .table
and .cell
height:100%;
.table {
display: table;
height:100%;
}
.cell {
border: 1px solid black;
display: table-cell;
vertical-align:top;
height: 100%;
}
.container {
height: 100%;
border: 10px solid green;
}
Here is my dark theme (based on Darcula IntelliJ Theme):
https://github.com/mervick/Qt-Creator-Darcula
Are you sure you need a list in this case? If you are populating the list with many items, performance will suffer with myList.Contains
or myList.Any
; the run-time will be quadratic. You might want to consider using a better data structure. For example,
public class MyClass
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
public class MyClassComparer : EqualityComparer<MyClass>
{
public override bool Equals(MyClass x, MyClass y)
{
if(x == null || y == null)
return x == y;
return x.Property1 == y.Property1 && x.Property2 == y.Property2;
}
public override int GetHashCode(MyClass obj)
{
return obj == null ? 0 : (obj.Property1.GetHashCode() ^ obj.Property2.GetHashCode());
}
}
You could use a HashSet in the following manner:
var set = new HashSet<MyClass>(new MyClassComparer());
foreach(var myClass in ...)
set.Add(myClass);
Of course, if this definition of equality for MyClass
is 'universal', you needn't write an IEqualityComparer
implementation; you could just override GetHashCode
and Equals
in the class itself.
Use string interpolation decimalVar:0.00
To count:
SELECT COUNT(*) as total FROM (SELECT TABLE_NAME as tab, TABLES.* FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='database_name' GROUP BY tab) tables;
To list:
SELECT TABLE_NAME as table, TABLES.* FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='database_name' GROUP BY table;
I always like to write my own "custom enum". Than I have one class that is a little bit more complex, but I can reuse it:
public abstract class CustomEnum
{
private readonly string _name;
private readonly object _id;
protected CustomEnum( string name, object id )
{
_name = name;
_id = id;
}
public string Name
{
get { return _name; }
}
public object Id
{
get { return _id; }
}
public override string ToString()
{
return _name;
}
}
public abstract class CustomEnum<TEnumType, TIdType> : CustomEnum
where TEnumType : CustomEnum<TEnumType, TIdType>
{
protected CustomEnum( string name, TIdType id )
: base( name, id )
{ }
public new TIdType Id
{
get { return (TIdType)base.Id; }
}
public static TEnumType FromName( string name )
{
try
{
return FromDelegate( entry => entry.Name.Equals( name ) );
}
catch (ArgumentException ae)
{
throw new ArgumentException( "Illegal name for custom enum '" + typeof( TEnumType ).Name + "'", ae );
}
}
public static TEnumType FromId( TIdType id )
{
try
{
return FromDelegate( entry => entry.Id.Equals( id ) );
}
catch (ArgumentException ae)
{
throw new ArgumentException( "Illegal id for custom enum '" + typeof( TEnumType ).Name + "'", ae );
}
}
public static IEnumerable<TEnumType> GetAll()
{
var elements = new Collection<TEnumType>();
var infoArray = typeof( TEnumType ).GetFields( BindingFlags.Public | BindingFlags.Static );
foreach (var info in infoArray)
{
var type = info.GetValue( null ) as TEnumType;
elements.Add( type );
}
return elements;
}
protected static TEnumType FromDelegate( Predicate<TEnumType> predicate )
{
if(predicate == null)
throw new ArgumentNullException( "predicate" );
foreach (var entry in GetAll())
{
if (predicate( entry ))
return entry;
}
throw new ArgumentException( "Element not found while using predicate" );
}
}
Now I just need to create my enum I want to use:
public sealed class SampleEnum : CustomEnum<SampleEnum, int>
{
public static readonly SampleEnum Element1 = new SampleEnum( "Element1", 1, "foo" );
public static readonly SampleEnum Element2 = new SampleEnum( "Element2", 2, "bar" );
private SampleEnum( string name, int id, string additionalText )
: base( name, id )
{
AdditionalText = additionalText;
}
public string AdditionalText { get; private set; }
}
At last I can use it like I want:
static void Main( string[] args )
{
foreach (var element in SampleEnum.GetAll())
{
Console.WriteLine( "{0}: {1}", element, element.AdditionalText );
Console.WriteLine( "Is 'Element2': {0}", element == SampleEnum.Element2 );
Console.WriteLine();
}
Console.ReadKey();
}
And my output would be:
Element1: foo
Is 'Element2': False
Element2: bar
Is 'Element2': True
if you are running from inside eclipse with wtp, you should be able to change the port from the "servers" view (window -> show view -> servers)
A great search engine for special characters that I recenetly found: amp-what?
You can even search by object name, like "arrow", "chess", etc...
I know i'm late to answer this, but i hope it is of some help to anybody who have similar problem. It also works when page refreshes for any reason.
$(document).ready(function(){
if ($(window).width() < 960 && $(window).load()) {
$("#up").hide();
}
if($(window).load()){
if ($(window).width() < 960) {
$("#up").hide();
}
}
$(window).resize(function() {
if ($(window).width() < 960 && $(window).load()) {
$("#up").hide();
}
else{
$("#up").show();
}
if($(window).load()){
if ($(window).width() < 960) {
$("#up").hide();
}
}
else{
$("#up").show();
}
});});
Use crosstab()
from the tablefunc module.
SELECT * FROM crosstab(
$$SELECT user_id, user_name, rn, email_address
FROM (
SELECT u.user_id, u.user_name, e.email_address
, row_number() OVER (PARTITION BY u.user_id
ORDER BY e.creation_date DESC NULLS LAST) AS rn
FROM usr u
LEFT JOIN email_tbl e USING (user_id)
) sub
WHERE rn < 4
ORDER BY user_id
$$
, 'VALUES (1),(2),(3)'
) AS t (user_id int, user_name text, email1 text, email2 text, email3 text);
I used dollar-quoting for the first parameter, which has no special meaning. It's just convenient if you have to escape single quotes in the query string which is a common case:
Detailed explanation and instructions here:
And in particular, for "extra columns":
The special difficulties here are:
The lack of key names.
-> We substitute with row_number()
in a subquery.
The varying number of emails.
-> We limit to a max. of three in the outer SELECT
and use crosstab()
with two parameters, providing a list of possible keys.
Pay attention to NULLS LAST
in the ORDER BY
.
JavaScript has a RegExp
object which does what you want. The String
object has a match()
function that will help you out.
var matches = text.match(/price\[(\d+)\]\[(\d+)\]/);
var productId = matches[1];
var shopId = matches[2];
Only integral values (e.g., static const int ARRAYSIZE
) are initialized in header file because they are usually used in class header to define something such as the size of an array. Non-integral values are initialized in implementation file.
Yes since there are 2 distinct Global Assembly Cache (GAC), you will have to manage each of them individually.
In .NET Framework 4.0, the GAC went through a few changes. The GAC was split into two, one for each CLR.
The CLR version used for both .NET Framework 2.0 and .NET Framework 3.5 is CLR 2.0. There was no need in the previous two framework releases to split GAC. The problem of breaking older applications in Net Framework 4.0.
To avoid issues between CLR 2.0 and CLR 4.0 , the GAC is now split into private GAC’s for each runtime.The main change is that CLR v2.0 applications now cannot see CLR v4.0 assemblies in the GAC.
Why?
It seems to be because there was a CLR change in .NET 4.0 but not in 2.0 to 3.5. The same thing happened with 1.1 to 2.0 CLR. It seems that the GAC has the ability to store different versions of assemblies as long as they are from the same CLR. They do not want to break old applications.
See the following information in MSDN about the GAC changes in 4.0.
For example, if both .NET 1.1 and .NET 2.0 shared the same GAC, then a .NET 1.1 application, loading an assembly from this shared GAC, could get .NET 2.0 assemblies, thereby breaking the .NET 1.1 application
The CLR version used for both .NET Framework 2.0 and .NET Framework 3.5 is CLR 2.0. As a result of this, there was no need in the previous two framework releases to split the GAC. The problem of breaking older (in this case, .NET 2.0) applications resurfaces in Net Framework 4.0 at which point CLR 4.0 released. Hence, to avoid interference issues between CLR 2.0 and CLR 4.0, the GAC is now split into private GACs for each runtime.
As the CLR is updated in future versions you can expect the same thing. If only the language changes then you can use the same GAC.
Use git reset HEAD
to reset the index without removing files. (If you only want to reset a particular file in the index, you can use git reset HEAD -- /path/to/file
to do so.)
The pipe operator, in a shell, takes the stdout
of the process on the left and passes it as stdin
to the process on the right. It's essentially the equivalent of:
$ proc1 > proc1.out
$ proc2 < proc1.out
$ rm proc1.out
but instead it's $ proc1 | proc2
, the second process can start getting data before the first is done outputting it, and there's no actual file involved.
I think you need to make the .holder
position:relative;
and .popup
position:absolute;
From your question I guess you are using Ubuntu (or a derivate). If you use:
apt-file search opencv.pc
then you see that you have to install libopencv-dev
.
After you do so, pkg-config --cflags opencv
and pkg-config --libs opencv
should work as expected.
An alias will expand to the string it represents. Anything after the alias will appear after its expansion without needing to be or able to be passed as explicit arguments (e.g. $1
).
$ alias foo='/path/to/bar'
$ foo some args
will get expanded to
$ /path/to/bar some args
If you want to use explicit arguments, you'll need to use a function
$ foo () { /path/to/bar "$@" fixed args; }
$ foo abc 123
will be executed as if you had done
$ /path/to/bar abc 123 fixed args
To undefine an alias:
unalias foo
To undefine a function:
unset -f foo
To see the type and definition (for each defined alias, keyword, function, builtin or executable file):
type -a foo
Or type only (for the highest precedence occurrence):
type -t foo
We can use enum type for this.We don't require a library. For example
enum {false,true};
the value for false
will be 0 and the value for true
will be 1.
Never faced this problem before (not worked much on email, I avoid it like the plague) but you could try declaring the bullet with the unicode code point (different notation for CSS than for HTML): content: '\2022'
. (you need to use the hex number, not the 8226 decimal one)
Then, in case you use something that picks up those characters and HTML-encodes them into entities (which won't work for CSS strings), I guess it will ignore that.
On server window Double click on tomcat, It will open the tomcat's Overview window .
In the Overview window you will find Open launch configuration under General information and click on Open launch configuration.
I'm looking at this and thinking, if you can only get variables into php in a form, why not just make a form and put a hidden input in the thing so it doesn't show on screen, and then put the value from your javascript into the hidden input and POST that into the php? It would sure be a lot less hassle than some of this other stuff right?
You can get a property by name using the Select-Object
cmdlet and specifying the property name(s) that you're interested in. Note that this doesn't simply return the raw value for that property; instead you get something that still behaves like an object.
[PS]> $property = (Get-Process)[0] | Select-Object -Property Name
[PS]> $property
Name
----
armsvc
[PS]> $property.GetType().FullName
System.Management.Automation.PSCustomObject
In order to use the value for that property, you will still need to identify which property you are after, even if there is only one property:
[PS]> $property.Name
armsvc
[PS]> $property -eq "armsvc"
False
[PS]> $property.Name -eq "armsvc"
True
[PS]> $property.Name.GetType().FullName
System.String
As per other answers here, if you want to use a single property within a string, you need to evaluate the expression (put brackets around it) and prefix with a dollar sign ($) to declare the expression dynamically as a variable to be inserted into the string:
[PS]> "The first process in the list is: $($property.Name)"
The first process in the list is: armsvc
Quite correctly, others have answered this question by recommending the -ExpandProperty
parameter for the Select-Object
cmdlet. This bypasses some of the headache by returning the value of the property specified, but you will want to use different approaches in different scenarios.
-ExpandProperty <String>
Specifies a property to select, and indicates that an attempt should be made to expand that property
[PS]> (Get-Process)[0] | Select-Object -ExpandProperty Name
armsvc
Had one of these as well, but the parameter of the action was an interface with no public properties. Ended up using It.Is() with a seperate method and within this method had to do some mocking of the interface
public interface IQuery
{
IQuery SetSomeFields(string info);
}
void DoSomeQuerying(Action<IQuery> queryThing);
mockedObject.Setup(m => m.DoSomeQuerying(It.Is<Action<IQuery>>(q => MyCheckingMethod(q)));
private bool MyCheckingMethod(Action<IQuery> queryAction)
{
var mockQuery = new Mock<IQuery>();
mockQuery.Setup(m => m.SetSomeFields(It.Is<string>(s => s.MeetsSomeCondition())
queryAction.Invoke(mockQuery.Object);
mockQuery.Verify(m => m.SetSomeFields(It.Is<string>(s => s.MeetsSomeCondition(), Times.Once)
return true
}
You can select elements with multiple classes like so:
$("element.firstClass.anotherClass");
Simply chain the next class onto the first one, without a space (spaces mean "children of").
New version - psql 12 - will support --csv
.
--csv
Switches to CSV (Comma-Separated Values) output mode. This is equivalent to \pset format csv.
csv_fieldsep
Specifies the field separator to be used in CSV output format. If the separator character appears in a field's value, that field is output within double quotes, following standard CSV rules. The default is a comma.
Usage:
psql -c "SELECT * FROM pg_catalog.pg_tables" --csv postgres
psql -c "SELECT * FROM pg_catalog.pg_tables" --csv -P csv_fieldsep='^' postgres
psql -c "SELECT * FROM pg_catalog.pg_tables" --csv postgres > output.csv
Maybe something like this:
SELECT count(*) FROM user_tab_columns WHERE table_name = 'FOO'
this will count number of columns in a the table FOO
You can also just
select count(*) from all_tab_columns where owner='BAR' and table_name='FOO';
where the owner is schema and note that Table Names are upper case
Change your gradle version or update it
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
alt+enter and choose "replace with specific version".
setenv.sh is better, because you can easily port such configuration from one machine to another, or from one Tomcat version to another. catalina.sh changes from one version of Tomcat to another. But you can keep your setenv.sh unchanged with any version of Tomcat.
Another advantage is, that it is easier to track the history of your changes if you add it to your backup or versioning system. If you look how you setenv.sh changes along the history, you will see only your own changes. Whereas if you use catalina.sh, you will always see not only your changes, but also changes that came with each newer version of the Tomcat.
http://api.football-data.org/index is free and useful. The API is in active development, stable and recently the first versioned release called alpha was put online. Check the blog section to follow updates and changes.
i'm a huge fan of making an image the background of a div/node -- then you can just use the background-position: center
attribute to center it regardless of screen size
use FileInputStream's readLine() method to read and parse the returned String to int using Integer.parseInt() method.
Very easy trick is using a CSS calc
formula. All modern browsers, IE9, wide range of mobile browsers should support this.
<div style='white-space:nowrap'>
<span style='display:inline-block;width:80px;font-weight:bold'>
<label for='field1'>Field1</label>
</span>
<input id='field1' name='field1' type='text' value='Some text' size='30' style='width:calc(100% - 80px)' />
</div>
Use the -s
option BEFORE the command to specify the device, for example:
adb -s 7f1c864e shell
See also http://developer.android.com/tools/help/adb.html#directingcommands
for VS2008 with feature pack update, shared_ptr can be found under namespace std::tr1.
std::tr1::shared_ptr<int> MyIntSmartPtr = new int;
of
if you had boost installation path (for example @ C:\Program Files\Boost\boost_1_40_0
) added to your IDE settings:
#include <boost/shared_ptr.hpp>
<div class="tabbable">
<ul class="nav nav-tabs">
<li class="active"><a href="#aaa" data-toggle="tab">AAA</a></li>
<li><a href="#bbb" data-toggle="tab">BBB</a></li>
<li><a href="#ccc" data-toggle="tab">CCC</a></li>
</ul>
<div class="tab-content" id="tabs">
<div class="tab-pane fade active in" id="aaa">...Content...</div>
<div class="tab-pane" id="bbb">...Content...</div>
<div class="tab-pane" id="ccc">...Content...</div>
</div>
</div>
Add active class to any li element you want to be active after page load. And also adding active class to content div is needed ,fade in classes are useful for a smooth transition.
npm start --prefix path/to/your/app
& inside package.json add the following script
"scripts": {
"preinstall":"cd $(pwd)"
}
NOT SUPPORTED BY IE
More info here: Can I Use?
.container {_x000D_
overflow: hidden;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
.container img {_x000D_
object-fit: cover;_x000D_
width: 100%;_x000D_
min-height: 100%;_x000D_
}
_x000D_
<div class='container'>_x000D_
<img src='http://i.imgur.com/H9lpVkZ.jpg' />_x000D_
</div>
_x000D_
To expand on the above and make a quick reference:
ALTER USER username WITH SUPERUSER;
ALTER USER username WITH NOSUPERUSER;
ALTER USER username CREATEDB;
You can also use CREATEROLE
and CREATEUSER
to allow a user privileges without making them a superuser.
I would like to add to the answer provided by Sangam Belose. Here's his code:
select ('id') as id, ('time') as time, ('unit') as unit
UNION ALL
SELECT * INTO OUTFILE 'C:/Users/User/Downloads/data.csv'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM sensor
However, if you have not set up your "secure_file_priv"
within the variables, it may not work. For that, check the folder set on that variable by:
SHOW VARIABLES LIKE "secure_file_priv"
The output should look like this:
mysql> show variables like "%secure_file_priv%";
+------------------+------------------------------------------------+
| Variable_name | Value |
+------------------+------------------------------------------------+
| secure_file_priv | C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\ |
+------------------+------------------------------------------------+
1 row in set, 1 warning (0.00 sec)
You can either change this variable or change the query to output the file to the default path showing.
An alternative approach would be:
df1 = sqlContext.createDataFrame(
[(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
("x1", "x2", "x3"))
df2 = sqlContext.createDataFrame(
[(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x4"))
df = df1.join(df2, ['x1','x2'])
df.show()
which outputs:
+---+---+---+---+
| x1| x2| x3| x4|
+---+---+---+---+
| 2| b|3.0|0.0|
+---+---+---+---+
With the main advantage being that the columns on which the tables are joined are not duplicated in the output, reducing the risk of encountering errors such as org.apache.spark.sql.AnalysisException: Reference 'x1' is ambiguous, could be: x1#50L, x1#57L.
Whenever the columns in the two tables have different names, (let's say in the example above, df2
has the columns y1
, y2
and y4
), you could use the following syntax:
df = df1.join(df2.withColumnRenamed('y1','x1').withColumnRenamed('y2','x2'), ['x1','x2'])
You could just use a for loop and there is no need to add an extra if
inside the for
body:
for (int i = 0; i < Model.Results.Count - 1; i++) {
var item = Model.Results[i];
}
The -1
in the for
condition takes care of skipping the last item.
The first thing you should check for is the file permission of /etc/ssl
and /etc/ssl/certs
.
I made the mistake of dropping file permissions (or blowing away the SSL rm -rf /etc/ssl/*
directories) when using ssl-cert
group name/ID while working on my Certificate Authority Management Tool.
It was then that I noticed the exact same error message for wget
and curl
CLI browser tools:
server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none
Once I brought the /etc/ssl
and /etc/ssl/cert
directories' file permission up to o+rx-w
, those CLI browser tools started to breath a bit easier:
mkdir -p /etc/ssl/certs
chmod u+rwx,go+rx /etc/ssl /etc/ssl/certs
I also had to recreate Java subdirectory and reconstruct the Trusted CA certificate directories:
mkdir /etc/ssl/certs/java
chmod u+rwx,go+rx /etc/ssl/certs/java
update-ca-certificates
and the coast was clear.
Idle Timeout is if no action has been asked from your web app, it the process will drop and release everything from memory
Recycle is a forced action on the application where your processed is closed and started again, for memory leaking purposes and system health
The negative impact of both is usually the use of your Session and Application state is lost if you mess with Recycle to a faster time.(logged in users etc will be logged out, if they where about to "check out" all would have been lost" that's why recycle is at such a large time out value, idle timeout doesn't matter because nobody is logged in anyway and figure 20 minutes an no action they are not still "shopping"
The positive would be get rid of the idle time out as your website will respond faster on its "first" response if its not a highly active site where a user would have to wait for it to load if you have 1 user every 20 minutes lets say. So a website that get his less then 1 time in 20 minutes actually you would want to increase this value as the website has to load up again from scratch for each user. but if you set this to 0 over a long time, any memory leaks in code could over a certain amount of time, entirely take over the server.
Compiler shows following error :
Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: 'Storyboard (<UIStoryboard: 0x7fedf2d5c9a0>) doesn't contain a
ViewController with identifier 'SBAddEmployeeVC''
Here the object of the storyboard created is not the main storyboard which contains our ViewControllers. As storyboard file on which we work is named as Main.storyboard. So we need to have reference of object of the Main.storyboard.
Use following code for that :
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
Here storyboardWithName
is the name of the storyboard file we are working with and bundle
specifies the bundle in which our storyboard is (i.e. mainBundle
).
nginx
log format taken from here: http://nginx.org/en/docs/http/ngx_http_log_module.html
no need to install anything extra
worked for me for GET
and POST
requests:
upstream my_upstream {
server upstream_ip:upstream_port;
}
location / {
log_format postdata '$remote_addr - $remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" "$request_body"';
access_log /path/to/nginx_access.log postdata;
proxy_set_header Host $http_host;
proxy_pass http://my_upstream;
}
}
just change upstream_ip
and upstream_port
memset(array, 0, sizeof(int [n][n]));
Basically this happens when you have not installed pre required software installed on your machine while installing Wampserver you might have got error bellow error at the time of installation.
program can't start because msvcr120.dll is missing OR
program can't start because msvcr120.dll is missing
If you fixed those issue after the installation of wampserver then you might get stuck at this problem.
Then You can simply uninstall and install wamp server again
And If you have not install pre required dependency then first of all uninstall wampserver . And then install pre requirement first and then finally you can install Wampserver and it should work now.
you can download Pre-required applications from following link
For x64 Machines
microsoft visual c++ 2010 redistributable package (x64) https://www.microsoft.com/en-in/download/details.aspx?id=14632
Visual C++ Redistributable for Visual Studio 2012 Update 4 https://www.microsoft.com/en-in/download/details.aspx?id=30679
Visual C++ Redistributable Packages for Visual Studio 2013 https://www.microsoft.com/en-in/download/details.aspx?id=40784
Visual C++ Redistributable for Visual Studio 2015 https://www.microsoft.com/en-in/download/details.aspx?id=48145
For x86 Machines
Microsoft Visual C++ 2010 Redistributable Package (x86) https://www.microsoft.com/en-in/download/details.aspx?id=14632
Visual C++ Redistributable for Visual Studio 2012 Update 4 https://www.microsoft.com/en-in/download/details.aspx?id=30679
Visual C++ Redistributable Packages for Visual Studio 2013 https://www.microsoft.com/en-in/download/details.aspx?id=40784
Visual C++ Redistributable for Visual Studio 2015 https://www.microsoft.com/en-in/download/details.aspx?id=48145
Note:- Take backup of your project files before uninstall
Be sure your DOCKERfile
is in the ROOT of the application directory, I had mine in src which resulted in this error because Docker was not finding the path to DOCKERfile
This would also happen when you are trying to restore a newer version backup in a older SQL database. For example when you try to restore a DB backup that is created in 2012 with 110 compatibility and you are trying to restore it in 2008 R2.
An extern
variable is a declaration (thanks to sbi for the correction) of a variable which is defined in another translation unit. That means the storage for the variable is allocated in another file.
Say you have two .c
-files test1.c
and test2.c
. If you define a global variable int test1_var;
in test1.c
and you'd like to access this variable in test2.c
you have to use extern int test1_var;
in test2.c
.
Complete sample:
$ cat test1.c
int test1_var = 5;
$ cat test2.c
#include <stdio.h>
extern int test1_var;
int main(void) {
printf("test1_var = %d\n", test1_var);
return 0;
}
$ gcc test1.c test2.c -o test
$ ./test
test1_var = 5
No, cp
can copy multiple sources but will only copy to a single destination. You need to arrange to invoke cp
multiple times - once per destination - for what you want to do; using, as you say, a loop or some other tool.
This question is confusing. A regular object, {}
doesn't have a length
property unless you're intending to make your own function constructor which generates custom objects which do have it ( in which case you didn't specify ).
Meaning, you have to get the "length" by a for..in
statement on the object, since length
is not set, and increment a counter.
I'm confused as to why you need the length
. Are you manually setting 0
on the object, or are you relying on custom string keys? eg obj['foo'] = 'bar';
. If the latter, again, why the need for length?
Edit #1: Why can't you just do this?
list = [ {name:'john'}, {name:'bob'} ];
Then iterate over list? The length
is already set.
Here is how you can read the entire file contents, and if done successfully, start a webserver which displays the JPG image in response to every request:
var http = require('http')
var fs = require('fs')
fs.readFile('image.jpg', function(err, data) {
if (err) throw err // Fail if the file can't be read.
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'image/jpeg'})
res.end(data) // Send the file data to the browser.
}).listen(8124)
console.log('Server running at http://localhost:8124/')
})
Note that the server is launched by the "readFile" callback function and the response header has Content-Type: image/jpeg
.
[Edit] You could even embed the image in an HTML page directly by using an <img>
with a data URI source. For example:
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<html><body><img src="data:image/jpeg;base64,')
res.write(Buffer.from(data).toString('base64'));
res.end('"/></body></html>');
This depend on how you want to incorporate it. The scenario 1. click on a link 2. explorer window popped up
<a href="\\server\folder\path" target="_blank">click</a>
If there is a need in a fancy UI - then it will barely serve as a solution.
I've never used Lua before, but I Googled it and came up with this:
Check question 1.26.
This is a common complaint. The Lua authors felt that continue was only one of a number of possible new control flow mechanisms (the fact that it cannot work with the scope rules of repeat/until was a secondary factor.)
In Lua 5.2, there is a goto statement which can be easily used to do the same job.
There are two ways to escaping the single quote in JavaScript.
1- Use double-quote or backticks to enclose the string.
Example: "fsdsd'4565sd" or `fsdsd'4565sd`.
2- Use backslash before any special character, In our case is the single quote
Example:strInputString = strInputString.replace(/ ' /g, " \\' ");
Note: use a double backslash.
Both methods work for me.
My problem was that I had spaces in between the options on 5.7.20. Removing them so the line looked like
[mysqld]
sql-mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
If your application is already using Spring framework, you have Scheduling built in
CFAbsoluteTimeGetCurrent()
returns the absolute time as a double
value, but I don't know what its precision is -- it might only update every dozen milliseconds, or it might update every microsecond, I don't know.
If you need bracket dates to be dynamic ..
$todayStr = date('Y-m-d');
$todayObj=date('Y-m-d', strtotime($todayStr));
$currentYrStr = date('Y');
$DateBegin = date('Y-m-d', strtotime("06/01/$currentYrStr"));
$DateEnd = date('Y-m-d', strtotime("10/01/$currentYrStr"));
if (($todayObj > $contractDateBegin) && ($paymentDate < $contractDateEnd)){
$period="summer";
}else{
$period="winter";
}
Design patterns are just tools--kind of like library functions. If you know that they are there and their approximate function, you can go dig them out of a book when needed.
There is nothing magic about design patterns, and any good programmer figured 90% of them out for themselves before any books came out. For the most part I consider the books to be most useful at simply defining names for the various patterns so we can discuss them more easily.
My preferences is to use
try
{
}
catch (Exception ex)
{
...
throw new Exception ("Put more context here", ex)
}
This preserves the original error, but allows you to put more context, such as an object ID, a connection string, stuff like that. Often my exception reporting tool will have 5 chained exceptions to report, each reporting more detail.
Your second way is correct.
def foo(opts: dict = {}):
pass
print(foo.__annotations__)
this outputs
{'opts': <class 'dict'>}
It's true that's it's not listed in PEP 484, but type hints are an application of function annotations, which are documented in PEP 3107. The syntax section makes it clear that keyword arguments works with function annotations in this way.
I strongly advise against using mutable keyword arguments. More information here.
Because by default jQuery serializes objects passed as the data
parameter to $.ajax
. It uses $.param
to convert the data to a query string.
From the jQuery docs for $.ajax
:
[the
data
argument] is converted to a query string, if not already a string
If you want to send JSON, you'll have to encode it yourself:
data: JSON.stringify(arr);
Note that JSON.stringify
is only present in modern browsers. For legacy support, look into json2.js
If you want to return more than 1 value use this:
DECLARE @sqlstatement2 NVARCHAR(MAX);
DECLARE @retText NVARCHAR(MAX);
DECLARE @ParmDefinition NVARCHAR(MAX);
DECLARE @retIndex INT = 0;
SELECT @sqlstatement = 'SELECT @retIndexOUT=column1 @retTextOUT=column2 FROM XXX WHERE bla bla';
SET @ParmDefinition = N'@retIndexOUT INT OUTPUT, @retTextOUT NVARCHAR(MAX) OUTPUT';
exec sp_executesql @sqlstatement, @ParmDefinition, @retIndexOUT=@retIndex OUTPUT, @retTextOUT=@retText OUTPUT;
returned values are in @retIndex and @retText
Try this (using default keyword)
bool foo = default(bool); if (foo) { }
I'm using the following method based on @Watki02's answer:
That way you can keep your visual studio instance as your own user whilst debugging from the other.
This is purely because I had to spend time making/editing this when it should be widely available, so I'm providing it to everyone else.
The below script will Output a couple of CSV files to TEMP with the versions and vulnerability status of each machine in a selected (in the code) OU. You'll be able to remotely "security audit" an OU of machines.
Powershell 7.0 needed for the connection test line RSAT needed to get the AD module Visual Studio Code needed to get powershell 7.0 (on win7)
By the time you read this, the version list will probably be out of date within the file. Use this website https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/versions-and-dependencies to add newer dotnet entries. It's just a bunch of key values in "DotNet4Builds"
If within CompromisedCheck.csv a machine shows as =0, it's had it's security turned off manually, and you should raise whether the supplier did it, or a suspect employee.
I hope this helps someone searching for it for their business.
<#
Script Name : Get-DotNetVersions_Tweaked.ps1
Description : This script reports the various .NET Framework versions installed on the local or a remote set of computers
Author : Original by Martin Schvartzman - Edited by Mark Purnell
Reference : https://msdn.microsoft.com/en-us/library/hh925568
#>
$ErrorActionPreference = "Continue”
import-module ActiveDirectory
$searchOU = "OU=OU LEVEL 1,OU=OU LEVEL 2,OU=MACHINES,OU=OUR LAPTOPS,DC=PUT,DC=MY,DC=DOMAIN,DC=CONTROLLER,DC=HERE,DC=OK"
$computerList = Get-ADComputer -searchbase $searchOU -Filter *
function Get-DotNetFrameworkVersion($computerList)
{
$dotNetter = @()
$compromisedCheck = @()
$dotNetRoot = 'SOFTWARE\Microsoft\.NETFramework'
$dotNetRegistry = 'SOFTWARE\Microsoft\NET Framework Setup\NDP'
$dotNet4Registry = 'SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full'
$dotNet4Builds = @{
'30319' = @{ Version = [System.Version]'4.0' }
'378389' = @{ Version = [System.Version]'4.5' }
'378675' = @{ Version = [System.Version]'4.5.1' ; Comment = '(8.1/2012R2)' }
'378758' = @{ Version = [System.Version]'4.5.1' ; Comment = '(8/7 SP1/Vista SP2)' }
'379893' = @{ Version = [System.Version]'4.5.2' }
'380042' = @{ Version = [System.Version]'4.5' ; Comment = 'and later with KB3168275 rollup' }
'393295' = @{ Version = [System.Version]'4.6' ; Comment = '(Windows 10)' }
'393297' = @{ Version = [System.Version]'4.6' ; Comment = '(NON Windows 10)' }
'394254' = @{ Version = [System.Version]'4.6.1' ; Comment = '(Windows 10)' }
'394271' = @{ Version = [System.Version]'4.6.1' ; Comment = '(NON Windows 10)' }
'394802' = @{ Version = [System.Version]'4.6.2' ; Comment = '(Windows 10 Anniversary Update)' }
'394806' = @{ Version = [System.Version]'4.6.2' ; Comment = '(NON Windows 10)' }
'460798' = @{ Version = [System.Version]'4.7' ; Comment = '(Windows 10 Creators Update)' }
'460805' = @{ Version = [System.Version]'4.7' ; Comment = '(NON Windows 10)' }
'461308' = @{ Version = [System.Version]'4.7.1' ; Comment = '(Windows 10 Fall Creators Update)' }
'461310' = @{ Version = [System.Version]'4.7.1' ; Comment = '(NON Windows 10)' }
'461808' = @{ Version = [System.Version]'4.7.2' ; Comment = '(Windows 10 April & Winserver)' }
'461814' = @{ Version = [System.Version]'4.7.2' ; Comment = '(NON Windows 10)' }
'528040' = @{ Version = [System.Version]'4.8' ; Comment = '(Windows 10 May 2019 Update)' }
'528049' = @{ Version = [System.Version]'4.8' ; Comment = '(NON Windows 10)' }
}
foreach($computerObject in $computerList)
{
$computerName = $computerObject.DNSHostName
write-host("PCName is " + $computerName)
if(test-connection -TargetName $computerName -Quiet -TimeOutSeconds 1 -count 2){
if($regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $computerName))
{
$os = (Get-WMIObject win32_operatingsystem -ComputerName SPL305350).Name
if(!$?){
write-host("wim not available")
$dotNetter += New-Object -TypeName PSObject -Property @{
'ComputerName' = $computerName
'OS' = "WIM not available"
'Build' = "WIM not available"
'Version' = "WIM not available"
'Comment' = "WIM not available"
}
}
else{
if ($netRegKey = $regKey.OpenSubKey("$dotNetRegistry"))
{
foreach ($versionKeyName in $netRegKey.GetSubKeyNames())
{
if ($versionKeyName -match '^v[123]') {
$versionKey = $netRegKey.OpenSubKey($versionKeyName)
$version = [System.Version]($versionKey.GetValue('Version', ''))
write-host("adding old dotnet")
$dotNetter += New-Object -TypeName PSObject -Property @{
ComputerName = $computerName
OS = $os
Build = $version.Build
Version = $version
Comment = ''
}
}
}
}
if ($net4RegKey = $regKey.OpenSubKey("$dotNet4Registry"))
{
if(-not ($net4Release = $net4RegKey.GetValue('Release')))
{
$net4Release = 30319
}
write-host("adding new dotnet")
$dotNetter += New-Object -TypeName PSObject -Property @{
'ComputerName' = $computerName
'OS' = $os
'Build' = $net4Release
'Version' = $dotNet4Builds["$net4Release"].Version
'Comment' = $dotNet4Builds["$net4Release"].Comment
}
}
if ($netRegKey = $regKey.OpenSubKey("$dotNetRoot")){
write-host("Checking for hacked keys")
foreach ($versionKeyName in $netRegKey.GetSubKeyNames())
{
if ($versionKeyName -match '^v[1234]') {
$versionKey = $netRegKey.OpenSubKey($versionKeyName)
write-host("versionKeyName is" + $versionKeyName)
write-host('ASPNetEnforceViewStateMac = ' + $versionKey.GetValue('ASPNetEnforceViewStateMac', ''))
$compromisedCheck += New-Object -TypeName PSObject -Property @{
'ComputerName' = $computerName
'version' = $versionKeyName
'compromisedCheck' = ('ASPNetEnforceViewStateMac = ' + $versionKey.GetValue('ASPNetEnforceViewStateMac', ''))
}
}
}
}
}
}
}
else{
write-host("could not connect to machine")
$dotNetter += New-Object -TypeName PSObject -Property @{
'ComputerName' = $computerName
'OS' = $os
'Build' = "Could not connect"
'Version' = "Could not connect"
'Comment' = "Could not connect"
}
}
}
$dotNetter | export-CSV c:\temp\DotNetVersions.csv
$compromisedCheck | export-CSV C:\temp\CompromisedCheck.csv
}
get-dotnetframeworkversion($computerList)
Now this is a very old thread i've come across but as many have pushed their answer's, here is mine in a hope to help someone with this simple code.
var search_value = "This is a dummy sentence!";_x000D_
var letter = 'a'; /*Can take any letter, have put in a var if anyone wants to use this variable dynamically*/_x000D_
letter = letter && "string" === typeof letter ? letter : "";_x000D_
var count;_x000D_
for (var i = count = 0; i < search_value.length; count += (search_value[i++] == letter));_x000D_
console.log(count);
_x000D_
I'm not sure if it is the fastest solution but i preferred it for simplicity and for not using regex (i just don't like using them!)
From the Android Developers page,
onPause():
Called when the system is about to start resuming a previous activity. This is typically used to commit unsaved changes to persistent data, stop animations and other things that may be consuming CPU, etc. Implementations of this method must be very quick because the next activity will not be resumed until this method returns. Followed by either onResume() if the activity returns back to the front, or onStop() if it becomes invisible to the user.
onStop():
Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one. This may happen either because a new activity is being started, an existing one is being brought in front of this one, or this one is being destroyed. Followed by either onRestart() if this activity is coming back to interact with the user, or onDestroy() if this activity is going away.
Now suppose there are three Activities and you go from A to B, then onPause of A will be called now from B to C, then onPause of B and onStop of A will be called.
The paused Activity gets a Resume and Stopped gets Restarted.
When you call this.finish()
, onPause-onStop-onDestroy will be called. The main thing to remember is: paused Activities get Stopped and a Stopped activity gets Destroyed whenever Android requires memory for other operations.
I hope it's clear enough.
html
<input type="hidden" value="hidden value" id='h_v' class='h_v'>
js
var hv = $('#h_v').attr("value");
alert(hv);
You can set a control variable in vars files located in group_vars/
or directly in hosts file like this:
[vagrant:vars]
test_var=true
[location-1]
192.168.33.10 hostname=apollo
[location-2]
192.168.33.20 hostname=zeus
[vagrant:children]
location-1
location-2
And run tasks like this:
- name: "test"
command: "echo {{test_var}}"
when: test_var is defined and test_var
The below command worked for me :
conda install -c anaconda numpy
This is more of an xpath question, but like this, assuming the context is the parent element:
<xsl:value-of select="name/@attribute1" />
str.replace(/\s/g,'')
Works for me.
jQuery.trim
has the following hack for IE, although I'm not sure what versions it affects:
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
Your HTML code:
<div>Stack Overflow is the BEST !!!</div>
CSS:
div {
width: 100px;
white-space:nowrap;
overflow:hidden;
text-overflow:ellipsis;
}
Now the result should be:
Stack Overf...
You can run something like this:
sqlcmd -S MyServer -d myDB -E -Q "select col1, col2, col3 from SomeTable"
-o "MyData.csv" -h-1 -s"," -w 700
-h-1
removes column name headers from the result-s","
sets the column seperator to , -w 700
sets the row width to 700 chars (this will need to be as wide as the longest row or it will wrap to the next line)I use intellj idea and in windows in terminal type:
gradlew.bat run
it is working for me.
Except dir(module) or help(module) mentioned in previous answers, you can also try:
- Open ipython
- import module_name
- type module_name, press tab. It'll open a small window with listing all functions in the python module.
It looks very neat.
Here is snippet listing all functions of hashlib module
(C:\Program Files\Anaconda2) C:\Users\lenovo>ipython
Python 2.7.12 |Anaconda 4.2.0 (64-bit)| (default, Jun 29 2016, 11:07:13) [MSC v.1500 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.
IPython 5.1.0 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]: import hashlib
In [2]: hashlib.
hashlib.algorithms hashlib.new hashlib.sha256
hashlib.algorithms_available hashlib.pbkdf2_hmac hashlib.sha384
hashlib.algorithms_guaranteed hashlib.sha1 hashlib.sha512
hashlib.md5 hashlib.sha224
Try putting this HTML snippet into your served document:
<img id="ItemPreview" src="">
Then, on JavaScript side, you can dynamically modify image's src
attribute with so-called Data URL.
document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;
Alternatively, using jQuery:
$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);
This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..."
part) in the URL accordingly.
Similar Questions:
You could use an asymmetrical border to make curves with CSS.
border-radius: 50%/100px 100px 0 0;
.box {_x000D_
width: 500px; _x000D_
height: 100px; _x000D_
border: solid 5px #000;_x000D_
border-color: #000 transparent transparent transparent;_x000D_
border-radius: 50%/100px 100px 0 0;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
SELECT TABLE_SCHEMA
, TABLE_NAME
, number = COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
GROUP BY TABLE_SCHEMA, TABLE_NAME;
This one worked for me.
I use standard HTML tags, like
<!---
your comment goes here
and here
-->
Note the triple dash. The advantage is that it works with pandoc when generating TeX or HTML output. More information is available on the pandoc-discuss group.
I think your best best is to run the VNC server with a different geometry on a different port. I would try based on the man page
$vncserver :0 -geometry 1600x1200 $vncserver :1 -geometry 1440x900
Then you can connect from work to one port and from home to another.
Edit: Then use xmove to move windows between the two x-servers.
The toString() method of Selenium's By-Class produces something like "By.xpath: //XpathFoo"
So you could take a substring starting at the colon with something like this:
String selector = divA.toString().substring(s.indexOf(":") + 2);
With this, you could find your element inside your other element with this:
WebElement input = driver.findElement( By.xpath( selector + "//input" ) );
Advantage: You have to search only once on the actual SUT, so it could give you a bonus in performance.
Disadvantage: Ugly... if you want to search for the parent element with css selectory and use xpath for it's childs, you have to check for types before you concatenate... In this case, Slanec's solution (using findElement on a WebElement) is much better.
For people looking this up now:
It seems that now setting the User-Agent
header is allowed since Firefox 43. See https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name for the current list of forbidden headers.
Store your data in temp table
Select * into tempTable from table1
Now update the column
UPDATE table1
SET table1.FileName = (select FileName from tempTable where tempTable.id = table1.ID);
If you list all of window.navigator
's properties using
console.log(navigator);
_x000D_
You'll see something like this
# platform = Win32
# appCodeName = Mozilla
# appName = Netscape
# appVersion = 5.0 (Windows; en-US)
# language = en-US
# mimeTypes = [object MimeTypeArray]
# oscpu = Windows NT 5.1
# vendor = Firefox
# vendorSub = 1.0.7
# product = Gecko
# productSub = 20050915
# plugins = [object PluginArray]
# securityPolicy =
# userAgent = Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7
# cookieEnabled = true
# javaEnabled = function javaEnabled() { [native code] }
# taintEnabled = function taintEnabled() { [native code] }
# preference = function preference() { [native code] }
Note that oscpu
attribute gives you the Windows version. Also, you should know that:
'Windows 3.11' => 'Win16',
'Windows 95' => '(Windows 95)|(Win95)|(Windows_95)',
'Windows 98' => '(Windows 98)|(Win98)',
'Windows 2000' => '(Windows NT 5.0)|(Windows 2000)',
'Windows XP' => '(Windows NT 5.1)|(Windows XP)',
'Windows Server 2003' => '(Windows NT 5.2)',
'Windows Vista' => '(Windows NT 6.0)',
'Windows 7' => '(Windows NT 6.1)',
'Windows 8' => '(Windows NT 6.2)|(WOW64)',
'Windows 10' => '(Windows 10.0)|(Windows NT 10.0)',
'Windows NT 4.0' => '(Windows NT 4.0)|(WinNT4.0)|(WinNT)|(Windows NT)',
'Windows ME' => 'Windows ME',
'Open BSD' => 'OpenBSD',
'Sun OS' => 'SunOS',
'Linux' => '(Linux)|(X11)',
'Mac OS' => '(Mac_PowerPC)|(Macintosh)',
'QNX' => 'QNX',
'BeOS' => 'BeOS',
'OS/2' => 'OS/2',
'Search Bot'=>'(nuhk)|(Googlebot)|(Yammybot)|(Openbot)|(Slurp)|(MSNBot)|(Ask Jeeves/Teoma)|(ia_archiver)'
There are 3 things you need.
You need to oAuth with the owner of those photos. (with the 'user_photos' extended permission)
You need the access token (which you get returned in the URL box after the oAuth is done.)
When those are complete you can then access the photos like so https://graph.facebook.com/me?access_token=ACCESS_TOKEN
You can find all of the information in more detail here: http://developers.facebook.com/docs/authentication
I've found a more reliable method (at least on Excel 2016 for Mac) is:
Assuming your long list is in column A, and the list of things to be removed from this is in column B, then paste this into all the rows of column C:
= IF(COUNTIF($B$2:$B$99999,A2)>0,"Delete","Keep")
Then just sort the list by column C to find what you have to delete.
So this is long after the initial question, and technically it isn't a direct answer to how to use Ajax call to populate exterior variable as the question asks. However in research and responses it's been found to be extremely difficult to do this without disabling asynchronous functions within the call, or by descending into what seems like the potential for callback hell. My solution for this has been to use Axios. Using this has dramatically simplified my usages of asynchronous calls getting in the way of getting at data.
For example if I were trying to access session variables in PHP, like the User ID, via a call from JS this might be a problem. Doing something like this..
async function getSession() {
'use strict';
const getSession = await axios("http:" + url + "auth/" + "getSession");
log(getSession.data);//test
return getSession.data;
}
Which calls a PHP function that looks like this.
public function getSession() {
$session = new SessionController();
$session->Session();
$sessionObj = new \stdClass();
$sessionObj->user_id = $_SESSION["user_id"];
echo json_encode($sessionObj);
}
To invoke this using Axios do something like this.
getSession().then(function (res) {
log(res);//test
anyVariable = res;
anyFunction(res);//set any variable or populate another function waiting for the data
});
The result would be, in this case a Json object from PHP.
{"user_id":"1111111-1111-1111-1111-111111111111"}
Which you can either use in a function directly in the response section of the Axios call or set a variable or invoke another function.
Proper syntax for the Axios call would actually look like this.
getSession().then(function (res) {
log(res);//test
anyVariable = res;
anyFunction(res);//set any variable or populate another function waiting for the data
}).catch(function (error) {
console.log(error);
});
For proper error handling.
I hope this helps anyone having these issues. And yes I am aware this technically is not a direct answer to the question but given the answers supplied already I felt the need to provide this alternative solution which dramatically simplified my code on the client and server sides.
It is possible with EditorConfig.
EditorConfig helps developers define and maintain consistent coding styles between different editors and IDEs.
This also includes file encoding.
EditorConfig is built-in Visual Studio 2017 by default, and I there were plugins available for versions as old as VS2012. Read more from EditorConfig Visual Studio Plugin page.
You can set up a EditorConfig configuration file high enough in your folder structure to span all your intended repos (up to your drive root should your files be really scattered everywhere) and configure the setting charset
:
charset: set to latin1, utf-8, utf-8-bom, utf-16be or utf-16le to control the character set.
You can add filters and exceptions etc on every folder level or by file name/type should you wish for finer control.
Once configured then compatible IDEs should automatically do it's thing to make matching files comform to set rules. Note that Visual Studio does not automatically convert all your files but do its bit when you work with files in IDE (open and save).
While you could have a Visual-studio-wide setup, I strongly suggest to still include an EditorConfig root to your solution version control, so that explicit settings are automatically synced to all team members as well. Your drive root editorconfig file can be the fallback should some project not have their own editorconfig files set up yet.
Instance of java.util.Date stores a date. So how can you store nothing in it or have it empty? It can only store references to instances of java.util.Date
. If you make it null
means that it is not referring any instance of java.util.Date
.
You have tried date2="";
what you mean to do by this statement you want to reference the instance of String
to a variable that is suppose to store java.util.Date
. This is not possible as Java is Strongly Typed Language.
Edit
After seeing the comment posted to the answer of LastFreeNickname
I am having a form that the date textbox should be by default blank in the textbox, however while submitting the data if the user didn't enter anything, it should accept it
I would suggest you could check if the textbox is empty. And if it is empty, then you could store default date in your variable or current date or may be assign it null
as shown below:
if(textBox.getText() == null || textBox.getText().equals(""){
date2 = null; // For Null;
// date2 = new Date(); For Current Date
// date2 = new Date(0); For Default Date
}
Also I can assume since you are asking user to enter a date in a TextBox
, you are using a DateFormat
to parse the text that is entered in the TextBox
. If this is the case you could simply call the dateFormat.parse()
which throws a ParseException
if the format in which the date was written is incorrect or is empty string. Here in the catch
block you could put the above statements as show below:
try{
date2 = dateFormat.parse(textBox.getText());
}catch(ParseException e){
date2 = null; // For Null;
// date2 = new Date(); For Current Date
// date2 = new Date(0); For Default Date
}
In this case no conditionals are needed to set the variable.
This one-liner XPath expression:
boolean(joined-subclass)
is true()
only when the child of the current node, named joined-subclass
exists and it is false()
otherwise.
The complete stylesheet is:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="class">
<xsl:variable name="subexists"
select="boolean(joined-subclass)"
/>
subexists: <xsl:text/>
<xsl:value-of select="$subexists" />
</xsl:template>
</xsl:stylesheet>
Do note, that the use of the XPath function boolean()
in this expression is to convert a node (or its absense) to one of the boolean values true()
or false()
.
Try this
$("#message span").text("hello world!");
function Errormessage(txt) {
var elem = $("#message");
elem.fadeIn("slow");
// find the span inside the div and assign a text
elem.children("span").text("your text");
elem.children("a.close-notify").click(function() {
elem.fadeOut("slow");
});
}
@BD at Rivenhill: Since this old question has gotten renewed attention last year, let us go on a bit, just for the sake of discussion.
The body of your doIt
method does not do anything T
-specific at all. Here it is:
public class Clazz<T> {
static <T> void doIt(T object) {
System.out.println("shake that booty '" + object.getClass().toString()
+ "' !!!");
}
// ...
}
So you can entirely drop all type variables and just code
public class Clazz {
static void doIt(Object object) {
System.out.println("shake that booty '" + object.getClass().toString()
+ "' !!!");
}
// ...
}
Ok. But let's get back closer to the original problem. The first type variable on the class declaration is redundant. Only the second one on the method is needed. Here we go again, but it is not the final answer, yet:
public class Clazz {
static <T extends Saying> void doIt(T object) {
System.out.println("shake that booty "+ object.say());
}
public static void main(String args[]) {
Clazz.doIt(new KC());
Clazz.doIt(new SunshineBand());
}
}
// Output:
// KC
// Sunshine
interface Saying {
public String say();
}
class KC implements Saying {
public String say() {
return "KC";
}
}
class SunshineBand implements Saying {
public String say() {
return "Sunshine";
}
}
However, it's all too much fuss about nothing, since the following version works just the same way. All it needs is the interface type on the method parameter. No type variables in sight anywhere. Was that really the original problem?
public class Clazz {
static void doIt(Saying object) {
System.out.println("shake that booty "+ object.say());
}
public static void main(String args[]) {
Clazz.doIt(new KC());
Clazz.doIt(new SunshineBand());
}
}
interface Saying {
public String say();
}
class KC implements Saying {
public String say() {
return "KC";
}
}
class SunshineBand implements Saying {
public String say() {
return "Sunshine";
}
}
Use a for loop. There's nothing built into array. Or switch to a java.util Collection class.
The integrated Text-Viewer of Total Commander can open huge files (>10GB) for viewing without any problems. It also provides different views, e.g. a Hex-View.
String can be converted to numbers in MongoDB v4.0 using $toInt operator. In this case
db.col.aggregate([
{
$project: {
_id: 0,
moopNumber: { $toInt: "$moop" }
}
}
])
outputs:
{ "moopNumber" : 1234 }
Use this I think it's better
*isAngularSite(false);*
browser.get(crmUrl);
login.username.sendKeys(username);
login.password.sendKeys(password);
login.submit.click();
*isAngularSite(true);*
For you to use this setting of isAngularSite should put this in your protractor.conf.js here:
global.isAngularSite = function(flag) {
browser.ignoreSynchronization = !flag;
};
If you want to set something on a timer, you can use JavaScript's setTimeout
or setInterval
methods:
setTimeout ( expression, timeout );
setInterval ( expression, interval );
Where expression
is a function and timeout
and interval
are integers in milliseconds. setTimeout
runs the timer once and runs the expression
once whereas setInterval will run the expression
every time the interval
passes.
So in your case it would work something like this:
setInterval(function() {
//call $.ajax here
}, 5000); //5 seconds
As far as the Ajax goes, see jQuery's ajax()
method. If you run an interval, there is nothing stopping you from calling the same ajax()
from other places in your code.
If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:
setInterval()
returns an integer which is the ID of the interval.
var id = setInterval(function() {
//call $.ajax here
}, 30000); // 30 seconds
If you store that ID in a variable, you can then call clearInterval(id)
which will stop the progression.
Then you can reinstantiate the setInterval()
call after you've completed your ajax form submission.
Something like this:
NSTimer *timer;
timer = [NSTimer scheduledTimerWithTimeInterval: 0.5
target: self
selector: @selector(handleTimer:)
userInfo: nil
repeats: YES];
Please see: http://www.sap-img.com/oracle-database/finding-oracle-sid-of-a-database.htm
What is the difference between Oracle SIDs and Oracle SERVICE NAMES. One config tool looks for SERVICE NAME and then the next looks for SIDs! What's going on?!
Oracle SID is the unique name that uniquely identifies your instance/database where as Service name is the TNS alias that you give when you remotely connect to your database and this Service name is recorded in Tnsnames.ora file on your clients and it can be the same as SID and you can also give it any other name you want.
SERVICE_NAME is the new feature from oracle 8i onwards in which database can register itself with listener. If database is registered with listener in this way then you can use SERVICE_NAME parameter in tnsnames.ora otherwise - use SID in tnsnames.ora.
Also if you have OPS (RAC) you will have different SERVICE_NAME for each instance.
SERVICE_NAMES specifies one or more names for the database service to which this instance connects. You can specify multiple services names in order to distinguish among different uses of the same database. For example:
SERVICE_NAMES = sales.acme.com, widgetsales.acme.com
You can also use service names to identify a single service that is available from two different databases through the use of replication.
In an Oracle Parallel Server environment, you must set this parameter for every instance.
In short: SID = the unique name of your DB instance, ServiceName = the alias used when connecting
I'm adding another answer to this as I had the same problem and solved it the same way:
I had installed SSL on apache2 using a2enmod ssl
, which seems to have added an extra configuration in /etc/apache2/ports.conf
:
NameVirtualHost *:80
Listen 80
NameVirtualHost *:443
Listen 443
<IfModule mod_ssl.c>
Listen 443
</IfModule>
<IfModule mod_gnutls.c>
Listen 443
</IfModule>
I had to comment out the first Listen 443
after the NameVirtualHost *:443
directive:
NameVirtualHost *:443
#Listen 443
But I'm thinking I can as well let it and comment the others. Anyway, thank you for the solution :)
I'm using rc.4 and this method works for ES2015(ES6):
import {DomSanitizationService} from '@angular/platform-browser';
@Component({
templateUrl: 'build/pages/veeu/veeu.html'
})
export class VeeUPage {
static get parameters() {
return [NavController, App, MenuController, DomSanitizationService];
}
constructor(nav, app, menu, sanitizer) {
this.app = app;
this.nav = nav;
this.menu = menu;
this.sanitizer = sanitizer;
}
photoURL() {
return this.sanitizer.bypassSecurityTrustUrl(this.mediaItems[1].url);
}
}
In the HTML:
<iframe [src]='photoURL()' width="640" height="360" frameborder="0"
webkitallowfullscreen mozallowfullscreen allowfullscreen>
</iframe>
Using a function will ensure that the value doesn't change after you sanitize it. Also be aware that the sanitization function you use depends on the context.
For images, bypassSecurityTrustUrl
will work but for other uses you need to refer to the documentation:
https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html
As simple as joining lists in python itself.
ansible -m debug -a msg="{{ '-'.join(('list', 'joined', 'together')) }}" localhost
localhost | SUCCESS => {
"msg": "list-joined-together" }
Works the same way using variables:
ansible -m debug -a msg="{{ '-'.join((var1, var2, var3)) }}" localhost
You can redirect in jQuery like this:
$(location).attr('href', 'http://yourPage.com/');
The difference between them is that they use different pins. Seriously, that's it. The reason they both exist is that RTS/CTS wasn't supposed to ever be a flow control mechanism, originally; it was for half-duplex modems to coordinate who was sending and who was receiving. RTS and CTS got misused for flow control so often that it became standard.
To Use Jquery in Angular2(4)
Follow these setps
install the Jquery and Juqry type defination
For Jquery Installation npm install jquery --save
For Jquery Type defination Installation npm install @types/jquery --save-dev
and then simply import the jquery
import { Component } from '@angular/core';
import * as $ from 'jquery';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
console.log($(window)); // jquery is accessible
}
For zooming your map two level then just add this small code of line
map.setZoom(map.getZoom() + 2);
Yes, that will work as you expect it to. Unfortunately, I seem to be having trouble to find an explicit statement of this in the MySQL manual.
Foreign keys mean the value must exist in the other table. NULL refers to the absence of value, so when you set a column to NULL, it wouldn't make sense to try to enforce constraints on that.
Painfully slow (and crudely implemented) but a combination of svn log and svn cat works if you are searching the history of single files or small repositories:
svn log filetosearch |
grep '^r' |
cut -f1 -d' ' |
xargs -i bash -c "echo '{}'; svn cat filetosearch -'{}'"
will output each revision number where file changed and the file. You could always cat each revision into a different file and then grep for changes.
PS. Massive upvotes to anyone that shows me how to do this properly!
This problem is because port 80 is used by some other application. Try to reconfigure port.
For me the Anonymous User access was fine at the server level, but varied at just one of my "virtual" folders.
Took me quite a bit of foundering about and then some help from a colleague to learn that IIS has "authentication" settings at the virtual folder level too - hopefully this helps someone else with my predicament.
This might be a memmory issue on mysql try to increase max_allowed_packet in my.ini
CONTAINS
is for a Full Text Indexed field - if not, then use LIKE
pip
/ conda
After extensively documenting a similar problem with Git (How can I make git accept a self signed certificate?), here we are again behind a corporate firewall with a proxy giving us a MitM "attack" that we should trust and:
NEVER disable all SSL verification!
This creates a bad security culture. Don't be that person.
pip config set global.cert path/to/ca-bundle.crt
pip config list
conda config --set ssl_verify path/to/ca-bundle.crt
conda config --show ssl_verify
# Bonus while we are here...
git config --global http.sslVerify true
git config --global http.sslCAInfo path/to/ca-bundle.crt
But where do we get ca-bundle.crt
?
cURL publishes an extract of the Certificate Authorities bundled with Mozilla Firefox
https://curl.haxx.se/docs/caextract.html
I recommend you open up this cacert.pem
file in a text editor as we will need to add our self-signed CA to this file.
Certificates are a document complying with X.509 but they can be encoded to disk a few ways. The below article is a good read but the short version is that we are dealing with the base64 encoding which is often called PEM in the file extensions. You will see it has the format:
----BEGIN CERTIFICATE----
....
base64 encoded binary data
....
----END CERTIFICATE----
Below are a few options on how to get our self signed certificate:
echo quit | openssl s_client -showcerts -servername "curl.haxx.se" -connect curl.haxx.se:443 > cacert.pem
Thanks to this answer and the linked blog, it shows steps (on Windows) how to view the certificate and then copy to file using the base64 PEM encoding option.
Copy the contents of this exported file and paste it at the end of your cacerts.pem
file.
For consistency rename this file cacerts.pem
--> ca-bundle.crt
and place it somewhere easy like:
# Windows
%USERPROFILE%\certs\ca-bundle.crt
# or *nix
$HOME/certs/cabundle.crt
Thanks to all the brilliant answers in:
How to get response SSL certificate from requests in python?
I have put together the following to attempt to take it a step further.
https://github.com/neozenith/get-ca-py
Set the configuration in pip and conda so that it knows where this CA store resides with our extra self-signed CA.
pip config set global.cert %USERPROFILE%\certs\ca-bundle.crt
conda config --set ssl_verify %USERPROFILE%\certs\ca-bundle.crt
OR
pip config set global.cert $HOME/certs/ca-bundle.crt
conda config --set ssl_verify $HOME/certs/ca-bundle.crt
THEN
pip config list
conda config --show ssl_verify
# Hot tip: use -v to show where your pip config file is...
pip config list -v
# Example output for macOS and homebrew installed python
For variant 'global', will try loading '/Library/Application Support/pip/pip.conf'
For variant 'user', will try loading '/Users/jpeak/.pip/pip.conf'
For variant 'user', will try loading '/Users/jpeak/.config/pip/pip.conf'
For variant 'site', will try loading '/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/pip.conf'
Part of the answer to 'handle' the 'Sequence has no elements' Exception in VB is to test for empty
If Not (myMap Is Nothing) Then
' execute code
End if
Where MyMap is the sequence queried returning empty/null. FYI
There are 2 ways to do this.
1)
function something(options) {
var timeToLive = options.timeToLive || 200; // default to 200 if not set
...
}
2)
function something(timeToDie /*, timeToLive*/) {
var timeToLive = arguments[1] || 200; // default to 200 if not set
..
}
In 1), options
is a JS object with what ever attributes are required. This is easier to maintain and extend.
In 2), the function signature is clear to read and understand that a second argument can be provided. I've seen this style used in Mozilla code and documentation.
Gmail: OAuth
Client ID
and Secret ID
. Finally click OK to close the credentials pop up.Google API
. Click on Overview in the left pane.Google API
under Social APIs section.That’s all from the Google part.
Come back to your application, open App_start/Startup.Auth.cs
and uncomment the following snippet
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
ClientId = "",
ClientSecret = ""
});
Update the ClientId
and ClientSecret
with the values from Google API
credentials which you have created already.
Gmail
id.Gmail
id into your application database.The screenshot was very helpful - the following code will do the job (assuming data is located in column A starting A1):
Sub RemoveRows()
Dim i As Long
i = 1
Do While i <= ThisWorkbook.ActiveSheet.Range("A1").CurrentRegion.Rows.Count
If InStr(1, ThisWorkbook.ActiveSheet.Cells(i, 1).Text, "-", vbTextCompare) > 0 Then
ThisWorkbook.ActiveSheet.Cells(i, 1).EntireRow.Delete
Else
i = i + 1
End If
Loop
End Sub
Sample file is shared: https://www.dropbox.com/s/2vhq6vw7ov7ssya/RemoweDashRows.xlsm
The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND
command on another connection, but it apparently was "not opening [it] up in sync with the client side".
Well, the main reason would be there was no synchronisation whatsoever. Calling:
cs.send("SEND " + FILE)
cs.close()
would just place the data into a OS buffer; close
would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep
after close
might mitigate the problem, but this is not synchronisation.
The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK
, or better PORT 36250
to indicate where to connect). This would make sure the server is already listening.
The other thing is you must check the return values of send
to make sure how many bytes was taken from your buffer. Or use sendall
.
(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)
Add new column to DataTable
and use column Expression
property to set your Status expression.
Here you can find good example: DataColumn.Expression
Property
DataTable and DataColumn Expressions in ADO.NET - Calculated Columns
UPDATE
Code sample:
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("colBestBefore", typeof(DateTime)));
dt.Columns.Add(new DataColumn("colStatus", typeof(string)));
dt.Columns["colStatus"].Expression = String.Format("IIF(colBestBefore < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
dt.Rows.Add(DateTime.Now.AddDays(-1));
dt.Rows.Add(DateTime.Now.AddDays(1));
dt.Rows.Add(DateTime.Now.AddDays(2));
dt.Rows.Add(DateTime.Now.AddDays(-2));
demoGridView.DataSource = dt;
UPDATE #2
dt.Columns["colStatus"].Expression = String.Format("IIF(CONVERT(colBestBefore, 'System.DateTime') < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
Here's what I would try first:
1) Create an interface (let's call it OnScrollTopOrBottomListener) with these methods:
void onScrollTop();
void onScrollBottom();
2) In your list's adapter, add a member instance, typed as the interface you created and supply a setter and getter.
3) In the getView() implementation of your adapter, check if the position parameter is either 0 or getCount() - 1. Also check that your OnScrollTopOrBottomListener instance is not null.
4) If the position is 0, call onScrollTopOrBottomListener.onScrollTop(). If position is getCount() - 1, call onScrollTopOrBottomListener.onScrollBottom().
5) In your OnScrollTopOrBottomListener implementation, call the appropriate methods to get the desired data.
Hope that helps in some way.
-Brandon
Let's try to take an example and understand:
I have a branch, say master, pointing to X <commit-id>, and I have a new branch pointing to Y <sha1>.
Where Y <commit-id> = <master> branch commits - few commits
Now say for Y branch I have to gap-close the commits between the master branch and the new branch. Below is the procedure we can follow:
Step 1:
git checkout -b local origin/new
where local is the branch name. Any name can be given.
Step 2:
git merge origin/master --no-ff --stat -v --log=300
Merge the commits from master branch to new branch and also create a merge commit of log message with one-line descriptions from at most <n> actual commits that are being merged.
For more information and parameters about Git merge, please refer to:
git merge --help
Also if you need to merge a specific commit, then you can use:
git cherry-pick <commit-id>
In short, no, you can't.
Long answer, extension methods are just syntactic sugar. IE:
If you have an extension method on string let's say:
public static string SomeStringExtension(this string s)
{
//whatever..
}
When you then call it:
myString.SomeStringExtension();
The compiler just turns it into:
ExtensionClass.SomeStringExtension(myString);
So as you can see, there's no way to do that for static methods.
And another thing just dawned on me: what would really be the point of being able to add static methods on existing classes? You can just have your own helper class that does the same thing, so what's really the benefit in being able to do:
Bool.Parse(..)
vs.
Helper.ParseBool(..);
Doesn't really bring much to the table...
This is fixed in Hamcrest 1.3. The below code compiles and does not generate any warnings:
// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, is(not(empty())));
But if you have to use older version - instead of bugged empty()
you could use:
hasSize(greaterThan(0))
(import static org.hamcrest.number.OrderingComparison.greaterThan;
or
import static org.hamcrest.Matchers.greaterThan;
)
Example:
// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, hasSize(greaterThan(0)));
The most important thing about above solutions is that it does not generate any warnings. The second solution is even more useful if you would like to estimate minimum result size.
$image_folder = APPPATH . "../images/owner_profile/" . $_POST ['mob_no'] [0] . $na;
if (isset ( $_FILES ['image'] ) && $_FILES ['image'] ['error'] == 0) {
list ( $a, $b ) = explode ( '.', $_FILES ['image'] ['name'] );
$b = end ( explode ( '.', $_FILES ['image'] ['name'] ) );
$up = move_uploaded_file ( $_FILES ['image'] ['tmp_name'], $image_folder . "." . $b );
$path = ($_POST ['mob_no'] [0] . $na . "." . $b);
It may be possible (but very hackish) with only CSS using the :before or :after pseudo elements:
.bgtext {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.bgtext:after {_x000D_
content: "Background text";_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
z-index: -1;_x000D_
}
_x000D_
<div class="bgtext">_x000D_
Foreground text_x000D_
</div>
_x000D_
This seems to work, but you'll probably need to tweak it a little. Also note it won't work in IE6 because it doesn't support :after
.
http://www.w3schools.com/tags/tag_ul.asp
ul {
display: block;
list-style-type: disc;
margin-top: 1em;
margin-bottom: 1em;
margin-left: 0;
margin-right: 0;
padding-left: 40px;
}
The JSONP comes to mind:
JSONP or "JSON with padding" is a complement to the base JSON data format, a usage pattern that allows a page to request and more meaningfully use JSON from a server other than the primary server. JSONP is an alternative to a more recent method called Cross-Origin Resource Sharing.
collection.ToList().ForEach(c => c.PropertyToSet = value);
AngularJS relies on input names to expose validation errors.
Unfortunately, as of today, it is not possible (without using a custom directive) to dynamically generate a name of an input. Indeed, checking input docs we can see that the name attribute accepts a string only.
To solve the 'dynamic name' problem you need to create an inner form (see ng-form):
<div ng-repeat="social in formData.socials">
<ng-form name="urlForm">
<input type="url" name="socialUrl" ng-model="social.url">
<span class="alert error" ng-show="urlForm.socialUrl.$error.url">URL error</span>
</ng-form>
</div>
The other alternative would be to write a custom directive for this.
Here is the jsFiddle showing the usage of the ngForm: http://jsfiddle.net/pkozlowski_opensource/XK2ZT/2/
In ES8 using moment, now and start being moment objects.
const duration = moment.duration(now.diff(start));
const timespan = duration.get("hours").toString().padStart(2, '0') +":"+ duration.get("minutes").toString().padStart(2, '0') +":"+ duration.get("seconds").toString().padStart(2, '0');
First include the header
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script type="text/JavaScript" src="https://cdnjs.cloudflare.com/ajax/libs/jQuery.print/1.6.0/jQuery.print.js"></script>
As you are using a print function with a selector which is a part of print.js so you need to call them before you use it...
Else
window.print()
will do it
$("#btn").click(function () {
$("#printarea").print();
});
or
$("#btn").on('click',function () {
$("#printarea").print();
});
//Learn more: www.tenoclocks.com
This is my solution, may be it can helps I use IntelliJ IDE. File -> Setting -> Maven -> Importing change JDK for importer to 1.8( you can change to lower, higher)
In Java, you can't, as foreach was meant to hide the iterator. You must do the normal For loop in order to get the current iteration.
In projects that use the Gradle build system, what you want to change is the applicationId
in the build.gradle file. The build system uses this value to override anything specified by hand in the manifest file when it does the manifest merge and build.
For example, your module's build.gradle file looks something like this:
apply plugin: 'com.android.application'
android {
compileSdkVersion 20
buildToolsVersion "20.0.0"
defaultConfig {
// CHANGE THE APPLICATION ID BELOW
applicationId "com.example.fred.myapplication"
minSdkVersion 10
targetSdkVersion 20
versionCode 1
versionName "1.0"
}
}
applicationId
is the name the build system uses for the property that eventually gets written to the package
attribute of the manifest
tag in the manifest file. It was renamed to prevent confusion with the Java package name (which you have also tried to modify), which has nothing to do with it.
$criteria = new \Doctrine\Common\Collections\Criteria();
$criteria->where($criteria->expr()->gt('id', 'id'))
->setMaxResults(1)
->orderBy(array("id" => $criteria::DESC));
$results = $articlesRepo->matching($criteria);
String fileName="foo.bar";
int dotIndex=fileName.lastIndexOf('.');
if(dotIndex>=0) { // to prevent exception if there is no dot
fileName=fileName.substring(0,dotIndex);
}
Is this a trick question? :p
I can't think of a faster way atm.
You can use parameter substitution in the twig globals section of the config:
Parameter config:
parameters:
app.version: 0.1.0
Twig config:
twig:
globals:
version: '%app.version%'
Twig template:
{{ version }}
This method provides the benefit of allowing you to use the parameter in ContainerAware
classes as well, using:
$container->getParameter('app.version');
Comma separate the values:
UPDATE settings SET postsPerPage = $postsPerPage, style = $style WHERE id = '1'"
tSql escapes a double quote with another double quote. So if you wanted it to be part of your sql string literal you would do this:
declare @xml xml
set @xml = "<transaction><item value=""hi"" /></transaction>"
If you want to include a quote inside a value in the xml itself, you use an entity, which would look like this:
declare @xml xml
set @xml = "<transaction><item value=""hi "mom" lol"" /></transaction>"