I was inspired by Labithiotis's express-list-routes, but I wanted an overview of all my routes and brute urls in one go, and not specify a router, and figure out the prefix each time. Something I came up with was to simply replace the app.use function with my own function which stores the baseUrl and given router. From there I can print any table of all my routes.
NOTE this works for me because I declare my routes in a specific routes file (function) which gets passed in the app object, like this:
// index.js
[...]
var app = Express();
require(./config/routes)(app);
// ./config/routes.js
module.exports = function(app) {
// Some static routes
app.use('/users', [middleware], UsersRouter);
app.use('/users/:user_id/items', [middleware], ItemsRouter);
app.use('/otherResource', [middleware], OtherResourceRouter);
}
This allows me to pass in another 'app' object with a fake use function, and I can get ALL the routes. This works for me (removed some error checking for clarity, but still works for the example):
// In printRoutes.js (or a gulp task, or whatever)
var Express = require('express')
, app = Express()
, _ = require('lodash')
// Global array to store all relevant args of calls to app.use
var APP_USED = []
// Replace the `use` function to store the routers and the urls they operate on
app.use = function() {
var urlBase = arguments[0];
// Find the router in the args list
_.forEach(arguments, function(arg) {
if (arg.name == 'router') {
APP_USED.push({
urlBase: urlBase,
router: arg
});
}
});
};
// Let the routes function run with the stubbed app object.
require('./config/routes')(app);
// GRAB all the routes from our saved routers:
_.each(APP_USED, function(used) {
// On each route of the router
_.each(used.router.stack, function(stackElement) {
if (stackElement.route) {
var path = stackElement.route.path;
var method = stackElement.route.stack[0].method.toUpperCase();
// Do whatever you want with the data. I like to make a nice table :)
console.log(method + " -> " + used.urlBase + path);
}
});
});
This full example (with some basic CRUD routers) was just tested and printed out:
GET -> /users/users
GET -> /users/users/:user_id
POST -> /users/users
DELETE -> /users/users/:user_id
GET -> /users/:user_id/items/
GET -> /users/:user_id/items/:item_id
PUT -> /users/:user_id/items/:item_id
POST -> /users/:user_id/items/
DELETE -> /users/:user_id/items/:item_id
GET -> /otherResource/
GET -> /otherResource/:other_resource_id
POST -> /otherResource/
DELETE -> /otherResource/:other_resource_id
Using cli-table I got something like this:
+--------------------------------+
¦ ¦ => Users ¦
+--------+-----------------------¦
¦ GET ¦ /users/users ¦
+--------+-----------------------¦
¦ GET ¦ /users/users/:user_id ¦
+--------+-----------------------¦
¦ POST ¦ /users/users ¦
+--------+-----------------------¦
¦ DELETE ¦ /users/users/:user_id ¦
+--------------------------------+
+-----------------------------------------+
¦ ¦ => Items ¦
+--------+--------------------------------¦
¦ GET ¦ /users/:user_id/items/ ¦
+--------+--------------------------------¦
¦ GET ¦ /users/:user_id/items/:item_id ¦
+--------+--------------------------------¦
¦ PUT ¦ /users/:user_id/items/:item_id ¦
+--------+--------------------------------¦
¦ POST ¦ /users/:user_id/items/ ¦
+--------+--------------------------------¦
¦ DELETE ¦ /users/:user_id/items/:item_id ¦
+-----------------------------------------+
+--------------------------------------------+
¦ ¦ => OtherResources ¦
+--------+-----------------------------------¦
¦ GET ¦ /otherResource/ ¦
+--------+-----------------------------------¦
¦ GET ¦ /otherResource/:other_resource_id ¦
+--------+-----------------------------------¦
¦ POST ¦ /otherResource/ ¦
+--------+-----------------------------------¦
¦ DELETE ¦ /otherResource/:other_resource_id ¦
+--------------------------------------------+
Which kicks ass.
Try to use the fleqn
document class option.
\documentclass[fleqn]{article}
(See also http://en.wikibooks.org/wiki/LaTeX/Basics for a list of other options.)
This was the easiest solution that I found.
Select Table
Press ALT + F1
Scroll and view constraint names
Then the query is simple:
ALTER TABLE [Table]
DROP CONSTRAINT [Constraint]
For SwiftUI
If you are making your own TextView using UIViewRepresentable
and want to control the padding, in your makeUIView
function, simply do:
uiTextView.textContainerInset = UIEdgeInsets(top: 10, left: 18, bottom: 0, right: 18)
or whatever you want.
Try this:
Select Name, ELT(Age-12,'Thirteen','Fourteen','Fifteen','Sixteen',
'Seventeen','Eighteen','Nineteen','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult') AS AgeBracket FROM Person
<div>
<p class="some_class">lohrem text (it will be of red color )</p>
<div>
<p class="some_class">lohrem text (it will NOT be of red color)</p>
</div>
<p class="some_class">lohrem text (it will be of red color )</p>
</div>
css
div > p.some_class{
color:red;
}
All the direct children that are <p>
with .some_class
would get the style applied to them.
Check that your index is really datetime
, not str
Can be helpful:
data.index = pd.to_datetime(data['Index']).values
If you want to use SQL Server Management Studio, you want to install the full Oracle client, not the Instant Client. The full Oracle client is on the same download page as the Oracle database. Assuming that you are installing on a 64-bit version of Windows, I expect you want the "Oracle Database 11g Release 2 Client (11.2.0.1.0) for Microsoft Windows (x64)" download. This is several hundred MB rather than a couple of MB for the Instant Client.
If file = open(filename, encoding="utf8")
doesn't work, try
file = open(filename, errors="ignore")
, if you want to remove unneeded characters.
All the answers above couldn't solve the problem in my case. My ImageView
was placed in a customized UITableViewCell
. Therefore I had also call the layoutIfNeeded()
method from here. Example:
class NameTableViewCell:UITableViewCell,UITextFieldDelegate { ...
override func awakeFromNib() {
self.layoutIfNeeded()
profileImageView.layoutIfNeeded()
profileImageView.isUserInteractionEnabled = true
let square = profileImageView.frame.size.width < profileImageView.frame.height ? CGSize(width: profileImageView.frame.size.width, height: profileImageView.frame.size.width) : CGSize(width: profileImageView.frame.size.height, height: profileImageView.frame.size.height)
profileImageView.addGestureRecognizer(tapGesture)
profileImageView.layer.cornerRadius = square.width/2
profileImageView.clipsToBounds = true;
}
Avoid using strcat
in C code. The cleanest and, most importantly, the safest way is to use snprintf
:
char buf[256];
snprintf(buf, sizeof buf, "%s%s%s%s", str1, str2, str3, str4);
Some commenters raised an issue that the number of arguments may not match the format string and the code will still compile, but most compilers already issue a warning if this is the case.
Minor update in @Joran's code.
Using the code below, you can avoid the ambiguity and only get the unique of two columns:
dat <- data.frame(id=c(1,1,3), id2=c(1,1,4) ,somevalue=c("x","y","z"))
dat[row.names(unique(dat[,c("id", "id2")])), c("id", "id2")]
In SQL Server vNext this will be built in with the STRING_AGG function, read more about it here: https://msdn.microsoft.com/en-us/library/mt790580.aspx
Changed to:
SELECT FORMAT(SA.[RequestStartDate],'dd/MM/yyyy') as 'Service Start Date', SA.[RequestEndDate] as 'Service End Date', FROM (......)SA WHERE......
Have no idea which SQL engine you are using, for other SQL engine, CONVERT can be used in SELECT statement to change the format in the form you needed.
You need to:
implements Comparable<Animal>
to the class declaration; andint compareTo( Animal a )
method to perform the comparisons.Like this:
public class Animal implements Comparable<Animal>{
public String name;
public int year_discovered;
public String population;
public Animal(String name, int year_discovered, String population){
this.name = name;
this.year_discovered = year_discovered;
this.population = population;
}
public String toString(){
String s = "Animal name: "+ name+"\nYear Discovered: "+year_discovered+"\nPopulation: "+population;
return s;
}
@Override
public int compareTo( final Animal o) {
return Integer.compare(this.year_discovered, o.year_discovered);
}
}
I believe for databases which support listagg function, you can do:
select id, issue, customfield, parentkey, listagg(stingvalue, ',') within group (order by id)
from jira.customfieldvalue
where customfield = 12534 and issue = 19602
group by id, issue, customfield, parentkey
The format is as follows:
MINUTE (0-59), HOUR (0-23), DAY (1-31), MONTH (1-12), DAY OF THE WEEK (0-6)
The letter H, representing the word Hash can be inserted instead of any of the values. It will calculate the parameter based on the hash code of you project name.
This is so that if you are building several projects on your build machine at the same time, let’s say midnight each day, they do not all start their build execution at the same time. Each project starts its execution at a different minute depending on its hash code.
You can also specify the value to be between numbers, i.e. H(0,30) will return the hash code of the project where the possible hashes are 0-30.
Examples:
Start build daily at 08:30 in the morning, Monday - Friday: 30 08 * * 1-5
Weekday daily build twice a day, at lunchtime 12:00 and midnight 00:00, Sunday to Thursday: 00 0,12 * * 0-4
Start build daily in the late afternoon between 4:00 p.m. - 4:59 p.m. or 16:00 -16:59 depending on the projects hash: H 16 * * 1-5
Start build at midnight: @midnight or start build at midnight, every Saturday: 59 23 * * 6
Every first of every month between 2:00 a.m. - 02:30 a.m.: H(0,30) 02 01 * *
My solution is this:
$tempDate = '2012-07-10';
echo date('l', strtotime( $tempDate));
Output is: Tuesday
$tempDate = '2012-07-10';
echo date('D', strtotime( $tempDate));
Output is: Tue
To get around the problems explained by eyquem, you could use the copy
module to return a tuple containing (reversed) copies of the values, via a function:
from copy import copy
def swapper(x, y):
return (copy(y), copy(x))
Same function as a lambda
:
swapper = lambda x, y: (copy(y), copy(x))
Then, assign those to the desired names, like this:
x, y = swapper(y, x)
NOTE: if you wanted to you could import/use deepcopy
instead of copy
.
You could use $
extraction:
class(aframe$a1)
[1] "numeric"
or the double square bracket:
class(aframe[["a1"]])
[1] "numeric"
Go to facebook developer dashboard Select settings -> select WEB(for website) -> Add platform Add your site URL.
This should resolve your issue.
Just to add my two cents: In working with both JavaScript and PHP a few years back, I've become accustomed to using single quotes so I can type the escape character ('') without having to escape it as well. I usually used it when typing raw strings with file paths, etc.
Anyhow, my convention ended up becoming the use of single quotes on identifier-type raw strings, such as if (typeof s == 'string') ...
(in which escape characters would never be used - ever), and double quotes for texts, such as "Hey, what's up?". I also use single quotes in comments as a typographical convention to show identifier names. This is just a rule of thumb, and I break off only when needed, such as when typing HTML strings '<a href="#"> like so <a>'
(though you could reverse the quotes here also). I'm also aware that, in the case of JSON, double quotes are used for the names - but outside that, personally, I prefer the single quotes when escaping is never required for the text between the quotes - like document.createElement('div')
.
The bottom line is, and as some have mentioned/alluded to, to pick a convention, stick with it, and only deviate when necessary.
Go to view and press "Switch to scale mode" which will adjust the virtual screen when you adjust the application.
An easy way to get the max and min value in an array is as follows. This has been explained at get max & min values in array
var myarray = [5,8,2,4,11,7,3];
// Function to get the Max value in Array
Array.max = function( array ){
return Math.max.apply( Math, array );
};
// Function to get the Min value in Array
Array.min = function( array ){
return Math.min.apply( Math, array );
};
// Usage
alert(Array.max(myarray));
alert(Array.min(myarray));
I had the same issue, and I uncomment extension=pdo_sqlite
and ran the migration
and everything worked fine.
Use setDataAndType on the Intent
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(newVideoPath), "video/mp4");
startActivity(intent);
Use "video/mp4" as MIME or use "video/*" if you don't know the type.
Go to your desired perspective. Go to 'Window->show view' menu.
If you see logcat there, click it and you are done.
Else, click on 'other' (at the bottom), chose 'Android'->logcat.
Hope that helps :-)
If I'm not wrong starting from version 1.5 SVN can track moved files\folders. In TortoiseSVN use can move file via drag&drop.
write this to see your commits
git log --oneline
copy the name of the commit you want to go back to. then write:
git checkout "name of the commit"
when you do this, the files of that commit will be replaced with your current files. then you can do whatever you want to these and once you're done, you can write the following command to extract the current files into another newly created branch so whatever you make doesn't have any danger for the previous branch that you extracted a commit from
git checkout -b "name of a branch to extract the files to"
right now, you have the content of a specified commit, into another branch .
<script type="text/javascript">
function idleTimer() {
var t;
//window.onload = resetTimer;
window.onmousemove = resetTimer; // catches mouse movements
window.onmousedown = resetTimer; // catches mouse movements
window.onclick = resetTimer; // catches mouse clicks
window.onscroll = resetTimer; // catches scrolling
window.onkeypress = resetTimer; //catches keyboard actions
function logout() {
window.location.href = 'logout.php'; //Adapt to actual logout script
}
function reload() {
window.location = self.location.href; //Reloads the current page
}
function resetTimer() {
clearTimeout(t);
t = setTimeout(logout, 1800000); // time is in milliseconds (1000 is 1 second)
t= setTimeout(reload, 300000); // time is in milliseconds (1000 is 1 second)
}
}
idleTimer();
</script>
IF you are using Android Studio 3+ This will work: android:theme="@style/Theme.AppCompat.NoActionBar"
@android:style/Theme.NoTitleBar will not support in new API and force you app close.
To disable the "Show Entries" label, add the code dom: 'Bfrtip' or you can add "bInfo": false
$('#example').DataTable({
dom: 'Bfrtip'
})
There is one more ability to achieve a desired results: command trap
. It can be used to clean-up purposes for example.
On my Ubuntu VM, with 1048 MB total RAM, java -XX:+PrintFlagsFinal -version | grep HeapSize
printed : uintx MaxHeapSize := 266338304
, which is approx 266MB and is 1/4th of my total RAM.
I used the following code, it's working!
using System.Data.OleDb;
using System.IO;
using System.Text.RegularExpressions;
private void btopen_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog openFileDialog1 = new OpenFileDialog(); //create openfileDialog Object
openFileDialog1.Filter = "XML Files (*.xml; *.xls; *.xlsx; *.xlsm; *.xlsb) |*.xml; *.xls; *.xlsx; *.xlsm; *.xlsb";//open file format define Excel Files(.xls)|*.xls| Excel Files(.xlsx)|*.xlsx|
openFileDialog1.FilterIndex = 3;
openFileDialog1.Multiselect = false; //not allow multiline selection at the file selection level
openFileDialog1.Title = "Open Text File-R13"; //define the name of openfileDialog
openFileDialog1.InitialDirectory = @"Desktop"; //define the initial directory
if (openFileDialog1.ShowDialog() == DialogResult.OK) //executing when file open
{
string pathName = openFileDialog1.FileName;
fileName = System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
DataTable tbContainer = new DataTable();
string strConn = string.Empty;
string sheetName = fileName;
FileInfo file = new FileInfo(pathName);
if (!file.Exists) { throw new Exception("Error, file doesn't exists!"); }
string extension = file.Extension;
switch (extension)
{
case ".xls":
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
break;
case ".xlsx":
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
break;
default:
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
break;
}
OleDbConnection cnnxls = new OleDbConnection(strConn);
OleDbDataAdapter oda = new OleDbDataAdapter(string.Format("select * from [{0}$]", sheetName), cnnxls);
oda.Fill(tbContainer);
dtGrid.DataSource = tbContainer;
}
}
catch (Exception)
{
MessageBox.Show("Error!");
}
}
Your declaration is int ttTreeInsert(int value);
However, your definition/implementation is
ttTree::ttTreeInsert(int value)
{
}
Notice that the return type int
is missing in the implementation. Instead it should be
int ttTree::ttTreeInsert(int value)
{
return 1; // or some valid int
}
There are two solutions posted on that page. The one with lower votes I would recommend if possible.
If you are using HTML5 then it is perfectly valid to put a div
inside of a
. As long as the div doesn't also contain some other specific elements like other link tags.
<a href="Music.html">
<div id="music" class="nav">
Music I Like
</div>
</a>
The solution you are confused about actually makes the link as big as its container div. To make it work in your example you just need to add position: relative
to your div. You also have a small syntax error which is that you have given the span a class instead of an id. You also need to put your span inside the link because that is what the user is clicking on. I don't think you need the z-index
at all from that example.
div { position: relative; }
.hyperspan {
position:absolute;
width:100%;
height:100%;
left:0;
top:0;
}
<div id="music" class="nav">Music I Like
<a href="http://www.google.com">
<span class="hyperspan"></span>
</a>
</div>
When you give absolute
positioning to an element it bases its location and size after the first parent it finds that is relatively positioned. If none, then it uses the document. By adding relative
to the parent div you tell the span to only be as big as that.
How about this:
from pandas import *
idx = Int64Index([171, 174, 173])
df = DataFrame(index = idx, data =([1,2,3]))
print df
It gives me:
0
171 1
174 2
173 3
Is this what you are looking for?
I just want to throw this answer in the mix, intended as a reminder that – given the right conditions – you sometimes don't need to overthink the issue at hand. What you want might be achievable with flex: wrap
and max-width
instead of :nth-child
.
ul {
display: flex;
flex-wrap: wrap;
justify-content: center;
max-width: 420px;
list-style-type: none;
background-color: tomato;
margin: 0 auto;
padding: 0;
}
li {
display: inline-block;
background-color: #ccc;
border: 1px solid #333;
width: 23px;
height: 23px;
text-align: center;
font-size: 1rem;
line-height: 1.5;
margin: 0.2rem;
flex-shrink: 0;
}
_x000D_
<div class="root">
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>G</li>
<li>H</li>
<li>I</li>
<li>J</li>
<li>K</li>
<li>L</li>
<li>M</li>
<li>N</li>
<li>O</li>
<li>P</li>
<li>Q</li>
<li>R</li>
<li>S</li>
<li>T</li>
<li>U</li>
<li>V</li>
<li>W</li>
<li>X</li>
<li>Y</li>
<li>Z</li>
</ul>
</div>
_x000D_
i had the same problem and just easy solve it make sure the package name for package in mainfest tag inside manifest.xml file and the applicationId in application tag inside gradle app level file has the same package name
in manifest.xml
package="com.example.work"
in gradle app level
applicationId "com.example.work"
hope it help
This works for DLLs locked by other processes. This routine will not find out for example that a text file is locked by a word process.
C#:
using System.Management;
using System.IO;
static class Module1
{
static internal ArrayList myProcessArray = new ArrayList();
private static Process myProcess;
public static void Main()
{
string strFile = "c:\\windows\\system32\\msi.dll";
ArrayList a = getFileProcesses(strFile);
foreach (Process p in a) {
Debug.Print(p.ProcessName);
}
}
private static ArrayList getFileProcesses(string strFile)
{
myProcessArray.Clear();
Process[] processes = Process.GetProcesses;
int i = 0;
for (i = 0; i <= processes.GetUpperBound(0) - 1; i++) {
myProcess = processes(i);
if (!myProcess.HasExited) {
try {
ProcessModuleCollection modules = myProcess.Modules;
int j = 0;
for (j = 0; j <= modules.Count - 1; j++) {
if ((modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) == 0)) {
myProcessArray.Add(myProcess);
break; // TODO: might not be correct. Was : Exit For
}
}
}
catch (Exception exception) {
}
//MsgBox(("Error : " & exception.Message))
}
}
return myProcessArray;
}
}
VB.Net:
Imports System.Management
Imports System.IO
Module Module1
Friend myProcessArray As New ArrayList
Private myProcess As Process
Sub Main()
Dim strFile As String = "c:\windows\system32\msi.dll"
Dim a As ArrayList = getFileProcesses(strFile)
For Each p As Process In a
Debug.Print(p.ProcessName)
Next
End Sub
Private Function getFileProcesses(ByVal strFile As String) As ArrayList
myProcessArray.Clear()
Dim processes As Process() = Process.GetProcesses
Dim i As Integer
For i = 0 To processes.GetUpperBound(0) - 1
myProcess = processes(i)
If Not myProcess.HasExited Then
Try
Dim modules As ProcessModuleCollection = myProcess.Modules
Dim j As Integer
For j = 0 To modules.Count - 1
If (modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) = 0) Then
myProcessArray.Add(myProcess)
Exit For
End If
Next j
Catch exception As Exception
'MsgBox(("Error : " & exception.Message))
End Try
End If
Next i
Return myProcessArray
End Function
End Module
It is a tradition to use Turbo C for graphic in C/C++. But it’s also a pain in the neck. We are using Code::Blocks IDE, which will ease out our work.
Steps to run graphics code in CodeBlocks:
To test the setting copy paste run following code:
#include <graphics.h>
int main( )
{
initwindow(400, 300, "First Sample");
circle(100, 50, 40);
while (!kbhit( ))
{
delay(200);
}
return 0;
}
Here is a complete setup instruction for Code::Blocks
I'm using db2 7.1 and SQuirrel. This is the only query that worked for me.
select * from SYSIBM.tables where table_schema = 'my_schema' and table_type = 'BASE TABLE';
Okay, I know this is an old question, but I made a super-efficient url parser so I thought I'd share it.
As you can see, the structure of the function is very odd, but it's for efficiency. No prototype functions are used, the string doesn't get iterated more than once, and no character is processed more than necessary.
function getDomain(url) {
var dom = "", v, step = 0;
for(var i=0,l=url.length; i<l; i++) {
v = url[i]; if(step == 0) {
//First, skip 0 to 5 characters ending in ':' (ex: 'https://')
if(i > 5) { i=-1; step=1; } else if(v == ':') { i+=2; step=1; }
} else if(step == 1) {
//Skip 0 or 4 characters 'www.'
//(Note: Doesn't work with www.com, but that domain isn't claimed anyway.)
if(v == 'w' && url[i+1] == 'w' && url[i+2] == 'w' && url[i+3] == '.') i+=4;
dom+=url[i]; step=2;
} else if(step == 2) {
//Stop at subpages, queries, and hashes.
if(v == '/' || v == '?' || v == '#') break; dom += v;
}
}
return dom;
}
This is what Wikipedia says about finally clause:
More common is a related clause (finally, or ensure) that is executed whether an exception occurred or not, typically to release resources acquired within the body of the exception-handling block.
Let's dissect your program.
try {
System.out.print(1);
q();
}
So, 1
will be output into the screen, then q()
is called. In q()
, an exception is thrown. The exception is then caught by Exception y
but it does nothing. A finally clause is then executed (it has to), so, 3
will be printed to screen. Because (in method q()
there's an exception thrown in the finally clause, also q()
method passes the exception to the parent stack (by the throws Exception
in the method declaration) new Exception()
will be thrown and caught by catch ( Exception i )
, MyExc2
exception will be thrown (for now add it to the exception stack), but a finally in the main
block will be executed first.
So in,
catch ( Exception i ) {
throw( new MyExc2() );
}
finally {
System.out.print(2);
throw( new MyExc1() );
}
A finally clause is called...(remember, we've just caught Exception i
and thrown MyExc2
) in essence, 2
is printed on screen...and after the 2
is printed on screen, a MyExc1
exception is thrown. MyExc1
is handled by the public static void main(...)
method.
Output:
"132Exception in thread main MyExc1"
Lecturer is correct! :-)
In essence, if you have a finally in a try/catch clause, a finally will be executed (after catching the exception before throwing the caught exception out)
npm install google-closure-library --save
require("google-closure-library");
goog.require('goog.crypt.base64');
var result =goog.crypt.base64.encodeByteArray(Uint8Array.of(1,83,27,99,102,66));
console.log(result);
$node index.js
would write AVMbY2Y= to the console.
var valKeyDown;
var valKeyUp;
function integerOnly(e) {
e = e || window.event;
var code = e.which || e.keyCode;
if (!e.ctrlKey) {
var arrIntCodes1 = new Array(96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 8, 9, 116); // 96 TO 105 - 0 TO 9 (Numpad)
if (!e.shiftKey) { //48 to 57 - 0 to 9
arrIntCodes1.push(48); //These keys will be allowed only if shift key is NOT pressed
arrIntCodes1.push(49); //Because, with shift key (48 to 57) events will print chars like @,#,$,%,^, etc.
arrIntCodes1.push(50);
arrIntCodes1.push(51);
arrIntCodes1.push(52);
arrIntCodes1.push(53);
arrIntCodes1.push(54);
arrIntCodes1.push(55);
arrIntCodes1.push(56);
arrIntCodes1.push(57);
}
var arrIntCodes2 = new Array(35, 36, 37, 38, 39, 40, 46);
if ($.inArray(e.keyCode, arrIntCodes2) != -1) {
arrIntCodes1.push(e.keyCode);
}
if ($.inArray(code, arrIntCodes1) == -1) {
return false;
}
}
return true;
}
$('.integerOnly').keydown(function (event) {
valKeyDown = this.value;
return integerOnly(event);
});
$('.integerOnly').keyup(function (event) { //This is to protect if user copy-pastes some character value ,..
valKeyUp = this.value; //In that case, pasted text is replaced with old value,
if (!new RegExp('^[0-9]*$').test(valKeyUp)) { //which is stored in 'valKeyDown' at keydown event.
$(this).val(valKeyDown); //It is not possible to check this inside 'integerOnly' function as,
} //one cannot get the text printed by keydown event
}); //(that's why, this is checked on keyup)
$('.integerOnly').bind('input propertychange', function(e) { //if user copy-pastes some character value using mouse
valKeyUp = this.value;
if (!new RegExp('^[0-9]*$').test(valKeyUp)) {
$(this).val(valKeyDown);
}
});
It is most likely that you got your repo's SSH URL wrong.
To confirm, go to your repository on Github and click the clone or download button
. Then click the use SSH
link.
Now copy your official repo's SSH link. Mine looked like this - [email protected]:borenho/que-ay.git
You can now do git remote add origin [email protected]:borenho/que-ay.git
if you didn't have origin
yet.
If you had set origin
before, change it by using git remote set-url origin [email protected]:borenho/que-ay.git
Now push with git push -u origin master
I've got the same error. I have been trying to fixing this by setting higher permission to account running SQL Client service, however it didnt help. The problem was that I run MS Sql Management studio just within my account. So, next time... assure that you are running it as Run as Administrator, if using Win7 with UAC enabled.
The database registers its service name(s) with the listener when it starts up. If it is unable to do so then it tries again periodically - so if the listener starts after the database then there can be a delay before the service is recognised.
If the database isn't running, though, nothing will have registered the service, so you shouldn't expect the listener to know about it - lsnrctl status
or lsnrctl services
won't report a service that isn't registered yet.
You can start the database up without the listener; from the Oracle account and with your ORACLE_HOME
, ORACLE_SID
and PATH
set you can do:
sqlplus /nolog
Then from the SQL*Plus prompt:
connect / as sysdba
startup
Or through the Grid infrastructure, from the grid account, use the srvctl start database
command:
srvctl start database -d db_unique_name [-o start_options] [-n node_name]
You might want to look at whether the database is set to auto-start in your oratab
file, and depending on what you're using whether it should have started automatically. If you're expecting it to be running and it isn't, or you try to start it and it won't come up, then that's a whole different scenario - you'd need to look at the error messages, alert log, possibly trace files etc. to see exactly why it won't start, and if you can't figure it out, maybe ask on Database Adminsitrators rather than on Stack Overflow.
If the database can't see +DATA
then ASM may not be running; you can see how to start that here; or using srvctl start asm
. As the documentation says, make sure you do that from the grid home, not the database home.
PDB is an abbreviation for Program Data Base. As the name suggests, it is a repository (persistent storage such as databases) to maintain information required to run your program in debug mode. It contains many important relevant information required while you debug your code (in Visual Studio), for e.g. at what points you have inserted break points where you expect the debugger to break in Visual Studio.
This is the reason why many times Visual Studio fails to hit the break points if you remove the *.pdb
files from your debug folders. Visual Studio debugger is also able to tell you the precise line number of code file at which an exception occurred in a stack trace with the help of *.pdb
files. So effectively pdb files are really a boon to developers while debugging a program.
Generally it is not recommended to exclude the generation of *.pdb
files. From production release stand-point what you should be doing is create the pdb files but don't ship them to customer site in product installer. Preserve all the generated PDB files on to a symbol server from where it can be used/referenced in future if required. Specially for cases when you debug issues like process crash. When you start analysing the crash dump files and if your original *.pdb
files created during the build process are not preserved then Visual Studio will not be able to make out the exact line of code which is causing crash.
If you still want to disable generation of *.pdb
files altogether for any release then go to properties of the project -> Build Tab -> Click on Advanced button -> Choose none
from "Debug Info" drop-down box -> press OK as shown in the snapshot below.
Note: This setting will have to be done separately for "Debug" and "Release" build configurations.
Try Below Simple Ruby Magics :)
(1..x).each { |n| puts n }
x.times { |n| puts n }
1.upto(x) { |n| print n }
You need to parse the string you are sending from javascript object to the JSON object
var json=$.parseJSON(data);
Following answer can help in this and other similar situations like synchronous AJAX call -
Working example
waitForMe().then(function(intentsArr){
console.log('Finally, I can execute!!!');
},
function(err){
console.log('This is error message.');
})
function waitForMe(){
// Returns promise
console.log('Inside waitForMe');
return new Promise(function(resolve, reject){
if(true){ // Try changing to 'false'
setTimeout(function(){
console.log('waitForMe\'s function succeeded');
resolve();
}, 2500);
}
else{
setTimeout(function(){
console.log('waitForMe\'s else block failed');
resolve();
}, 2500);
}
});
}
std::string s(v.begin(), v.end());
Where v is pretty much anything iterable. (Specifically begin() and end() must return InputIterators.)
Scipy.org recommends that you use arrays:
*'array' or 'matrix'? Which should I use? - Short answer
Use arrays.
They are the standard vector/matrix/tensor type of numpy. Many numpy function return arrays, not matrices.
There is a clear distinction between element-wise operations and linear algebra operations.
You can have standard vectors or row/column vectors if you like.
The only disadvantage of using the array type is that you will have to use
dot
instead of*
to multiply (reduce) two tensors (scalar product, matrix vector multiplication etc.).
I was able to use the name attribute that you described in your example for the loop I am working on and it worked, perhaps because I created unique ids? I'm still considering whether I should switch to an editor template instead as mentioned in the links in another answer.
@Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "true", new {Name = item.Description.QuestionId, id = string.Format("CBY{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" }) Yes
@Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "false", new { Name = item.Description.QuestionId, id = string.Format("CBN{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" } ) No
Just to point out that there is an approach using functions from the tidyverse
, which I find more readable than gsub
:
a %>% stringr::str_remove(pattern = ".*_")
If you wish to have "Save as" dialog, just pass image into php script, which adds appropriate headers
Example "all-in-one" script script.php
<?php if(isset($_GET['image'])):
$image = $_GET['image'];
if(preg_match('#^data:image/(.*);base64,(.*)$#s', $image, $match)){
$base64 = $match[2];
$imageBody = base64_decode($base64);
$imageFormat = $match[1];
header('Content-type: application/octet-stream');
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private", false); // required for certain browsers
header("Content-Disposition: attachment; filename=\"file.".$imageFormat."\";" ); //png is default for toDataURL
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".strlen($imageBody));
echo $imageBody;
}
exit();
endif;?>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js?ver=1.7.2'></script>
<canvas id="canvas" width="300" height="150"></canvas>
<button id="btn">Save</button>
<script>
$(document).ready(function(){
var canvas = document.getElementById('canvas');
var oCtx = canvas.getContext("2d");
oCtx.beginPath();
oCtx.moveTo(0,0);
oCtx.lineTo(300,150);
oCtx.stroke();
$('#btn').on('click', function(){
// opens dialog but location doesnt change due to SaveAs Dialog
document.location.href = '/script.php?image=' + canvas.toDataURL();
});
});
</script>
If you don't want the full blown ActiveMQ, I recommend to consider RabbitMQ. RabbitMQ is lightweight messaging that uses the AMQP standard.
I recommend to also look into php-amqplib - a popular AMQP client library to access AMQP based message brokers.
System.Threading.Thread.Sleep(
(int)System.TimeSpan.FromSeconds(3).TotalMilliseconds);
Or with using
statements:
Thread.Sleep((int)TimeSpan.FromSeconds(2).TotalMilliseconds);
I prefer this to 1000 * numSeconds
(or simply 3000
) because it makes it more obvious what is going on to someone who hasn't used Thread.Sleep
before. It better documents your intent.
Sounds like you don't have the execute flag set on the file permissions, try:
chmod u+x program_name
In your example, the compiler has no way of knowing what type should TModel
be. You could do something close to what you are probably trying to do with an extension method.
static class ModelExtensions
{
public static IDictionary<string, object> GetHtmlAttributes<TModel, TProperty>
(this TModel model, Expression<Func<TModel, TProperty>> propertyExpression)
{
return new Dictionary<string, object>();
}
}
But you wouldn't be able to have anything similar to virtual
, I think.
EDIT:
Actually, you can do virtual
, using self-referential generics:
class ModelBase<TModel>
{
public virtual IDictionary<string, object> GetHtmlAttributes<TProperty>
(Expression<Func<TModel, TProperty>> propertyExpression)
{
return new Dictionary<string, object>();
}
}
class FooModel : ModelBase<FooModel>
{
public override IDictionary<string, object> GetHtmlAttributes<TProperty>
(Expression<Func<FooModel, TProperty>> propertyExpression)
{
return new Dictionary<string, object> { { "foo", "bar" } };
}
}
_WIN32 identifier is not defined.
use #include <SDKDDKVer.h>
MSVS generated projects wrap this include by generating a local "targetver.h"
which is included by "stdafx.h"
that is comiled into a precompiled-header through "stdafx.cpp"
.
EDIT : do you have a /D "WIN32" on your commandline ?
Using http.createServer
is very low-level and really not useful for creating web applications as-is.
A good framework to use on top of it is Express, and I would seriously suggest using it. You can install it using npm install express
.
When you have, you can create a basic application to handle your form:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(express.bodyParser());
app.post('/myaction', function(req, res) {
res.send('You sent the name "' + req.body.name + '".');
});
app.listen(8080, function() {
console.log('Server running at http://127.0.0.1:8080/');
});
You can make your form point to it using:
<form action="http://127.0.0.1:8080/myaction" method="post">
The reason you can't run Node on port 80 is because there's already a process running on that port (which is serving your index.html
). You could use Express to also serve static content, like index.html
, using the express.static
middleware.
I'd recommend raising the connection timeout time before getting the output stream, like so:
urlConnection.setConnectTimeout(1000);
Where 1000 is in milliseconds (1000 milliseconds = 1 second).
Jim's answer to this question may help; I copy it here. Quoting Guido van Rossum:
First of all, I chose len(x) over x.len() for HCI reasons (def __len__() came much later). There are two intertwined reasons actually, both HCI:
(a) For some operations, prefix notation just reads better than postfix — prefix (and infix!) operations have a long tradition in mathematics which likes notations where the visuals help the mathematician thinking about a problem. Compare the easy with which we rewrite a formula like x*(a+b) into xa + xb to the clumsiness of doing the same thing using a raw OO notation.
(b) When I read code that says len(x) I know that it is asking for the length of something. This tells me two things: the result is an integer, and the argument is some kind of container. To the contrary, when I read x.len(), I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standard len(). Witness the confusion we occasionally have when a class that is not implementing a mapping has a get() or keys() method, or something that isn’t a file has a write() method.
Saying the same thing in another way, I see ‘len‘ as a built-in operation. I’d hate to lose that. /…/
Try to modify the eclipse.ini
so that both Xms
and Xmx
are of the same value:
-Xms6000m
-Xmx6000m
This should force the Eclipse's VM to allocate 6GB
of heap right from the beginning.
But be careful about either using the eclipse.ini
or the command-line ./eclipse/eclipse -vmargs ...
. It should work in both cases but pick one and try to stick with it.
My understanding is that you have to create a partial class to "extend" your model and add a property that is readonly that can utilize the rest of the class's properties.
public partial class Contact{
public string ContactIdString
{
get{
return this.ContactId.ToString();
}
}
}
Then
var items = from c in contacts
select new ListItem
{
Value = c.ContactIdString,
Text = c.Name
};
That should work, but don't kill yourself trying to figure it out. Just use 2 passes.
str = str.replaceAll("(\r\n)", "<br />");
str = str.replaceAll("(\n)", "<br />");
Disclaimer: this is not very efficient.
Cmd+opt+?/?/?/? navigate similarly to vim's C-w hjkl.
See http://www.oracle.com/technetwork/java/javase/tsg-vm-149989.pdf. You can use "jdb" directly on the core file.
If you have a rooted device you can use kill
command
Connect to your device with adb:
adb shell
Once the session is established, you have to escalade privileges:
su
Then
ps
will list running processes. Note down the PID of the process you want to terminate. Then get rid of it
kill PID
OSX users can follow by Nicolay77 or mikkom that uses the mdbtools utility. You can install it via Homebrew. Just have your homebrew installed and then go
$ homebrew install mdbtools
Then create one of the scripts described by the guys and use it. I've used mikkom's one, converted all my mdb files into sql.
$ ./to_mysql.sh myfile.mdb > myfile.sql
(which btw contains more than 1 table)
If you want to play it, you should use
$("#audio")[0].play();
If you want to stop it, you should use
$("#audio").stop();
I don't know why, but it works!
If you inherit from Exception, you have to provide a constructor that takes a String as a parameter (it will contain the error message).
Another possible reason: you're using npm when your project is initialized in yarn. (I did this myself). So it would be yarn start
instead of npm start
.
use sc.nextLine(); two time so that we can read the last line of string
sc.nextLine() sc.nextLine()
Try this to reload jqGrid with new data
jQuery("#grid").jqGrid('setGridParam',{datatype:'json'}).trigger('reloadGrid');
This may not be the best way but it definitely makes sure that exception is not thrown from the code block that is being tested.
import org.assertj.core.api.Assertions;
import org.junit.Test;
public class AssertionExample {
@Test
public void testNoException(){
assertNoException();
}
private void assertException(){
Assertions.assertThatThrownBy(this::doNotThrowException).isInstanceOf(Exception.class);
}
private void assertNoException(){
Assertions.assertThatThrownBy(() -> assertException()).isInstanceOf(AssertionError.class);
}
private void doNotThrowException(){
//This method will never throw exception
}
}
Use a std::wstring
instead of a C99 variable length array. The current standard guarantees a contiguous buffer for std::basic_string
. E.g.,
std::wstring wc( cSize, L'#' );
mbstowcs( &wc[0], c, cSize );
C++ does not support C99 variable length arrays, and so if you compiled your code as pure C++, it would not even compile.
With that change your function return type should also be std::wstring
.
Remember to set relevant locale in main
.
E.g., setlocale( LC_ALL, "" )
.
Cheers & hth.,
There is a section in the MySQL manual on how to reset the root password which will solve your problem.
Offhand, I can't think of a real scenario in which extending Application is either preferable to another approach or necessary to accomplish something. If you have an expensive, frequently used object you can initialize it in an IntentService when you detect that the object isn't currently present. Application itself runs on the UI thread, while IntentService runs on its own thread.
I prefer to pass data from Activity to Activity with explicit Intents, or use SharedPreferences. There are also ways to pass data from a Fragment to its parent Activity using interfaces.
You can do this using pure CSS; no JavaScript needed. This utilizes the (somewhat counterintuitive) fact that padding-top
percentages are relative to the containing block's width. Here's an example:
.wrapper {_x000D_
width: 50%;_x000D_
/* whatever width you want */_x000D_
display: inline-block;_x000D_
position: relative;_x000D_
}_x000D_
.wrapper:after {_x000D_
padding-top: 56.25%;_x000D_
/* 16:9 ratio */_x000D_
display: block;_x000D_
content: '';_x000D_
}_x000D_
.main {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
right: 0;_x000D_
left: 0;_x000D_
/* fill parent */_x000D_
background-color: deepskyblue;_x000D_
/* let's see it! */_x000D_
color: white;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="main">_x000D_
This is your div with the specified aspect ratio._x000D_
</div>_x000D_
</div>
_x000D_
I don't know TeamCity so I hope this can work for you.
The best way I've found to do this is with MSDeploy.exe. This is part of the WebDeploy project run by Microsoft. You can download the bits here.
With WebDeploy, you run the command line
msdeploy.exe -verb:sync -source:contentPath=c:\webApp -dest:contentPath=c:\DeployedWebApp
This does the same thing as the VS Publish command, copying only the necessary bits to the deployment folder.
You can use \centering
with your parbox to do this.
(Sorry for the Google cached link; the original one I had doesn't work anymore.)
To achieve this you can use a Regular Expression to remove all the whitespace in the string. If the length of the resulting string is 0
, then you can be sure the original only contained whitespace. Try this:
var str = " ";_x000D_
if (!str.replace(/\s/g, '').length) {_x000D_
console.log('string only contains whitespace (ie. spaces, tabs or line breaks)');_x000D_
}
_x000D_
There's so many conflicting answers to this, most of which had no effect for me.
I was finally able to set (or retrieve current) X-axis minimum & maximum displayed values with chart.options.scales.xAxes[0].ticks.min
(even if min & max are only a subset of the data assigned to the chart.)
Using a time scale in my case, I used:
chart.options.scales.xAxes[0].ticks.min = 1590969600000; //Jun 1, 2020
chart.options.scales.xAxes[0].ticks.max = 1593561600000; //Jul 1, 2020
chart.update();
(I found no need to set the step values or beginAtZero
, etc.)
The best solution if you are using Spring 3 and need the authenticated principal in your controller is to do something like this:
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
@Controller
public class KnoteController {
@RequestMapping(method = RequestMethod.GET)
public java.lang.String list(Model uiModel, UsernamePasswordAuthenticationToken authToken) {
if (authToken instanceof UsernamePasswordAuthenticationToken) {
user = (User) authToken.getPrincipal();
}
...
}
I think when you see the phrase "core Java," they are talking about the basics of the language and maybe some knowledge of Java SE. I don't know why they would bother to put the "core" on there.
You can use jQuery
to achieve this
Example:
$(function () {
$('.map').maphilight();
});
Go through this LINK to know more.
If the above one doesnt work then go through this link.
EDIT :
Give same class to each area
tag like class="mapping"
and try this below code
$('.mapping').mouseover(function() {
alert($(this).attr('id'));
}).mouseout(function(){
alert('Mouseout....');
});
Change Minute parameter to 0.
You can set the cron for every three hours as:
0 */3 * * * your command here ..
you can use the identity
log[a]x
log[b]x = ---------
log[a]b
so this would be applicable for log2.
log[10]x
log[2]x = ----------
log[10]2
just plug this into the java Math log10 method....
See here for an example from the OpenJPA docs. CascadeType.ALL
means it will do all actions.
Quote:
CascadeType.PERSIST: When persisting an entity, also persist the entities held in its fields. We suggest a liberal application of this cascade rule, because if the EntityManager finds a field that references a new entity during the flush, and the field does not use CascadeType.PERSIST, it is an error.
CascadeType.REMOVE: When deleting an entity, it also deletes the entities held in this field.
CascadeType.REFRESH: When refreshing an entity, also refresh the entities held in this field.
CascadeType.MERGE: When merging entity state, also merge the entities held in this field.
Sebastian
Similar to Bass, I had to also set the overflow-y. That could actually be done in the CSS
$('#myModal').on('show.bs.modal', function () {
$('.modal .modal-body').css('overflow-y', 'auto');
$('.modal .modal-body').css('max-height', $(window).height() * 0.7);
});
The "do nothing" doesn't really work for ?
if by // Return Nothing you actually mean return null then write
return Source;
if you mean, ignore the codepath then write
if ( Source != null )
{
return Source;
}
// source is null so continue on.
And for the last
if ( Source != value )
{ Source = value;
RaisePropertyChanged ( "Source" );
}
// nothing done.
A better solution is not to make your page dependable on zoom settings. If you set limits like the one you are proposing, you are limiting accessibility. If someone cannot read your text well, they just won't be able to change that. I would use proper CSS to make it look nice in any zoom.
If your really insist, take a look at this question on how to detect zoom level using JavaScript (nightmare!): How to detect page zoom level in all modern browsers?
also try
## Notice the lack of quotes
iris %>% select (-c(Sepal.Length, Sepal.Width))
By all means, please use set()
to create an empty set.
But, if you want to impress people, tell them that you can create an empty set using literals and *
with Python >= 3.5 (see PEP 448) by doing:
>>> s = {*()} # or {*{}} or {*[]}
>>> print(s)
set()
this is basically a more condensed way of doing {_ for _ in ()}
, but, don't do this.
I have used Gnostice in the past and found them to be very good.
Other answers have suggested using TryParse
, which might fit your needs, but the safest way to provide the functionality of the IsNumeric
function is to reference the VB library and use the IsNumeric
function.
IsNumeric
is more flexible than TryParse
. For example, IsNumeric
returns true
for the string "$100"
, while the TryParse
methods all return false
.
To use IsNumeric
in C#, add a reference to Microsoft.VisualBasic.dll. The function is a static method of the Microsoft.VisualBasic.Information
class, so assuming you have using Microsoft.VisualBasic;
, you can do this:
if (Information.IsNumeric(txtMyText.Text.Trim())) //...
binding name="BindingName"
maxReceivedMessageSize="2097152"
maxBufferSize="2097152"
maxBufferPoolSize="2097152"
on client side and server side
When I started a new project
react-native init MyPrroject
I got could not connect to development server
on both platforms iOS
and Android
.
My solution is to
sudo lsof -i :8081
//find a PID of node
kill -9 <node_PID>
Also make sure that you use your local IP address
ipconfig getifaddr en0
In the C++ standard, cout
is defined in the std
namespace, so you need to either say std::cout
or put
using namespace std;
in your code in order to get at it.
However, this was not always the case, and in the past cout
was just in the global namespace (or, later on, in both global and std
). I would therefore conclude that your classes used an older C++ compiler.
private makes the class accessible only to the class in which it is declared. If we make entire class private no one from outside can access the class and makes it useless.
Inner class can be made private because the outer class can access inner class where as it is not the case with if you make outer class private.
If you support apis for AndroidR in your app then you can use the below method.
In kotlin :
var imeInsets = view.rootWindowInsets.getInsets(Type.ime())
if (imeInsets.isVisible) {
view.translationX = imeInsets.bottom
}
Note: This is only available for the AndroidR and below android version needs to follow some of other answer or i will update it for that.
SELECT *
FROM people
WHERE names ='SMITH'
ORDER BY names asc
limit 10
If you need add group by clause. If you search Smith you would have to sort on something else.
This worked for me:
git fsck --full --no-reflogs --unreachable --lost-found
git show d6e883ff45be514397dcb641c5a914f40b938c86
git branch helpme 15e521b0f716269718bb4e4edc81442a6c11c139
You need to include your pipe in module declaration:
declarations: [ UsersPipe ],
providers: [UsersPipe]
My workaround had been using gnu sed
. Worked fine for my purposes.
I had the same problem when I wrote two upstreams in NGINX conf
upstream php_upstream {
server unix:/var/run/php/my.site.sock;
server 127.0.0.1:9000;
}
...
fastcgi_pass php_upstream;
but in /etc/php/7.3/fpm/pool.d/www.conf
I listened the socket only
listen = /var/run/php/my.site.sock
So I need just socket, no any 127.0.0.1:9000
, and I just removed IP+port upstream
upstream php_upstream {
server unix:/var/run/php/my.site.sock;
}
This could be rewritten without an upstream
fastcgi_pass unix:/var/run/php/my.site.sock;
Unitialized variables check. Link 1 and 2 already seem to do this just fine, though.
I can't say I have used any of these intensively, though :)
$('#frmTest input:checked').length > 0
If you did git push origin -u localBranchName:remoteBranchName
and on sequentially git push
commands, you get errors that then origin doesn't exist, then follow these steps:
git remote -v
Check if there is any remote that I don't care.
Delete them with git remote remove 'name'
git config --edit
Look for possible signs of a old/non-existent remote.
Look for pushdefault
:
[remote]
pushdefault = oldremote
Update oldremote
value and save.
git push
should work now.
SELECT *
FROM DBA_OBJECTS
WHERE OBJECT_TYPE = 'VIEW'
Why would you need an intermediate cast to void * in C++ Because cpp doesn't allow direct conversion between pointers, you need to use reinterpret_cast or casting to void* does the thing.
Other folks have already done a good job of explaining this ridiculus conundrum ... and I think Chris Hoffman did an even better job here: https://www.howtogeek.com/326509/whats-the-difference-between-the-system32-and-syswow64-folders-in-windows/
My two thoughts:
We all make stupid short-sighted mistakes in life. When Microsoft named their (at the time) Win32 DLL directory "System32", it made sense at the time ... they just didn't take into consideration what would happen if/when a 64-bit (or 128-bit) version of their OS got developed later - and the massive backward compatibility issue such a directory name would cause. Hindsight is always 20-20, so I can't really blame them (too much) for such a mistake. ...HOWEVER... When Microsoft did later develop their 64-bit operating system, even with the benefit of hindsight, why oh why would they make not only the exact same short-sighted mistake AGAIN but make it even worse by PURPOSEFULLY giving it such a misleading name?!? Shame on them!!! Why not AT LEAST actually name the directory "SysWin32OnWin64" to avoid confusion?!? And what happens when they eventually produce a 128-bit OS ... then where are they going to put their 32-bit, 64-bit, and 128-bit DLLs?!?
All of this logic still seems completely flawed to me. On 32-bit versions of Windows, System32 contains 32-bit DLLs; on 64-bit versions of Windows, System32 contains 64-bit DLLs ... so that developers wouldn't have to make code changes, correct? The problem with this logic is that those developers are either now making 64-bit apps needing 64-bit DLLs or they're making 32-bit apps needing 32-bit DLLs ... either way, aren't they still screwed? I mean, if they're still making a 32-bit app, for it to now run on a 64-bit Windows, they'll now need to make a code change to find/reference the same ol' 32-bit DLL they used before (now located in SysWOW64). Or, if they're working on a 64-bit app, they're going to need to re-write their old app for the new OS anyway ... so a recompile/rebuild was going to be needed anyway!!!
Microsoft just hurts me sometimes.
For me once I disabled MTP (in Settings>Storage>Menu>MTP) I finally got the RSA prompt
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2.compareTo(o1);
}
};
// option 1
Integer[] array = new Integer[] { 1, 24, 4, 4, 345 };
Arrays.sort(array, comparator);
// option 2
int[] array2 = new int[] { 1, 24, 4, 4, 345 };
List<Integer>list = Ints.asList(array2);
Collections.sort(list, comparator);
array2 = Ints.toArray(list);
It depends on what you are trying to do.
file, err := os.Open("file.txt")
fmt.print(file)
The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File
), not file-content. To obtain file-content, you may READ
from a file-descriptor.
To read all file content(in bytes) to memory, ioutil.ReadAll
package main
import (
"fmt"
"io/ioutil"
"os"
"log"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
b, err := ioutil.ReadAll(file)
fmt.Print(b)
}
But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read
from *os.File
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
buf := make([]byte, 32*1024) // define your buffer size here.
for {
n, err := file.Read(buf)
if n > 0 {
fmt.Print(buf[:n]) // your read buffer.
}
if err == io.EOF {
break
}
if err != nil {
log.Printf("read %d bytes: %v", n, err)
break
}
}
}
Otherwise, you could also use the standard util package: bufio
, try Scanner
. A Scanner
reads your file in tokens: separator.
By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).
package main
import (
"fmt"
"os"
"log"
"bufio"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = f.Close(); err != nil {
log.Fatal(err)
}
}()
scanner := bufio.NewScanner(file)
for scanner.Scan() { // internally, it advances token based on sperator
fmt.Println(scanner.Text()) // token in unicode-char
fmt.Println(scanner.Bytes()) // token in bytes
}
}
Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.
I saw a lot of people use an image tag. I prefer to use a background image because I can manipulate it. For example, I can:
background-size: cover;
" property.The HTML/CSS:
.overlay-box {_x000D_
background-color: #f5f5f5;_x000D_
height: 100%;_x000D_
background-repeat: no-repeat;_x000D_
background-size: cover;_x000D_
}_x000D_
_x000D_
.overlay-box:hover .desc,_x000D_
.overlay-box:focus .desc {_x000D_
opacity: 1;_x000D_
}_x000D_
_x000D_
/* opacity 0.01 for accessibility */_x000D_
/* adjust the styles like height,padding to match your design*/_x000D_
.overlay-box .desc {_x000D_
opacity: 0.01;_x000D_
min-height: 355px;_x000D_
font-size: 1rem;_x000D_
height: 100%;_x000D_
padding: 30px 25px 20px;_x000D_
transition: all 0.3s ease;_x000D_
background: rgba(0, 0, 0, 0.7);_x000D_
color: #fff;_x000D_
}
_x000D_
<div class="overlay-box" style="background-image: url('https://via.placeholder.com/768x768');">_x000D_
<div class="desc">_x000D_
<p>Place your text here</p>_x000D_
<ul>_x000D_
<li>lorem ipsum dolor</li>_x000D_
<li>lorem lipsum</li>_x000D_
<li>lorem</li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>
_x000D_
If you are only interested in the domain name and want to ignore the subdomain then you need to parse it out of host
and hostname
.
The following code does this:
var firstDot = window.location.hostname.indexOf('.');
var tld = ".net";
var isSubdomain = firstDot < window.location.hostname.indexOf(tld);
var domain;
if (isSubdomain) {
domain = window.location.hostname.substring(firstDot == -1 ? 0 : firstDot + 1);
}
else {
domain = window.location.hostname;
}
>>> import random
>>> random.randrange(10)
3
>>> random.randrange(10)
1
To get a list of ten samples:
>>> [random.randrange(10) for x in range(10)]
[9, 0, 4, 0, 5, 7, 4, 3, 6, 8]
do like this
set classpath=%classpath%(ur jarfile);
Here's a little help on delegates between two view controllers:
Step 1: Make a protocol in the UIViewController that you will be removing/will be sending the data.
protocol FooTwoViewControllerDelegate:class {
func myVCDidFinish(_ controller: FooTwoViewController, text: String)
}
Step2: Declare the delegate in the sending class (i.e. UIViewcontroller)
class FooTwoViewController: UIViewController {
weak var delegate: FooTwoViewControllerDelegate?
[snip...]
}
Step3: Use the delegate in a class method to send the data to the receiving method, which is any method that adopts the protocol.
@IBAction func saveColor(_ sender: UIBarButtonItem) {
delegate?.myVCDidFinish(self, text: colorLabel.text) //assuming the delegate is assigned otherwise error
}
Step 4: Adopt the protocol in the receiving class
class ViewController: UIViewController, FooTwoViewControllerDelegate {
Step 5: Implement the delegate method
func myVCDidFinish(_ controller: FooTwoViewController, text: String) {
colorLabel.text = "The Color is " + text
controller.navigationController.popViewController(animated: true)
}
Step 6: Set the delegate in the prepareForSegue:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "mySegue" {
let vc = segue.destination as! FooTwoViewController
vc.colorString = colorLabel.text
vc.delegate = self
}
}
And that should work. This is of course just code fragments, but should give you the idea. For a long explanation of this code you can go over to my blog entry here:
If you are interested in what's going on under the hood with a delegate I did write on that here:
in sometimes, because the branch you are pushing has been protected, so you can ask the repository's maintainers to change the protecting status. in git-lab , you can find it in
Settings > Repository > Protected Branches .
:)
Building upon suryaPavan's answer this slight modification can cleanup the empty object after removing the invidival emptys inside the object or array. this ensures that you don't have an empty array or object hanging around.
function removeNullsInObject(obj) {
if( typeof obj === 'string' || obj === "" ){
return;
}
$.each(obj, function(key, value){
if (value === "" || value === null){
delete obj[key];
} else if ($.isArray(value)) {
if( value.length === 0 ){
delete obj[key];
return;
}
$.each(value, function (k,v) {
removeNullsInObject(v);
});
if( value.length === 0 ){
delete obj[key];
}
} else if (typeof value === 'object') {
if( Object.keys(value).length === 0 ){
delete obj[key];
return;
}
removeNullsInObject(value);
if( Object.keys(value).length === 0 ){
delete obj[key];
}
}
});
}
Create your own confirm box:
<div id="confirmBox">
<div class="message"></div>
<span class="yes">Yes</span>
<span class="no">No</span>
</div>
Create your own confirm()
method:
function doConfirm(msg, yesFn, noFn)
{
var confirmBox = $("#confirmBox");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes,.no").unbind().click(function()
{
confirmBox.hide();
});
confirmBox.find(".yes").click(yesFn);
confirmBox.find(".no").click(noFn);
confirmBox.show();
}
Call it by your code:
doConfirm("Are you sure?", function yes()
{
form.submit();
}, function no()
{
// do nothing
});
You'll need to add CSS to style and position your confirm box appropriately.
Working demo: jsfiddle.net/Xtreu
1320917972 is Unix timestamp using number of seconds since 00:00:00 UTC on January 1, 1970. You can use TimeUnit
class for unit conversion - from System.currentTimeMillis()
to seconds.
String timeStamp = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
Once I used double slash while calling the API then I got the same error.
I had to call http://localhost:8080/getSomething but I did Like http://localhost:8080//getSomething. I resolved it by removing extra slash.
Interestingly, both C & C++ (and I think C#, but I'm not sure) specifically allow the trailing comma -- for exactly the reason given: It make programmaticly generating lists much easier. Not sure why JavaScript didn't follow their lead.
Capturing lambdas cannot be converted to function pointers, as this answer pointed out.
However, it is often quite a pain to supply a function pointer to an API that only accepts one. The most often cited method to do so is to provide a function and call a static object with it.
static Callable callable;
static bool wrapper()
{
return callable();
}
This is tedious. We take this idea further and automate the process of creating wrapper
and make life much easier.
#include<type_traits>
#include<utility>
template<typename Callable>
union storage
{
storage() {}
std::decay_t<Callable> callable;
};
template<int, typename Callable, typename Ret, typename... Args>
auto fnptr_(Callable&& c, Ret (*)(Args...))
{
static bool used = false;
static storage<Callable> s;
using type = decltype(s.callable);
if(used)
s.callable.~type();
new (&s.callable) type(std::forward<Callable>(c));
used = true;
return [](Args... args) -> Ret {
return Ret(s.callable(std::forward<Args>(args)...));
};
}
template<typename Fn, int N = 0, typename Callable>
Fn* fnptr(Callable&& c)
{
return fnptr_<N>(std::forward<Callable>(c), (Fn*)nullptr);
}
And use it as
void foo(void (*fn)())
{
fn();
}
int main()
{
int i = 42;
auto fn = fnptr<void()>([i]{std::cout << i;});
foo(fn); // compiles!
}
This is essentially declaring an anonymous function at each occurrence of fnptr
.
Note that invocations of fnptr
overwrite the previously written callable
given callables of the same type. We remedy this, to a certain degree, with the int
parameter N
.
std::function<void()> func1, func2;
auto fn1 = fnptr<void(), 1>(func1);
auto fn2 = fnptr<void(), 2>(func2); // different function
From MSDN: SqlCommand.ExecuteNonQuery Method
You can use the ExecuteNonQuery to perform catalog operations (for example, querying the structure of a database or creating database objects such as tables), or to change the data in a database without using a DataSet by executing UPDATE, INSERT, or DELETE statements.
Although the ExecuteNonQuery returns no rows, any output parameters or return values mapped to parameters are populated with data.
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.
You are using SELECT query, thus you get -1
In the answers above, the super
is initialized without any (keyword) arguments. Often, however, you would like to do that, as well as pass on some 'custom' arguments of your own. Here is an example which illustrates this use case:
class SortedList(list):
def __init__(self, *args, reverse=False, **kwargs):
super().__init__(*args, **kwargs) # Initialize the super class
self.reverse = reverse
self.sort(reverse=self.reverse) # Do additional things with the custom keyword arguments
This is a subclass of list
which, when initialized, immediately sorts itself in the direction specified by the reverse
keyword argument, as the following tests illustrate:
import pytest
def test_1():
assert SortedList([5, 2, 3]) == [2, 3, 5]
def test_2():
SortedList([5, 2, 3], reverse=True) == [5, 3, 2]
def test_3():
with pytest.raises(TypeError):
sorted_list = SortedList([5, 2, 3], True) # This doesn't work because 'reverse' must be passed as a keyword argument
if __name__ == "__main__":
pytest.main([__file__])
Thanks to the passing on of *args
to super
, the list can be initialized and populated with items instead of only being empty. (Note that reverse
is a keyword-only argument in accordance with PEP 3102).
In AndroidManifest.xml:
<application
android:icon="@drawable/launcher"
android:label="@string/app_name"
android:name="com..."
android:theme="@style/Theme">...</Application>
In styles.xml: (See android:icon
)
<style name="Theme" parent="@android:style/Theme.Holo.Light">
<item name="android:actionBarStyle">@style/ActionBar</item>
</style>
<style name="ActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
<item name="android:icon">@drawable/icon</item>
</style>
Net::HTTP is built into Ruby, but let's face it, often it's easier not to use its cumbersome 1980s style and try a higher level alternative:
You need to use a group by clause.
SELECT site_id, MAX(ts) as TIME, count(*) group by site_id
Few things to try, Ensure the Framework and all it's headers are imported into your project properly.
Also in your Build Settings
set YES
to Always search user paths
, and make sure your User header paths
are pointing to the Framework.
Finally, Build->Clean and Restart Xcode.
Hope this helps !
UPDATE: According to SDWebImage's installation, it's required you make a modification to Header Search Path
and not User header paths
, As seen below.
Have you done this as well? I suggest slowly, re-doing all the installation steps from the beginning.
The app is stored in %LocalAppData%
in your %UserProfile%
. So the full path could be:
C:\Users\username\AppData\Local\GitHub
It registers the driver; something of the form:
public class SomeDriver implements Driver {
static {
try {
DriverManager.registerDriver(new SomeDriver());
} catch (SQLException e) {
// TODO Auto-generated catch block
}
}
//etc: implemented methods
}
If you are using CentOS or another Linux flavour then just do Ctrl
+R
at the prompt and type git
.
If you keep hitting Ctrl
+R
this will do a reverse search through your history for commands that start with git
I didn't post to answer JeremyRR's questions (as they have already been answered); instead, I posted merely to give a suggestion.
To JeremyRR, you could do this:
{
string someString = "testing";
for(int counter = 0; counter <= 10; counter++)
{
cout << someString;
}
// The variable is in scope.
}
// The variable is no longer in scope.
I don't know if you realize (I didn't when I first started programming), that brackets (as long they are in pairs) can be placed anywhere within the code, not just after "if", "for", "while", etc.
My code compiled in Microsoft Visual C++ 2010 Express, so I know it works; also, I have tried to to use the variable outside of the brackets that it was defined in and I received an error, so I know that the variable was "destroyed".
I don't know if it is bad practice to use this method, as a lot of unlabeled brackets could quickly make the code unreadable, but maybe some comments could clear things up.
Additional to the jQuery thing treated in the other answers there is another meaning in JavaScript - as prefix for the RegExp properties representing matches, for example:
"test".match( /t(e)st/ );
alert( RegExp.$1 );
will alert "e"
But also here it's not "magic" but simply part of the properties name
Here's a google chrome extension that'll allow you to download your reviews: https://chrome.google.com/webstore/detail/my-play-store-reviews/ldggikfajgoedghjnflfafiiheagngoa?hl=en
Nullable types did not come in until 2.0.
If nullable types had been made in the beginning of the language then string would have been non-nullable and string? would have been nullable. But they could not do this du to backward compatibility.
A lot of people talk about ref-type or not ref type, but string is an out of the ordinary class and solutions would have been found to make it possible.
You have a return
statement that isn't in a function. Functions are started by the def
keyword:
def function(argument):
return "something"
print function("foo") #prints "something"
return
has no meaning outside of a function, and so python raises an error.
We can add the following to a particular tag in CSS:
-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
In case of half rotation change 90
to 45
.
reference here
!== is the strict not equal operator and only returns a value of true if both the operands are not equal and/or not of the same type. The following examples return a Boolean true:
a !== b
a !== "2"
4 !== '4'
I was having problems here (i.e. sending form-data whilst uploading a file) until I used the following:
files = {'file': (filename, open(filepath, 'rb'), 'text/xml'),
'Content-Disposition': 'form-data; name="file"; filename="' + filename + '"',
'Content-Type': 'text/xml'}
That's the input that ended up working for me. In Chrome Dev Tools -> Network tab, I clicked the request I was interested in. In the Headers tab, there's a Form Data section, and it showed both the Content-Disposition and the Content-Type headers being set there.
I did NOT need to set headers in the actual requests.post() command for this to succeed (including them actually caused it to fail)
set /p choice= "Please Select one of the above options :"
echo '%choice%'
The space after =
is very important.
The Spinner class implements DialogInterface.OnClickListener
, thereby effectively hijacking the standard View.OnClickListener
.
If you are not using a sub-classed Spinner or don't intend to, choose another answer.
Otherwise just add the following code to your custom Spinner:
@Override
/** Override triggered on 'tap' of closed Spinner */
public boolean performClick() {
// [ Do anything you like here ]
return super.performClick();
}
Example: Display a pre-supplied hint via Snackbar whenever the Spinner is opened:
private String sbMsg=null; // Message seen by user when Spinner is opened.
public void setSnackbarMessage(String msg) { sbMsg=msg; }
@Override
/** Override triggered on 'tap' of closed Spinner */
public boolean performClick() {
if (sbMsg!=null && !sbMsg.isEmpty()) { /* issue Snackbar */ }
return super.performClick();
}
A custom Spinner is a terrific starting point for programmatically standardising Spinner appearance throughout your project.
If interested, looky here
The JSON sample you provided is not valid. Check it online with this JSON Validator http://jsonlint.com/. You need to remove the extra comma on line 59.
One you have valid json you can use this code to convert it to an array.
json_decode($json, true);
Array
(
[bpath] => http://www.sampledomain.com/
[clist] => Array
(
[0] => Array
(
[cid] => 11
[display_type] => grid
[ctitle] => abc
[acount] => 71
[alist] => Array
(
[0] => Array
(
[aid] => 6865
[adate] => 2 Hours ago
[atitle] => test
[adesc] => test desc
[aimg] =>
[aurl] => ?nid=6865
[weburl] => news.php?nid=6865
[cmtcount] => 0
)
[1] => Array
(
[aid] => 6857
[adate] => 20 Hours ago
[atitle] => test1
[adesc] => test desc1
[aimg] =>
[aurl] => ?nid=6857
[weburl] => news.php?nid=6857
[cmtcount] => 0
)
)
)
[1] => Array
(
[cid] => 1
[display_type] => grid
[ctitle] => test1
[acount] => 2354
[alist] => Array
(
[0] => Array
(
[aid] => 6851
[adate] => 1 Days ago
[atitle] => test123
[adesc] => test123 desc
[aimg] =>
[aurl] => ?nid=6851
[weburl] => news.php?nid=6851
[cmtcount] => 7
)
[1] => Array
(
[aid] => 6847
[adate] => 2 Days ago
[atitle] => test12345
[adesc] => test12345 desc
[aimg] =>
[aurl] => ?nid=6847
[weburl] => news.php?nid=6847
[cmtcount] => 7
)
)
)
)
)
Since you're using requests
, you should use the response's json
method.
import requests
response = requests.get(...)
data = response.json()
Strings are immutable types. You cannot modify them, only return new string instances.
Because of that, formatting with an instance method makes little sense, as it would have to be called like:
String formatted = "%s: %s".format(key, value);
The original Java authors (and .NET authors) decided that a static method made more sense in this situation, as you are not modifying the target, but instead calling a format method and passing in an input string.
Here is an example of why format()
would be dumb as an instance method. In .NET (and probably in Java), Replace()
is an instance method.
You can do this:
"I Like Wine".Replace("Wine","Beer");
However, nothing happens, because strings are immutable. Replace()
tries to return a new string, but it is assigned to nothing.
This causes lots of common rookie mistakes like:
inputText.Replace(" ", "%20");
Again, nothing happens, instead you have to do:
inputText = inputText.Replace(" ","%20");
Now, if you understand that strings are immutable, that makes perfect sense. If you don't, then you are just confused. The proper place for Replace()
would be where format()
is, as a static method of String
:
inputText = String.Replace(inputText, " ", "%20");
Now there is no question as to what's going on.
The real question is, why did the authors of these frameworks decide that one should be an instance method, and the other static? In my opinion, both are more elegantly expressed as static methods.
Regardless of your opinion, the truth is that you are less prone to make a mistake using the static version, and the code is easier to understand (No Hidden Gotchas).
Of course there are some methods that are perfect as instance methods, take String.Length()
int length = "123".Length();
In this situation, it's obvious we are not trying to modify "123", we are just inspecting it, and returning its length. This is a perfect candidate for an instance method.
My simple rules for Instance Methods on Immutable Objects:
I have a pure javascript library to do that https://github.com/robertodecurnex/J50Npi/blob/master/J50Npi.js
Take a look at it and let me know if you need any help using or understanding the code.
Btw, you have simple usage example here: http://robertodecurnex.github.com/J50Npi/
This question has been asked before. Please see this question.
Using the accepted answer and adapting it to your problem you get:
SELECT tt.*
FROM myTable tt
INNER JOIN
(SELECT ID, MAX(Date) AS MaxDateTime
FROM myTable
GROUP BY ID) groupedtt
ON tt.ID = groupedtt.ID
AND tt.Date = groupedtt.MaxDateTime
Try this
Get-ChildItem | % { Write-Host "$($_.FullName)\$buildConfig\$($_.Name).dll" }
In your code,
$build-Config
is not a valid variable name. $.FullName
should be $_.FullName
$
should be $_.Name
There's no difference, ==
is a synonym for =
(for the C/C++ people, I assume). See here, for example.
You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.
Python doesn't have an sscanf
equivalent built-in, and most of the time it actually makes a whole lot more sense to parse the input by working with the string directly, using regexps, or using a parsing tool.
Probably mostly useful for translating C, people have implemented sscanf
, such as in this module: http://hkn.eecs.berkeley.edu/~dyoo/python/scanf/
In this particular case if you just want to split the data based on multiple split characters, re.split
is really the right tool.
and then go to control panel > system and security > windows firewall and turn windows firewall off
now you can access your wamp server from another computer over local network by the network IP of computer which have wamp server installed like http://192.168.2.34/mysite
For setting value in hidden field do in the following way:
@Html.HiddenFor(model => model.title,
new { id= "natureOfVisitField", Value = @Model.title})
It will work
For the find jockeys out there like me:
find $PWD -maxdepth 0 -printf "%f\n"
An example where things could go wrong with Shell=True is shown here
>>> from subprocess import call
>>> filename = input("What file would you like to display?\n")
What file would you like to display?
non_existent; rm -rf / # THIS WILL DELETE EVERYTHING IN ROOT PARTITION!!!
>>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...
Check the doc here: subprocess.call()
Try to login via the terminal using the following command:
mysql -u root -p
It will then prompt for your password. If this fails, then definitely the username or password is incorrect. If this works, then your database's password needs to be enclosed in quotes:
database_password: "0000"
R interpreter has a duck-typing memory allocation system. There is no builtin method to tell you the datatype of your pointer to memory. Duck typing is done for speed, but turned out to be a bad idea because now statements such as: print(is.integer(5))
returns FALSE and is.integer(as.integer(5))
returns TRUE. Go figure.
The R-manual on basic types: https://cran.r-project.org/doc/manuals/R-lang.html#Basic-types
The best you can hope for is to write your own function to probe your pointer to memory, then use process of elimination to decide if it is suitable for your needs.
Your object()
needs to be penetrated with get(...)
before you can see inside. Example:
a <- 10
myGlobals <- objects()
for(i in myGlobals){
typeof(i) #prints character
typeof(get(i)) #prints integer
}
The R function typeof
has a bias to give you the type at maximum depth, for example.
library(tibble)
#expression notes type
#----------------------- -------------------------------------- ----------
typeof(TRUE) #a single boolean: logical
typeof(1L) #a single numeric with L postfixed: integer
typeof("foobar") #A single string in double quotes: character
typeof(1) #a single numeric: double
typeof(list(5,6,7)) #a list of numeric: list
typeof(2i) #an imaginary number complex
typeof(5 + 5L) #double + integer is coerced: double
typeof(c()) #an empty vector has no type: NULL
typeof(!5) #a bang before a double: logical
typeof(Inf) #infinity has a type: double
typeof(c(5,6,7)) #a vector containing only doubles: double
typeof(c(c(TRUE))) #a vector of vector of logicals: logical
typeof(matrix(1:10)) #a matrix of doubles has a type: list
typeof(substr("abc",2,2))#a string at index 2 which is 'b' is: character
typeof(c(5L,6L,7L)) #a vector containing only integers: integer
typeof(c(NA,NA,NA)) #a vector containing only NA: logical
typeof(data.frame()) #a data.frame with nothing in it: list
typeof(data.frame(c(3))) #a data.frame with a double in it: list
typeof(c("foobar")) #a vector containing only strings: character
typeof(pi) #builtin expression for pi: double
typeof(1.66) #a single numeric with mantissa: double
typeof(1.66L) #a double with L postfixed double
typeof(c("foobar")) #a vector containing only strings: character
typeof(c(5L, 6L)) #a vector containing only integers: integer
typeof(c(1.5, 2.5)) #a vector containing only doubles: double
typeof(c(1.5, 2.5)) #a vector containing only doubles: double
typeof(c(TRUE, FALSE)) #a vector containing only logicals: logical
typeof(factor()) #an empty factor has default type: integer
typeof(factor(3.14)) #a factor containing doubles: integer
typeof(factor(T, F)) #a factor containing logicals: integer
typeof(Sys.Date()) #builtin R dates: double
typeof(hms::hms(3600)) #hour minute second timestamp double
typeof(c(T, F)) #T and F are builtins: logical
typeof(1:10) #a builtin sequence of numerics: integer
typeof(NA) #The builtin value not available: logical
typeof(c(list(T))) #a vector of lists of logical: list
typeof(list(c(T))) #a list of vectors of logical: list
typeof(c(T, 3.14)) #a vector of logicals and doubles: double
typeof(c(3.14, "foo")) #a vector of doubles and characters: character
typeof(c("foo",list(T))) #a vector of strings and lists: list
typeof(list("foo",c(T))) #a list of strings and vectors: list
typeof(TRUE + 5L) #a logical plus an integer: integer
typeof(c(TRUE, 5L)[1]) #The true is coerced to 1 integer
typeof(c(c(2i), TRUE)[1])#logical coerced to complex: complex
typeof(c(NaN, 'batman')) #NaN's in a vector don't dominate: character
typeof(5 && 4) #doubles are coerced by order of && logical
typeof(8 < 'foobar') #string and double is coerced logical
typeof(list(4, T)[[1]]) #a list retains type at every index: double
typeof(list(4, T)[[2]]) #a list retains type at every index: logical
typeof(2 ** 5) #result of exponentiation double
typeof(0E0) #exponential lol notation double
typeof(0x3fade) #hexidecimal double
typeof(paste(3, '3')) #paste promotes types to string character
typeof(3 + ?) #R pukes on unicode error
typeof(iconv("a", "latin1", "UTF-8")) #UTF-8 characters character
typeof(5 == 5) #result of a comparison: logical
The R function class
has a bias to give you the type of container or structure encapsulating your types, for example.
library(tibble)
#expression notes class
#--------------------- ---------------------------------------- ---------
class(matrix(1:10)) #a matrix of doubles has a class: matrix
class(factor("hi")) #factor of items is: factor
class(TRUE) #a single boolean: logical
class(1L) #a single numeric with L postfixed: integer
class("foobar") #A single string in double quotes: character
class(1) #a single numeric: numeric
class(list(5,6,7)) #a list of numeric: list
class(2i) #an imaginary complex
class(data.frame()) #a data.frame with nothing in it: data.frame
class(Sys.Date()) #builtin R dates: Date
class(sapply) #a function is function
class(charToRaw("hi")) #convert string to raw: raw
class(array("hi")) #array of items is: array
class(5 + 5L) #double + integer is coerced: numeric
class(c()) #an empty vector has no class: NULL
class(!5) #a bang before a double: logical
class(Inf) #infinity has a class: numeric
class(c(5,6,7)) #a vector containing only doubles: numeric
class(c(c(TRUE))) #a vector of vector of logicals: logical
class(substr("abc",2,2))#a string at index 2 which is 'b' is: character
class(c(5L,6L,7L)) #a vector containing only integers: integer
class(c(NA,NA,NA)) #a vector containing only NA: logical
class(data.frame(c(3))) #a data.frame with a double in it: data.frame
class(c("foobar")) #a vector containing only strings: character
class(pi) #builtin expression for pi: numeric
class(1.66) #a single numeric with mantissa: numeric
class(1.66L) #a double with L postfixed numeric
class(c("foobar")) #a vector containing only strings: character
class(c(5L, 6L)) #a vector containing only integers: integer
class(c(1.5, 2.5)) #a vector containing only doubles: numeric
class(c(TRUE, FALSE)) #a vector containing only logicals: logical
class(factor()) #an empty factor has default class: factor
class(factor(3.14)) #a factor containing doubles: factor
class(factor(T, F)) #a factor containing logicals: factor
class(hms::hms(3600)) #hour minute second timestamp hms difftime
class(c(T, F)) #T and F are builtins: logical
class(1:10) #a builtin sequence of numerics: integer
class(NA) #The builtin value not available: logical
class(c(list(T))) #a vector of lists of logical: list
class(list(c(T))) #a list of vectors of logical: list
class(c(T, 3.14)) #a vector of logicals and doubles: numeric
class(c(3.14, "foo")) #a vector of doubles and characters: character
class(c("foo",list(T))) #a vector of strings and lists: list
class(list("foo",c(T))) #a list of strings and vectors: list
class(TRUE + 5L) #a logical plus an integer: integer
class(c(TRUE, 5L)[1]) #The true is coerced to 1 integer
class(c(c(2i), TRUE)[1])#logical coerced to complex: complex
class(c(NaN, 'batman')) #NaN's in a vector don't dominate: character
class(5 && 4) #doubles are coerced by order of && logical
class(8 < 'foobar') #string and double is coerced logical
class(list(4, T)[[1]]) #a list retains class at every index: numeric
class(list(4, T)[[2]]) #a list retains class at every index: logical
class(2 ** 5) #result of exponentiation numeric
class(0E0) #exponential lol notation numeric
class(0x3fade) #hexidecimal numeric
class(paste(3, '3')) #paste promotes class to string character
class(3 + ?) #R pukes on unicode error
class(iconv("a", "latin1", "UTF-8")) #UTF-8 characters character
class(5 == 5) #result of a comparison: logical
storage.mode
of your variable:When an R variable is written to disk, the data layout changes again, and is called the data's storage.mode
. The function storage.mode(...)
reveals this low level information: see Mode, Class, and Type of R objects. You shouldn't need to worry about R's storage.mode unless you are trying to understand delays caused by round trip casts/coercions that occur when assigning and reading data to and from disk.
gettype(your_variable)
:Run this R code then adapt it for your purposes, it'll make a pretty good guess as to what type it is.
get_type <- function(variable){
sz <- as.integer(length(variable)) #length of your variable
tof <- typeof(variable) #typeof your variable
cls <- class(variable) #class of your variable
isc <- is.character(variable) #what is.character() has to say about it.
d <- dim(variable) #dimensions of your variable
isv <- is.vector(variable)
if (is.matrix(variable)){
d <- dim(t(variable)) #dimensions of your matrix
}
#observations ----> datatype
if (sz>=1 && tof == "logical" && cls == "logical" && isv == TRUE){ return("vector of logical") }
if (sz>=1 && tof == "integer" && cls == "integer" ){ return("vector of integer") }
if (sz==1 && tof == "double" && cls == "Date" ){ return("Date") }
if (sz>=1 && tof == "raw" && cls == "raw" ){ return("vector of raw") }
if (sz>=1 && tof == "double" && cls == "numeric" ){ return("vector of double") }
if (sz>=1 && tof == "double" && cls == "array" ){ return("vector of array of double") }
if (sz>=1 && tof == "character" && cls == "array" ){ return("vector of array of character") }
if (sz>=0 && tof == "list" && cls == "data.frame" ){ return("data.frame") }
if (sz>=1 && isc == TRUE && isv == TRUE){ return("vector of character") }
if (sz>=1 && tof == "complex" && cls == "complex" ){ return("vector of complex") }
if (sz==0 && tof == "NULL" && cls == "NULL" ){ return("NULL") }
if (sz>=0 && tof == "integer" && cls == "factor" ){ return("factor") }
if (sz>=1 && tof == "double" && cls == "numeric" && isv == TRUE){ return("vector of double") }
if (sz>=1 && tof == "double" && cls == "matrix"){ return("matrix of double") }
if (sz>=1 && tof == "character" && cls == "matrix"){ return("matrix of character") }
if (sz>=1 && tof == "list" && cls == "list" && isv == TRUE){ return("vector of list") }
if (sz>=1 && tof == "closure" && cls == "function" && isv == FALSE){ return("closure/function") }
return("it's pointer to memory, bruh")
}
assert <- function(a, b){
if (a == b){
cat("P")
}
else{
cat("\nFAIL!!! Sniff test:\n")
sz <- as.integer(length(variable)) #length of your variable
tof <- typeof(variable) #typeof your variable
cls <- class(variable) #class of your variable
isc <- is.character(variable) #what is.character() has to say about it.
d <- dim(variable) #dimensions of your variable
isv <- is.vector(variable)
if (is.matrix(variable)){
d <- dim(t(variable)) #dimensions of your variable
}
if (!is.function(variable)){
print(paste("value: '", variable, "'"))
}
print(paste("get_type said: '", a, "'"))
print(paste("supposed to be: '", b, "'"))
cat("\nYour pointer to memory has properties:\n")
print(paste("sz: '", sz, "'"))
print(paste("tof: '", tof, "'"))
print(paste("cls: '", cls, "'"))
print(paste("d: '", d, "'"))
print(paste("isc: '", isc, "'"))
print(paste("isv: '", isv, "'"))
quit()
}
}
#these asserts give a sample for exercising the code.
assert(get_type(TRUE), "vector of logical") #everything is a vector in R by default.
assert(get_type(c(TRUE)), "vector of logical") #c() just casts to vector
assert(get_type(c(c(TRUE))),"vector of logical") #casting vector multiple times does nothing
assert(get_type(!5), "vector of logical") #bang inflicts 'not truth-like'
assert(get_type(1L), "vector of integer") #naked integers are still vectors of 1
assert(get_type(c(1L, 2L)), "vector of integer") #Longs are not doubles
assert(get_type(c(1L, c(2L, 3L))),"vector of integer") #nested vectors of integers
assert(get_type(c(1L, c(TRUE))), "vector of integer") #logicals coerced to integer
assert(get_type(c(FALSE, c(1L))), "vector of integer") #logicals coerced to integer
assert(get_type("foobar"), "vector of character") #character here means 'string'
assert(get_type(c(1L, "foobar")), "vector of character") #integers are coerced to string
assert(get_type(5), "vector of double")
assert(get_type(5 + 5L), "vector of double")
assert(get_type(Inf), "vector of double")
assert(get_type(c(5,6,7)), "vector of double")
assert(get_type(NaN), "vector of double")
assert(get_type(list(5)), "vector of list") #your list is in a vector.
assert(get_type(list(5,6,7)), "vector of list")
assert(get_type(c(list(5,6,7))),"vector of list")
assert(get_type(list(c(5,6),T)),"vector of list") #vector of list of vector and logical
assert(get_type(list(5,6,7)), "vector of list")
assert(get_type(2i), "vector of complex")
assert(get_type(c(2i, 3i, 4i)), "vector of complex")
assert(get_type(c()), "NULL")
assert(get_type(data.frame()), "data.frame")
assert(get_type(data.frame(4,5)),"data.frame")
assert(get_type(Sys.Date()), "Date")
assert(get_type(sapply), "closure/function")
assert(get_type(charToRaw("hi")),"vector of raw")
assert(get_type(c(charToRaw("a"), charToRaw("b"))), "vector of raw")
assert(get_type(array(4)), "vector of array of double")
assert(get_type(array(4,5)), "vector of array of double")
assert(get_type(array("hi")), "vector of array of character")
assert(get_type(factor()), "factor")
assert(get_type(factor(3.14)), "factor")
assert(get_type(factor(TRUE)), "factor")
assert(get_type(matrix(3,4,5)), "matrix of double")
assert(get_type(as.matrix(5)), "matrix of double")
assert(get_type(matrix("yatta")),"matrix of character")
I put in a C++/Java/Python ideology here that gives me the scoop of what the memory most looks like. R triad typing system is like trying to nail spaghetti to the wall, <-
and <<-
will package your matrix to a list when you least suspect. As the old duck-typing saying goes: If it waddles like a duck and if it quacks like a duck and if it has feathers, then it's a duck.
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int width_px = Resources.getSystem().getDisplayMetrics().widthPixels;
int height_px =Resources.getSystem().getDisplayMetrics().heightPixels;
int pixeldpi = Resources.getSystem().getDisplayMetrics().densityDpi;
int width_dp = (width_px/pixeldpi)*160;
int height_dp = (height_px/pixeldpi)*160;
yes yes, git gc
is the solution, naturally,
and locally - you can just delete the local repository and clone it again,
the seconds you wait for that huge git & externals to process are collected to long minutes in which are collected to hours of inefficient time spent,
Create a new (entirely, not just a branch) repository from scratch, including the only recent version of files, naturally you'll loose all the history,
but when in code-world it is not time to get sentimental, there is no point dragging along the entire 5 years of code every commit or diff, you can still store the old git & externals somewhere, if you get nostalgic :]
but, at some point you really have to move along :]
your team will thank you!
let headers = [
"cache-control": "no-cache",
"postman-token": "6f8a-12c6-87a1-ac0f25d6385a"
]
let request = NSMutableURLRequest(url: NSURL(string: "Your url string")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if error == nil && data != nil {
do {
// Convert NSData to Dictionary where keys are of type String, and values are of any type
let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:AnyObject]
print(json)
//do your stuff
// completionHandler(true)
} catch {
// completionHandler(false)
}
}
else if error != nil
{
//completionHandler(false)
}
}).resume()
}
Using FilenameUtils
in Apache Commons IO :
String name1 = FilenameUtils.getName("/ab/cd/xyz.txt");
String name2 = FilenameUtils.getName("c:\\ab\\cd\\xyz.txt");
There is one way to react to a kill -9: that is to have a separate process that monitors the process being killed and cleans up after it if necessary. This would probably involve IPC and would be quite a bit of work, and you can still override it by killing both processes at the same time. I assume it will not be worth the trouble in most cases.
Whoever kills a process with -9 should theoretically know what he/she is doing and that it may leave things in an inconsistent state.
Find your spinner name and find id then implement this method.
spinnername.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
Cool.
I also found the documentation regarding the E:
http://www.postgresql.org/docs/8.3/interactive/sql-syntax-lexical.html#SQL-SYNTAX-STRINGS
PostgreSQL also accepts "escape" string constants, which are an extension to the SQL standard. An escape string constant is specified by writing the letter E (upper or lower case) just before the opening single quote, e.g. E'foo'. (When continuing an escape string constant across lines, write E only before the first opening quote.) Within an escape string, a backslash character (\) begins a C-like backslash escape sequence, in which the combination of backslash and following character(s) represents a special byte value. \b is a backspace, \f is a form feed, \n is a newline, \r is a carriage return, \t is a tab. Also supported are \digits, where digits represents an octal byte value, and \xhexdigits, where hexdigits represents a hexadecimal byte value. (It is your responsibility that the byte sequences you create are valid characters in the server character set encoding.) Any other character following a backslash is taken literally. Thus, to include a backslash character, write two backslashes (\\). Also, a single quote can be included in an escape string by writing \', in addition to the normal way of ''.
Currently Swift does not support any built in mechanism for observing property changes of objects other than 'self', so no, it does not support KVO.
However, KVO is such a fundamental part of Objective-C and Cocoa that it seems quite likely that it will be added in the future. The current documentation seems to imply this:
Key-Value Observing
Information forthcoming.
I think you just need COUNT(DISTINCT post_id) FROM votes
.
See "4.2.7. Aggregate Expressions" section in http://www.postgresql.org/docs/current/static/sql-expressions.html.
EDIT: Corrected my careless mistake per Erwin's comment.
string connectionstring="DataSource=severname;InitialCatlog=databasename;Uid=; password=;"
SqlConnection con=new SqlConnection(connectionstring)
Incase someone wants to postion a child div directly under a parent
#father {
position: relative;
}
#son1 {
position: absolute;
top: 100%;
}
Working demo Codepen
As Blexy already answered, go to "Behavior > Site Content > All Pages".
Just pay attention that "Behavior" appears two times in the left sidebar and we need to click on the second option:
@user544079
Even though it is very old and irrelevant now, I am replying to help people like me! it should be like this:
<form method="post" action="mailto:$emailID?subject=$MySubject &message= $MyMessageText">
Here $emailID, $MySubject, $MyMessageText are variables which you assign from a FORM or a DATABASE Table or just you can assign values in your code itself. Alternatively you can put the code like this (normally it is not used):
<form method="post" action="mailto:[email protected]?subject=New Registration Alert &message= New Registration requires your approval">
use the timeIntervalSince1970 function of the NSDate class like below:
double start = [startDate timeIntervalSince1970];
double end = [endDate timeIntervalSince1970];
double difference = end - start;
basically, this is what i use to compare the difference in seconds between 2 different dates. also check this link here
Specify the buildpack while creating the app.
heroku create appname --buildpack heroku/python
Adding mode:'no-cors'
to the request header guarantees that no response will be available in the response
Adding a "non standard" header, line 'access-control-allow-origin'
will trigger a OPTIONS preflight request, which your server must handle correctly in order for the POST request to even be sent
You're also doing fetch
wrong ... fetch
returns a "promise" for a Response
object which has promise creators for json
, text
, etc. depending on the content type...
In short, if your server side handles CORS correctly (which from your comment suggests it does) the following should work
function send(){
var myVar = {"id" : 1};
console.log("tuleb siia", document.getElementById('saada').value);
fetch("http://localhost:3000", {
method: "POST",
headers: {
"Content-Type": "text/plain"
},
body: JSON.stringify(myVar)
}).then(function(response) {
return response.json();
}).then(function(muutuja){
document.getElementById('väljund').innerHTML = JSON.stringify(muutuja);
});
}
however, since your code isn't really interested in JSON (it stringifies the object after all) - it's simpler to do
function send(){
var myVar = {"id" : 1};
console.log("tuleb siia", document.getElementById('saada').value);
fetch("http://localhost:3000", {
method: "POST",
headers: {
"Content-Type": "text/plain"
},
body: JSON.stringify(myVar)
}).then(function(response) {
return response.text();
}).then(function(muutuja){
document.getElementById('väljund').innerHTML = muutuja;
});
}
Try this simple solution to convert file to base64 string
String base64String = imageFileToByte(file);
public String imageFileToByte(File file){
Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
return Base64.encodeToString(b, Base64.DEFAULT);
}
You could use animation like this:
-webkit-animation: spin 1s infinite linear;
@-webkit-keyframes spin {
0% {-webkit-transform: rotate(0deg)}
100% {-webkit-transform: rotate(360deg)}
}
Even though you asked for wait()
and notify()
specifically, I feel that this quote is still important enough:
Josh Bloch, Effective Java 2nd Edition, Item 69: Prefer concurrency utilities to wait
and notify
(emphasis his):
Given the difficulty of using
wait
andnotify
correctly, you should use the higher-level concurrency utilities instead [...] usingwait
andnotify
directly is like programming in "concurrency assembly language", as compared to the higher-level language provided byjava.util.concurrent
. There is seldom, if ever, reason to usewait
andnotify
in new code.
I think now, the best practice is use display: inline-block;
look like this demo: https://jsfiddle.net/vjLw1z7w/
EDIT (02/2021):
Best practice now may be to using display: flex; flex-wrap: wrap;
on div container and flex-basis: XX%;
on div
look like this demo: https://jsfiddle.net/42L1emus/1/
I already said that I was new to exec()
function. After doing some more digging, I came upon 2>&1
which needs to be added at the end of command in exec()
.
Thanks @mattosmat
for pointing it out in the comments too. I did not try this at once because you said it is a Linux command, I am on Windows.
So, what I have discovered, the command is actually executing in the back-end. That is why I could not see it actually running, which I was expecting to happen.
For all of you, who had similar problem, my advise is to use that command. It will point out all the errors and also tell you info/details about execution.
exec('some_command 2>&1', $output);
print_r($output); // to see the response to your command
Thanks for all the help guys, I appreciate it ;)
There is a function in scipy named scipy.signal.find_peaks_cwt
which sounds like is suitable for your needs, however I don't have experience with it so I cannot recommend..
http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks_cwt.html
INSERT INTO prices (group, id, price)
SELECT 7, articleId, 1.50 FROM article WHERE name LIKE 'ABC%'
<title>Registration Form</title>
<script>
var table;
function check() {
debugger;
var name = document.myForm.name.value;
if (name == "" || name == null) {
document.getElementById("span1").innerHTML = "Please enter the Name";
document.myform.name.focus();
document.getElementById("name").style.border = "2px solid red";
return false;
}
else {
document.getElementById("span1").innerHTML = "";
document.getElementById("name").style.border = "2px solid green";
}
var age = document.myForm.age.value;
var ageFormat = /^(([1][8-9])|([2-5][0-9])|(6[0]))$/gm;
if (age == "" || age == null) {
document.getElementById("span2").innerHTML = "Please provide Age";
document.myForm.age.focus();
document.getElementById("age").style.border = "2px solid red";
return false;
}
else if (!ageFormat.test(age)) {
document.getElementById("span2").innerHTML = "Age can't be leass than 18 and greater than 60";
document.myForm.age.focus();
document.getElementById("age").style.border = "2px solid red";
return false;
}
else {
document.getElementById("span2").innerHTML = "";
document.getElementById("age").style.border = "2px solid green";
}
var password = document.myForm.password.value;
if (document.myForm.password.length < 6) {
alert("Error: Password must contain at least six characters!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
re = /[0-9]/g;
if (!re.test(password)) {
alert("Error: password must contain at least one number (0-9)!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
re = /[a-z]/g;
if (!re.test(password)) {
alert("Error: password must contain at least one lowercase letter (a-z)!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
re = /[A-Z]/g;
if (!re.test(password)) {
alert("Error: password must contain at least one uppercase letter (A-Z)!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
re = /[$&+,:;=?@#|'<>.^*()%!-]/g;
if (!re.test(password)) {
alert("Error: password must contain at least one special character!");
document.myForm.password.focus();
document.getElementById("password").style.border = "2px solid red";
return false;
}
else {
document.getElementById("span3").innerHTML = "";
document.getElementById("password").style.border = "2px solid green";
}
if (document.getElementById("data") == null)
createTable();
else {
appendRow();
}
return true;
}
function createTable() {
var myTableDiv = document.getElementById("myTable"); //indiv
table = document.createElement("TABLE"); //TABLE??
table.setAttribute("id", "data");
table.border = '1';
myTableDiv.appendChild(table); //appendChild() insert it in the document (table --> myTableDiv)
debugger;
var header = table.createTHead();
var th0 = table.tHead.appendChild(document.createElement("th"));
th0.innerHTML = "Name";
var th1 = table.tHead.appendChild(document.createElement("th"));
th1.innerHTML = "Age";
appendRow();
}
function appendRow() {
var name = document.myForm.name.value;
var age = document.myForm.age.value;
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = name;
row.insertCell(1).innerHTML = age;
clearForm();
}
function clearForm() {
debugger;
document.myForm.name.value = "";
document.myForm.password.value = "";
document.myForm.age.value = "";
}
function restrictCharacters(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (((charCode >= '65') && (charCode <= '90')) || ((charCode >= '97') && (charCode <= '122')) || (charCode == '32')) {
return true;
}
else {
return false;
}
}
</script>
<div>
<form name="myForm">
<table id="tableid">
<tr>
<th>Name</th>
<td>
<input type="text" name="name" placeholder="Name" id="name" onkeypress="return restrictCharacters(event);" /></td>
<td><span id="span1"></span></td>
</tr>
<tr>
<th>Age</th>
<td>
<input type="text" onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));" placeholder="Age"
name="age" id="age" /></td>
<td><span id="span2"></span></td>
</tr>
<tr>
<th>Password</th>
<td>
<input type="password" name="password" id="password" placeholder="Password" /></td>
<td><span id="span3"></span></td>
</tr>
<tr>
<td></td>
<td>
<input type="button" value="Submit" onclick="check();" /></td>
<td>
<input type="reset" name="Reset" /></td>
</tr>
</table>
</form>
<div id="myTable">
</div>
</div>
Another Alternative for those who are probing around and/or in interactive mode:
$Error[0].Exception.LoaderExceptions
Note: [0] grabs the most recent Error from the stack
You would typically do something like:
protected void btnClose_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
}
However, keep in mind that different things will happen in different scenerios.
Firefox won't let you close a window that wasn't opened by you (opened with window.open()
).
IE7 will prompt the user with a "This page is trying to close (Yes | No)" dialog.
In any case, you should be prepared to deal with the window not always closing!
One fix for the 2 above issues is to use:
protected void btnClose_Click(object sender, EventArgs e) {
ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.open('close.html', '_self', null);", true);
}
And create a close.html:
<html><head>
<title></title>
<script language="javascript" type="text/javascript">
var redirectTimerId = 0;
function closeWindow()
{
window.opener = top;
redirectTimerId = window.setTimeout('redirect()', 2000);
window.close();
}
function stopRedirect()
{
window.clearTimeout(redirectTimerId);
}
function redirect()
{
window.location = 'default.aspx';
}
</script>
</head>
<body onload="closeWindow()" onunload="stopRedirect()" style="">
<center><h1>Please Wait...</h1></center>
</body></html>
Note that close.html will redirect to default.aspx if the window does not close after 2 sec for some reason.
You might also try:
background-size: cover;
There are some good articles to read about using this CSS3 property: Perfect Full Page Background Image by CSS-Tricks and CSS Background-Size by David Walsh.
PLEASE NOTE - This will not work with IE8-. However, it will work on most versions of Chrome, Firefox and Safari.
You can also do something like this...
<input @input="myHandler('foo', 'bar', ...arguments)">
Evan You himself recommended this technique in one post on Vue forum. In general some events may emit more than one argument. Also as documentation states internal variable $event is meant for passing original DOM event.
If you want a really simple answer:
s_1 = "abc def ghi"
s_2 = "def ghi abc"
flag = 0
for i in s_1:
if i not in s_2:
flag = 1
if flag == 0:
print("a == b")
else:
print("a != b")
.png files are nice, but .ico files provide alpha-channel transparency, too, plus they give you backwards compatibility.
Have a look at which type StackOverflow uses for example (note that it's transparent):
<link rel="shortcut icon" href="http://sstatic.net/so/favicon.ico">
<link rel="apple-touch-icon" href="http://sstatic.net/so/apple-touch-icon.png">
The apple-itouch thingy is for iphone users that make a shortcut to a website.
If you want to convert an int which is in the range 0-9 to a char, you may usually write something like this:
int x;
char c = '0' + x;
Now, if you want a character string, just add a terminating '\0' char:
char s[] = {'0' + x, '\0'};
Note that:
Before understanding next
, you need to have a little idea of Request-Response cycle in node though not much in detail.
It starts with you making an HTTP request for a particular resource and it ends when you send a response back to the user i.e. when you encounter something like res.send(‘Hello World’);
let’s have a look at a very simple example.
app.get('/hello', function (req, res, next) {
res.send('USER')
})
Here we do not need next(), because resp.send will end the cycle and hand over the control back to the route middleware.
Now let’s take a look at another example.
app.get('/hello', function (req, res, next) {
res.send("Hello World !!!!");
});
app.get('/hello', function (req, res, next) {
res.send("Hello Planet !!!!");
});
Here we have 2 middleware functions for the same path. But you always gonna get the response from the first one. Because that is mounted first in the middleware stack and res.send will end the cycle.
But what if we always do not want the “Hello World !!!!” response back. For some conditions we may want the "Hello Planet !!!!" response. Let’s modify the above code and see what happens.
app.get('/hello', function (req, res, next) {
if(some condition){
next();
return;
}
res.send("Hello World !!!!");
});
app.get('/hello', function (req, res, next) {
res.send("Hello Planet !!!!");
});
What’s the next
doing here. And yes you might have gusses. It’s gonna skip the first middleware function if the condition is true and invoke the next middleware function and you will have the "Hello Planet !!!!"
response.
So, next pass the control to the next function in the middleware stack.
What if the first middleware function does not send back any response but do execute a piece of logic and then you get the response back from second middleware function.
Something like below:-
app.get('/hello', function (req, res, next) {
// Your piece of logic
next();
});
app.get('/hello', function (req, res, next) {
res.send("Hello !!!!");
});
In this case you need both the middleware functions to be invoked. So, the only way you reach the second middleware function is by calling next();
What if you do not make a call to next. Do not expect the second middleware function to get invoked automatically. After invoking the first function your request will be left hanging. The second function will never get invoked and you will not get back the response.