Ctrl+p is the normal alternative to the up arrow. Make sure you have gnu readline enabled in your Python build.
Try putting it in quotes:
find . -name '*test.c'
Just call it using super.
public void myMethod()
{
// B stuff
super.myMethod();
// B stuff
}
You can use stack
from the base package. But, you need first to coerce your matrix to a data.frame
and to reorder the columns once the data is stacked.
mat <- as.data.frame(mat)
res <- data.frame(time= mat$time,stack(mat,select=-time))
res[,c(3,1,2)]
ind time values
1 C_0 0.0 0.1
2 C_0 0.5 0.2
3 C_0 1.0 0.3
4 C_1 0.0 0.3
5 C_1 0.5 0.4
6 C_1 1.0 0.5
Note that stack
is generally more efficient than the reshape2
package.
Thanks for spotting this I was about to add strings thinking the same as you that they'd get added to end of collection. It appears the params are:
msg.to.Add(<MailAddress>) adds MailAddress to the end of the collection
msg.to.Add(<string>) add a list of emails to the collection
Slightly different actions depending on param type, I think this is pretty bad form i'd have prefered split methods AddStringList of something.
xmlns - xml namespace. It's just a method to avoid element name conflicts. For example:
<config xmlns:rnc="URI1" xmlns:bsc="URI2">
<rnc:node>
<rnc:rncId>5</rnc:rncId>
</rnc:node>
<bsc:node>
<bsc:cId>5</bsc:cId>
</bsc:node>
</config>
Two different node
elements in one xml file. Without namespaces this file would not be valid.
Also if you want to get most frequent value(positive or negative) without loading any modules you can use the following code:
lVals = [1,2,3,1,2,1,1,1,3,2,2,1]
print max(map(lambda val: (lVals.count(val), val), set(lVals)))
Terminal opens a login shell. This means, ~/.bash_profile
will get executed, ~/.bashrc
not.
The solution on most systems is to "require" the ~/.bashrc
in the ~/.bash_profile
: just put this snippet in your ~/.bash_profile
:
[[ -s ~/.bashrc ]] && source ~/.bashrc
You can create a non-nullable DATETIME column on your table, and create a DEFAULT constraint on it to auto populate when a row is added.
e.g.
CREATE TABLE Example
(
SomeField INTEGER,
DateCreated DATETIME NOT NULL DEFAULT(GETDATE())
)
If you're using Tortoise SVN, you should be able to revert changes from just that revision into your working copy (effectively performing a reverse-merge), then do another commit to re-add the file. Steps to follow are:
Use:
date.format("MM/DD/YYYY") or date.format("MM-DD-YYYY")}
Other Supported formats for reference:
M 1 2 ... 11 12
Mo 1st 2nd ... 11th 12th
MM 01 02 ... 11 12
MMM Jan Feb ... Nov Dec
MMMM January February ... November December
d 0 1 ... 5 6
do 0th 1st ... 5th 6th
dd Su Mo ... Fr Sa
ddd Sun Mon ... Fri Sat
dddd Sunday Monday ... Friday Saturday
YY 70 71 ... 29 30
YYYY 1970 1971 ... 2029 2030
Y 1970 1971 ... 9999 +10000 +10001
Try like below,
$('input[type=text]').val (function () {
return this.value.toUpperCase();
})
You should use input[type=text]
instead of :input
or input
as I believe your intention are to operate on textbox only.
When converting an ASP.Net webform prototype to a MVC site I got these errors:
TypeError: $(...).accordion is not a function
$("#accordion").accordion(
$('#dialog').dialog({
TypeError: $(...).dialog is not a function
It worked fine in the webforms. The problem/solution was this line in the _Layout.cshtml
@Scripts.Render("~/bundles/jquery")
Comment it out to see if the errors go away. Then fix it in the BundlesConfig:
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
You can add .a file in the linking command:
gcc yourfiles /path/to/library/libLIBRARY.a
But this is not talking with gcc driver, but with ld
linker as options like -Wl,anything
are.
When you tell gcc or ld -Ldir -lLIBRARY
, linker will check both static and dynamic versions of library (you can see a process with -Wl,--verbose
). To change order of library types checked you can use -Wl,-Bstatic
and -Wl,-Bdynamic
. Here is a man page of gnu LD: http://linux.die.net/man/1/ld
To link your program with lib1, lib3 dynamically and lib2 statically, use such gcc call:
gcc program.o -llib1 -Wl,-Bstatic -llib2 -Wl,-Bdynamic -llib3
Assuming that default setting of ld is to use dynamic libraries (it is on Linux).
Use an image loading library like Picasso or Glide. Using these libraries will prevent crashes in the future.
Use repr
>>> string = "abcd\n"
>>> print(repr(string))
'abcd\n'
Overload less than operator, then sort. This is an example I found off the web...
class MyData
{
public:
int m_iData;
string m_strSomeOtherData;
bool operator<(const MyData &rhs) const { return m_iData < rhs.m_iData; }
};
std::sort(myvector.begin(), myvector.end());
Source: here
_MSC_VER should be defined to a specific version number. You can either #ifdef on it, or you can use the actual define and do a runtime test. (If for some reason you wanted to run different code based on what compiler it was compiled with? Yeah, probably you were looking for the #ifdef. :))
As mentioned already, you can use the arguments
object to retrieve a variable number of function parameters.
If you want to call another function with the same arguments, use apply
. You can even add or remove arguments by converting arguments
to an array. For example, this function inserts some text before logging to console:
log() {
let args = Array.prototype.slice.call(arguments);
args = ['MyObjectName', this.id_].concat(args);
console.log.apply(console, args);
}
Just add compileOptions
in build.gradle yours app:
android {
...
defaultConfig {
...
jackOptions {
enabled true
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
If you want to see the configuration in data bricks use the below command
spark.sparkContext._conf.getAll()
Go to path and type
go get -u ./..
It will update all require packages.
building on @ltamar's answer:
Use summary and munge the output into something useful!
library(tidyr)
library(dplyr)
df %>%
summary %>%
data.frame %>%
select(-Var1) %>%
separate(data=.,col=Freq,into = c('metric','value'),sep = ':') %>%
rename(column_name=Var2) %>%
mutate(value=as.numeric(value),
metric = trimws(metric,'both')
) %>%
filter(!is.na(value)) -> metrics
It's not pretty and it is certainly not fast but it gets the job done!
Vincent Povirk's answer won't work completely;
import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
...
You have to change it in:
import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgdata = archive.read('img_01.png')
...
For details read the ZipFile
docs here.
function func1()
{
$inv = (Get-Variable MyInvocation -Scope 1).Value
#$inv.MyCommand | Format-List *
$Path1 = Split-Path $inv.scriptname
Write-Host $Path1
}
function Main()
{
func1
}
Main
You can add a watchpoint for each variable you're interested in.
A watchpoint is a special breakpoint that stops the execution of an application whenever the value of a given expression changes, without specifying where it might occur. Unlike breakpoints (which are line-specific), watchpoints are associated with files. They take effect whenever a specified condition is true, regardless of when or where it occurred. You can set a watchpoint on a global variable by highlighting the variable in the editor, or by selecting it in the Outline view.
Here's a cleaned-up, non-eval-using version of Ram-swaroop's "works in all browsers" variety--works in all browsers!
function onReady(yourMethod) {
var readyStateCheckInterval = setInterval(function() {
if (document && document.readyState === 'complete') { // Or 'interactive'
clearInterval(readyStateCheckInterval);
yourMethod();
}
}, 10);
}
// use like
onReady(function() { alert('hello'); } );
It does wait an extra 10 ms to run, however, so here's a more complicated way that shouldn't:
function onReady(yourMethod) {
if (document.readyState === 'complete') { // Or also compare to 'interactive'
setTimeout(yourMethod, 1); // Schedule to run immediately
}
else {
readyStateCheckInterval = setInterval(function() {
if (document.readyState === 'complete') { // Or also compare to 'interactive'
clearInterval(readyStateCheckInterval);
yourMethod();
}
}, 10);
}
}
// Use like
onReady(function() { alert('hello'); } );
// Or
onReady(functionName);
Maybe not so perfect as above ones, but I guess this is what you were looking for.
data[1:1,3:3] #works with positive integers
data[1:1, -3:-3] #does not work, gives the entire 1st row without the 3rd element
data[i:i,j:j] #given that i and j are positive integers
Here indexing will work from 1, i.e,
data[1:1,1:1] #means the top-leftmost element
I received this error when I had a config file with <?php
on the second line instead of the first.
One issue that can occur, and seemingly break this is when using auto minimization of css. The request path for the minified bundle can have a different path than the original css. This may happen automatically so it can cause confusion.
The mapped request path for the minified bundle should be "/originalcssfolder/minifiedbundlename" not just "minifiedbundlename".
In other words, name your bundles to have same path (with the /) as the original folder structure, this way any external resources like fonts, images will map to correct URIs by the browser. The alternative is to use absolute url( refs in your css but that isn't usually desirable.
If your <div>
has position: absolute
you need to use width: 100%;
#parent {
width: 100%;
text-align: center;
}
#child {
display: inline-block;
}
In Rider, this would be Ctrl +Shift+Keypad *, 2
But!, you cannot use the number 2 on keypad, only number 2 on the top row of the keyboard would work.
You add your ActionListener
twice to button
. So correct your code for button2
to
JButton button2 = new JButton("hello agin2");
panel.add(button2);
button2.addActionListener (new Action2());//note the button2 here instead of button
Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater
Since Python 3.5 you can unpack unlimited amount of list
s.
PEP 448 - Additional Unpacking Generalizations
So this will work:
a = ['1', '2', '3', '4']
b = ['5', '6']
function_that_needs_strings(*a, *b)
The steps in order to make a full check are:
Prepare the captor :
ArgumentCaptor<SomeArgumentClass> someArgumentCaptor = ArgumentCaptor.forClass(SomeArgumentClass.class);
verify the call to dependent on component (collaborator of subject under test). times(1) is the default value, so ne need to add it.
verify(dependentOnComponent, times(1)).send(someArgumentCaptor.capture());
Get the argument passed to collaborator
SomeArgumentClass someArgument = messageCaptor.getValue();
someArgument can be used for assertions
You can make a custom border using a span. Make a span with a class (Specifying the direction in which the border is going) and an id:
<html>
<body>
<div class="mdiv">
<span class="VerticalBorder" id="Span1"></span>
<header class="mheader">
<span class="HorizontalBorder" id="Span2"></span>
</header>
</div>
</body>
</html>
Then, go to you CSS and set the class to position:absolute
, height:100%
(For Vertical Borders), width:100%
(For Horizontal Borders), margin:0%
and background-color:#000000;
. Add everthing else that is necessary:
body{
margin:0%;
}
div.mdiv{
position:absolute;
width:100%;
height:100%;
top:0%;
left:0%;
margin:0%;
}
header.mheader{
position:absolute;
width:100%;
height:20%; /* You can set this to whatever. I will use 20 for easier calculations. You don't need a header. I'm using it to show you the difference. */
top:0%;
left:0%;
margin:0%;
}
span.HorizontalBorder{
position:absolute;
width:100%;
margin:0%;
background-color:#000000;
}
span.VerticalBorder{
position:absolute;
height:100%;
margin:0%;
background-color:#000000;
}
Then set the id that corresponds to class="VerticalBorder"
to top:0%;
, left:0%;
, width:1%;
(Since the width of the mdiv is equal to the width of the mheader at 100%, the width will be 100% of what you set it. If you set the width to 1% the border will be 1% of the window's width). Set the id that corresponds to the class="HorizontalBorder"
to top:99%
(Since it's in a header container the top refers to the position it is in according to the header. This + the height should add up to 100% if you want it to reach the bottom), left:0%;
and height:1%
(Since the height of the mdiv is 5 times greater than the mheader height [100% = 100, 20% = 20, 100/20 = 5], the height will be 20% of what you set it. If you set the height to 1% the border will be .2% of the window's height). Here is how it will look:
span#Span1{
top:0%;
left:0%;
width:.4%;
}
span#Span2{
top:99%;
left:0%;
width:1%;
}
DISCLAIMER: If you resize the window to a small enough size, the borders will disappear. A solution would be to cap of the size of the border if the window is resized to a certain point. Here is what I did:
window.addEventListener("load", Loaded);
function Loaded() {
window.addEventListener("resize", Resized);
function Resized() {
var WindowWidth = window.innerWidth;
var WindowHeight = window.innerHeight;
var Span1 = document.getElementById("Span1");
var Span2 = document.getElementById("Span2");
if (WindowWidth <= 800) {
Span1.style.width = .4;
}
if (WindowHeight <= 600) {
Span2.style.height = 1;
}
}
}
If you did everything right, it should look like how it is in this link: https://jsfiddle.net/umhgkvq8/12/ For some odd reason, the the border will disappear in jsfiddle but not if you launch it to a browser.
This will do it:
/[A-Za-z\u00C0-\u00FF ]+/.exec('hipopótamo maçã pólen ñ poção água língüa')
It explicitly selects a range of unicode characters. It will work for latin characters, but other strange characters may be out of this range.
var svg = d3.select("body")
.append("svg")
.style("width", 200)
.style("height", 100)
You can enter the following formula in the cell where you want to see the Overdue
or Not due
result:
=IF(ISBLANK(O10),"",IF(O10<TODAY(),"Overdue","Not due"))
This formula first tests if the source cell is blank. If it is, then the result cell will be filled with the empty string. If the source is not blank, then the formula tests if the date in the source cell is before the current day. If it is, then the value is set to Overdue
, otherwise it is set to Not due
.
Converting int64
:
n := int64(32)
str := strconv.FormatInt(n, 10)
fmt.Println(str)
// Prints "32"
There are two attributes, namely readonly
and disabled
, that can make a semi-read-only input. But there is a tiny difference between them.
<input type="text" readonly />
<input type="text" disabled />
readonly
attribute makes your input text disabled, and users are not able to change it anymore.disabled
attribute make your input-text disabled(unchangeable) but also cannot it be submitted.jQuery approach (1):
$("#inputID").prop("readonly", true);
$("#inputID").prop("disabled", true);
jQuery approach (2):
$("#inputID").attr("readonly","readonly");
$("#inputID").attr("disabled", "disabled");
JavaScript approach:
document.getElementById("inputID").readOnly = true;
document.getElementById("inputID").disabled = true;
PS prop
introduced with jQuery 1.6
.
Change your code to
document.write("<td width='74'><button id='button' type='button' onclick='myfunction(\""+ name + "\")'>click</button></td>")
find the numbers and then replaced with strings which specified. It is achieved by two methods
Using a regular expression literal
Using keyword RegExp object
Using a regular expression literal:
<script type="text/javascript">
var string = "my contact number is 9545554545. my age is 27.";
alert(string.replace(/\d+/g, "XXX"));
</script>
**Output:**my contact number is XXX. my age is XXX.
for more details:
http://www.infinetsoft.com/Post/How-to-replace-number-with-string-in-JavaScript/1156
Grab an executable from info-zip.
Info-ZIP supports hardware from microcomputers all the way up to Cray supercomputers, running on almost all versions of Unix, VMS, OS/2, Windows 9x/NT/etc. (a.k.a. Win32), Windows 3.x, Windows CE, MS-DOS, AmigaDOS, Atari TOS, Acorn RISC OS, BeOS, Mac OS, SMS/QDOS, MVS and OS/390 OE, VM/CMS, FlexOS, Tandem NSK and Human68K (Japanese). There is also some (old) support for LynxOS, TOPS-20, AOS/VS and Novell NLMs. Shared libraries (DLLs) are available for Unix, OS/2, Win32 and Win16, and graphical interfaces are available for Win32, Win16, WinCE and Mac OS.
Here is a simple way to implement ls
command using c
. To run use for example ./xls /tmp
#include<stdio.h>
#include <dirent.h>
void main(int argc,char *argv[])
{
DIR *dir;
struct dirent *dent;
dir = opendir(argv[1]);
if(dir!=NULL)
{
while((dent=readdir(dir))!=NULL)
{
if((strcmp(dent->d_name,".")==0 || strcmp(dent->d_name,"..")==0 || (*dent->d_name) == '.' ))
{
}
else
{
printf(dent->d_name);
printf("\n");
}
}
}
close(dir);
}
You can do the following
foreach (var it in someCollection.Select((x, i) => new { Value = x, Index = i }) )
{
if (it.Index > SomeNumber) //
}
This will create an anonymous type value for every entry in the collection. It will have two properties
Value
: with the original value in the collectionIndex
: with the index within the collectionI had a similar problem, but mine was related to unmanageable memory leak that I couldn't find on an app that has to run 24/7. With the customer I agreed that safe time to restart the app was 03:00AM if the memory consumption was over the defined value.
I tried Application.Restart
, but since it seems to use some mechanism that starts new instance while it is already running, I went for another scheme. I used the trick that file system handles persist until process that created them dies. So, from The Application, i dropped the file to the disk, and didn't Dispose()
the handle. I used the file to send 'myself' executable and starting directory also (to add flexibility).
Code:
_restartInProgress = true;
string dropFilename = Path.Combine(Application.StartupPath, "restart.dat");
StreamWriter sw = new StreamWriter(new FileStream(dropFilename, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite));
sw.WriteLine(Application.ExecutablePath);
sw.WriteLine(Application.StartupPath);
sw.Flush();
Process.Start(new ProcessStartInfo
{
FileName = Path.Combine(Application.StartupPath, "VideoPhill.Restarter.exe"),
WorkingDirectory = Application.StartupPath,
Arguments = string.Format("\"{0}\"", dropFilename)
});
Close();
Close()
at the end would initiate app shutdown, and file handle I used for StreamWriter
here would be held open until process really dies. Then...
Restarter.exe comes into action. It TRIES to read the file in exclusive mode, preventing it to gain access until main app wasn't dead, then starts main app, deletes the file and exists. I guess that it can't be simpler:
static void Main(string[] args)
{
string filename = args[0];
DateTime start = DateTime.Now;
bool done = false;
while ((DateTime.Now - start).TotalSeconds < 30 && !done)
{
try
{
StreamReader sr = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite));
string[] runData = new string[2];
runData[0] = sr.ReadLine();
runData[1] = sr.ReadLine();
Thread.Sleep(1000);
Process.Start(new ProcessStartInfo { FileName = runData[0], WorkingDirectory = runData[1] });
sr.Dispose();
File.Delete(filename);
done = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Thread.Sleep(1000);
}
}
The key is the parameters :
If you provide Parameters [ Height="" , Width="" ] , then it will open in new windows.
If you DON'T provide Parameters , then it will open in new tab.
Tested in Chrome and Firefox
Just in case if you wanna check user's group belongs to a predefined group list:
def is_allowed(user):
allowed_group = set(['admin', 'lead', 'manager'])
usr = User.objects.get(username=user)
groups = [ x.name for x in usr.groups.all()]
if allowed_group.intersection(set(groups)):
return True
return False
I would turn it into a json object, with the added benefit of keeping the keys if you are using an associative array:
$stringRepresentation= json_encode($arr);
Read up on RAII and make sure you understand it.
If you can turn the stored procedure into a function that returns a table, then you can use cross-apply.
For example, say you have a table of customers, and you want to compute the sum of their orders, you would create a function that took a CustomerID and returned the sum.
And you could do this:
SELECT CustomerID, CustomerSum.Total
FROM Customers
CROSS APPLY ufn_ComputeCustomerTotal(Customers.CustomerID) AS CustomerSum
Where the function would look like:
CREATE FUNCTION ComputeCustomerTotal
(
@CustomerID INT
)
RETURNS TABLE
AS
RETURN
(
SELECT SUM(CustomerOrder.Amount) AS Total FROM CustomerOrder WHERE CustomerID = @CustomerID
)
Obviously, the example above could be done without a user defined function in a single query.
The drawback is that functions are very limited - many of the features of a stored procedure are not available in a user-defined function, and converting a stored procedure to a function does not always work.
"Stack Me 123 Heppa1 oeu".toCharArray()
?
I've done the clean and rebuild thing. That didn't work (it usually does). Now, I am attaching to w3wp before calling through the service, then let it call the service once, hit another breakpoint, then I change the point of execution so that it will run the same line (calling the service) again, then it actually stops at my breakpoint inside the service method.
s[0:"s".index("&")]
what does this do:
Answer in Swift:
Add delegate UIGestureRecognizerDelegate
to your UITableViewController.
Within UITableViewController:
override func viewDidLoad() {
super.viewDidLoad()
let longPressGesture:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: "handleLongPress:")
longPressGesture.minimumPressDuration = 1.0 // 1 second press
longPressGesture.delegate = self
self.tableView.addGestureRecognizer(longPressGesture)
}
And the function:
func handleLongPress(longPressGesture:UILongPressGestureRecognizer) {
let p = longPressGesture.locationInView(self.tableView)
let indexPath = self.tableView.indexPathForRowAtPoint(p)
if indexPath == nil {
print("Long press on table view, not row.")
}
else if (longPressGesture.state == UIGestureRecognizerState.Began) {
print("Long press on row, at \(indexPath!.row)")
}
}
If you have multiple subplots, i.e.
fig, ax = plt.subplots(4, 2)
You can use the same y limits for all of them. It gets limits of y ax from first plot.
plt.setp(ax, ylim=ax[0,0].get_ylim())
eric@dev /home/el/kafka_2.10-0.8.1.1/libs $ for i in `find . -name "*.jar"`; do
> echo $i
> done
./slf4j-api-1.7.2.jar
./zookeeper-3.3.4.jar
./kafka_2.10-0.8.1.1-javadoc.jar
./kafka_2.10-0.8.1.1-sources.jar
It seems that most of the answers missed the original question.
Is there a standard sign function (signum, sgn) in C/C++?
Not in the standard library, however there is copysign
which can be used almost the same way via copysign(1.0, arg)
and there is a true sign function in boost
, which might as well be part of the standard.
#include <boost/math/special_functions/sign.hpp>
//Returns 1 if x > 0, -1 if x < 0, and 0 if x is zero.
template <class T>
inline int sign (const T& z);
Python 3 handles strings a bit different. Originally there was just one type for
strings: str
. When unicode gained traction in the '90s the new unicode
type
was added to handle Unicode without breaking pre-existing code1. This is
effectively the same as str
but with multibyte support.
In Python 3 there are two different types:
bytes
type. This is just a sequence of bytes, Python doesn't know
anything about how to interpret this as characters.str
type. This is also a sequence of bytes, but Python knows how to
interpret those bytes as characters.unicode
type was dropped. str
now supports unicode.In Python 2 implicitly assuming an encoding could cause a lot of problems; you
could end up using the wrong encoding, or the data may not have an encoding at
all (e.g. it’s a PNG image).
Explicitly telling Python which encoding to use (or explicitly telling it to
guess) is often a lot better and much more in line with the "Python philosophy"
of "explicit is better than implicit".
This change is incompatible with Python 2 as many return values have changed,
leading to subtle problems like this one; it's probably the main reason why
Python 3 adoption has been so slow. Since Python doesn't have static typing2
it's impossible to change this automatically with a script (such as the bundled
2to3
).
str
to bytes
with bytes('h€llo', 'utf-8')
; this should
produce b'H\xe2\x82\xacllo'
. Note how one character was converted to three
bytes.bytes
to str
with b'H\xe2\x82\xacllo'.decode('utf-8')
.Of course, UTF-8 may not be the correct character set in your case, so be sure to use the correct one.
In your specific piece of code, nextline
is of type bytes
, not str
,
reading stdout
and stdin
from subprocess
changed in Python 3 from str
to
bytes
. This is because Python can't be sure which encoding this uses. It
probably uses the same as sys.stdin.encoding
(the encoding of your system),
but it can't be sure.
You need to replace:
sys.stdout.write(nextline)
with:
sys.stdout.write(nextline.decode('utf-8'))
or maybe:
sys.stdout.write(nextline.decode(sys.stdout.encoding))
You will also need to modify if nextline == ''
to if nextline == b''
since:
>>> '' == b''
False
Also see the Python 3 ChangeLog, PEP 358, and PEP 3112.
1 There are some neat tricks you can do with ASCII that you can't do with multibyte character sets; the most famous example is the "xor with space to switch case" (e.g. chr(ord('a') ^ ord(' ')) == 'A'
) and "set 6th bit to make a control character" (e.g. ord('\t') + ord('@') == ord('I')
). ASCII was designed in a time when manipulating individual bits was an operation with a non-negligible performance impact.
2 Yes, you can use function annotations, but it's a comparatively new feature and little used.
Here is another way to use SQL SELECT
statement in VBA:
sSQL = "SELECT Variable FROM GroupTable WHERE VariableCode = '" & Me.comboBox & "'"
Set rs = CurrentDb.OpenRecordset(sSQL)
On Error GoTo resultsetError
dbValue = rs!Variable
MsgBox dbValue, vbOKOnly, "RS VALUE"
resultsetError:
MsgBox "Error Retrieving value from database",VbOkOnly,"Database Error"
I had a similar instance where I wanted to use .toFixed()
where necessary, but I didn't want the padding when it wasn't. So I ended up using parseFloat in conjunction with toFixed.
toFixed without padding
parseFloat(n.toFixed(4));
Another option that does almost the same thing
This answer may help your decision
Number(n.toFixed(4));
toFixed
will round/pad the number to a specific length, but also convert it to a string. Converting that back to a numeric type will not only make the number safer to use arithmetically, but also automatically drop any trailing 0's. For example:
var n = "1.234000";
n = parseFloat(n);
// n is 1.234 and in number form
Because even if you define a number with trailing zeros they're dropped.
var n = 1.23000;
// n == 1.23;
This is the simplest and most 'readable' way I know of:
git branch -m my_old_branch_name my_new_branch_name
git push origin -u my_new_branch_name
(setting 'upstream' essentially 'connects' your local branch to the remote, so that things like fetch, pull and push will work)
git push origin -D <old_name>
(your local branch is already gone, because you 'moved' it in the 1st step)
This works well:
{{ app('request')->input('a') }}
Where a
is the url parameter.
See more here: http://blog.netgloo.com/2015/07/17/lumen-getting-current-url-parameter-within-a-blade-view/
** for Hexa to String**
let input = '32343630';
Note : let output = new Buffer(input, 'hex'); // this is deprecated
let buf = Buffer.from(input, "hex");
let data = buf.toString("utf8");
In my case it was libjpeg
. All I had to do was run brew reinstall libjpeg
and everything just worked!
I had the same problem when trying to run a PowerShell script that only looked at a remote server to read the size of a hard disk.
I turned off the Firewall (Domain networks, Private networks, and Guest or public network) on the remote server and the script worked.
I then turned the Firewall for Domain networks back on, and it worked.
I then turned the Firewall for Private network back on, and it also worked.
I then turned the Firewall for Guest or public networks, and it also worked.
Reasoning from the comments to this question, it appears a lack of an adjusted session.save_path causes this misbehavior of PHP’s session handler. Just specify a directory (outside your document root directory) that exists and is both readable and writeable by PHP to fix this.
This is how you link a JS file in HTML
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
- tag is used to define a client-side script, such as a JavaScript.
type
- specify the type of the script
src
- script file name and path
Both if (one.length() > 0) {}
and if (!"".equals(one)) {}
will check against an empty foo parameter, and an empty parameter is what you'd get if the the form is submitted with no value in the foo
text field.
If there's any chance you can use the Expression Language to handle the parameter, you could
access it with empty param.foo
in an expression.
<c:if test='${not empty param.foo}'>
This page code gets rendered.
</c:if>
Active and passive are the two modes that FTP can run in.
For background, FTP actually uses two channels between client and server, the command and data channels, which are actually separate TCP connections.
The command channel is for commands and responses while the data channel is for actually transferring files.
This separation of command information and data into separate channels a nifty way of being able to send commands to the server without having to wait for the current data transfer to finish. As per the RFC, this is only mandated for a subset of commands, such as quitting, aborting the current transfer, and getting the status.
In active mode, the client establishes the command channel but the server is responsible for establishing the data channel. This can actually be a problem if, for example, the client machine is protected by firewalls and will not allow unauthorised session requests from external parties.
In passive mode, the client establishes both channels. We already know it establishes the command channel in active mode and it does the same here.
However, it then requests the server (on the command channel) to start listening on a port (at the servers discretion) rather than trying to establish a connection back to the client.
As part of this, the server also returns to the client the port number it has selected to listen on, so that the client knows how to connect to it.
Once the client knows that, it can then successfully create the data channel and continue.
More details are available in the RFC: https://www.ietf.org/rfc/rfc959.txt
Here's how to look in the documentation.
First, you're dealing with IO, so look in the java.io
package.
There are two classes that look interesting: FileFilter and FileNameFilter. When I clicked on the first, it showed me that there was a a listFiles()
method in the File class. And the documentation for that method says:
Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.
Scrolling up in the File
JavaDoc, I see the constructors. And that's really all I need to be able to create a File
instance and call listFiles()
on it. Scrolling still further, I can see some information about how files are named in different operating systems.
I recently came across Python 3 interpreter at CompileOnline.
open finder and go to applications and make sure that vscode exists there ,then open type in terminal export PATH="/Applications/Visual Studio Code.app/Contents/Resources/app/bin"
use getchar and a while that look like this
while(x = getchar())
{
if(x == '\n'||x == '\0')
do what you need when space or return is detected
else
mystring.append(x)
}
Sorry if I wrote a pseudo-code but I don't work with C language from a while.
You may need the following two functions: pad
- to pad(when doing encryption) and unpad
- to unpad (when doing decryption) when the length of input is not a multiple of BLOCK_SIZE.
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[:-ord(s[len(s)-1:])]
So you're asking the length of key? You can use the md5sum of the key rather than use it directly.
More, according to my little experience of using PyCrypto, the IV is used to mix up the output of a encryption when input is same, so the IV is chosen as a random string, and use it as part of the encryption output, and then use it to decrypt the message.
And here's my implementation, hope it will be useful for you:
import base64
from Crypto.Cipher import AES
from Crypto import Random
class AESCipher:
def __init__( self, key ):
self.key = key
def encrypt( self, raw ):
raw = pad(raw)
iv = Random.new().read( AES.block_size )
cipher = AES.new( self.key, AES.MODE_CBC, iv )
return base64.b64encode( iv + cipher.encrypt( raw ) )
def decrypt( self, enc ):
enc = base64.b64decode(enc)
iv = enc[:16]
cipher = AES.new(self.key, AES.MODE_CBC, iv )
return unpad(cipher.decrypt( enc[16:] ))
Simply you cant !! but you have some possbile options :
1- Excute php page as external page.
2- write your html code inside the php page itself.
3- use iframe to include the php within the html page.
to be more specific , unless you wanna edit your htaccess file , you may then consider this:
I had similar problem. I changed Direct connection to Native and it worked.
Preferences ? General ? Network Connections.
try this
var events = [];
alert(doc);
var obj = jQuery.parseJSON(doc);
$.each(obj, function (key, value) {
alert(value.title);
});
Here is a more detailed version of how to use the Github token without publishing in the package.json
file.
git config --global url."https://<TOKEN HERE>:[email protected]/".insteadOf https://[email protected]/
npm install --loglevel verbose --save git+https://[email protected]/<USERNAME HERE>/<REPOSITORY HERE>.git#v0.1.27
In case access to Github fails, try running the git ls-remote ...
command that the npm install will print
I kinda disagree with the accepted answer. Sometimes an application architecture doesn't want you to mess with the array id, or makes it inconvenient. For instance, I use CakePHP quite a lot, and a database query returns the primary key as a value in each record, very similar to the above.
Assuming the array is not stupidly large, I would use array_filter. This will create a copy of the array, minus the records you want to remove, which you can assign back to the original array variable.
Although this may seem inefficient it's actually very much in vogue these days to have variables be immutable, and the fact that most php array functions return a new array rather than futzing with the original implies that PHP kinda wants you to do this too. And the more you work with arrays, and realize how difficult and annoying the unset() function is, this approach makes a lot of sense.
Anyway:
$my_array = array_filter($my_array,
function($el) {
return $el["value"]!="Completed" && $el!["value"]!="Marked as Spam";
});
You can use whatever inclusion logic (eg. your id field) in the embedded function that you want.
thisTag = _tags.FirstOrDefault(t => t.Key == tag);
is an inefficient and a little bit strange way to find something by key in a dictionary. Looking things up for a Key is the basic function of a Dictionary.
The basic solution would be:
if (_tags.Containskey(tag)) { string myValue = _tags[tag]; ... }
But that requires 2 lookups.
TryGetValue(key, out value)
is more concise and efficient, it only does 1 lookup. And that answers the last part of your question, the best way to do a lookup is:
string myValue;
if (_tags.TryGetValue(tag, out myValue)) { /* use myValue */ }
VS 2017 update, for C# 7 and beyond we can declare the result variable inline:
if (_tags.TryGetValue(tag, out string myValue))
{
// use myValue;
}
// use myValue, still in scope, null if not found
I've recently created library which helps to cope with pagination cases like:
DEMO page implements all above features.
Source code you can find on Github
You mean this?
from string import punctuation, digits
takeout = punctuation + digits
turnthis = "(fjskl) 234 = -345 089 abcdef"
turnthis = turnthis.translate(None, takeout)[::-1]
print turnthis
Sure, you can open the devtools with Ctrl+Shift+I, and then click the inspect element button (square with the arrow)
You should pass the event object when calling the function :
{<td><span onClick={(e) => this.toggle(e)}>Details</span></td>}
If you don't need to handle onClick event you can also type :
{<td><span onClick={(e) => this.toggle()}>Details</span></td>}
Now you can also add your parameters within the function.
Just to add an example with parameters:
class B(A):
def __init__(self, x, y, z):
A.__init__(self, x, y)
Given a derived class B that requires the variables x, y, z to be defined, and a superclass A that requires x, y to be defined, you can call the static method init of the superclass A with a reference to the current subclass instance (self) and then the list of expected arguments.
std::getline( stream, where to?, delimiter ie
std::string in;
std::getline(std::cin, in, ' '); //will split on space
or you can read in a line, then tokenize it based on whichever delimiter you wish.
You're thinking too much in pure Javascript. Get rid of your listeners on those React lifecycle methods and use event.key
instead of event.keyCode
(because this is not a JS event object, it is a React SyntheticEvent). Your entire component could be as simple as this (assuming you haven't bound your methods in a constructor).
onKeyPressed(e) {
console.log(e.key);
}
render() {
let player = this.props.boards.dungeons[this.props.boards.currentBoard].player;
return (
<div
className="player"
style={{ position: "absolute" }}
onKeyDown={this.onKeyPressed}
>
<div className="light-circle">
<div className="image-wrapper">
<img src={IMG_URL+player.img} />
</div>
</div>
</div>
)
}
I am a little late to this thread but in fact there is direct support for the like operator in MS SQL server.
As documented in LIKE help if the datatype is not a string it is attempted to convert it to a string. And as documented in cast\convert documentation:
default datetime conversion to string is type 0 (,100) which is mon dd yyyy hh:miAM (or PM).
If you have a date like this in the DB:
2015-06-01 11:52:59.057
and you do queries like this:
select * from wws_invoice where invdate like 'Jun%'
select * from wws_invoice where invdate like 'Jun 1%'
select * from wws_invoice where invdate like 'Jun 1 %'
select * from wws_invoice where invdate like 'Jun 1 2015:%'
select * from wws_invoice where invdate like 'Jun ? 2015%'
...
select * from wws_invoice where invdate like 'Jun 1 2015 11:52AM'
you get that row.
However, this date format suggests that it is a DateTime2, then documentation says:
21 or 121 -- ODBC canonical (with milliseconds) default for time, date, datetime2, and datetimeoffset. -- yyyy-mm-dd hh:mi:ss.mmm(24h)
That makes it easier and you can use:
select * from wws_invoice where invdate like '2015-06-01%'
and get the invoice record. Here is a demo code:
DECLARE @myDates TABLE (myDate DATETIME2);
INSERT INTO @myDates (myDate)
VALUES
('2015-06-01 11:52:59.057'),
('2015-06-01 11:52:59.054'),
('2015-06-01 13:52:59.057'),
('2015-06-01 14:52:59.057');
SELECT * FROM @myDates WHERE myDate LIKE '2015-06-01%';
SELECT * FROM @myDates WHERE myDate LIKE '2015-06-01 11%';
SELECT * FROM @myDates WHERE myDate LIKE '2015-06-01 11:52:59%';
SELECT * FROM @myDates WHERE myDate LIKE '2015-06-01 11:52:59.054%';
Doing datetime searches in SQL server without any conversion to string has always been problematic. Getting each date part is an overkill (which unlikely would use an index). Probably a better way when you don't use string conversion would be to use range checks. ie:
select * from record
where register_date >= '20091010' and register_date < '20091011';
Use jQTouch instead - its jQuery's mobile version
If you want an 2d array of integers, which elements are allocated sequentially in memory, you must declare it like
int (*intPtr)[n] = new int[x][n]
where instead of x you can write any dimension, but n must be the same in two places. Example
int (*intPtr)[8] = new int[75][8];
intPtr[5][5] = 6;
cout<<intPtr[0][45]<<endl;
must print 6.
It's also important to realize that simply moving the program break pointer around with brk
and sbrk
doesn't actually allocate the memory, it just sets up the address space. On Linux, for example, the memory will be "backed" by actual physical pages when that address range is accessed, which will result in a page fault, and will eventually lead to the kernel calling into the page allocator to get a backing page.
What about data binding?
@JvmStatic
@BindingAdapter("textHtml")
fun setHtml(textView: TextView, resource: String) {
val html: Spanned = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(resource, Html.FROM_HTML_MODE_COMPACT)
} else {
Html.fromHtml(resource)
}
textView.movementMethod = LinkMovementMethod.getInstance()
textView.text = html
}
strings.xml
<string name="text_with_link"><a href=%2$s>%1$s</a> </string>
in your layout.xml
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:textHtml="@{@string/text_with_link(model.title, model.url)}"
tools:text="Some text" />
Where title and link in xml is a simple String
Also you can pass multiple arguments to data binding adapter
@JvmStatic
@BindingAdapter(value = ["textLink", "link"], requireAll = true)
fun setHtml(textView: TextView, textLink: String?, link: String?) {
val resource = String.format(textView.context.getString(R.string.text_with_link, textLink, link))
val html: Spanned = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(resource, Html.FROM_HTML_MODE_COMPACT)
} else {
Html.fromHtml(resource)
}
textView.movementMethod = LinkMovementMethod.getInstance()
textView.text = html
}
and in .xml pass arguments separately
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:link="@{model.url}"
app:textLink="@{model.title}"
tools:text="Some text" />
You can use this library:
https://github.com/kmfish/MultiTypeListViewAdapter (written by me)
Setup adapter:
adapter = new BaseRecyclerAdapter();
adapter.registerDataAndItem(TextModel.class, LineListItem1.class);
adapter.registerDataAndItem(ImageModel.class, LineListItem2.class);
adapter.registerDataAndItem(AbsModel.class, AbsLineItem.class);
For each line item:
public class LineListItem1 extends BaseListItem<TextModel, LineListItem1.OnItem1ClickListener> {
TextView tvName;
TextView tvDesc;
@Override
public int onGetLayoutRes() {
return R.layout.list_item1;
}
@Override
public void bindViews(View convertView) {
Log.d("item1", "bindViews:" + convertView);
tvName = (TextView) convertView.findViewById(R.id.text_name);
tvDesc = (TextView) convertView.findViewById(R.id.text_desc);
tvName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (null != attachInfo) {
attachInfo.onNameClick(getData());
}
}
});
tvDesc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (null != attachInfo) {
attachInfo.onDescClick(getData());
}
}
});
}
@Override
public void updateView(TextModel model, int pos) {
if (null != model) {
Log.d("item1", "updateView model:" + model + "pos:" + pos);
tvName.setText(model.getName());
tvDesc.setText(model.getDesc());
}
}
public interface OnItem1ClickListener {
void onNameClick(TextModel model);
void onDescClick(TextModel model);
}
}
You can use chars as is as single byte integers.
The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.
> db.test.insert({date: ISODate()})
> db.test.insert({date: new Date()})
> db.test.find()
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") }
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") }
The native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.
If you need to, you can easily convert Date
objects to and from Unix timestamps1), using the getTime()
method and Date(milliseconds)
constructor, respectively.
1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.
You may also use LiveData
that works like an EventBus
.
class MyService : LifecycleService() {
companion object {
val BUS = MutableLiveData<Any>()
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
super.onStartCommand(intent, flags, startId)
val testItem : Object
// expose your data
if (BUS.hasActiveObservers()) {
BUS.postValue(testItem)
}
return START_NOT_STICKY
}
}
Then add an observer from your Activity
.
MyService.BUS.observe(this, Observer {
it?.let {
// Do what you need to do here
}
})
You can read more from this blog.
Displaying left middle and right of there parents. If you have more then 3 elements then use nth-child() for them.
HTML sample:
<body>
<ul class="nav-tabs">
<li><a id="btn-tab-business" class="btn-tab nav-tab-selected" onclick="openTab('business','btn-tab-business')"><i class="fas fa-th"></i>Business</a></li>
<li><a id="btn-tab-expertise" class="btn-tab" onclick="openTab('expertise', 'btn-tab-expertise')"><i class="fas fa-th"></i>Expertise</a></li>
<li><a id="btn-tab-quality" class="btn-tab" onclick="openTab('quality', 'btn-tab-quality')"><i class="fas fa-th"></i>Quality</a></li>
</ul>
</body>
CSS sample:
.nav-tabs{
position: relative;
padding-bottom: 50px;
}
.nav-tabs li {
display: inline-block;
position: absolute;
list-style: none;
}
.nav-tabs li:first-child{
top: 0px;
left: 0px;
}
.nav-tabs li:last-child{
top: 0px;
right: 0px;
}
.nav-tabs li:nth-child(2){
top: 0px;
left: 50%;
transform: translate(-50%, 0%);
}
few Unicode alternatives
var s = "0";
var s1 = string.Concat(s.Select(c => $"{(int)c:x4}")); // left padded with 0 - "0030d835dfcfd835dfdad835dfe5d835dff0d835dffb"
var sL = BitConverter.ToString(Encoding.Unicode.GetBytes(s)).Replace("-", ""); // Little Endian "300035D8CFDF35D8DADF35D8E5DF35D8F0DF35D8FBDF"
var sB = BitConverter.ToString(Encoding.BigEndianUnicode.GetBytes(s)).Replace("-", ""); // Big Endian "0030D835DFCFD835DFDAD835DFE5D835DFF0D835DFFB"
// no encodding "300035D8CFDF35D8DADF35D8E5DF35D8F0DF35D8FBDF"
byte[] b = new byte[s.Length * sizeof(char)];
Buffer.BlockCopy(s.ToCharArray(), 0, b, 0, b.Length);
var sb = BitConverter.ToString(b).Replace("-", "");
func tabGesture_Call
{
let tapRec = UITapGestureRecognizer(target: self, action: "handleTap:")
tapRec.delegate = self
self.view.addGestureRecognizer(tapRec)
//where we want to gesture like: view, label etc
}
func handleTap(sender: UITapGestureRecognizer)
{
NSLog("Touch..");
//handling code
}
My problem was my Target profile didn't have the proper code signing option selected:
Target Menu -> Code Signing -> Code Signing Identity
Choose "iPhone developer" then select the provisional profile you created.
"Last day of month
" is actually "First day of *next* month, minus 1
". So here's what I use, no need for "DaysInMonth" method:
public static DateTime FirstDayOfMonth(this DateTime value)
{
return new DateTime(value.Year, value.Month, 1);
}
public static DateTime LastDayOfMonth(this DateTime value)
{
return value.FirstDayOfMonth()
.AddMonths(1)
.AddMinutes(-1);
}
NOTE:
The reason I use AddMinutes(-1)
, not AddDays(-1)
here is because usually you need these date functions for reporting for some date-period, and when you build a report for a period, the "end date" should actually be something like Oct 31 2015 23:59:59
so your report works correctly - including all the data from last day of month.
I.e. you actually get the "last moment of the month" here. Not Last day.
OK, I'm going to shut up now.
Different timeouts mean different things. When you're working on the client.. you're probably looking mostly at the SendTimeout - check this reference - wonderful and relevant explanation: http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/84551e45-19a2-4d0d-bcc0-516a4041943d/
It says:
Brief summary of binding timeout knobs...
Client side:
SendTimeout is used to initialize the OperationTimeout, which governs the whole interaction for sending a message (including receiving a reply message in a request-reply case). This timeout also applies when sending reply messages from a CallbackContract method.
OpenTimeout and CloseTimeout are used when opening and closing channels (when no explicit timeout value is passed).
ReceiveTimeout is not used.
Server side:
Send, Open, and Close Timeout same as on client (for Callbacks).
ReceiveTimeout is used by ServiceFramework layer to initialize the session-idle timeout.
Perhaps not in the context that you have it, but you could use
SELECT DISTINCT col1,
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1),
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1, col3),
FROM TableA
You would use this to return different levels of aggregation returned in a single row. The use case would be for when a single grouping would not suffice all of the aggregates needed.
It is not elegant but possible to do it as one-liner <a>
element
<a href onclick="event.preventDefault(); location+='&like=like'">Like</a>
_x000D_
Here is a function which I made to find executable similar to the Unix command 'WHICH`
app_path_func.cmd:
@ECHO OFF
CLS
FOR /F "skip=2 tokens=1,2* USEBACKQ" %%N IN (`reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\%~1" /t REG_SZ /v "Path"`) DO (
IF /I "%%N" == "Path" (
SET wherepath=%%P%~1
GoTo Found
)
)
FOR /F "tokens=* USEBACKQ" %%F IN (`where.exe %~1`) DO (
SET wherepath=%%F
GoTo Found
)
FOR /F "tokens=* USEBACKQ" %%F IN (`where.exe /R "%PROGRAMFILES%" %~1`) DO (
SET wherepath=%%F
GoTo Found
)
FOR /F "tokens=* USEBACKQ" %%F IN (`where.exe /R "%PROGRAMFILES(x86)%" %~1`) DO (
SET wherepath=%%F
GoTo Found
)
FOR /F "tokens=* USEBACKQ" %%F IN (`where.exe /R "%WINDIR%" %~1`) DO (
SET wherepath=%%F
GoTo Found
)
:Found
SET %2=%wherepath%
:End
Test:
@ECHO OFF
CLS
CALL "app_path_func.cmd" WINWORD.EXE PROGPATH
ECHO %PROGPATH%
PAUSE
Result:
C:\Program Files (x86)\Microsoft Office\Office15\
Press any key to continue . . .
Firstly, you need to change this line:
element.setAttribute("onclick", alert("blabla"));
To something like this:
element.setAttribute("onclick", function() { alert("blabla"); });
Secondly, you may have browser compatibility issues when attaching events that way. You might need to use .attachEvent / .addEvent, depending on which browser. I haven't tried manually setting event handlers for a while, but I remember firefox and IE treating them differently.
select Qty, vajan, Rate,Amt,nhamali,ncommission,ntolai from SalesDtl,SalesMSt where SalesDtl.PurEntryNo=1 and SalesMST.SaleDate= (22/03/2014) and SalesMST.SaleNo= SalesDtl.SaleNo;
That should work.
The fastest way is changing the Build configuration type and return to previous configuration again.
?php
/* Database config */
$db_host = 'localhost';
$db_user = '~';
$db_pass = '~';
$db_database = 'banners';
/* End config */
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
The complete article that works for me: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding
The part where we encode from Unicode/UTF-8 is
function utf8_to_b64( str ) {
return window.btoa(unescape(encodeURIComponent( str )));
}
function b64_to_utf8( str ) {
return decodeURIComponent(escape(window.atob( str )));
}
// Usage:
utf8_to_b64('? à la mode'); // "4pyTIMOgIGxhIG1vZGU="
b64_to_utf8('4pyTIMOgIGxhIG1vZGU='); // "? à la mode"
This is one of the most used methods nowadays.
Take an input float as left. Then take the button and float it right. You can clearfix class when you take more than one to distance.
<input style="width:65%;float:left"class="btn btn-primary" type="text" name="name">
<div style="width:8%;float:left"> </div>
<button class="btn btn-default" type="button">Go!</button>
<div class="clearfix" style="margin-bottom:10px"> </div>
Go to this link
Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download
Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.
In VS 2019, just do FETCH Do not pull code.
This is what I did. Added below in .gitconfig file so that I can use Beyond Compare
File location: C:\Users\[username]\.gitconfig
Added below
[diff]
tool = bc
[difftool "bc"]
path = c:/Program Files/Beyond Compare 4/bcomp.exe
Open command prompt and go to working directory. I gave below to compare local DEV branch to remote DEV branch
git difftool dev origin/dev --dir-diff
This will open Beyond Compare and open directories which have files that differ. If no changes Beyond Compare will not launch.
Here is good solution with less coding...
var y = "";
var arr = x.toString().split("");
for(var i=0; i<arr.length; i++)
{
y += arr[i];
if((arr.length-i-1)%3==0 && i<arr.length-1) y += ",";
}
Because this is a very popular question i add another, now available, solution. With python 3.9 (https://docs.python.org/3.9/whatsnew/3.9.html) the function removesuffix()
will be added (and removeprefix()
) and this function is exactly what was questioned here.
url = 'abcdc.com'
print(url.removesuffix('.com'))
output:
'abcdc'
PEP 616 (https://www.python.org/dev/peps/pep-0616/) shows how it will behave (it is not the real implementation):
def removeprefix(self: str, prefix: str, /) -> str:
if self.startswith(prefix):
return self[len(prefix):]
else:
return self[:]
and what benefits it has against self-implemented solutions:
Less fragile: The code will not depend on the user to count the length of a literal.
More performant: The code does not require a call to the Python built-in len function nor to the more expensive str.replace() method.
More descriptive: The methods give a higher-level API for code readability as opposed to the traditional method of string slicing.
A negative look ahead is a correct answer, but it can be written more cleanly like:
(\\)(?!.*\\)
This looks for an occurrence of \ and then in a check that does not get matched, it looks for any number of characters followed by the character you don't want to see after it. Because it's negative, it only matches if it does not find a match.
You can use the from
and size
parameters to page through all your data. This could be very slow depending on your data and how much is in the index.
http://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-from-size.html
After writing
header('HTTP/1.0 404 Not Found');
add one more header for any inexisting page on your site. It works, for sure.
header("Location: http://yoursite/nowhere");
die;
The values()
method returns a QuerySet containing dictionaries:
<QuerySet [{'comment_id': 1}, {'comment_id': 2}]>
The values_list()
method returns a QuerySet containing tuples:
<QuerySet [(1,), (2,)]>
If you are using values_list()
with a single field, you can use flat=True
to return a QuerySet of single values instead of 1-tuples:
<QuerySet [1, 2]>
You can use Lodash
const _ = require('lodash');
let firstObject = {'email' : '[email protected]};
let secondObject = { 'name' : { 'first':message.firstName } };
_.merge(firstObject, secondObject)
You can use the Media Library Folders plugin. It allows you to create folders, move or copy images to a folder and even includes a sync function to bulk add images uploaded by FTP to the server to the Wordpress media library.
You can do:
SELECT column1, column2, column4 FROM table WHERE whatever
without getting column3, though perhaps you were looking for a more general solution?
I don't think you understand how \n works. The resulting string still just contains a byte with value 10. This is represented in javascript source code with \n.
The code snippet you posted doesn't actually work, but if it did, the newline would be equivalent to \n, unless it's a windows-style newline, in which case it would be \r\n. (but even that the replace would still work).
Lots of answers already here, but I found they didn't handle all cases, such as the base and target being the same. This function takes a base directory and a target path and returns the relative path. If no relative path exists, the target path is returned. File.separator is unnecessary.
public static String getRelativePath (String baseDir, String targetPath) {
String[] base = baseDir.replace('\\', '/').split("\\/");
targetPath = targetPath.replace('\\', '/');
String[] target = targetPath.split("\\/");
// Count common elements and their length.
int commonCount = 0, commonLength = 0, maxCount = Math.min(target.length, base.length);
while (commonCount < maxCount) {
String targetElement = target[commonCount];
if (!targetElement.equals(base[commonCount])) break;
commonCount++;
commonLength += targetElement.length() + 1; // Directory name length plus slash.
}
if (commonCount == 0) return targetPath; // No common path element.
int targetLength = targetPath.length();
int dirsUp = base.length - commonCount;
StringBuffer relative = new StringBuffer(dirsUp * 3 + targetLength - commonLength + 1);
for (int i = 0; i < dirsUp; i++)
relative.append("../");
if (commonLength < targetLength) relative.append(targetPath.substring(commonLength));
return relative.toString();
}
The other answers detail the reason for the error. A possible cause (to check) may be your class has a variable and method with the same name, which you then call. Python accesses the variable as a callable - with ()
.
e.g. Class A defines self.a
and self.a()
:
>>> class A:
... def __init__(self, val):
... self.a = val
... def a(self):
... return self.a
...
>>> my_a = A(12)
>>> val = my_a.a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>>
document.querySelector('#edit-submitted-first-name').required = false;
$('#edit-submitted-first-name').removeAttr('required');
A little bug with indexcolumn in alexander's answer: We need to take care of "not found" column:
int GetColumnIndexByName(GridViewRow row, string columnName)
{
int columnIndex = 0;
int foundIndex=-1;
foreach (DataControlFieldCell cell in row.Cells)
{
if (cell.ContainingField is BoundField)
{
if (((BoundField)cell.ContainingField).DataField.Equals(columnName))
{
foundIndex=columnIndex;
break;
}
}
columnIndex++; // keep adding 1 while we don't have the correct name
}
return foundIndex;
}
and
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int index = GetColumnIndexByName(e.Row, "myDataField");
if( index>0)
{
string columnValue = e.Row.Cells[index].Text;
}
}
}
You can use array_slice function, but do you will use another values? or only the first 5? because if you will use only the first 5 you can use the LIMIT on SQL.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("p").append(" <b>Appended text</b>.");
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button id="btn1">Append text</button>
</body>
</html>
create table payment(
user_id int(11),
account int(11) not null,
zip int(11) not null,
dt date not null
);
insert into payment values
(1,123,55555,'2009-12-12'),
(1,123,66666,'2009-12-12'),
(1,123,77777,'2009-12-13'),
(2,456,77777,'2009-12-14'),
(2,456,77777,'2009-12-14'),
(2,789,77777,'2009-12-14'),
(2,789,77777,'2009-12-14');
select foo.user_id, foo.cnt from
(select user_id,count(account) as cnt, dt from payment group by account, dt) foo
where foo.cnt > 1;
When MS-DOS and Windows 3.1 operated in 16-bit mode, an Intel 8086 word was 16 bits, a Microsoft WORD was 16 bits, a Microsoft DWORD was 32 bits, and a typical compiler's unsigned int was 16 bits.
When Windows NT operated in 32-bit mode, an Intel 80386 word was 32 bits, a Microsoft WORD was 16 bits, a Microsoft DWORD was 32 bits, and a typical compiler's unsigned int was 32 bits. The names WORD and DWORD were no longer self-descriptive but they preserved the functionality of Microsoft programs.
When Windows operates in 64-bit mode, an Intel word is 64 bits, a Microsoft WORD is 16 bits, a Microsoft DWORD is 32 bits, and a typical compiler's unsigned int is 32 bits. The names WORD and DWORD are no longer self-descriptive, AND an unsigned int no longer conforms to the principle of least surprises, but they preserve the functionality of lots of programs.
I don't think WORD or DWORD will ever change.
You should be able to get the text using getText()
(for the option element you got using getFirstSelectedOption()
):
Select select = new Select(driver.findElement(By.xpath("//select")));
WebElement option = select.getFirstSelectedOption();
String defaultItem = option.getText();
System.out.println(defaultItem );
Use the source, Luke.
No, but seriously I found that building Node.js from source, running the tests, and looking at the benchmarks did get me on the right track. From there, the .js files in the lib directory are a good place to look, especially the file http.js.
Update: I wrote this answer over a year ago, and since that time there has an explosion in the number of great resources available for people learning Node.js. Though I still believe diving into the source is worthwhile, I think that there are now better ways to get started. I would suggest some of the books on Node.js that are starting to come out.
This can be done without a function. Code below will convert a UTC time to Mountain time accounting for daylight savings. Adjust all the -6 and -7 numbers to your timezone accordingly (i.e. for EST you would adjust to -4 and -5 respectively)
--Adjust a UTC value, in the example the UTC field is identified as UTC.Field, to account for daylight savings time when converting out of UTC to Mountain time.
CASE
--When it's between March and November, it is summer time which is -6 from UTC
WHEN MONTH ( UTC.Field ) > 3 AND MONTH ( UTC.Field ) < 11
THEN DATEADD ( HOUR , -6 , UTC.Field )
--When its March and the day is greater than the 14, you know it's summer (-6)
WHEN MONTH ( UTC.Field ) = 3
AND DATEPART ( DAY , UTC.Field ) >= 14
THEN
--However, if UTC is before 9am on that Sunday, then it's before 2am Mountain which means it's still Winter daylight time.
CASE
WHEN DATEPART ( WEEKDAY , UTC.Field ) = 1
AND UTC.Field < '9:00'
--Before 2am mountain time so it's winter, -7 hours for Winter daylight time
THEN DATEADD ( HOUR , -7 , UTC.Field )
--Otherwise -6 because it'll be after 2am making it Summer daylight time
ELSE DATEADD ( HOUR , -6 , UTC.Field )
END
WHEN MONTH ( UTC.Field ) = 3
AND ( DATEPART ( WEEKDAY , UTC.Field ) + 7 ) <= DATEPART ( day , UTC.Field )
THEN
--According to the date, it's moved onto Summer daylight, but we need to account for the hours leading up to 2am if it's Sunday
CASE
WHEN DATEPART ( WEEKDAY , UTC.Field ) = 1
AND UTC.Field < '9:00'
--Before 9am UTC is before 2am Mountain so it's winter Daylight, -7 hours
THEN DATEADD ( HOUR , -7 , UTC.Field )
--Otherwise, it's summer daylight, -6 hours
ELSE DATEADD ( HOUR , -6 , UTC.Field )
END
--When it's November and the weekday is greater than the calendar date, it's still Summer so -6 from the time
WHEN MONTH ( UTC.Field ) = 11
AND DATEPART ( WEEKDAY , UTC.Field ) > DATEPART ( DAY , UTC.Field )
THEN DATEADD ( HOUR , -6 , UTC.Field )
WHEN MONTH ( UTC.Field ) = 11
AND DATEPART ( WEEKDAY , UTC.Field ) <= DATEPART ( DAY , UTC.Field )
--If the weekday is less than or equal to the calendar day it's Winter daylight but we need to account for the hours leading up to 2am.
CASE
WHEN DATEPART ( WEEKDAY , UTC.Field ) = 1
AND UTC.Field < '8:00'
--If it's before 8am UTC and it's Sunday in the logic outlined, then it's still Summer daylight, -6 hours
THEN DATEADD ( HOUR , -6 , UTC.Field )
--Otherwise, adjust for Winter daylight at -7
ELSE DATEADD ( HOUR , -7 , UTC.Field )
END
--If the date doesn't fall into any of the above logic, it's Winter daylight, -7
ELSE
DATEADD ( HOUR , -7 , UTC.Field )
END
This may work as well.
SELECT *
FROM myTable
WHERE CHARINDEX('mall', name) > 0
OR CHARINDEX('mall', description) > 0
you can use EditText.setFocusable(false)
to disable editingEditText.setFocusableInTouchMode(true)
to enable editing;
It may be possible (but very hackish) with only CSS using the :before or :after pseudo elements:
.bgtext {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.bgtext:after {_x000D_
content: "Background text";_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
z-index: -1;_x000D_
}
_x000D_
<div class="bgtext">_x000D_
Foreground text_x000D_
</div>
_x000D_
This seems to work, but you'll probably need to tweak it a little. Also note it won't work in IE6 because it doesn't support :after
.
new Thing();
is explicit that you want a constructor called whereas new Thing;
is taken to imply you don't mind if the constructor isn't called.
If used on a struct/class with a user-defined constructor, there is no difference. If called on a trivial struct/class (e.g. struct Thing { int i; };
) then new Thing;
is like malloc(sizeof(Thing));
whereas new Thing();
is like calloc(sizeof(Thing));
- it gets zero initialized.
The gotcha lies in-between:
struct Thingy {
~Thingy(); // No-longer a trivial class
virtual WaxOn();
int i;
};
The behavior of new Thingy;
vs new Thingy();
in this case changed between C++98 and C++2003. See Michael Burr's explanation for how and why.
I had the same problem but also wanted to get the content of the file (after the YAML front-matter).
This is the best solution I have found:
if (md = contents.match(/^(?<metadata>---\s*\n.*?\n?)^(---\s*$\n?)/m))
self.contents = md.post_match
self.metadata = YAML.load(md[:metadata])
end
Source and discussion: https://practicingruby.com/articles/tricks-for-working-with-text-and-files
Basically, don't use ArrayList.toString()
- build the string up for yourself. For example:
StringBuilder builder = new StringBuilder();
for (String value : publicArray) {
builder.append(value);
}
String text = builder.toString();
(Personally I wouldn't call the variable publicArray
when it's not actually an array, by the way.)
The above methods work well for small images, but when you try to resize a very large image, you will quickly run out of memory and crash the app. A much better way is to use CGImageSourceCreateThumbnailAtIndex
to resize the image without completely decoding it first.
If you have the path to the image you want to resize, you can use this:
- (void)resizeImageAtPath:(NSString *)imagePath {
// Create the image source (from path)
CGImageSourceRef src = CGImageSourceCreateWithURL((__bridge CFURLRef) [NSURL fileURLWithPath:imagePath], NULL);
// To create image source from UIImage, use this
// NSData* pngData = UIImagePNGRepresentation(image);
// CGImageSourceRef src = CGImageSourceCreateWithData((CFDataRef)pngData, NULL);
// Create thumbnail options
CFDictionaryRef options = (__bridge CFDictionaryRef) @{
(id) kCGImageSourceCreateThumbnailWithTransform : @YES,
(id) kCGImageSourceCreateThumbnailFromImageAlways : @YES,
(id) kCGImageSourceThumbnailMaxPixelSize : @(640)
};
// Generate the thumbnail
CGImageRef thumbnail = CGImageSourceCreateThumbnailAtIndex(src, 0, options);
CFRelease(src);
// Write the thumbnail at path
CGImageWriteToFile(thumbnail, imagePath);
}
More details here.
To remotely access database Mysql server 8:
CREATE USER 'root'@'%' IDENTIFIED BY 'Pswword@123';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
There are two different contexts in Android. One for your application (Let's call it the BIG one) and one for each view (let's call it the activity context).
A linearLayout is a view, so you have to call the activity context. To call it from an activity, simply call "this". So easy isn't it?
When you use
this.getApplicationContext();
You call the BIG context, the one that describes your application and cannot manage your view.
A big problem with Android is that a context cannot call your activity. That's a big deal to avoid this when someone begins with the Android development. You have to find a better way to code your class (or replace "Context context" by "Activity activity" and cast it to "Context" when needed).
Regards.
Just to update my answer. The easiest way to get your Activity context
is to define a static
instance in your Activity
. For example
public class DummyActivity extends Activity
{
public static DummyActivity instance = null;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Do some operations here
}
@Override
public void onResume()
{
super.onResume();
instance = this;
}
@Override
public void onPause()
{
super.onPause();
instance = null;
}
}
And then, in your Task
, Dialog
, View
, you could use that kind of code to get your Activity context
:
if (DummyActivity.instance != null)
{
// Do your operations with DummyActivity.instance
}
Applying the Observer Pattern with delegates and events in c# is named "Event Pattern" according to MSDN which is a slight variation.
In this Article you will find well structured examples of how to apply the pattern in c# both the classic way and using delegates and events.
Exploring the Observer Design Pattern
public class Stock
{
//declare a delegate for the event
public delegate void AskPriceChangedHandler(object sender,
AskPriceChangedEventArgs e);
//declare the event using the delegate
public event AskPriceChangedHandler AskPriceChanged;
//instance variable for ask price
object _askPrice;
//property for ask price
public object AskPrice
{
set
{
//set the instance variable
_askPrice = value;
//fire the event
OnAskPriceChanged();
}
}//AskPrice property
//method to fire event delegate with proper name
protected void OnAskPriceChanged()
{
AskPriceChanged(this, new AskPriceChangedEventArgs(_askPrice));
}//AskPriceChanged
}//Stock class
//specialized event class for the askpricechanged event
public class AskPriceChangedEventArgs : EventArgs
{
//instance variable to store the ask price
private object _askPrice;
//constructor that sets askprice
public AskPriceChangedEventArgs(object askPrice) { _askPrice = askPrice; }
//public property for the ask price
public object AskPrice { get { return _askPrice; } }
}//AskPriceChangedEventArgs
To get a NumPy array, you should use the values
attribute:
In [1]: df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['a', 'b', 'c']); df
A B
a 1 4
b 2 5
c 3 6
In [2]: df.index.values
Out[2]: array(['a', 'b', 'c'], dtype=object)
This accesses how the data is already stored, so there's no need for a conversion.
Note: This attribute is also available for many other pandas' objects.
In [3]: df['A'].values
Out[3]: Out[16]: array([1, 2, 3])
To get the index as a list, call tolist
:
In [4]: df.index.tolist()
Out[4]: ['a', 'b', 'c']
And similarly, for columns.
<?php
$toDay = date('d-m-Y');
$dbhost = "localhost";
$dbuser = "YOUR DB USER";
$dbpass = "USER PASSWORD";
$dbname = "DB NAME";
exec("mysqldump --user=$dbuser --password='$dbpass' --host=$dbhost $dbname > /home/....../public_html/".$toDay."_DB.sql");
?>
Store a reference to the meter instance as a member in Production:
public class Production {
//The other members, properties etc...
private Meter m;
Production(Meter m) {
this.m = m;
}
}
And then in the Meter-class:
public class Meter
{
private int _powerRating = 0;
private Production _production;
public Meter()
{
_production = new Production(this);
}
}
Also note that you need to implement an accessor method/property so that the Production class can actually access the powerRating member of the Meter class.
Based on above solutions I made a class var_string for my project to make life easy. Examples:
var_string x("abc %d %s", 123, "def");
std::string y = (std::string)x;
const char *z = x.c_str();
The class itself:
#include <stdlib.h>
#include <stdarg.h>
class var_string
{
public:
var_string(const char *cmd, ...)
{
va_list args;
va_start(args, cmd);
vsnprintf(buffer, sizeof(buffer) - 1, cmd, args);
}
~var_string() {}
operator std::string()
{
return std::string(buffer);
}
operator char*()
{
return buffer;
}
const char *c_str()
{
return buffer;
}
int system()
{
return ::system(buffer);
}
private:
char buffer[4096];
};
Still wondering if there will be something better in C++ ?
This may be old, but I may as well write what I've learned down. So anyway I did it this way.
---------->
Before you start, make sure the Apache rewrites module is enabled and then follow the steps below.
1) Log-in to your Magento administration area then go to System > Configuration > Web.
2) Navigate to the Unsecure and Secure tabs. Make sure the Unsecured and Secure - Base Url options have your domain name within it, and do not leave the forward slash off at the end of the URL. Example: http://www.yourdomain.co.uk/
3) While still on the Web page, navigate to Search Engine Optimisation tab and select YES underneath the Use Web Server Rewrites option.
4) Navigate to the Secure tab again (if not already on it) and select Yes on the Use Secure URLs in Front-End option.
5) Now go to the root of your Magento website folder and use this code for your .htaccess:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
Save the .htaccess and replace the original file. (PLEASE MAKE SURE TO BACKUP YOUR ORIGINAL .htaccess FILE BEFORE MESSING WITH IT!!!)
6) Now go to System > Cache Management and select all fields and make sure the Actions dropdown is set on Refresh, then submit. (This will of-course refresh the Cache.)
---------->
If this did not work please follow these extra steps.
7) Go to System > Configuration > web again. This time look for the Current Configuration Scope and select your website from the dropdown menu. (This is of course, it is set to Default Config)
8) Make sure the Unsecure and Secure fields contain the same domain as the previous Default Config file.
9) Navigate to the Search Engines Optimisation tab and select Yes underneath the Use Web Server Rewrites section.
10) Once the URLs are the same, and the rewrite is enabled save that page, then go back and make sure they are all checked as default, then save again if needed.
11) Repeat step 6.
Now your index.php problem should be fixed and all should be well!!!
I hope this helps, and good luck.
To insert value into ArrayList at particular index, use:
public void add(int index, E element)
This method will shift the subsequent elements of the list. but you can not guarantee the List will remain sorted as the new Object you insert may sit on the wrong position according to the sorting order.
To replace the element at the specified position, use:
public E set(int index, E element)
This method replaces the element at the specified position in the list with the specified element, and returns the element previously at the specified position.
In short you can try this....
<div data-role="page" style="background:url('backgrnd.png'); background-repeat: no-repeat; background-size: 100% 100%;" >
Where I have used few css and js...
<link rel="stylesheet" href="css/jquery.mobile-1.0.1.min.css" />
<script src="js/jquery-1.7.1.min.js"></script>
<script src="js/jquery.mobile-1.0.1.min.js"></script>
And it is working fine for me.
Since you've got both the shell that you're typing into and the shell that sudo -s
runs, you need to quote or escape twice. (EDITED fixed quoting)
sudo -su db2inst1 '/opt/ibm/db2/V9.7/bin/db2 force application \(1995\)'
or
sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \\\(1995\\\)
Out of curiosity, why do you need -s? Can't you just do this:
sudo -u db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)
Here is the solution.
The HTML:
<div class="rating">
<span>?</span><span>?</span><span>?</span><span>?</span><span>?</span>
</div>
The CSS:
.rating {
unicode-bidi: bidi-override;
direction: rtl;
}
.rating > span {
display: inline-block;
position: relative;
width: 1.1em;
}
.rating > span:hover:before,
.rating > span:hover ~ span:before {
content: "\2605";
position: absolute;
}
Hope this helps.
Expat is pretty decent. It's hard to give good recommendations without more information though.
Another thing you can do is cat
out what you are echoing and pipe with inline cut -c 1-1
If you prefer simplicity and more control on SQL queries then I would suggest going with Spring Data/ Spring JDBC.
Its good amount of learning curve in JPA and sometimes difficult to debug issues. On the other hand, while you have full control over SQL, it becomes much easier to optimize query and improve performance. You can easily share your SQL with DBA or someone who has a better understanding of Database.
function myStringify(obj, maxDeepLevel = 2) {
if (obj === null) {
return 'null';
}
if (obj === undefined) {
return 'undefined';
}
if (maxDeepLevel < 0 || typeof obj !== 'object') {
return obj.toString();
}
return Object
.entries(obj)
.map(x => x[0] + ': ' + myStringify(x[1], maxDeepLevel - 1))
.join('\r\n');
}
If you're running a recent-ish version of pandas then you can use the datetime attribute dt
to access the datetime components:
In [6]:
df['date'] = pd.to_datetime(df['date'])
df['year'], df['month'] = df['date'].dt.year, df['date'].dt.month
df
Out[6]:
date Count year month
0 2010-06-30 525 2010 6
1 2010-07-30 136 2010 7
2 2010-08-31 125 2010 8
3 2010-09-30 84 2010 9
4 2010-10-29 4469 2010 10
EDIT
It looks like you're running an older version of pandas in which case the following would work:
In [18]:
df['date'] = pd.to_datetime(df['date'])
df['year'], df['month'] = df['date'].apply(lambda x: x.year), df['date'].apply(lambda x: x.month)
df
Out[18]:
date Count year month
0 2010-06-30 525 2010 6
1 2010-07-30 136 2010 7
2 2010-08-31 125 2010 8
3 2010-09-30 84 2010 9
4 2010-10-29 4469 2010 10
Regarding why it didn't parse this into a datetime in read_csv
you need to pass the ordinal position of your column ([0]
) because when True
it tries to parse columns [1,2,3]
see the docs
In [20]:
t="""date Count
6/30/2010 525
7/30/2010 136
8/31/2010 125
9/30/2010 84
10/29/2010 4469"""
df = pd.read_csv(io.StringIO(t), sep='\s+', parse_dates=[0])
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 5 entries, 0 to 4
Data columns (total 2 columns):
date 5 non-null datetime64[ns]
Count 5 non-null int64
dtypes: datetime64[ns](1), int64(1)
memory usage: 120.0 bytes
So if you pass param parse_dates=[0]
to read_csv
there shouldn't be any need to call to_datetime
on the 'date' column after loading.
'vb.net
'Extended file stributes
'visual basic .net sample
Dim sFile As Object
Dim oShell = CreateObject("Shell.Application")
Dim oDir = oShell.Namespace("c:\temp")
For i = 0 To 34
TextBox1.Text = TextBox1.Text & oDir.GetDetailsOf(oDir, i) & vbCrLf
For Each sFile In oDir.Items
TextBox1.Text = TextBox1.Text & oDir.GetDetailsOf(sFile, i) & vbCrLf
Next
TextBox1.Text = TextBox1.Text & vbCrLf
Next
204 responses are sometimes used in AJAX to track clicks and page activity. In this case, the only information being passed to the server in the get request is a cookie and not specific information in request parameters, so this doesn't seem to be the case here.
It seems that clients1.google.com is the server behind google search suggestions. When you visit http://www.google.com, the cookie is passed to http://clients1.google.com/generate_204. Perhaps this is to start up some kind of session on the server? Whatever the use, I doubt it's a very standard use.
Try this, This will show all commits recorded in git for a period of time
git reflog
Find the commit you want with
git log HEAD@{3}
or
git log -p HEAD@{3}
Then check it out if it's the right one:
git checkout HEAD@{3}
This will create a detached head for that commit. Add and commit any changes if needed
git status
git add
git commit -m "temp_work"
Now if want to restore commit back to a branch lets say master you will need to name this branch switch to master then merge to master.
git branch temp
git checkout master
git merge temp
Here's also a link specifically for reflog on a Git tutorial site: Atlassian Git Tutorial
if (File.Exists(localUploadDirectory + "/" + fileName))
{
`Your code here`
}
I am reading some data from a file using read. Here I am reading data in a 2d char pointer but the method is the same for the 1d also. Just read character by character and do not worry about the exceptions because the condition in the while loop is handling the exceptions :D
while ( (n = read(fd, buffer,1)) > 0 )
{
if(buffer[0] == '\n')
{
r++;
char**tempData=(char**)malloc(sizeof(char*)*r);
for(int a=0;a<r;a++)
{
tempData[a]=(char*)malloc(sizeof(char)*BUF_SIZE);
memset(tempData[a],0,BUF_SIZE);
}
for(int a=0;a<r-1;a++)
{
strcpy(tempData[a],data[a]);
}
data=tempData;
c=0;
}
else
{
data[r-1][c]=buffer[0];
c++;
buffer[1]='\0';
}
}
To add to Oleg's answer:
I was able to find the DLL at runtime by appending Visual Studio's $(ExecutablePath)
to the PATH environment variable in Configuration Properties->Debugging. This macro is exactly what's defined in the Configuration Properties->VC++ Directories->Executable Directories field*, so if you have that setup to point to any DLLs you need, simply adding this to your PATH makes finding the DLLs at runtime easy!
* I actually don't know if the $(ExecutablePath)
macro uses the project's Executable Directories setting or the global Property Pages' Executable Directories setting. Since I have all of my libraries that I often use configured through the Property Pages, these directories show up as defaults for any new projects I create.
A java program to set AWS environment vairiable.
Map<String, String> environment = new HashMap<String, String>();
environment.put("AWS_ACCESS_KEY_ID", "*****************");
environment.put("AWS_SECRET_KEY", "*************************");
private static void setEnv(Map<String, String> newenv) throws Exception {
try {
Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
theEnvironmentField.setAccessible(true);
Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
env.putAll(newenv);
Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
theCaseInsensitiveEnvironmentField.setAccessible(true);
Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
cienv.putAll(newenv);
} catch (NoSuchFieldException e) {
Class[] classes = Collections.class.getDeclaredClasses();
Map<String, String> env = System.getenv();
for (Class cl : classes) {
if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
Field field = cl.getDeclaredField("m");
field.setAccessible(true);
Object obj = field.get(env);
Map<String, String> map = (Map<String, String>) obj;
map.clear();
map.putAll(newenv);
}
}
}
}
Just because this hasn't been mentioned at all, what usually works well in situations like yours:
Placing the copyright-div after the container-div
You would only have to format the copyright-div in a similar way to the other container (same overall width, centering, etc.), and all is fine.
CSS:
#container, #copyright {
width: 1000px;
margin:0 auto;
}
HTML:
<div id="container">
<!-- Other elements here -->
</div>
<div id="copyright">
Copyright Foo web designs
</div>
The only time this might not be ideal is when your container-div is declared with height:100%
, and the user would need to scroll down to see the copyright. But even still you could work around (e.g. margin-top:-20px
- when the height of your copyright element is 20px).
Aside: I know the OP asked for a solution that "... sticks to the bottom of the 'container' div ...", and not something under it, but come on, people are looking for good solutions here, and this is one!
userAgent can be changed. for more robust, use the global variable specified by chrome
$.browser.chrome = (typeof window.chrome === "object");
You didn't bind all your bindings here
$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM comments WHERE articleid = :art
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );
You've declared a binding called :numRows but you never actually bind anything to it.
UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion
Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.
In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)
An alternative approach, without searching for the field html:
var $form = $('#' + DynamicValueAssignedHere).find('form');
var formData = $form.serializeArray();
var myFieldName = 'FirstName';
var myFieldFilter = function (field) {
return field.name == myFieldName;
}
var value = formData.filter(myFieldFilter)[0].value;
what if you use
Map<String, ? extends Class<? extends Serializable>> expected = null;
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
found here
Unless you plan on creating your own drop down list (and not using a standard library drop down list), you are stuck. The DDL control's look is going to be based upon the system you are running and/or the browser that is rendering the output.
I used the info above to help create a more permanent solution. The following will create the alias sh that you can use to open Git Bash:
echo @start "" "%PROGRAMFILES%\Git\bin\sh.exe" --login > %systemroot%\sh.bat
When using Ajax components it is possible to start multiple downloads. Therefore you have to use https://cwiki.apache.org/confluence/display/WICKET/AJAX+update+and+file+download+in+one+blow
Add an instance of AJAXDownload to your Page or whatever. Create an AjaxButton and override onSubmit. Create an AbstractAjaxTimerBehavior and start downloading.
button = new AjaxButton("button2") {
private static final long serialVersionUID = 1L;
@Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form)
{
MultiSitePage.this.info(this);
target.add(form);
form.add(new AbstractAjaxTimerBehavior(Duration.milliseconds(1)) {
@Override
protected void onTimer(AjaxRequestTarget target) {
download.initiate(target);
}
});
}
Happy downloading!
write a button tag and on click function
var x = document.getElementById('codeRefer').innerHTML;
document.getElementById('codeRefer').innerHTML = x;
write this all in onclick function
try this: (you missed the single quotes)
var floorplanSettings = '@Html.Raw(Json.Encode(Model.FloorPlanSettings))';
The message you received is common when you have ruby 2.0.0p0 (2013-02-24)
on top of Windows.
The message "DL is deprecated, please use Fiddle
" is not an error; it's only a warning.
The source is the Deprecation notice for DL introduced some time ago in dl.rb
( see revisions/37910 ).
On Windows the lib/ruby/site_ruby/2.0.0/readline.rb
file still requires dl.rb
so the warning message comes out when you require 'irb'
( because irb requires 'readline'
) or when anything else wants to require 'readline'
.
You can open readline.rb
with your favorite text editor and look up the code ( near line 4369 ):
if RUBY_VERSION < '1.9.1'
require 'Win32API'
else
require 'dl'
class Win32API
DLL = {}
We can always hope for an improvement to work out this deprecation in future releases of Ruby.
EDIT: For those wanting to go deeper about Fiddle vs DL, let it be said that their purpose is to dynamically link external libraries with Ruby; you can read on the ruby-doc website about DL or Fiddle.
Meld is also a great tool for comparing two directories:
meld dir1/ dir2/
Meld has many options for comparing files or directories. If two files differ, it's easy to enter file comparison mode and see the exact differences.
You have to change date class to timestamp.
String s=df.format(c.getTime());
java.util.Date parsedUtilDate = df.parse(s);
java.sql.Timestamp timestamp = new java.sql.Timestamp(parsedUtilDate.getTime());
If you want to control the formatting of the unique identifier you can create your own <FieldType>
in SharePoint. MSDN also has a visual How-To. This basically means that you're creating a custom column.
WSS defines the Counter field type (which is what the ID column above is using). I've never had the need to re-use this or extend it, but it should be possible.
A solution might exist without creating a custom <FieldType>
. For example: if you wanted unique IDs like CUST1, CUST2, ... it might be possible to create a Calculated column and use the value of the ID column in you formula (="CUST" & [ID]
). I haven't tried this, but this should work :)
Check against any long running queries in your database.
Increasing your pool size will only make your webapp live a little longer (and probably get a lot slower)
You can use sql server profiler and filter on duration / reads to see which querys need optimization.
I also see you're probably keeping a global connection?
blnMainConnectionIsCreatedLocal
Let .net do the pooling for you and open / close your connection with a using statement.
Suggestions:
Always open and close a connection like this, so .net can manage your connections and you won't run out of connections:
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
// do some stuff
} //conn disposed
As I mentioned, check your query with sql server profiler and see if you can optimize it. Having a slow query with many requests in a web app can give these timeouts too.
I am not sure how to see the actual rows/records that come back.
Stored procedures do not return records. They may have a cursor as an output parameter, which is a pointer to a select statement. But it requires additional action to actually bring back rows from that cursor.
In SQL Developer, you can execute a procedure that returns a ref cursor as follows
var rc refcursor
exec proc_name(:rc)
After that, if you execute the following, it will show the results from the cursor:
print rc
bundle update json
. Helped to get through.
There are two easy ways:
In your cpanel Go to cpanel/ softaculous/ wordpress, under the current installation, you will see the websites you have installed with the wordpress. Click the "edit detail" of the particular website and you will see your SQL database username and password.
In your server Access your FTP and view the wp-config.php
I think I got there in the end.
The task is like this:
- name: Populate genders
set_fact:
genders: "{{ genders|default({}) | combine( {item.item.name: item.stdout} ) }}"
with_items: "{{ people.results }}"
It loops through each of the dicts (item
) in the people.results
array, each time creating a new dict like {Bob: "male"}
, and combine()
s that new dict in the genders
array, which ends up like:
{
"Bob": "male",
"Thelma": "female"
}
It assumes the keys (the name
in this case) will be unique.
I then realised I actually wanted a list of dictionaries, as it seems much easier to loop through using with_items
:
- name: Populate genders
set_fact:
genders: "{{ genders|default([]) + [ {'name': item.item.name, 'gender': item.stdout} ] }}"
with_items: "{{ people.results }}"
This keeps combining the existing list with a list containing a single dict. We end up with a genders
array like this:
[
{'name': 'Bob', 'gender': 'male'},
{'name': 'Thelma', 'gender': 'female'}
]
Going back to the __getattribute__ function; if the default implementation was not overridden; the following checks are done when executing the method:
This is the actual implementation of the object.__getattribute__ method:
.. c:function:: PyObject* PyObject_GenericGetAttr(PyObject *o, PyObject *name) Generic attribute getter function that is meant to be put into a type object's tp_getattro slot. It looks for a descriptor in the dictionary of classes in the object's MRO as well as an attribute in the object's :attr:~object.dict (if present). As outlined in :ref:descriptors, data descriptors take preference over instance attributes, while non-data descriptors don't. Otherwise, an :exc:AttributeError is raised.
As an alternative that doesn't require elevation or netsh you could also use TcpListener for instance.
The following is a modified excerpt of this sample: https://github.com/googlesamples/oauth-apps-for-windows/tree/master/OAuthDesktopApp
// Generates state and PKCE values.
string state = randomDataBase64url(32);
string code_verifier = randomDataBase64url(32);
string code_challenge = base64urlencodeNoPadding(sha256(code_verifier));
const string code_challenge_method = "S256";
// Creates a redirect URI using an available port on the loopback address.
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
string redirectURI = string.Format("http://{0}:{1}/", IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port);
output("redirect URI: " + redirectURI);
// Creates the OAuth 2.0 authorization request.
string authorizationRequest = string.Format("{0}?response_type=code&scope=openid%20profile&redirect_uri={1}&client_id={2}&state={3}&code_challenge={4}&code_challenge_method={5}",
authorizationEndpoint,
System.Uri.EscapeDataString(redirectURI),
clientID,
state,
code_challenge,
code_challenge_method);
// Opens request in the browser.
System.Diagnostics.Process.Start(authorizationRequest);
// Waits for the OAuth authorization response.
var client = await listener.AcceptTcpClientAsync();
// Read response.
var response = ReadString(client);
// Brings this app back to the foreground.
this.Activate();
// Sends an HTTP response to the browser.
WriteStringAsync(client, "<html><head><meta http-equiv='refresh' content='10;url=https://google.com'></head><body>Please close this window and return to the app.</body></html>").ContinueWith(t =>
{
client.Dispose();
listener.Stop();
Console.WriteLine("HTTP server stopped.");
});
// TODO: Check the response here to get the authorization code and verify the code challenge
The read and write methods being:
private string ReadString(TcpClient client)
{
var readBuffer = new byte[client.ReceiveBufferSize];
string fullServerReply = null;
using (var inStream = new MemoryStream())
{
var stream = client.GetStream();
while (stream.DataAvailable)
{
var numberOfBytesRead = stream.Read(readBuffer, 0, readBuffer.Length);
if (numberOfBytesRead <= 0)
break;
inStream.Write(readBuffer, 0, numberOfBytesRead);
}
fullServerReply = Encoding.UTF8.GetString(inStream.ToArray());
}
return fullServerReply;
}
private Task WriteStringAsync(TcpClient client, string str)
{
return Task.Run(() =>
{
using (var writer = new StreamWriter(client.GetStream(), new UTF8Encoding(false)))
{
writer.Write("HTTP/1.0 200 OK");
writer.Write(Environment.NewLine);
writer.Write("Content-Type: text/html; charset=UTF-8");
writer.Write(Environment.NewLine);
writer.Write("Content-Length: " + str.Length);
writer.Write(Environment.NewLine);
writer.Write(Environment.NewLine);
writer.Write(str);
}
});
}
let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.alignment = .center
let titleFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
let title = NSMutableAttributedString(string: "You Are Registered",
attributes: [.font: titleFont,
.foregroundColor: UIColor.red,
.paragraphStyle: titleParagraphStyle])
let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.alignment = .center
let titleFont = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
let title = NSMutableAttributedString(string: "You Are Registered",
attributes: [NSFontAttributeName:titleFont,
NSForegroundColorAttributeName:UIColor.red,
NSParagraphStyleAttributeName: titleParagraphStyle])
(original answer below)
let titleParagraphStyle = NSMutableParagraphStyle()
titleParagraphStyle.alignment = .Center
let titleFont = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
let title = NSMutableAttributedString(string: "You Are Registered",
attributes:[NSFontAttributeName:titleFont,
NSForegroundColorAttributeName:UIColor.redColor(),
NSParagraphStyleAttributeName: titleParagraphStyle])
This will work everywhere.
<body>
<table style="table-layout:fixed;">
<tr>
<td><div style="word-wrap: break-word; width: 100px" > gdfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg</div></td>
</tr>
</table>
</body>
I liked the answer from kays1 but I couldn't implement it. So I built my own version using his concept.
public class JsonListHelper{
public static final <T> List<T> getList(String json) throws Exception {
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
Type typeOfList = new TypeToken<List<T>>(){}.getType();
return gson.fromJson(json, typeOfList);
}
}
Usage:
List<MyClass> MyList= JsonListHelper.getList(jsonArrayString);
Performing a single click on an HTML element: Simply do element.click()
. Most major browsers support this.
To repeat the click more than once: Add an ID to the element to uniquely select it:
<a href="#" target="_blank" id="my-link" onclick="javascript:Test('Test');">Google Chrome</a>
and call the .click()
method in your JavaScript code via a for loop:
var link = document.getElementById('my-link');
for(var i = 0; i < 50; i++)
link.click();
You don't have to simulate it. The second argument to res.send
I believe is the status code. Just pass 404 to that argument.
Let me clarify that: Per the documentation on expressjs.org it seems as though any number passed to res.send()
will be interpreted as the status code. So technically you could get away with:
res.send(404);
Edit: My bad, I meant res
instead of req
. It should be called on the response
Edit: As of Express 4, the send(status)
method has been deprecated. If you're using Express 4 or later, use: res.sendStatus(404)
instead. (Thanks @badcc for the tip in the comments)