I came across this question while trying to answer the same question. McCrohan's approach with the classes array & join is solid.
Through my experience, I have been working with a lot of legacy ruby code that is being converted to React and as we build the component(s) up I find myself reaching out for both existing css classes and inline styles.
example snippet inside a component:
// if failed, progress bar is red, otherwise green
<div
className={`progress-bar ${failed ? failed' : ''}`}
style={{ width: this.getPercentage() }}
/>
Again, I find myself reaching out to legacy css code, "packaging" it with the component and moving on.
So, I really feel that it is a bit in the air as to what is "best" as that label will vary greatly depending on your project.
To get the checked state of your checkbox the path would be:
this.refs.complete.state.checked
The alternative is to get it from the event passed into the handleChange
method:
event.target.checked
Before you extract values from $_POST
, you should check if they exist. You could use the isset
function for this (http://php.net/manual/en/function.isset.php)
Blazemonger's reply (above or below) needs voting up - but I don't have enough points.
I wanted to add a grey bar across some 20px wide CSS round buttons to indicate "not available" and tweaked Blazemonger's css:
.round_btn:after {
content:""; /* required property */
position: absolute;
top: 6px;
left: -1px;
border-top: 6px solid rgba(170,170,170,0.65);
height: 6px;
width: 19px;
}
For an unknow reason, the accepted answer partially works when I send email to my gmail address. I have the attachement but not the text of the email.
If you want both attachment and text try this based on the accepted answer :
Properties props = new java.util.Properties();
props.put("mail.smtp.host", "yourHost");
props.put("mail.smtp.port", "yourHostPort");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
// Session session = Session.getDefaultInstance(props, null);
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "password");
}
});
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(mailFrom));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
msg.setSubject("your subject");
Multipart multipart = new MimeMultipart();
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setText("your text");
MimeBodyPart attachmentBodyPart= new MimeBodyPart();
DataSource source = new FileDataSource(attachementPath); // ex : "C:\\test.pdf"
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(fileName); // ex : "test.pdf"
multipart.addBodyPart(textBodyPart); // add the text part
multipart.addBodyPart(attachmentBodyPart); // add the attachement part
msg.setContent(multipart);
Transport.send(msg);
} catch (MessagingException e) {
LOGGER.log(Level.SEVERE,"Error while sending email",e);
}
Update :
If you want to send a mail as an html content formated you have to do
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setContent(content, "text/html");
So basically setText
is for raw text and will be well display on every server email including gmail, setContent
is more for an html template and if you content is formatted as html it will maybe also works in gmail
The source for String.valueOf shows this:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
Not that it matters much, but I would use toString.
long start = System.currentTimeMillis();
long end = start + 60*1000; // 60 seconds * 1000 ms/sec
while (System.currentTimeMillis() < end)
{
// run
}
I think @Evert has the right answer:
plt.scatter(dates,values)
plt.plot(dates, values)
plt.show()
Which is pretty much the same as
plt.plot(dates, values, '-o')
plt.show()
or whatever linestyle you prefer.
Run the following from command line and you should be in the Mongo bin directory.
mongorestore -d db_name -c collection_name path/file.bson
Here is a very detailed description of Geo Distance Search with MySQL a solution based on implementation of Haversine Formula to mysql. The complete solution description with theory, implementation and further performance optimization. Although the spatial optimization part didn't work correct in my case. http://www.scribd.com/doc/2569355/Geo-Distance-Search-with-MySQL
You can solve that using display table.
Here is the updated JSFiddle that solves your problem.
CSS
.body {
display: table;
background-color: green;
}
.left-side {
background-color: blue;
float: none;
display: table-cell;
border: 1px solid;
}
.right-side {
background-color: red;
float: none;
display: table-cell;
border: 1px solid;
}
HTML
<div class="row body">
<div class="col-xs-9 left-side">
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
</div>
<div class="col-xs-3 right-side">
asdfdf
</div>
</div>
We were getting the same error.For us, it solved by upgrading pip version (also discussed in FAQ of OpenCV GitHub). Earlier we had pip-7.1.0, post upgrading it to "pip-9.0.2", it successfully installed.
pip install --upgrade pip
pip install opencv-python
Add another div
or img
to your main div
and blur that instead. jsfiddle
.blur {
background:url('http://i0.kym-cdn.com/photos/images/original/000/051/726/17-i-lol.jpg?1318992465') no-repeat center;
background-size:cover;
-webkit-filter: blur(13px);
-moz-filter: blur(13px);
-o-filter: blur(13px);
-ms-filter: blur(13px);
filter: blur(13px);
position:absolute;
width:100%;
height:100%;
}
I believe you need to .f
file as a parameter, not as a command-single-string. same with the "--domain "+i
, which i would split in two elements of the list.
Assuming that:
FORTRAN
executable, ~/
is indeed the correct way for the FORTRAN
executableI would change this line:
subprocess.Popen(["FORTRAN ~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain "+i])
to
subprocess.Popen(["FORTRAN", "~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain", i])
If that doesn't work, you should do a os.path.exists()
for the .f
file, and check that you can launch the FORTRAN
executable without any path, and set the path or system path variable accordingly
[EDIT 6-Mar-2017]
As the exception, detailed in the original post, is a python exception from subprocess
; it is likely that the WinError 2
is because it cannot find FORTRAN
I highly suggest that you specify full path for your executable:
for i in input:
exe = r'c:\somedir\fortrandir\fortran.exe'
fortran_script = r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f'
subprocess.Popen([exe, fortran_script, "--domain", i])
if you need to convert the forward-slashes to backward-slashes, as suggested in one of the comments, you can do this:
for i in input:
exe = os.path.normcase(r'c:\somedir\fortrandir\fortran.exe')
fortran_script = os.path.normcase(r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
i = os.path.normcase(i)
subprocess.Popen([exe, fortran_script, "--domain", i])
[EDIT 7-Mar-2017]
The following line is incorrect:
exe = os.path.normcase(r'~/C:/Program Files (x86)/Silverfrost/ftn95.exe'
I am not sure why you have ~/
as a prefix for every path, don't do that.
for i in input:
exe = os.path.normcase(r'C:/Program Files (x86)/Silverfrost/ftn95.exe'
fortran_script = os.path.normcase(r'C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
i = os.path.normcase(i)
subprocess.Popen([exe, fortran_script, "--domain", i])
[2nd EDIT 7-Mar-2017]
I do not know this FORTRAN or ftn95.exe, does it need a shell to function properly?, in which case you need to launch as follows:
subprocess.Popen([exe, fortran_script, "--domain", i], shell = True)
You really need to try to launch the command manually from the working directory which your python script is operating from. Once you have the command which is actually working, then build up the subprocess
command.
The reasons why (including the data in the leaf level of the index) have been nicely explained. The reason that you give two shakes about this, is that when you run your query, if you don't have the additional columns included (new feature in SQL 2005) the SQL Server has to go to the clustered index to get the additional columns which takes more time, and adds more load to the SQL Server service, the disks, and the memory (buffer cache to be specific) as new data pages are loaded into memory, potentially pushing other more often needed data out of the buffer cache.
You can apply a theme to any activity by including android:theme
inside <activity>
inside manifest file.
For example:
<activity android:theme="@android:style/Theme.Dialog">
<activity android:theme="@style/CustomTheme">
And if you want to set theme programatically then use setTheme()
before calling setContentView()
and super.onCreate()
method inside onCreate()
method.
For the examples you stated I'd use the following:
activate_login
POST /users/1/activation
deactivate_login
DELETE /users/1/activation
change_password
PUT /passwords
(this assumes the user is authenticated)
add_credit
POST /credits
(this assumes the user is authenticated)
For errors you'd return the error in the body in the format that you got the request in, so if you receive:
DELETE /users/1.xml
You'd send the response back in XML, the same would be true for JSON etc...
For authentication you should use http authentication.
I was having difficulty getting the answer by @fernando-aguirre using WindowChrome
to work. It was not working in my case because I was overriding OnSourceInitialized
in the MainWindow
and not calling the base class method.
protected override void OnSourceInitialized(EventArgs e)
{
ViewModel.Initialize(this);
base.OnSourceInitialized(e); // <== Need to call this!
}
This stumped me for a very long time.
%time%
should work, provided enough time has elapsed between calls:
@echo OFF
@echo %time%
ping -n 1 -w 1 127.0.0.1 1>nul
@echo %time%
On my system I get the following output:
6:46:13.50
6:46:13.60
This code worked for me:
$(function(){
$('input:radio').change(function(){
alert('changed');
});
});
This might be a simple solution to achieve this:
INSERT INTO funds (ID, date, price)
SELECT 23, DATE('2013-02-12'), 22.5
FROM dual
WHERE NOT EXISTS (SELECT 1
FROM funds
WHERE ID = 23
AND date = DATE('2013-02-12'));
p.s. alternatively (if ID
a primary key):
INSERT INTO funds (ID, date, price)
VALUES (23, DATE('2013-02-12'), 22.5)
ON DUPLICATE KEY UPDATE ID = 23; -- or whatever you need
see this Fiddle.
For googlers:
This jquery-workaround makes #containment get a height automatically (by, height: auto), then gets the actual height assigned as a pixel value.
<script type="text/javascript">
<!--
$(function () {
// workaround for webkit-bug http://stackoverflow.com/a/8468131/348841
var rz = function () {
$('#containment')
.css('height', 'auto')
.css('height', $('#containment').height() + 'px');
};
$(window).resize(function () {
rz();
});
rz();
})
-->
</script>
Yes you can! For a simple repository that only publish/retrieve artifacts, you can use nginx.
Make sure nginx has http dav module enabled, it should, but nonetheless verify it.
Configure nginx http dav module:
In Windows: d:\servers\nginx\nginx.conf
location / {
# maven repository
dav_methods PUT DELETE MKCOL COPY MOVE;
create_full_put_path on;
dav_access user:rw group:rw all:r;
}
In Linux (Ubuntu): /etc/nginx/sites-available/default
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
# try_files $uri $uri/ =404; # IMPORTANT comment this
dav_methods PUT DELETE MKCOL COPY MOVE;
create_full_put_path on;
dav_access user:rw group:rw all:r;
}
Don't forget to give permissions to the directory where the repo will be located:
sudo chmod +777 /var/www/html/repository
In your project's pom.xml
add the respective configuration:
Retrieve artifacts:
<repositories>
<repository>
<id>repository</id>
<url>http://<your.ip.or.hostname>/repository</url>
</repository>
</repositories>
Publish artifacts:
<build>
<extensions>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-http</artifactId>
<version>3.2.0</version>
</extension>
</extensions>
</build>
<distributionManagement>
<repository>
<id>repository</id>
<url>http://<your.ip.or.hostname>/repository</url>
</repository>
</distributionManagement>
To publish artifacts use mvn deploy
. To retrieve artifacts, maven will do it automatically.
And there you have it a simple maven repo.
A great way of doing this on WordPress consists of the following steps:
Step 1: Open your Jupyter notebook in a text editor and copy the content which may look like so: Your .ipynb file may look like this when opened in a text editor
Step 2: Ctrl + A and Ctrl + C this content. Then Ctrl + V this to a GitHub Gist that you should create.
Step 3: Create a public gist and embed the gist like you always embed gists on WordPress, viz., go to the HTML editor and add like so:
[gist gist_url]
I have actually implemented this on my blog. You can find the post here
If your markup is bound to a controller, directive or anything else with a $scope:
console.log($scope.movie);
The current selected solution appears to have misunderstood the problem.
The trick is to neither use absolute nor fixed positioning. Instead, have the close button outside of the div with its position set to relative and a left float so that it is immediately right of the div. Next, set a negative left margin and a positive z index so that it appears above the div.
Here's an example:
#close
{
position: relative;
float: left;
margin-top: 50vh;
margin-left: -100px;
z-index: 2;
}
#dialog
{
height: 100vh;
width: 100vw;
position: relative;
overflow: scroll;
float: left;
}
<body>
<div id="dialog">
****
</div>
<div id="close"> </div>
</body>
Convenience Things can have irregular plural names. Sometimes they don't have one. But Singular names are always there.
e.g. CustomerAddress over CustomerAddresses
Consider this related resource.
This /order/12/orderdetail/12
is more readable and logical than /orders/12/orderdetails/4
.
A resource represents an entity like a database table. It should have a logical singular name. Here's the answer over table names.
Classes are always singular. ORM tools generate tables with the same names as class names. As more and more tools are being used, singular names are becoming a standard.
Read more about A REST API Developer's Dilemma
In the case of trousers
and sunglasses
, they don't seem to have a singular counterpart. They are commonly known and they appear to be singular by use. Like a pair of shoes. Think about naming the class file Shoe
or Shoes
. Here these names must be considered as a singular entity by their use. You don't see anyone buying a single shoe to have the URL as
/shoe/23
We have to see Shoes
as a singular entity.
Reference: Top 6 REST Naming Best Practices
could you not just keep a running index?
var _selectIndex = 0;
...code...
var newSelectBox = document.createElement("select");
newSelectBox.setAttribute("id","select-"+_selectIndex++);
EDIT
Upon further consideration, you may actually prefer to use array-style names for your selects...
e.g.
<select name="city[]"><option ..../></select>
<select name="city[]"><option ..../></select>
<select name="city[]"><option ..../></select>
then, on the server side in php for example:
$cities = $_POST['city']; //array of option values from selects
EDIT 2 In response to OP comment
Dynamically creating options using DOM methods can be done as follows:
var newSelectBox = document.createElement("select");
newSelectBox.setAttribute("id","select-"+_selectIndex++);
var city = null,city_opt=null;
for (var i=0, len=cities.length; i< len; i++) {
city = cities[i];
var city_opt = document.createElement("option");
city_opt.setAttribute("value",city);
city_opt.appendChild(document.createTextNode(city));
newSelectBox.appendChild(city_opt);
}
document.getElementById("example_element").appendChild(newSelectBox);
assuming that the cities
array already exists
Alternatively you could use the innerHTML method.....
var newSelectBox = document.createElement("select");
newSelectBox.setAttribute("id","select-"+_selectIndex++);
document.getElementById("example_element").appendChild(newSelectBox);
var city = null,htmlStr="";
for (var i=0, len=cities.length; i< len; i++) {
city = cities[i];
htmlStr += "<option value='" + city + "'>" + city + "</option>";
}
newSelectBox.innerHTML = htmlStr;
There's no need for extra css the .btn-group-justified
class does this.
You have to add this to the parent element and then wrap each btn element in a div with .btn-group like this
<div class="form-group">
<div class="btn-group btn-group-justified">
<div class="btn-group">
<button type="submit" id="like" class="btn btn-lg btn-success ">Like</button>
</div>
<div class="btn-group">
<button type="submit" id="nope" class="btn btn-lg btn-danger ">Nope</button>
</div>
</div>
</div>
You'll probably want to try textContent
instead of innerHTML
.
Given innerHTML
will return DOM content as a String
and not exclusively the "text" in the div
. It's fine if you know that your div
contains only text but not suitable if every use case. For those cases, you'll probably have to use textContent
instead of innerHTML
For example, considering the following markup:
<div id="test">
Some <span class="foo">sample</span> text.
</div>
You'll get the following result:
var node = document.getElementById('test'),
htmlContent = node.innerHTML,
// htmlContent = "Some <span class="foo">sample</span> text."
textContent = node.textContent;
// textContent = "Some sample text."
See MDN for more details:
To avoid using scriplets in the jsp, follow the advice of "divideByZero", and use
${pageContext.request.requestURI}
This is a better way to go.
So your endpoint address defined in your first example is incomplete. You must also define endpoint identity as shown in client configuration. In code you can try this:
EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("host/mikev-ws");
var address = new EndpointAddress("http://id.web/Services/EchoService.svc", spn);
var client = new EchoServiceClient(address);
litResponse.Text = client.SendEcho("Hello World");
client.Close();
Actual working final version by valamas
EndpointIdentity spn = EndpointIdentity.CreateSpnIdentity("host/mikev-ws");
Uri uri = new Uri("http://id.web/Services/EchoService.svc");
var address = new EndpointAddress(uri, spn);
var client = new EchoServiceClient("WSHttpBinding_IEchoService", address);
client.SendEcho("Hello World");
client.Close();
Many people think garbage collection collects and discards dead objects.
In reality, Java garbage collection is doing the opposite! Live objects are tracked and everything else designated garbage.
When an object is no longer used, the garbage collector reclaims the underlying memory and reuses it for future object allocation. This means there is no explicit deletion and no memory is given back to the operating system. To determine which objects are no longer in use, the JVM intermittently runs what is very aptly called a mark-and-sweep algorithm.
Check this for more detail information: http://javabook.compuware.com/content/memory/how-garbage-collection-works.aspx
You must install the JDT/Eclipse Java 8 Support For Kepler. https://wiki.eclipse.org/JDT/Eclipse_Java_8_Support_For_Kepler
You can place the code into a subroutine, if you don't want pollute your namespace.
my $hash_ref =
sub{
my %hash;
@hash{ @{[ qw'one two three' ]} } = undef;
return \%hash;
}->();
Or even better:
sub keylist(@){
my %hash;
@hash{@_} = undef;
return \%hash;
}
my $hash_ref = keylist qw'one two three';
# or
my @key_list = qw'one two three';
my $hash_ref = keylist @key_list;
If you really wanted to pass an array reference:
sub keylist(\@){
my %hash;
@hash{ @{$_[0]} } = undef if @_;
return \%hash;
}
my @key_list = qw'one two three';
my $hash_ref = keylist @key_list;
and another way:
$input = array(
'item1' => 'object1',
'item2' => 'object2',
'item-n' => 'object-n'
);
$output = implode(', ', array_map(
function ($v, $k) {
if(is_array($v)){
return $k.'[]='.implode('&'.$k.'[]=', $v);
}else{
return $k.'='.$v;
}
},
$input,
array_keys($input)
));
or:
$output = implode(', ', array_map(
function ($v, $k) { return sprintf("%s='%s'", $k, $v); },
$input,
array_keys($input)
));
Try:
while [ $stats -gt 300 -o $stats -eq 0 ]
[
is a call to test
. It is not just for grouping, like parentheses in other languages. Check man [
or man test
for more information.
There is no way to avoid inconsistent rounding for prices with x.xx5 as actual value using either multiplication or division. If you need to calculate correct prices client-side you should keep all amounts in cents. This is due to the nature of the internal representation of numeric values in JavaScript. Notice that Excel suffers from the same problems so most people wouldn't notice the small errors caused by this phenomen. However errors may accumulate whenever you add up a lot of calculated values, there is a whole theory around this involving the order of calculations and other methods to minimize the error in the final result. To emphasize on the problems with decimal values, please note that 0.1 + 0.2 is not exactly equal to 0.3 in JavaScript, while 1 + 2 is equal to 3.
<?php echo 'apple'; ?>
is pretty much literally all you need on the server.
as for the JS side, the output of the server-side script is passed as a parameter to the success handler function, so you'd have
success: function(data) {
alert(data); // apple
}
What directory is file.txt in? cron runs jobs in your home directory, so unless your script cd
s somewhere else, that's where it's going to look for/create file.txt.
EDIT: When you refer to a file without specifying its full path (e.g. file.txt
, as opposed to the full path /home/myUser/scripts/file.txt
) in shell, it's taken that you're referring to a file in your current working directory. When you run a script (whether interactively or via crontab), the script's working directory has nothing at all to do with the location of the script itself; instead, it's inherited from whatever ran the script.
Thus, if you cd
(change working directory) to the directory the script's in and then run it, file.txt
will refer to a file in the same directory as the script. But if you don't cd
there first, file.txt
will refer to a file in whatever directory you happen to be in when you ran the script. For instance, if your home directory is /home/myUser, and you open a new shell and immediately run the script (as scripts/test.sh
or /home/myUser/scripts/test.sh
; ./test.sh
won't work), it'll touch the file /home/myUser/file.txt because /home/myUser is your current working directory (and therefore the script's).
When you run a script from cron
, it does essentially the same thing: it runs it with the working directory set to your home directory. Thus all file references in the script are taken relative to your home directory, unless the script cd
s somewhere else or specifies an absolute path to the file.
You can have multiple CSS declarations for the same properties by separating them with commas:
.abc, .xyz {
margin-left: 20px;
}
shell_exec
- Execute command via shell and return the complete output as a string
exec
- Execute an external program.
The difference is that with shell_exec
you get output as a return value.
Apply does the job well, but is quite slow. Using sapply and vapply could be useful. dplyr's rowwise could also be useful Let's see an example of how to do row wise product of any data frame.
a = data.frame(t(iris[1:10,1:3]))
vapply(a, prod, 0)
sapply(a, prod)
Note that assigning to variable before using vapply/sapply/ apply is good practice as it reduces time a lot. Let's see microbenchmark results
a = data.frame(t(iris[1:10,1:3]))
b = iris[1:10,1:3]
microbenchmark::microbenchmark(
apply(b, 1 , prod),
vapply(a, prod, 0),
sapply(a, prod) ,
apply(iris[1:10,1:3], 1 , prod),
vapply(data.frame(t(iris[1:10,1:3])), prod, 0),
sapply(data.frame(t(iris[1:10,1:3])), prod) ,
b %>% rowwise() %>%
summarise(p = prod(Sepal.Length,Sepal.Width,Petal.Length))
)
Have a careful look at how t() is being used
def myfunc(a,b):
c = a.intersection(b)
return bool(c)
bool()
will do something similar to not not
, but more ideomatic and clear.
See ยง6.7.9 Initialization:
21 If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
So, yes both of them work. Note that in C99 a new way of initialization, called designated initialization can be used too:
myStruct _m1 = {.c2 = 0, .c1 = 1};
I ran into this problem, and when I checked out the database directory, there were a number of exp
files (the ibd
and frm
files had been removed). Listing the files to look at their attributes (since the owner already had rw privileges on the files)
lsattr *.exp
-------------e-- foo.exp
-------------e-- bar.exp
Man page says
The 'e' attribute indicates that the file is using extents for mapping the blocks on disk.
It may not be removed using chattr(1).
You actually can chattr -e
these files, but mysql still won't let you drop the database. Removing the files with rm
, however, allows the database to be dropped cleanly.
$this->db->where_in('id', ['20','15','22','42','86']);
Reference: where_in
I was facing same issue with ffmpeg library after merging two Android projects as one project.
Actually issue was arriving due to two different versions of ffmpeg library but they were loaded with same names in memory. One library was placed in JNiLibs while other was inside another library used as module. I was not able to modify the code of module as it was readonly so I renamed the one used in my own code to ffmpegCamera and loaded it in memory with same name.
System.loadLibrary("ffmpegCamera");
This resolved the issue and now both versions of libraries are loading well as separate name and process id in memory.
There is loads of vim tricks but as of now, the one that I really enjoy is Ctrl+A as I happen to be dealing with some st**d code that hard-code array index.
You can use jquery's load function here.
$("#your_element_id").load("file_name.html");
If you need more info, here is the link.
Objective C Solution
NSArray * array = @[@"1", @"2", @"3"];
NSString * stringFromArray = [[array valueForKey:@"description"] componentsJoinedByString:@"-"]; // "1-2-3"
Those who are looking for a solution in Swift
If the array contains strings, you can use the String's join method:
var array = ["1", "2", "3"]
let stringFromArray = "-".join(array) // "1-2-3"
In Swift 2:
var array = ["1", "2", "3"]
let stringFromArray = array.joinWithSeparator("-") // "1-2-3"
In Swift 3 & 4
var array = ["1", "2", "3"]
let stringFromArray = array.joined(separator: "-") // "1-2-3"
if the data is the result of a formula, then it will never be empty (even if you set it to ""
), as having a formula is not the same as an empty cell
There are 2 methods, depending on how static the data is.
The easiest fix is to clear the cells that return empty strings, but that means you will have to fix things if data changes
the other fix involves a little editing of the formula, so instead of setting it equal to ""
, you set it equal to NA()
.
For example, if you have =IF(A1=0,"",B1/A1)
, you would change that to =IF(A1=0,NA(),B1/A1)
.
This will create the gaps you desire, and will also reflect updates to the data so you don't have to keep fixing it every time
Just another option, if you want to use only a cli interface, just use the define
option of webpack. I add the following script in my package.json
:
"build-production": "webpack -p --define process.env.NODE_ENV='\"production\"' --progress --colors"
So I just have to run npm run build-production
.
the window.top
property should be able to give what you need.
E.g.
alert(top.location.href)
Perhaps you have the compiler settings for your IDE set to Java 1.4 mode even if you are using a Java 5 JDK? Otherwise I agree with the other people who already mentioned autoboxing/unboxing.
With something like this:
String mDrawableName = "myappicon";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
Cast the datetime to a date, then GROUP BY using this syntax:
SELECT SUM(foo), DATE(mydate) FROM a_table GROUP BY DATE(a_table.mydate);
Or you can GROUP BY the alias as @orlandu63 suggested:
SELECT SUM(foo), DATE(mydate) DateOnly FROM a_table GROUP BY DateOnly;
Though I don't think it'll make any difference to performance, it is a little clearer.
with open('x.py') as f: s = f.read()
***grins***
In a function:
a += 1
will be interpreted by the compiler as assign to a => Create local variable a
, which is not what you want. It will probably fail with a a not initialized
error since the (local) a has indeed not been initialized:
>>> a = 1
>>> def f():
... a += 1
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
UnboundLocalError: local variable 'a' referenced before assignment
You might get what you want with the (very frowned upon, and for good reasons) global
keyword, like so:
>>> def f():
... global a
... a += 1
...
>>> a
1
>>> f()
>>> a
2
In general however, you should avoid using global variables which become extremely quickly out of hand. And this is especially true for multithreaded programs, where you don't have any synchronization mechanism for your thread1
to know when a
has been modified. In short: threads are complicated, and you cannot expect to have an intuitive understanding of the order in which events are happening when two (or more) threads work on the same value. The language, compiler, OS, processor... can ALL play a role, and decide to modify the order of operations for speed, practicality or any other reason.
The proper way for this kind of thing is to use Python sharing tools (locks and friends), or better, communicate data via a Queue instead of sharing it, e.g. like this:
from threading import Thread
from queue import Queue
import time
def thread1(threadname, q):
#read variable "a" modify by thread 2
while True:
a = q.get()
if a is None: return # Poison pill
print a
def thread2(threadname, q):
a = 0
for _ in xrange(10):
a += 1
q.put(a)
time.sleep(1)
q.put(None) # Poison pill
queue = Queue()
thread1 = Thread( target=thread1, args=("Thread-1", queue) )
thread2 = Thread( target=thread2, args=("Thread-2", queue) )
thread1.start()
thread2.start()
thread1.join()
thread2.join()
Only 1 emulator or device may be open at a time. Make sure you don't have multiple emulators running.
C# does have a preprocessor. It works just slightly differently than that of C++ and C.
Here is a MSDN links - the section on all preprocessor directives.
As neat solution, try-
$ open -a /Applications/Utilities/Terminal.app *.py
or
$ open -b com.apple.terminal *.py
For the shell launched, you can go to Preferences > Shell > set it to exit if no error.
That's it.
This solution worked for me:
The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5
. From the comment you put this needed to be declared elsewhere in your code
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
The error was because you are trying to execute a method that does not exist.
PS C:\Users\Matt> $md5 | gm
TypeName: System.Security.Cryptography.MD5CryptoServiceProvider
Name MemberType Definition
---- ---------- ----------
Clear Method void Clear()
ComputeHash Method byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...
The .ComputeHash()
of $md5.ComputeHash()
was the null valued expression. Typing in gibberish would create the same effect.
PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PowerShell by default allows this to happen as defined its StrictMode
When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.
The answer you want, "1317427200", is achieved if your reference months are January and October. If so, the dates you are looking for are 1970-JAN-01 and 2011-OCT-01, correct?
Then the problem are these numbers you are using for your months.
See, if you check the Calendar API documentation or even the constants provided in there ("Calendar.JANUARY", "Calendar.FEBRUARY" and so on), you'll discover that months start at 0 (being January).
So checking your code, you are passing february and november, which would result in "1317510000".
Best regards.
#pragma once
is based on the full path of the filename. So what you likely have is there are two identical copies of either MyClass.h or Winsock2.h in different directories.
I use this script to check if a file exists (also it handles the cross origin issue):
$.ajax(url, {
method: 'GET',
dataType: 'jsonp'
})
.done(function(response) {
// exists code
}).fail(function(response) {
// doesnt exist
})
Note that the following syntax error is thrown when the file being checked doesn't contain JSON.
Uncaught SyntaxError: Unexpected token <
Technically, the Integrity attribute helps with just that - it enables the proper verification of the data source. That is, it merely allows the browser to verify the numbers in the right source file with the amounts requested by the source file located on the CDN server.
Going a bit deeper, in case of the established encrypted hash value of this source and its checked compliance with a predefined value in the browser - the code executes, and the user request is successfully processed.
Crossorigin attribute helps developers optimize the rates of CDN performance, at the same time, protecting the website code from malicious scripts.
In particular, Crossorigin downloads the program code of the site in anonymous mode, without downloading cookies or performing the authentication procedure. This way, it prevents the leak of user data when you first load the site on a specific CDN server, which network fraudsters can easily replace addresses.
Source: https://yon.fun/what-is-link-integrity-and-crossorigin/
Obviously I'm a little out of season on this question but for the benefit of the next sufferer: I just had this problem and in my case (in contrast to OP who tried the same without success) the fix was to revise php.ini, changing
date.timezone = America/New York
to
date.timezone = America/New_York
That is adding the underscore.
check the following code to call one activity from another.
Intent intent = new Intent(CurrentActivity.this, OtherActivity.class);
CurrentActivity.this.startActivity(intent);
.extends()
create a class which is a child of another class.Child.prototype.__proto__
sets its value to Parent.prototype
.prototype
inherit features from one to another..__proto__
is a getter/setter for Prototype.The express.static
middleware is separate from res.sendFile
, so initializing it with an absolute path to your public
directory won't do anything to res.sendFile
. You need to use an absolute path directly with res.sendFile
. There are two simple ways to do it:
res.sendFile(path.join(__dirname, '../public', 'index1.html'));
res.sendFile('index1.html', { root: path.join(__dirname, '../public') });
Note: __dirname
returns the directory that the currently executing script is in. In your case, it looks like server.js
is in app/
. So, to get to public
, you'll need back out one level first: ../public/index1.html
.
Note: path
is a built-in module that needs to be require
d for the above code to work: var path = require('path');
Functions that use ele.parentNode.removeChild(ele)
won't work for elements you've created but not yet inserted into the HTML
. Libraries like jQuery
and Prototype
wisely use a method like the following to evade that limitation.
_limbo = document.createElement('div');
function deleteElement(ele){
_limbo.appendChild(ele);
_limbo.removeChild(ele);
}
I think JavaScript
works like that because the DOM's original designers held parent/child and previous/next navigation as a higher priority than the DHTML
modifications that are so popular today. Being able to read from one <input type='text'>
and write to another by relative location in the DOM was useful in the mid-90s, a time when the dynamic generation of entire HTML
forms or interactive GUI elements was barely a twinkle in some developer's eye.
Substring and Join methods are usable for this statement.
string no = "12345";
string [] numberArray = new string[no.Length];
int counter = 0;
for (int i = 0; i < no.Length; i++)
{
numberArray[i] = no.Substring(counter, 1); // 1 is split length
counter++;
}
Console.WriteLine(string.Join(" ", numberArray)); //output >>> 0 1 2 3 4 5
SELECT TRIM(ColumnName) FROM dual;
Put this .gitignore
into the folder, then git add .gitignore
.
*
*/
!.gitignore
The *
line tells git to ignore all files in the folder, but !.gitignore
tells git to still include the .gitignore
file. This way, your local repository and any other clones of the repository all get both the empty folder and the .gitignore
it needs.
Edit: May be obvious but also add */
to the .gitignore
to also ignore subfolders.
In Python 3 the following will work. I am using the lower level http.client from the standard library. Also check out section 2 of rfc2617 for details of basic authorization. This code won't check the certificate is valid, but will set up a https connection. See the http.client docs on how to do that.
from http.client import HTTPSConnection
from base64 import b64encode
#This sets up the https connection
c = HTTPSConnection("www.google.com")
#we need to base 64 encode it
#and then decode it to acsii as python 3 stores it as a byte string
userAndPass = b64encode(b"username:password").decode("ascii")
headers = { 'Authorization' : 'Basic %s' % userAndPass }
#then connect
c.request('GET', '/', headers=headers)
#get the response back
res = c.getresponse()
# at this point you could check the status etc
# this gets the page text
data = res.read()
Here is what I did
var domainNames =["fiddle.jshell.net"]; // we replace this by our production domain.
var logger = {
force:false,
original:null,
log:function(obj)
{
var hostName = window.location.hostname;
if(domainNames.indexOf(hostName) > -1)
{
if(window.myLogger.force === true)
{
window.myLogger.original.apply(this,arguments);
}
}else {
window.myLogger.original.apply(this,arguments);
}
},
forceLogging:function(force){
window.myLogger.force = force;
},
original:function(){
return window.myLogger.original;
},
init:function(){
window.myLogger.original = console.log;
console.log = window.myLogger.log;
}
}
window.myLogger = logger;
console.log("this should print like normal");
window.myLogger.init();
console.log("this should not print");
window.myLogger.forceLogging(true);
console.log("this should print now");
Also posted about it here. http://bhavinsurela.com/naive-way-of-overriding-console-log/
void foo() {
/* do some stuff */
if (!condition) {
return;
}
}
You can just use the return keyword just like you would in any other function.
The technical differences between an abstract class and an interface are already listed in the other answers precisely. I want to add an explanation to choose between a class and an interface while writing the code for the sake of object oriented programming.
A class should represent an entity whereas an interface should represent the behavior.
Let's take an example. A computer monitor is an entity and should be represented as a class.
class Monitor{
private int monitorNo;
}
It is designed to provide a display interface to you, so the functionality should be defined by an interface.
interface Display{
void display();
}
There are many other things to consider as explained in the other answers, but this is the most basic thing which most of the people ignore while coding.
Open Git Bash and run the command if you want to completely disable SSL verification.
git config --global http.sslVerify false
Note: This solution may open you to attacks like man-in-the-middle attacks. Therefore turn on verification again as soon as possible:
git config --global http.sslVerify true
For what it's worth, I needed to update the port and scheme for SSL for my RESTFul service. This is what I did. Apologies that it is a bit more that the original question, but hopefully useful to someone.
// Don't forget to add references to System.ServiceModel and System.ServiceModel.Web
using System.ServiceModel;
using System.ServiceModel.Configuration;
var port = 1234;
var isSsl = true;
var scheme = isSsl ? "https" : "http";
var currAssembly = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
Configuration config = ConfigurationManager.OpenExeConfiguration(currAssembly);
ServiceModelSectionGroup serviceModel = ServiceModelSectionGroup.GetSectionGroup(config);
// Get the first endpoint in services. This is my RESTful service.
var endp = serviceModel.Services.Services[0].Endpoints[0];
// Assign new values for endpoint
UriBuilder b = new UriBuilder(endp.Address);
b.Port = port;
b.Scheme = scheme;
endp.Address = b.Uri;
// Adjust design time baseaddress endpoint
var baseAddress = serviceModel.Services.Services[0].Host.BaseAddresses[0].BaseAddress;
b = new UriBuilder(baseAddress);
b.Port = port;
b.Scheme = scheme;
serviceModel.Services.Services[0].Host.BaseAddresses[0].BaseAddress = b.Uri.ToString();
// Setup the Transport security
BindingsSection bindings = serviceModel.Bindings;
WebHttpBindingCollectionElement x =(WebHttpBindingCollectionElement)bindings["webHttpBinding"];
WebHttpBindingElement y = (WebHttpBindingElement)x.ConfiguredBindings[0];
var e = y.Security;
e.Mode = isSsl ? WebHttpSecurityMode.Transport : WebHttpSecurityMode.None;
e.Transport.ClientCredentialType = HttpClientCredentialType.None;
// Save changes
config.Save();
As said above, should be: localStorageService.set('key', 'value');
and localStorageService.get('key');
For those looking a more modern approach, you can use the fetch API
. The following example shows how to download a PDF
file. It is easily done with the following code.
fetch(url, {
body: JSON.stringify(data),
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
})
.then(response => response.blob())
.then(response => {
const blob = new Blob([response], {type: 'application/pdf'});
const downloadUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = downloadUrl;
a.download = "file.pdf";
document.body.appendChild(a);
a.click();
})
I believe this approach to be much easier to understand than other XMLHttpRequest
solutions. Also, it has a similar syntax to the jQuery
approach, without the need to add any additional libraries.
Of course, I would advise checking to which browser you are developing, since this new approach won't work on IE. You can find the full browser compatibility list on the following [link][1].
Important: In this example I am sending a JSON request to a server listening on the given url
. This url
must be set, on my example I am assuming you know this part. Also, consider the headers needed for your request to work. Since I am sending a JSON, I must add the Content-Type
header and set it to application/json; charset=utf-8
, as to let the server know the type of request it will receive.
I ended up using the bootstrap 3 dropdown button, I'm posting my solution here in case it helps someone in future. Adding the bootstrap 3 list-inline to the class for the ul causes it to display in a nicely compact format as well.
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
Select icon <span class="caret"></span>
</button>
<ul class="dropdown-menu list-inline" role="menu">
<li><span class="glyphicon glyphicon-cutlery"></span></li>
<li><span class="glyphicon glyphicon-fire"></span></li>
<li><span class="glyphicon glyphicon-glass"></span></li>
<li><span class="glyphicon glyphicon-heart"></span></li>
</ul>
</div>
I'm using Angular.js so this is the actual code I used:
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
Avatar <span class="caret"></span>
</button>
<ul class="dropdown-menu list-inline" role="menu">
<li ng-repeat="avatar in avatars" ng-click="avatarSelected(avatar)">
<span ng-class="getAvatar(avatar)"></span>
</li>
</ul>
</div>
And in my controller:
$scope.avatars=['cutlery','eye-open','flag','flash','glass','fire','hand-right','heart','heart-empty','leaf','music','send','star','star-empty','tint','tower','tree-conifer','tree-deciduous','usd','user','wrench','time','road','cloud'];
$scope.getAvatar=function(avatar){
return 'glyphicon glyphicon-'+avatar;
};
Use a list comprehension:
[item for item in x if item not in y]
If you want to use the -
infix syntax, you can just do:
class MyList(list):
def __init__(self, *args):
super(MyList, self).__init__(args)
def __sub__(self, other):
return self.__class__(*[item for item in self if item not in other])
you can then use it like:
x = MyList(1, 2, 3, 4)
y = MyList(2, 5, 2)
z = x - y
But if you don't absolutely need list properties (for example, ordering), just use sets as the other answers recommend.
You probably need to chdir to the correct directory before calling the script. This way you can ensure what directory your script is "in" before calling the shell command.
$old_path = getcwd();
chdir('/my/path/');
$output = shell_exec('./script.sh var1 var2');
chdir($old_path);
File.OpenText() always uses an UTF-8 StreamReader implicitly. Create your own StreamReader instance instead and specify the desired encoding. like
using (StreamReader reader = new StreamReader(@"C:\test.txt", Encoding.Default)
{
// ...
}
You can use this as an example of your problem
Map<Integer, String> map = new HashMap<>();
map.put(10, "apple");
map.put(20, "orange");
map.put(30, "banana");
map.put(40, "watermelon");
map.put(50, "dragonfruit");
// split a map into 2 List
List<Integer> resultSortedKey = new ArrayList<>();
List<String> resultValues = map.entrySet().stream()
//sort a Map by key and stored in resultSortedKey
.sorted(Map.Entry.<Integer, String>comparingByKey().reversed())
.peek(e -> resultSortedKey.add(e.getKey()))
.map(x -> x.getValue())
// filter banana and return it to resultValues
.filter(x -> !"banana".equalsIgnoreCase(x))
.collect(Collectors.toList());
resultSortedKey.forEach(System.out::println);
resultValues.forEach(System.out::println);
you must add in your MODULE-LEVEL build.gradle file with:
//module-level build.gradle file
repositories {
maven {
url 'https://maven.google.com'
}
}
see: Google's Maven repository
I have observed that when I use Android Studio 2.3.3 I MUST add repositories{maven{url 'https://maven.google.com'}} in MODULE-LEVEL build.gradle. In the case of Android Studio 3.0.0 there is no need for the addition in module-level build.gradle. It is enough the addition in project-level build.gradle which has been referred to in the other posts here, namely:
//project-level build.gradle file
allprojects {
repositories {
jcenter()
maven {
url 'https://maven.google.com/'
name 'Google'
}
}
}
UPDATE 11-14-2017: The solution, that I present, was valid when I did the post. Since then, there have been various updates (even with respect to the site I refer to), and I do not know if now is valid. For one month I did my work depending on the solution above, until I upgraded to Android Studio 3.0.0
I believe this is what you're looking for. It automatically scaled the video to fit the container.
DEMO: http://jsfiddle.net/t8qhgxuy/
Video need to have height and width always set to 100% of the parent.
HTML:
<div class="one"> CONTENT OVER VIDEO
<video class="video-background" no-controls autoplay src="https://dl.dropboxusercontent.com/u/8974822/cloud-troopers-video.mp4" poster="http://thumb.multicastmedia.com/thumbs/aid/w/h/t1351705158/1571585.jpg"></video>
</div>
<div class="two">
<video class="video-background" no-controls autoplay src="https://dl.dropboxusercontent.com/u/8974822/cloud-troopers-video.mp4" poster="http://thumb.multicastmedia.com/thumbs/aid/w/h/t1351705158/1571585.jpg"></video> CONTENT OVER VIDEO
</div>
CSS:
body {
overflow: scroll;
padding: 60px 20px;
}
.one {
width: 90%;
height: 30vw;
overflow: hidden;
border: 15px solid red;
margin-bottom: 40px;
position: relative;
}
.two{
width: 30%;
height: 300px;
overflow: hidden;
border: 15px solid blue;
position: relative;
}
.video-background { /* class name used in javascript too */
width: 100%; /* width needs to be set to 100% */
height: 100%; /* height needs to be set to 100% */
position: absolute;
left: 0;
top: 0;
z-index: -1;
}
JS:
function scaleToFill() {
$('video.video-background').each(function(index, videoTag) {
var $video = $(videoTag),
videoRatio = videoTag.videoWidth / videoTag.videoHeight,
tagRatio = $video.width() / $video.height(),
val;
if (videoRatio < tagRatio) {
val = tagRatio / videoRatio * 1.02; <!-- size increased by 2% because value is not fine enough and sometimes leaves a couple of white pixels at the edges -->
} else if (tagRatio < videoRatio) {
val = videoRatio / tagRatio * 1.02;
}
$video.css('transform','scale(' + val + ',' + val + ')');
});
}
$(function () {
scaleToFill();
$('.video-background').on('loadeddata', scaleToFill);
$(window).resize(function() {
scaleToFill();
});
});
Wrap your Container in SingleChildScrollView() widget. Then it will not come above when keyboard pops up.
Use document.getElementsByClassName('className').style = your_style
.
var d = document.getElementsByClassName("left1");
d.className = d.className + " otherclass";
Use single quotes for JS strings contained within an html attribute's double quotes
Example
<div class="somelclass"></div>
then document.getElementsByClassName('someclass').style = "NewclassName";
<div class='someclass'></div>
then document.getElementsByClassName("someclass").style = "NewclassName";
This is personal experience.
You can get the PID of a particular process like MySQL by using following commands: ps -e | pgrep mysql
This command will give you the PID of MySQL rocess. e.g, 13954 Now, type following command on terminal. kill -9 13954 This will kill the process of MySQL.
I hade this error when transfering a csv to mssql I converted the columns to DT_NTEXT and some columns on mssql where set to nvarchar(255).
setting them to nvarchar(max) resolved it.
<div id='printarea'>
<p>This is a sample text for printing purpose.</p>
</div>
<input type='button' id='btn' value='Print' onlick="printDiv()">
<p>Do not print.</p>
function printDiv(){
var printContents = document.getElementById("printarea").innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
This Above function should be load on same page.
You can safely remove from a set during iteration with an Iterator object; attempting to modify a set through its API while iterating will break the iterator. the Set class provides an iterator through getIterator().
however, Integer objects are immutable; my strategy would be to iterate through the set and for each Integer i, add i+1 to some new temporary set. When you are finished iterating, remove all the elements from the original set and add all the elements of the new temporary set.
Set<Integer> s; //contains your Integers
...
Set<Integer> temp = new Set<Integer>();
for(Integer i : s)
temp.add(i+1);
s.clear();
s.addAll(temp);
May be this can help other guys: I had the same problem, and after looking with Google I found that can be because of the permissions of the folder... So, you need first to add permissions...
$ chmod 777 share_folder
Then run again
$ sudo mount -t vboxsf D:\share_folder_vm \share_folder
Check the answers here: Error mounting VirtualBox shared folders in an Ubuntu guest...
I tried many scripts but they didn't work for all objects. You can't move clustered objects from one tablespace to another. For that you will have to use expdp, so I will suggest expdp is the best option to move all objects to a different tablespace.
Below is the command:
nohup expdp \"/ as sysdba\" DIRECTORY=test_dir DUMPFILE=users.dmp LOGFILE=users.log TABLESPACES=USERS &
You can check this link for details.
Unexpected end of file
means that something else was expected before the PHP parser reached the end of the script.
Judging from your HUGE file, it's probably that you're missing a closing brace (}
) from an if
statement.
Please at least attempt the following things:
;
in some of your embedded PHP statements, and not in others, ie. <?php echo base_url(); ?>
vs <?php echo $this->layouts->print_includes() ?>
. It's not required, so don't use it (or do, just do one or the other).As of 3/10/2019, Anguar dropped the support of sass. No mater what option you passed to --style
when running ng new
, you always get .scss
files generated. It's a shame that sass support was dropped without any explanation.
You can use Task Scheduler Managed Wrapper:
using System;
using Microsoft.Win32.TaskScheduler;
class Program
{
static void Main(string[] args)
{
// Get the service on the local machine
using (TaskService ts = new TaskService())
{
// Create a new task definition and assign properties
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "Does something";
// Create a trigger that will fire the task at this time every other day
td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });
// Create an action that will launch Notepad whenever the trigger fires
td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));
// Register the task in the root folder
ts.RootFolder.RegisterTaskDefinition(@"Test", td);
// Remove the task we just created
ts.RootFolder.DeleteTask("Test");
}
}
}
Alternatively you can use native API or go for Quartz.NET. See this for details.
I would give the parent an ID, and store the parentID in the child object, so that you can pull information about the parent as needed without creating a parent-owns-child/child-owns-parent loop.
same for Terminator
Ctrl + Shift + V
Look at your terminal key-bindings if any if that doesn't work
Calling JavaScript function on code behind i.e.
On Page_Load
ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);
If you have UpdatePanel
there then try like this
ScriptManager.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);
View Blog Article : How to Call javascript function from code behind in asp.net c#
After following the guide (or using Spring Initializr), I had a WAR that worked on my local computer, but didn't work remote (running on Tomcat).
There was no error message, it just said "Spring servlet initializer was found", but didn't do anything at all.
17-Aug-2016 16:58:13.552 INFO [main] org.apache.catalina.core.StandardEngine.startInternal Starting Servlet Engine: Apache Tomcat/8.5.4
17-Aug-2016 16:58:13.593 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deploying web application archive /opt/tomcat/webapps/ROOT.war
17-Aug-2016 16:58:16.243 INFO [localhost-startStop-1] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
and
17-Aug-2016 16:58:16.301 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log 2 Spring WebApplicationInitializers detected on classpath
17-Aug-2016 16:58:21.471 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log Initializing Spring embedded WebApplicationContext
17-Aug-2016 16:58:25.133 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log ContextListener: contextInitialized()
17-Aug-2016 16:58:25.133 INFO [localhost-startStop-1] org.apache.catalina.core.ApplicationContext.log SessionListener: contextInitialized()
Nothing else happened. Spring Boot just didn't run.
Apparently I compiled the server with Java 1.8, and the remote computer had Java 1.7.
After compiling with Java 1.7, it started working.
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version> <!-- added this line -->
<start-class>myapp.SpringApplication</start-class>
</properties>
For a new document: Settings -> Preferences -> New Document/Default Directory
-> New Document -> Format -> Windows/Mac/Unix
And for an already-open document: Edit -> EOL Conversion
The other option in this particular case would be to type the degree symbol: ยฐ
R seems to handle it fine. Type Option-k on a Mac to get it. Not sure about other platforms.
To clarify, a database created under SQL Server 2008 R2 was being opened in an instance of SQL Server 2008 (the version prior to R2). The solution for me was to simply perform an upgrade installation of SQL Server 2008 R2. I can only speak for the Express edition, but it worked.
Oddly, though, the Web Platform Installer indicated that I had Express R2 installed. The better way to tell is to ask the database server itself:
SELECT @@VERSION
Stackpanel doesn't have built in scrolling mechanism but you can always wrap the StackPanel in a ScrollViewer
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel ... />
</ScrollViewer>
That depends on a lot of factors. Processes are more heavy-weight than threads, and have a higher startup and shutdown cost. Interprocess communication (IPC) is also harder and slower than interthread communication.
Conversely, processes are safer and more secure than threads, because each process runs in its own virtual address space. If one process crashes or has a buffer overrun, it does not affect any other process at all, whereas if a thread crashes, it takes down all of the other threads in the process, and if a thread has a buffer overrun, it opens up a security hole in all of the threads.
So, if your application's modules can run mostly independently with little communication, you should probably use processes if you can afford the startup and shutdown costs. The performance hit of IPC will be minimal, and you'll be slightly safer against bugs and security holes. If you need every bit of performance you can get or have a lot of shared data (such as complex data structures), go with threads.
You've correctly diagnosed your problem, so good job. Once you call into your search code, the for loop just keeps right on going.
I'm a big fan of https://github.com/caolan/async, and it serves me well. Basically with it you'd end up with something like:
var async = require('async')
async.eachSeries(Object.keys(config), function (key, next){
search(config[key].query, function(err, result) { // <----- I added an err here
if (err) return next(err) // <---- don't keep going if there was an error
var json = JSON.stringify({
"result": result
});
results[key] = {
"result": result
}
next() /* <---- critical piece. This is how the forEach knows to continue to
the next loop. Must be called inside search's callback so that
it doesn't loop prematurely.*/
})
}, function(err) {
console.log('iterating done');
});
I hope that helps!
If you're using Blend, to make it extra easy and not have any trouble getting the correct path for the Source attribute, just drag and drop the image from the Project panel onto the designer.
After some more research, it appears, for Mozilla/Firefox, that Array.sort() uses mergesort. See the code here.
There are 2 major differences.
Technical, there are 3 major differences:
First and foremost, Community doesn't have TFS support.
You'll just have to use git (arguable whether this constitutes a disadvantage or whether this actually is a good thing).
Note: This is what MS wrote. Actually, you can check-in&out with TFS as normal, if you have a TFS server in the network. You just cannot use Visual Studio as TFS SERVER.
Second, VS Community is severely limited in its testing capability.
Only unit tests. No Performance tests, no load tests, no performance profiling.
Third, VS Community's ability to create Virtual Environments has been severely cut.
On the other hand, syntax highlighting, IntelliSense, Step-Through debugging, GoTo-Definition, Git-Integration and Build/Publish are really all the features I need, and I guess that applies to a lot of developers.
For all other things, there are tools that do the same job faster, better and cheaper.
If you, like me, anyway use git, do unit testing with NUnit, and use Java-Tools to do Load-Testing on Linux plus TeamCity for CI, VS Community is more than sufficient, technically speaking.
Licensing:
A) If you're an individual developer (no enterprise, no organization), no difference (AFAIK), you can use CommunityEdition like you'd use the paid edition (as long as you don't do subcontracting)
B) You can use CommunityEdition freely for OpenSource (OSI) projects
C) If you're an educational insitution, you can use CommunityEdition freely (for education/classroom use)
D) If you're an enterprise with 250 PCs or users or more than one million US dollars in revenue (including subsidiaries), you are NOT ALLOWED to use CommunityEdition.
E) If you're not an enterprise as defined above, and don't do OSI or education, but are an "enterprise"/organization, with 5 or less concurrent (VS) developers, you can use VS Community freely (but only if you're the owner of the software and sell it, not if you're a subcontractor creating software for a larger enterprise, software which in the end the enterprise will own), otherwise you need a paid edition.
The above does not consitute legal advise.
See also:
https://softwareengineering.stackexchange.com/questions/262916/understanding-visual-studio-community-edition-license
You can use toLocaleString(). This is a javascript method.
var event = new Date("01/02/1993");_x000D_
_x000D_
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };_x000D_
_x000D_
console.log(event.toLocaleString('en', options));_x000D_
_x000D_
// expected output: "Saturday, January 2, 1993"
_x000D_
Almost all formats supported. Have look on this link for more details.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
I had a similar issue, my error was:
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: java.lang.ClassNotFoundException:org.glassfish.jersey.servlet.ServletContainer from [Module "deployment.RESTful_Services_CRUD.war:main" from Service Module Loader]
I use jboss
and glassfish
so I changed the web.xml
to the following:
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
Instead of:
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
Hope this work for you.
Use the correct call: strptime
is a classmethod of the datetime.datetime
class, it's not a function in the datetime
module.
self.date = datetime.datetime.strptime(self.d, "%Y-%m-%d")
As mentioned by Jon Clements in the comments, some people do from datetime import datetime
, which would bind the datetime
name to the datetime
class, and make your initial code work.
To identify which case you're facing (in the future), look at your import statements
import datetime
: that's the module (that's what you have right now).from datetime import datetime
: that's the class.You have two options here.
The individual row simply represents data, so it will not know what row it is located in.
NOTE: As of July 2020, text-overflow: ellipsis
works for <select>
on Chrome
HTML is limited in what it specifies for form controls. That leaves room for operating system and browser makers to do what they think is appropriate on that platform (like the iPhoneโs modal select
which, when open, looks totally different from the traditional pop-up menu).
If it bugs you, you can use a customizable replacement, like Chosen, which looks distinct from the native select
.
Or, file a bug against a major operating system or browser. For all we know, the way text is cut off in select
s might be the result of a years-old oversight that everyone copied, and it might be time for a change.
insert
is better from the point of exception safety.
The expression map[key] = value
is actually two operations:
map[key]
- creating a map element with default value.= value
- copying the value into that element.An exception may happen at the second step. As result the operation will be only partially done (a new element was added into map, but that element was not initialized with value
). The situation when an operation is not complete, but the system state is modified, is called the operation with "side effect".
insert
operation gives a strong guarantee, means it doesn't have side effects (https://en.wikipedia.org/wiki/Exception_safety). insert
is either completely done or it leaves the map in unmodified state.
http://www.cplusplus.com/reference/map/map/insert/:
If a single element is to be inserted, there are no changes in the container in case of exception (strong guarantee).
In most circumstances, I recommend using the <object>
tag to display SVG images. It feels a little unnatural, but it's the most reliable method if you want to provide dynamic effects.
For images without interaction, the <img>
tag or a CSS background can be used.
Inline SVGs or iframes are possible options for some projects, but it's best to avoid <embed>
But if you want to play with SVG stuff like
Go with the embedded one
<svg>
<g>
<path> </path>
</g>
</svg>
Swift 3.1
import UIKit
extension UILabel {
var fontSize: CGFloat {
get {
return self.font.pointSize
}
set {
self.font = UIFont(name: self.font.fontName, size: newValue)!
self.sizeToFit()
}
}
}
I see three possibilities here that will help you insert into your table without making a complete mess but "specifying" a value for the AUTO_INCREMENT column, since you are supplying all the values you can do either one of the following options.
First approach (Supplying NULL):
INSERT INTO test.authors VALUES (
NULL,'1','67','0','0','1','10','0','1','2012-01-03 12:50:49','108929',
'2012-01-03 12:50:59','198963','21','',
'/usr/local/nagios/libexec/check_ping 5','30','0','4.04159',
'0.102','1','PING WARNING -DUPLICATES FOUND! Packet loss = 0%, RTA = 2.86 ms',
'','rta=2.860000m=0%;80;100;0'
);
Second approach (Supplying '' {Simple quotes / apostrophes} although it will give you a warning):
INSERT INTO test.authors VALUES (
'','1','67','0','0','1','10','0','1','2012-01-03 12:50:49','108929',
'2012-01-03 12:50:59','198963','21','',
'/usr/local/nagios/libexec/check_ping 5','30','0','4.04159',
'0.102','1','PING WARNING -DUPLICATES FOUND! Packet loss = 0%, RTA = 2.86 ms',
'','rta=2.860000m=0%;80;100;0'
);
Third approach (Supplying default):
INSERT INTO test.authors VALUES (
default,'1','67','0','0','1','10','0','1','2012-01-03 12:50:49','108929',
'2012-01-03 12:50:59','198963','21','',
'/usr/local/nagios/libexec/check_ping 5','30','0','4.04159',
'0.102','1','PING WARNING -DUPLICATES FOUND! Packet loss = 0%, RTA = 2.86 ms',
'','rta=2.860000m=0%;80;100;0'
);
Either one of these examples should suffice when inserting into that table as long as you include all the values in the same order as you defined them when creating the table.
Use the %
wildcard, which matches any number of characters.
SELECT * FROM Accounts WHERE Username LIKE '%query%'
As you updated your question, here's an obtrustive example:
window.onload = function()
{
var div = document.getElementById("mydiv");
div.style.cursor = 'pointer';
div.onmouseover = function()
{
div.style.background = "#ff00ff";
};
}
Of course, be mindful that your program will only be useful in english speaking countries if you detect dates this way. You might want to consider:
Set<String> dayNames = Calendar.getInstance()
.getDisplayNames(Calendar.DAY_OF_WEEK,
Calendar.SHORT,
Locale.getDefault())
.keySet();
From there you can use .startsWith or .matches or whatever other method that others have mentioned above. This way you get the default locale for the jvm. You could always pass in the locale (and maybe default it to the system locale if it's null) as well to be more robust.
Warning you get is done by compiler, not by library (or utility method).
Simplest way using Jackson directly would be:
HashMap<String,Object> props;
// src is a File, InputStream, String or such
props = new ObjectMapper().readValue(src, new TypeReference<HashMap<String,Object>>() {});
// or:
props = (HashMap<String,Object>) new ObjectMapper().readValue(src, HashMap.class);
// or even just:
@SuppressWarnings("unchecked") // suppresses typed/untype mismatch warnings, which is harmless
props = new ObjectMapper().readValue(src, HashMap.class);
Utility method you call probably just does something similar to this.
This is used for data binding purposes in Spring MVC
. Let you have a jsp having a form element in it e.g
on
JSP
<form:form action="test-example" method="POST" commandName="testModelAttribute"> </form:form>
(Spring Form method, Simple form element can also be used)
On Controller Side
@RequestMapping(value = "/test-example", method = RequestMethod.POST)
public ModelAndView testExample(@ModelAttribute("testModelAttribute") TestModel testModel, Map<String, Object> map,...) {
}
Now when you will submit the form the form fields values will be available to you.
You can just use wildcards in the predicate (after IF, WHERE or ON):
@mainstring LIKE '%' + @substring + '%'
or in this specific case
' ' + @mainstring + ' ' LIKE '% ME[., ]%'
(Put the spaces in the quoted string if you're looking for the whole word, or leave them out if ME can be part of a bigger word).
In my case, using MAC OS X 10.11 and Android 2.0, and by doing exactly what Aqib Mumtaz has explained.
But, each time, I had this message : "A problem occurred configuring project ':app'. > Cannot evaluate module xxx : Configuration with name 'default' not found."
I found that the reason of this message is that Android 2.0 doesn't allow to create a library directly. So, I have decided first to create an app projet and then to modify the build.gradle in order to transform it as a library.
This solution doesn't work, because a Library project is very different than an app project.
So, I have resolved my problem like this :
Then continue with the solution proposed by Aqib Mumtaz.
As a result, your library source will be shared without needing to duplicate source files each time (it was an heresy for me!)
Hoping that this help you.
This was changing for me beginning with .NET 4.7.2 and it was due to the SameSite property on the session cookie. See here for more info: https://devblogs.microsoft.com/aspnet/upcoming-samesite-cookie-changes-in-asp-net-and-asp-net-core/
The default value changed to "Lax" and started breaking things. I changed it to "None" and things worked as expected.
Just in case you are lazy like me, here's a solution amalgamated from this and other answers on SO.
set @orig_lat=37.46;
set @orig_long=-122.25;
set @bounding_distance=1;
SELECT
*
,((ACOS(SIN(@orig_lat * PI() / 180) * SIN(`lat` * PI() / 180) + COS(@orig_lat * PI() / 180) * COS(`lat` * PI() / 180) * COS((@orig_long - `long`) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS `distance`
FROM `cities`
WHERE
(
`lat` BETWEEN (@orig_lat - @bounding_distance) AND (@orig_lat + @bounding_distance)
AND `long` BETWEEN (@orig_long - @bounding_distance) AND (@orig_long + @bounding_distance)
)
ORDER BY `distance` ASC
limit 25;
Download numpy-1.9.2+mkl-cp27-none-win32.whl from http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy .
Copy the file to C:\Python27\Scripts
Run cmd from the above location and type
pip install numpy-1.9.2+mkl-cp27-none-win32.whl
You will hopefully get the below output:
Processing c:\python27\scripts\numpy-1.9.2+mkl-cp27-none-win32.whl
Installing collected packages: numpy
Successfully installed numpy-1.9.2
Hope that works for you.
EDIT 1
Adding @oneleggedmule 's suggestion:
You can also run the following command in the cmd:
pip2.7 install numpy-1.9.2+mkl-cp27-none-win_amd64.whl
Basically, writing pip alone also works perfectly (as in the original answer). Writing the version 2.7 can also be done for the sake of clarity or specification.
IMO the most convenient way to do such tasks is to use a glob tool. Here's a glob package for node.js. Install with
npm install glob
Then use wild card to match filenames (example taken from package's website)
var glob = require("glob")
// options is optional
glob("**/*.js", options, function (er, files) {
// files is an array of filenames.
// If the `nonull` option is set, and nothing
// was found, then files is ["**/*.js"]
// er is an error object or null.
})
You can only break
a block scope if you label it. For example:
myBlock: {
var a = 0;
break myBlock;
a = 1; // this is never run
};
a === 0;
You cannot break a block scope from within a function in the scope. This means you can't do stuff like:
foo: { // this doesn't work
(function() {
break foo;
}());
}
You can do something similar though with functions:
function myFunction() {myFunction:{
// you can now use break myFunction; instead of return;
}}
There are two ways
Using split
Then just parse that string
var domain;
//find & remove protocol (http, ftp, etc.) and get domain
if (url.indexOf('://') > -1) {
domain = url.split('/')[2];
} if (url.indexOf('//') === 0) {
domain = url.split('/')[2];
} else {
domain = url.split('/')[0];
}
//find & remove port number
domain = domain.split(':')[0];
Using Regex
var r = /:\/\/(.[^/]+)/;
"http://stackoverflow.com/questions/5343288/get-url".match(r)[1]
=> stackoverflow.com
Hope this helps
Yes you can sort using query method in Spring Data.
Ex:ascending order or descending order by using the value of the id field.
Code:
public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
public findAllByOrderByIdAsc();
}
alternative solution:
@Repository
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDAO studentDao;
@Override
public List<Student> findAll() {
return studentDao.findAll(orderByIdAsc());
}
private Sort orderByIdAsc() {
return new Sort(Sort.Direction.ASC, "id")
.and(new Sort(Sort.Direction.ASC, "name"));
}
}
Spring Data Sorting: Sorting
ArrayList values = ... // your values
Set uniqueValues = new HashSet(values); //now unique
I also like zzzeek's answer but Andre is correct that a queue is required to prevent garbling. I had some luck with the pipe, but did see garbling which is somewhat expected. Implementing it turned out to be harder than I thought, particularly due to running on Windows, where there are some additional restrictions about global variables and stuff (see: How's Python Multiprocessing Implemented on Windows?)
But, I finally got it working. This example probably isn't perfect, so comments and suggestions are welcome. It also does not support setting the formatter or anything other than the root logger. Basically, you have to reinit the logger in each of the pool processes with the queue and set up the other attributes on the logger.
Again, any suggestions on how to make the code better are welcome. I certainly don't know all the Python tricks yet :-)
import multiprocessing, logging, sys, re, os, StringIO, threading, time, Queue
class MultiProcessingLogHandler(logging.Handler):
def __init__(self, handler, queue, child=False):
logging.Handler.__init__(self)
self._handler = handler
self.queue = queue
# we only want one of the loggers to be pulling from the queue.
# If there is a way to do this without needing to be passed this
# information, that would be great!
if child == False:
self.shutdown = False
self.polltime = 1
t = threading.Thread(target=self.receive)
t.daemon = True
t.start()
def setFormatter(self, fmt):
logging.Handler.setFormatter(self, fmt)
self._handler.setFormatter(fmt)
def receive(self):
#print "receive on"
while (self.shutdown == False) or (self.queue.empty() == False):
# so we block for a short period of time so that we can
# check for the shutdown cases.
try:
record = self.queue.get(True, self.polltime)
self._handler.emit(record)
except Queue.Empty, e:
pass
def send(self, s):
# send just puts it in the queue for the server to retrieve
self.queue.put(s)
def _format_record(self, record):
ei = record.exc_info
if ei:
dummy = self.format(record) # just to get traceback text into record.exc_text
record.exc_info = None # to avoid Unpickleable error
return record
def emit(self, record):
try:
s = self._format_record(record)
self.send(s)
except (KeyboardInterrupt, SystemExit):
raise
except:
self.handleError(record)
def close(self):
time.sleep(self.polltime+1) # give some time for messages to enter the queue.
self.shutdown = True
time.sleep(self.polltime+1) # give some time for the server to time out and see the shutdown
def __del__(self):
self.close() # hopefully this aids in orderly shutdown when things are going poorly.
def f(x):
# just a logging command...
logging.critical('function number: ' + str(x))
# to make some calls take longer than others, so the output is "jumbled" as real MP programs are.
time.sleep(x % 3)
def initPool(queue, level):
"""
This causes the logging module to be initialized with the necessary info
in pool threads to work correctly.
"""
logging.getLogger('').addHandler(MultiProcessingLogHandler(logging.StreamHandler(), queue, child=True))
logging.getLogger('').setLevel(level)
if __name__ == '__main__':
stream = StringIO.StringIO()
logQueue = multiprocessing.Queue(100)
handler= MultiProcessingLogHandler(logging.StreamHandler(stream), logQueue)
logging.getLogger('').addHandler(handler)
logging.getLogger('').setLevel(logging.DEBUG)
logging.debug('starting main')
# when bulding the pool on a Windows machine we also have to init the logger in all the instances with the queue and the level of logging.
pool = multiprocessing.Pool(processes=10, initializer=initPool, initargs=[logQueue, logging.getLogger('').getEffectiveLevel()] ) # start worker processes
pool.map(f, range(0,50))
pool.close()
logging.debug('done')
logging.shutdown()
print "stream output is:"
print stream.getvalue()
r = 13 + 7.*rand(100,1);
Where 100,1 is the size of the desidered vector
How about using this method?
HashSet<Integer> zipcodeSet = new HashSet<Integer>(Arrays.asList(zipcodeList));
duplicates = zipcodeSet.size()!=zipcodeList.length;
java.sql.Timestamp
is a subclass of java.util.Date
. So, just upcast it.
Date dtStart = resultSet.getTimestamp("dtStart");
Date dtEnd = resultSet.getTimestamp("dtEnd");
Using SimpleDateFormat
and creating Joda DateTime
should be straightforward from this point on.
You can use Boost numeric_cast
.
This throws an exception if the source value is out of range of the destination type, but it doesn't detect loss of precision when converting to double
.
Whatever function you use, though, you should decide what you want to happen in the case where the value in the size_t
is greater than INT_MAX
. If you want to detect it use numeric_cast
or write your own code to check. If you somehow know that it cannot possibly happen then you could use static_cast
to suppress the warning without the cost of a runtime check, but in most cases the cost doesn't matter anyway.
Union Operation is combined result of the Vertical Aggregate of the rows, Union Operation is combined result of the Horizontal Aggregate of the Columns.
If you include a font file (otf, ttf, etc.) in your package, you can use the font in your application via the method described here:
Oracle Java SE 6: java.awt.Font
There is a tutorial available from Oracle that shows this example:
try {
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf")));
} catch (IOException|FontFormatException e) {
//Handle exception
}
I would probably wrap this up in some sort of resource loader though as to not reload the file from the package every time you want to use it.
An answer more closely related to your original question would be to install the font as part of your application's installation process. That process will depend on the installation method you choose. If it's not a desktop app you'll have to look into the links provided.
Here's my pure pathlib
recursive directory unlinker:
from pathlib import Path
def rmdir(directory):
directory = Path(directory)
for item in directory.iterdir():
if item.is_dir():
rmdir(item)
else:
item.unlink()
directory.rmdir()
rmdir(Path("dir/"))
public int this[int index]
{
get => values[index];
}
[DllImport ( "Shlwapi.dll", CharSet = CharSet.Auto )]
public static extern long StrFormatByteSize (
long fileSize
, [MarshalAs ( UnmanagedType.LPTStr )] StringBuilder buffer
, int bufferSize );
/// <summary>
/// Converts a numeric value into a string that represents the number expressed as a size value in bytes, kilobytes, megabytes, or gigabytes, depending on the size.
/// </summary>
/// <param name="filelength">The numeric value to be converted.</param>
/// <returns>the converted string</returns>
public static string StrFormatByteSize (long filesize) {
StringBuilder sb = new StringBuilder( 11 );
StrFormatByteSize( filesize, sb, sb.Capacity );
return sb.ToString();
}
From: http://www.pinvoke.net/default.aspx/shlwapi/StrFormatByteSize.html
you can unpack your tuples and get only the first element using a list comprehension:
l = [(1, u'abc'), (2, u'def')]
[f for f, *_ in l]
output:
[1, 2]
this will work no matter how many elements you have in a tuple:
l = [(1, u'abc'), (2, u'def', 2, 4, 5, 6, 7)]
[f for f, *_ in l]
output:
[1, 2]
Essentially you want to add code to the Calculate
event of the relevant Worksheet.
In the Project window of the VBA editor, double-click the sheet you want to add code to and from the drop-downs at the top of the editor window, choose 'Worksheet' and 'Calculate' on the left and right respectively.
Alternatively, copy the code below into the editor of the sheet you want to use:
Private Sub Worksheet_Calculate()
If Sheets("MySheet").Range("A1").Value > 0.5 Then
MsgBox "Over 50%!", vbOKOnly
End If
End Sub
This way, every time the worksheet recalculates it will check to see if the value is > 0.5 or 50%.
IntelliJ has intellisense and refactoring support from code into jspx documents.
I think this should work .. :)
<input type="checkbox" name="Days[]" value="Daily">Daily<br>
<input type="checkbox" name="Days[]" value="Sunday">Sunday<br>
I tried all above options but was still getting error, in my case issue was I have not setup gradle installation directory in eclipse, following worked:
eclipse -> Window -> Preferences -> Gradle -> "Select Local Installation Directory"
Click on Browse button and provide path.
Even though question is answered, thought to share in case somebody else is facing similar issue.
Cheers !
In my case, I was able to use a simple insert statement to bulk insert many rows into TABLE_A using just one column from TABLE_B and getting the other data elsewhere (sequence and a hardcoded value) :
INSERT INTO table_a (
id,
column_a,
column_b
)
SELECT
table_a_seq.NEXTVAL,
b.name,
123
FROM
table_b b;
Result:
ID: NAME: CODE:
1, JOHN, 123
2, SAM, 123
3, JESS, 123
etc
This is commonly caused by running out of file descriptors.
There is the systems total file descriptor limit, what do you get from the command:
sysctl fs.file-nr
This returns counts of file descriptors:
<in_use> <unused_but_allocated> <maximum>
To find out what a users file descriptor limit is run the commands:
sudo su - <username>
ulimit -Hn
To find out how many file descriptors are in use by a user run the command:
sudo lsof -u <username> 2>/dev/null | wc -l
So now if you are having a system file descriptor limit issue you will need to edit your /etc/sysctl.conf file and add, or modify it it already exists, a line with fs.file-max and set it to a value large enough to deal with the number of file descriptors you need and reboot.
fs.file-max = 204708
If the server's certificate is self-signed, then this is working as designed and you will have to import the server's certificate into your keystore.
Assuming the server certificate is signed by a well-known CA, this is happening because the set of CA certificates available to a modern browser is much larger than the limited set that is shipped with the JDK/JRE.
The EasySSL solution given in one of the posts you mention just buries the error, and you won't know if the server has a valid certificate.
You must import the proper Root CA into your keystore to validate the certificate. There's a reason you can't get around this with the stock SSL code, and that's to prevent you from writing programs that behave as if they are secure but are not.
I had a similar problem where i have to center the toolTip. React setState in componentDidUpdate did put me in infinite loop, i tried condition it worked. But i found using in ref callback gave me simpler and clean solution, if you use inline function for ref callback you will face the null problem for every component update. So use function reference in ref callback and set the state there, which will initiate the re-render
This should solve your problem: FB Share button/dialog documentation Genereally speaking you can use either normal HTML code and style it with CSS, or you can use Javascript.
Here is an example:
<a href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fparse.com" target="_blank" rel="noopener">
<img class="YOUR_FB_CSS_STYLING_CLASS" src="img/YOUR_FB_ICON_IMAGE.png" width="22px" height="22px" alt="Share on Facebook">
</a>
Replace https%3A%2F%2Fparse.com, YOUR_FB_CSS_STYLING_CLASS and YOUR_FB_ICON_IMAGE.png with your own choices and you should be ok.
Note: For the sake of your users' security use the HTTPS link to FB, like in the a's href attribute.
On your device Go To Settings -> Dev Settings, And Select "Allow OEM Unlock" As shown on Unlock Your Bootloader
At least this worked for me on my MotoE 4G.
If your OS is Windows, then it is very simple. When you install Android Studio, adb.exe is located in the following folder:
C:\Users\**your-user-name**\AppData\Local\Android\Sdk\platform-tools
Copy the path and paste in your environment variables.
Open your terminal and type: adb
it's done!
These commands worked for me
sudo npm cache clean --force
sudo npm cache verify
sudo npm i npm@latest -g
It would be great to use axios for the api request which supports cancellation, interceptors etc. Along with axios, l use react-redux for state management and redux-saga/redux-thunk for the side effects.
This question is over a decade old, but it looks like it gets a good amount of traffic, so I wanted to post an alternative using modern C++ features that I haven't seen anywhere else.
This solution uses CRTP and SFINAE to perform static dispatching. That, in itself, is nothing new, but all such implementations I've found lack strict signature checking for "overrides." This implementation requires that the "overriding" method signature exactly matches that of the "overridden" method. This behavior more closely resembles that of virtual functions, while also allowing us to effectively overload and "override" a static method.
Note that I put override in quotes because, strictly speaking, we're not technically overriding anything. Instead, we're calling a dispatch method X with signature Y that forwards all of its arguments to T::X, where T is to the first type among a list of types such that T::X exists with signature Y. This list of types considered for dispatching can be anything, but generally would include a default implementation class and the derived class.
Implementation
#include <experimental/type_traits>
template <template <class...> class Op, class... Types>
struct dispatcher;
template <template <class...> class Op, class T>
struct dispatcher<Op, T> : std::experimental::detected_t<Op, T> {};
template <template <class...> class Op, class T, class... Types>
struct dispatcher<Op, T, Types...>
: std::experimental::detected_or_t<
typename dispatcher<Op, Types...>::type, Op, T> {};
// Helper to convert a signature to a function pointer
template <class Signature> struct function_ptr;
template <class R, class... Args> struct function_ptr<R(Args...)> {
using type = R (*)(Args...);
};
// Macro to simplify creation of the dispatcher
// NOTE: This macro isn't smart enough to handle creating an overloaded
// dispatcher because both dispatchers will try to use the same
// integral_constant type alias name. If you want to overload, do it
// manually or make a smarter macro that can somehow put the signature in
// the integral_constant type alias name.
#define virtual_static_method(name, signature, ...) \
template <class VSM_T> \
using vsm_##name##_type = std::integral_constant< \
function_ptr<signature>::type, &VSM_T::name>; \
\
template <class... VSM_Args> \
static auto name(VSM_Args&&... args) \
{ \
return dispatcher<vsm_##name##_type, __VA_ARGS__>::value( \
std::forward<VSM_Args>(args)...); \
}
Example Usage
#include <iostream>
template <class T>
struct Base {
// Define the default implementations
struct defaults {
static std::string alpha() { return "Base::alpha"; };
static std::string bravo(int) { return "Base::bravo"; }
};
// Create the dispatchers
virtual_static_method(alpha, std::string(void), T, defaults);
virtual_static_method(bravo, std::string(int), T, defaults);
static void where_are_the_turtles() {
std::cout << alpha() << std::endl; // Derived::alpha
std::cout << bravo(1) << std::endl; // Base::bravo
}
};
struct Derived : Base<Derived> {
// Overrides Base::alpha
static std::string alpha(){ return "Derived::alpha"; }
// Does not override Base::bravo because signatures differ (even though
// int is implicitly convertible to bool)
static std::string bravo(bool){ return "Derived::bravo"; }
};
int main() {
Derived::where_are_the_turtles();
}
SELECT NAME AS ObjectName
,schema_name(o.schema_id) AS SchemaName, OBJECT_NAME(o.parent_object_id) as TableName
,type
,o.type_desc
FROM sys.objects o
WHERE o.is_ms_shipped = 0
AND o.NAME LIKE '%UniqueID%'
ORDER BY o.NAME
Came across this problem myself and in the end wrote a small library cloneable-ts that provides an abstract class, which adds a clone method to any class extending it. The abstract class borrows the Deep Copy Function described in the accepted answer by Fenton only replacing copy = {};
with copy = Object.create(originalObj)
to preserve the class of the original object. Here is an example of using the class.
import {Cloneable, CloneableArgs} from 'cloneable-ts';
// Interface that will be used as named arguments to initialize and clone an object
interface PersonArgs {
readonly name: string;
readonly age: number;
}
// Cloneable abstract class initializes the object with super method and adds the clone method
// CloneableArgs interface ensures that all properties defined in the argument interface are defined in class
class Person extends Cloneable<TestArgs> implements CloneableArgs<PersonArgs> {
readonly name: string;
readonly age: number;
constructor(args: TestArgs) {
super(args);
}
}
const a = new Person({name: 'Alice', age: 28});
const b = a.clone({name: 'Bob'})
a.name // Alice
b.name // Bob
b.age // 28
Or you could just use the Cloneable.clone
helper method:
import {Cloneable} from 'cloneable-ts';
interface Person {
readonly name: string;
readonly age: number;
}
const a: Person = {name: 'Alice', age: 28};
const b = Cloneable.clone(a, {name: 'Bob'})
a.name // Alice
b.name // Bob
b.age // 28
If you have a code like
int arr[10] = {0, 5, 3, 64};
, and you want to append or add a value to next index, you can simply add it by typing a[5] = 5
.
The main advantage of doing it like this is you can add or append a value to an any index not required to be continued one, like if I want to append the value 8
to index 9, I can do it by the above concept prior to filling up before indices.
But in python by using list.append()
you can do it by continued indices.
By implementing the SpinnerAdapter for your adapter object i use interested.getItem(i).toString()
A pull request is just that: a request to merge one branch into another.
Your pull request doesn't "contain" anything, it's just a marker saying "please merge this branch into that one".
The set of changes the PR shows in the web UI is just the changes between the target branch and your feature branch. To modify your pull request, you must modify your feature branch, probably with a force push to the feature branch.
In your case, you'll probably want to amend your commit. Not sure about your exact situation, but some combination of interactive rebase and add -p
should sort you out.
Try this:
Encoding iso = Encoding.GetEncoding("ISO-8859-1");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(Message);
byte[] isoBytes = Encoding.Convert(utf8,iso,utfBytes);
string msg = iso.GetString(isoBytes);
<asp:GridView ID="gv_Document" CssClass="gridstyle" runat="server" OnRowDataBound="gv_Document_RowDataBound" AutoGenerateColumns="false" DataKeyNames="SourceGUID,Source,FilePath" ShowHeaderWhenEmpty="false" OnRowDeleting="gv_Document_RowDeleting">
<Columns>
<asp:BoundField HeaderText="ItemID" DataField="ItemID" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
<asp:BoundField HeaderText="SourceGUID" DataField="SourceGUID" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
<asp:BoundField HeaderText="Source" DataField="Source" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:HyperLink ID="hyperLink" runat="server" Target="_blank" NavigateUrl='<%# Bind("FilePath")%>'
Text='<%# Bind("FileName")%>'> </asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Type" DataField="FileExtension" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
<asp:BoundField HeaderText="Content type" DataField="FileMimeType" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
<asp:BoundField HeaderText="File Path" DataField="FilePath" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
<asp:CommandField ShowDeleteButton="True" DeleteText="Delete" />
</Columns>
Use this code to disable delete button in gridview from code behind.
protected void gv_Document_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
((LinkButton)e.Row.Cells[7].Controls[0]).Visible = false;
}
}
Just to complement m59's correct answer, here is a working jsfiddle:
<body ng-app='myApp'>
<div>
<button my-directive>Click Me!</button>
</div>
<h1>{{2+3}}</h1>
</body>
In my notepad++ I press
Ctrl+A = To select all words
Ctrl+U = To convert lowercase
Ctrl+Shift+U = To convert uppercase
Hope to help you!
I put together a quick solution for anyone wanting to create hover popups without CSS using the onmouseover and onmouseout behaviors.
<div style="position:relative;width:100px;background:#ddffdd;overflow:hidden;" onmouseover="this.style.overflow='';" onmouseout="this.style.overflow='hidden';">first hover<div style="width:100px;position:absolute;top:5px;left:110px;background:white;border:1px solid gray;">stuff inside</div></div>
Try
<IfModule mod_rewrite.so>
...
...
...
</IfModule>
instead of <IfModule mod_rewrite.c>
For me the following command did the trick
sudo apt install php-mbstring
To plot text on a ggplot
you use the geom_text
. But I find it helpful to summarise the data first using ddply
dfl <- ddply(df, .(x), summarize, y=length(x))
str(dfl)
Since the data is pre-summarized, you need to remember to change add the stat="identity"
parameter to geom_bar
:
ggplot(dfl, aes(x, y=y, fill=x)) + geom_bar(stat="identity") +
geom_text(aes(label=y), vjust=0) +
opts(axis.text.x=theme_blank(),
axis.ticks=theme_blank(),
axis.title.x=theme_blank(),
legend.title=theme_blank(),
axis.title.y=theme_blank()
)
I am using Spring STS 3.8.3. I had a similar problem. I fixed it by using information from this thread And also by fixing some maven settings. click Spring Tool Suite -> Preferences -> Maven and uncheck the box that says "Do not automatically update dependencies from remote depositories" Also I checked the boxes that say "Download Artifact Sources" and "download Artifact javadoc".
The <f:viewParam>
manages the setting, conversion and validation of GET parameters. It's like the <h:inputText>
, but then for GET parameters.
The following example
<f:metadata>
<f:viewParam name="id" value="#{bean.id}" />
</f:metadata>
does basically the following:
id
.required
, validator
and converter
attributes and nest a <f:converter>
and <f:validator>
in it like as with <h:inputText>
)#{bean.id}
value, or if the value
attribute is absent, then set it as request attribtue on name id
so that it's available by #{id}
in the view.So when you open the page as foo.xhtml?id=10
then the parameter value 10
get set in the bean this way, right before the view is rendered.
As to validation, the following example sets the param to required="true"
and allows only values between 10 and 20. Any validation failure will result in a message being displayed.
<f:metadata>
<f:viewParam id="id" name="id" value="#{bean.id}" required="true">
<f:validateLongRange minimum="10" maximum="20" />
</f:viewParam>
</f:metadata>
<h:message for="id" />
You can use the <f:viewAction>
for this.
<f:metadata>
<f:viewParam id="id" name="id" value="#{bean.id}" required="true">
<f:validateLongRange minimum="10" maximum="20" />
</f:viewParam>
<f:viewAction action="#{bean.onload}" />
</f:metadata>
<h:message for="id" />
with
public void onload() {
// ...
}
The <f:viewAction>
is however new since JSF 2.2 (the <f:viewParam>
already exists since JSF 2.0). If you can't upgrade, then your best bet is using <f:event>
instead.
<f:event type="preRenderView" listener="#{bean.onload}" />
This is however invoked on every request. You need to explicitly check if the request isn't a postback:
public void onload() {
if (!FacesContext.getCurrentInstance().isPostback()) {
// ...
}
}
When you would like to skip "Conversion/Validation failed" cases as well, then do as follows:
public void onload() {
FacesContext facesContext = FacesContext.getCurrentInstance();
if (!facesContext.isPostback() && !facesContext.isValidationFailed()) {
// ...
}
}
Using <f:event>
this way is in essence a workaround/hack, that's exactly why the <f:viewAction>
was introduced in JSF 2.2.
You can "pass-through" the view parameters in navigation links by setting includeViewParams
attribute to true
or by adding includeViewParams=true
request parameter.
<h:link outcome="next" includeViewParams="true">
<!-- Or -->
<h:link outcome="next?includeViewParams=true">
which generates with the above <f:metadata>
example basically the following link
<a href="next.xhtml?id=10">
with the original parameter value.
This approach only requires that next.xhtml
has also a <f:viewParam>
on the very same parameter, otherwise it won't be passed through.
The <f:viewParam>
can also be used in combination with "plain HTML" GET forms.
<f:metadata>
<f:viewParam id="query" name="query" value="#{bean.query}" />
<f:viewAction action="#{bean.search}" />
</f:metadata>
...
<form>
<label for="query">Query</label>
<input type="text" name="query" value="#{empty bean.query ? param.query : bean.query}" />
<input type="submit" value="Search" />
<h:message for="query" />
</form>
...
<h:dataTable value="#{bean.results}" var="result" rendered="#{not empty bean.results}">
...
</h:dataTable>
With basically this @RequestScoped
bean:
private String query;
private List<Result> results;
public void search() {
results = service.search(query);
}
Note that the <h:message>
is for the <f:viewParam>
, not the plain HTML <input type="text">
! Also note that the input value displays #{param.query}
when #{bean.query}
is empty, because the submitted value would otherwise not show up at all when there's a validation or conversion error. Please note that this construct is invalid for JSF input components (it is doing that "under the covers" already).
Or you can use this javascript
$(function () {
$("#projectKey").change(function () {
alert($('#projectKey option:selected').text());
});
});
The clone is a shallow copy of the array.
This test code prints:
[1, 2] / [1, 2] [100, 200] / [100, 2]
because the MutableInteger
is shared in both arrays as objects[0]
and objects2[0]
, but you can change the reference objects[1]
independently from objects2[1]
.
import java.util.Arrays;
public class CloneTest {
static class MutableInteger {
int value;
MutableInteger(int value) {
this.value = value;
}
@Override
public String toString() {
return Integer.toString(value);
}
}
public static void main(String[] args) {
MutableInteger[] objects = new MutableInteger[] {
new MutableInteger(1), new MutableInteger(2) };
MutableInteger[] objects2 = objects.clone();
System.out.println(Arrays.toString(objects) + " / " +
Arrays.toString(objects2));
objects[0].value = 100;
objects[1] = new MutableInteger(200);
System.out.println(Arrays.toString(objects) + " / " +
Arrays.toString(objects2));
}
}
The logical OR '||' automatically short circuits if it meets a true condition once.
false || false || true || false = true, stops at second condition.
On the other hand, the logical AND '&&' automatically short circuits if it meets a false condition once.
false && true && true && true = false, stops at first condition.
pip install --trusted-host=pypi.org --trusted-host=files.pythonhosted.org opencv-python
.If you'd like to truncate a file to zero bytes, useful for clearing logs, try this:
:> file.log
Or, in order to avoid modifying slowFunc
(say you don't have access to the source code for instance):
var source = new CancellationTokenSource(); //original code
source.Token.Register(CancelNotification); //original code
source.CancelAfter(TimeSpan.FromSeconds(1)); //original code
var completionSource = new TaskCompletionSource<object>(); //New code
source.Token.Register(() => completionSource.TrySetCanceled()); //New code
var task = Task<int>.Factory.StartNew(() => slowFunc(1, 2), source.Token); //original code
//original code: await task;
await Task.WhenAny(task, completionSource.Task); //New code
You can also use nice extension methods from https://github.com/StephenCleary/AsyncEx and have it looks as simple as:
await Task.WhenAny(task, source.Token.AsTask());
If the goal is to randomly shuffle each column, some of the above answers don't work since the columns are shuffled jointly (this preserves inter-column correlations). Others require installing a package. Yet a one-liner exist:
df2 = lapply(df1, function(x) { sample(x) })
Use the keyword size
instead of fontsize
.
You can change this using SQL query. Here is sql query to change the sequence of column.
ALTER TABLE table name
CHANGE COLUMN `column1` `column1` INT(11) NOT NULL COMMENT '' AFTER `column2`;
First Solution:
You can call start activity inside your adapter like this:
public class YourAdapter extends Adapter {
private Context context;
public YourAdapter(Context context) {
this.context = context;
}
public View getView(...){
View v;
v.setOnClickListener(new OnClickListener() {
void onClick() {
context.startActivity(...);
}
});
}
}
Second Solution:
You can call onClickListener
of your button out of the YourAdapter
class. Follow these steps:
Craete an interface like this:
public YourInterface{
public void yourMethod(args...);
}
Then inside your adapter:
public YourAdapter extends BaseAdapter{
private YourInterface listener;
public YourAdapter (Context context, YourInterface listener){
this.listener = listener;
this.context = context;
}
public View getView(...){
View v;
v.setOnClickListener(new OnClickListener() {
void onClick() {
listener.yourMethod(args);
}
});
}
And where you initiate yourAdapter will be like this:
YourAdapter adapter = new YourAdapter(getContext(), (args) -> {
startActivity(...);
});
This link can be useful for you.
I got this error with my own code. My problem was that I had duplicate keys in the config file.
Just a note. If you want to compare a string with ""
,in your case, use
If LEN(str) > 0 Then
or even just
If LEN(str) Then
instead.
The concept for all these providers is much simpler than it initially appears. If you dissect a provider you and pull out the different parts it becomes very clear.
To put it simply each one of these providers is a specialized version of the other, in this order: provider
> factory
> value
/ constant
/ service
.
So long the provider does what you can you can use the provider further down the chain which would result in writing less code. If it doesn't accomplish what you want you can go up the chain and you'll just have to write more code.
This image illustrates what I mean, in this image you will see the code for a provider, with the portions highlighted showing you which portions of the provider could be used to create a factory, value, etc instead.
(source: simplygoodcode.com)
For more details and examples from the blog post where I got the image from go to: http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/
We use blat to do this all the time in our environment. I use it as well to connect to Gmail with Stunnel. Here's the params to send a file
blat -to [email protected] -server smtp.example.com -f [email protected] -subject "subject" -body "body" -attach c:\temp\file.txt
Or you can put that file in as the body
blat c:\temp\file.txt -to [email protected] -server smtp.example.com -f [email protected] -subject "subject"
Add this to your web config and change the catalog name which is your database name:
<connectionStrings>
<add name="MyConnectionString" connectionString="Data Source=SERGIO-DESKTOP\SQLEXPRESS;Initial Catalog=YourDatabaseName;Integrated Security=True;"/></connectionStrings>
Reference System.Configuration assembly in your project.
Here is how you retrieve connection string from the config file:
System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
Perhaps you should check NLS_DATE_FORMAT
and use the date string conforming the format.
Or you can use to_date
function within the INSERT
statement, like the following:
insert into visit
values(123456,
to_date('19-JUN-13', 'dd-mon-yy'),
to_date('13-AUG-13 12:56 A.M.', 'dd-mon-yyyy hh:mi A.M.'));
Additionally, Oracle DATE
stores date and time information together.
In my experience, the most friendly way of dealing with this is to have a function that converts a string into a table of values.
There are many splitter functions available on the web, you'll easily find one for whatever if your flavour of SQL.
You can then do...
SELECT * FROM table WHERE id IN (SELECT id FROM split(@list_of_ids))
Or
SELECT * FROM table INNER JOIN (SELECT id FROM split(@list_of_ids)) AS list ON list.id = table.id
(Or similar)
For those of you who have this problem with PHP 5.6, you can use the following command:
yum install php56w-pgsql
For a list of more package names for PHP 5.6, open the following link and scroll down to packages: