The error is from this:
def playSound(myList):
for i in range(myList): # <= myList is a list, not an integer
You cannot pass a list to range
which expects an integer. Most likely, you meant to do:
def playSound(myList):
for list_item in myList:
OR
def playSound(myList):
for i in range(len(myList)):
OR
def playSound(myList):
for i, list_item in enumerate(myList):
You could ignore SIGINTs after shutdown starts by calling signal.signal(signal.SIGINT, signal.SIG_IGN)
before you start your cleanup code.
This works fine for me:
while True:
answer = input('Do you want to continue?:')
if answer.lower().startswith("y"):
print("ok, carry on then")
elif answer.lower().startswith("n"):
print("sayonara, Robocop")
exit()
edit: use input
in python 3.2 instead of raw_input
Using 2.7:
from functools import partial
from random import randint
for roll in iter(partial(randint, 1, 8), 1):
print 'you rolled: {}'.format(roll)
print 'oops you rolled a 1!'
you rolled: 7
you rolled: 7
you rolled: 8
you rolled: 6
you rolled: 8
you rolled: 5
oops you rolled a 1!
Then change the "oops" print to a raise SystemExit
You can do this thing using performSegueWithIdentifier
function.
Syntax :
func performSegueWithIdentifier(identifier: String, sender: AnyObject?)
Example :
performSegueWithIdentifier("homeScreenVC", sender: nil)
If the number of elements in the array is not given, you can alternatively make use of list comprehension like:
str_arr = raw_input().split(' ') //will take in a string of numbers separated by a space
arr = [int(num) for num in str_arr]
I would use
WHERE columnName LIKE '%[%]%'
SQL Server stores string summary statistics for use in estimating the number of rows that will match a LIKE
clause. The cardinality estimates can be better and lead to a more appropriate plan when the square bracket syntax is used.
The response to this Connect Item states
We do not have support for precise cardinality estimation in the presence of user defined escape characters. So we probably get a poor estimate and a poor plan. We'll consider addressing this issue in a future release.
An example
CREATE TABLE T
(
X VARCHAR(50),
Y CHAR(2000) NULL
)
CREATE NONCLUSTERED INDEX IX ON T(X)
INSERT INTO T (X)
SELECT TOP (5) '10% off'
FROM master..spt_values
UNION ALL
SELECT TOP (100000) 'blah'
FROM master..spt_values v1, master..spt_values v2
SET STATISTICS IO ON;
SELECT *
FROM T
WHERE X LIKE '%[%]%'
SELECT *
FROM T
WHERE X LIKE '%\%%' ESCAPE '\'
Shows 457 logical reads for the first query and 33,335 for the second.
This answer concerns developers for Windows. You want to pick an XML parsing module that does NOT depend on node-expat. Node-expat requires node-gyp and node-gyp requires you to install Visual Studio on your machine. If your machine is a Windows Server, you definitely don't want to install Visual Studio on it.
So, which XML parsing module to pick?
Save yourself a lot of trouble and use either xml2js or xmldoc. They depend on sax.js which is a pure Javascript solution that doesn't require node-gyp.
Both libxmljs and xml-stream require node-gyp. Don't pick these unless you already have Visual Studio on your machine installed or you don't mind going down that road.
Update 2015-10-24: it seems somebody found a solution to use node-gyp on Windows without installing VS: https://github.com/nodejs/node-gyp/issues/629#issuecomment-138276692
your initial request is "I have a large PDF file that is a floor map for a building. "
I am afraid to tell you this might be harder than you guess.
Cause the last known lib everyones use to parse pdf is smalot, and this one is known to encounter issue regarding large file.
Here too, Lookig for a real php lib to parse pdf, without any memory peak that need a php configuration to disable memory limit as lot of "developers" does (which I guess is really not advisable).
see this post for more details about smalot performance : https://github.com/smalot/pdfparser/issues/163
Mhh.. I think @Damian asks for remove undefined field (property) from an JS object
.
Then, I would simply do :
for (const i in myObj)
if (typeof myObj[i] === 'undefined')
delete myObj[i];
Short and efficient solution, in (vanilla) JS ! Example :
const myObj = {_x000D_
a: 1,_x000D_
b: undefined,_x000D_
c: null, _x000D_
d: 'hello world'_x000D_
};_x000D_
_x000D_
for (const i in myObj) _x000D_
if (typeof myObj[i] === 'undefined') _x000D_
delete myObj[i]; _x000D_
_x000D_
console.log(myObj);
_x000D_
You can use /* tslint:disable-next-line */
to locally disable tslint. However, as this is a compiler error disabling tslint might not help.
You can always temporarily cast $
to any
:
delete ($ as any).summernote.options.keyMap.pc.TAB
which will allow you to access whatever properties you want.
Edit: As of Typescript 2.6, you can now bypass a compiler error/warning for a specific line:
if (false) {
// @ts-ignore: Unreachable code error
console.log("hello");
}
Note that the official docs "recommend you use [this] very sparingly". It is almost always preferable to cast to any
instead as that better expresses intent.
If you're talking MS SQL, here's the most efficient way. This retrieves the current identity seed from a table based on whatever column is the identity.
select IDENT_CURRENT('TableName') as LastIdentity
Using MAX(id)
is more generic, but for example I have an table with 400 million rows that takes 2 minutes to get the MAX(id)
. IDENT_CURRENT
is nearly instantaneous...
You can use android-ripple-background
Start Effect
final RippleBackground rippleBackground=(RippleBackground)findViewById(R.id.content);
ImageView imageView=(ImageView)findViewById(R.id.centerImage);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
rippleBackground.startRippleAnimation();
}
});
Stop animation:
rippleBackground.stopRippleAnimation();
For KOTLIN
val rippleBackground = findViewById(R.id.content) as RippleBackground
val imageView: ImageView = findViewById(R.id.centerImage) as ImageView
imageView.setOnClickListener(object : OnClickListener() {
fun onClick(view: View?) {
rippleBackground.startRippleAnimation()
}
})
This can be accessed through Javascript because it's a property of the loaded document, not of its parent.
Here's a quick example:
<script type="text/javascript">
document.write(document.referrer);
</script>
The same thing in PHP would be:
<?php echo $_SERVER["HTTP_REFERER"]; ?>
date.parse(valueToBeTested) > 0
is all that's needed. A valid date will return the epoch value and an invalid value will return NaN which will fail > 0
test by virtue of not even being a number.
This is so simple that a helper function won't save code though it might be a bit more readable. If you wanted one:
String.prototype.isDate = function() {
return !Number.isNaN(Date.parse(this));
}
OR
To use:
"StringToTest".isDate();
private void DrawEllipseRectangle(PaintEventArgs e)
{
Pen p = new Pen(Color.Black, 3);
Rectangle r = new Rectangle(100, 100, 100, 100);
e.Graphics.DrawEllipse(p, r);
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
DrawEllipseRectangle(e);
}
You cannot instantiate an abstract class, Jackson neither. You should give Jackson information on how to instantiate MyAbstractClass with a concrete type.
See this answer on stackoverflow: Jackson JSON library: how to instantiate a class that contains abstract fields
And maybe also see Jackson Polymorphic Deserialization
The string.isalpha()
function will work for you.
If you are using FormBuilder
, see @dfsq's answer.
If you are not using FormBuilder
, there are two ways to be notified of changes.
Method 1
As discussed in the comments on the question, use an event binding on each input element. Add to your template:
<input type="text" class="form-control" required [ngModel]="model.first_name"
(ngModelChange)="doSomething($event)">
Then in your component:
doSomething(newValue) {
model.first_name = newValue;
console.log(newValue)
}
The Forms page has some additional information about ngModel that is relevant here:
The
ngModelChange
is not an<input>
element event. It is actually an event property of theNgModel
directive. When Angular sees a binding target in the form[(x)]
, it expects thex
directive to have anx
input property and anxChange
output property.The other oddity is the template expression,
model.name = $event
. We're used to seeing an$event
object coming from a DOM event. The ngModelChange property doesn't produce a DOM event; it's an AngularEventEmitter
property that returns the input box value when it fires..We almost always prefer
[(ngModel)]
. We might split the binding if we had to do something special in the event handling such as debounce or throttle the key strokes.
In your case, I suppose you want to do something special.
Method 2
Define a local template variable and set it to ngForm
.
Use ngControl on the input elements.
Get a reference to the form's NgForm directive using @ViewChild, then subscribe to the NgForm's ControlGroup for changes:
<form #myForm="ngForm" (ngSubmit)="onSubmit()">
....
<input type="text" ngControl="firstName" class="form-control"
required [(ngModel)]="model.first_name">
...
<input type="text" ngControl="lastName" class="form-control"
required [(ngModel)]="model.last_name">
class MyForm {
@ViewChild('myForm') form;
...
ngAfterViewInit() {
console.log(this.form)
this.form.control.valueChanges
.subscribe(values => this.doSomething(values));
}
doSomething(values) {
console.log(values);
}
}
For more information on Method 2, see Savkin's video.
See also @Thierry's answer for more information on what you can do with the valueChanges
observable (such as debouncing/waiting a bit before processing changes).
This question may be a little old, but because I think the "right" answer here is only one way which can lead to some issues hidden Issues later in your code. Even if there is a little Controversy, Checked Exceptions exist for a reason.
The most elegant way in my opinion can you find was given by Misha here Aggregate runtime exceptions in Java 8 streams by just performing the actions in "futures". So you can run all the working parts and collect not working Exceptions as a single one. Otherwise you could collect them all in a List and process them later.
A similar approach comes from Benji Weber. He suggests to create an own type to collect working and not working parts.
Depending on what you really want to achieve a simple mapping between the input values and Output Values occurred Exceptions may also work for you.
If you don't like any of these ways consider using (depending on the Original Exception) at least an own exception.
If you're using oh-my-zsh
Type
omz update
in the terminal
Note: upgrade_oh_my_zsh
is deprecated
If you are using forms authentication you could try the code below:
<authentication mode="Forms">
<forms name=".FORM" loginUrl="Login.aspx" defaultUrl="CreateThings.aspx" protection="All" timeout="30" path="/">
</forms>
</authentication>
In my case, the file C:\Users\xxx\AppData\Local\PreEmptive Solutions\Dotfuscator Professional Edition\4.0\dfusrprf.xml
was full of NULL.
I deleted it; it was recreated on the first launch of Dotfuscator, and after that, normality was restored.
A way to do is to go to terminal
$ sudo gedit /etc/hosts
***enter your ip address ipaddress of your pc localhost
ipaddress of your pc localhost(Edit your pc name with localhost) **
and again restart your ssh service using:
$ service ssh restart
Problem will be resolve. Thanks
The complete first argument of exec
is being interpreted as the executable. Use
p = rt.exec(new String[] {"winrar.exe", "x", "h:\\myjar.jar", "*.*", "h:\\new" }
null,
dir);
Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.
I had a opened record set of the post that was created by:
Set RecSet = Conn.Execute()
This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...
RecSet.Close
Set RecSet = Nothing
...everything worked just fine.
So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.
You can't remove hidden without also removing system.
You want:
cd mydir
attrib -H -S /D /S
That will remove the hidden and system attributes from all the files/folders inside of your current directory.
In my tray app, I needed to clean Excel and Word Interops. So This simple method kills processes generically.
This uses a general exception handler, but could be easily split for multiple exceptions like stated in other answers. I may do this if my logging produces alot of false positives (ie can't kill already killed). But so far so guid (work joke).
/// <summary>
/// Kills Processes By Name
/// </summary>
/// <param name="names">List of Process Names</param>
private void killProcesses(List<string> names)
{
var processes = new List<Process>();
foreach (var name in names)
processes.AddRange(Process.GetProcessesByName(name).ToList());
foreach (Process p in processes)
{
try
{
p.Kill();
p.WaitForExit();
}
catch (Exception ex)
{
// Logging
RunProcess.insertFeedback("Clean Processes Failed", ex);
}
}
}
This is how i called it then:
killProcesses((new List<string>() { "winword", "excel" }));
Here's the better answer:
You can't implement a button clicked event for button cells in a DataGridViewButtonColumn. Instead, you use the DataGridView's CellClicked event and determine if the event fired for a cell in your DataGridViewButtonColumn. Use the event's DataGridViewCellEventArgs.RowIndex property to find out which row was clicked.
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) {
// Ignore clicks that are not in our
if (e.ColumnIndex == dataGridView1.Columns["MyButtonColumn"].Index && e.RowIndex >= 0) {
Console.WriteLine("Button on row {0} clicked", e.RowIndex);
}
}
found here: button click event in datagridview
You can also work with a so called boolean vector, aka logical
:
row_to_keep = c(TRUE, FALSE, TRUE, FALSE, TRUE, FALSE, TRUE)
myData = myData[row_to_keep,]
Note that the !
operator acts as a NOT, i.e. !TRUE == FALSE
:
myData = myData[!row_to_keep,]
This seems a bit cumbersome in comparison to @mrwab's answer (+1 btw :)), but a logical vector can be generated on the fly, e.g. where a column value exceeds a certain value:
myData = myData[myData$A > 4,]
myData = myData[!myData$A > 4,] # equal to myData[myData$A <= 4,]
You can transform a boolean vector to a vector of indices:
row_to_keep = which(myData$A > 4)
Finally, a very neat trick is that you can use this kind of subsetting not only for extraction, but also for assignment:
myData$A[myData$A > 4,] <- NA
where column A
is assigned NA
(not a number) where A
exceeds 4.
You can access elements using $document ($document need to be injected)
var target = $document('#appBusyIndicator');
var target = $document('appBusyIndicator');
or with angular element, the specified elements can be accessed as:
var targets = angular.element(document).find('div'); //array of all div
var targets = angular.element(document).find('p');
var target = angular.element(document).find('#appBusyIndicator');
These days IMHO the best short, sane & valid way for an empty img src is like this:
<img src="data:," alt>
or
<img src="data:," alt="Alternative Text">
The second example displays "Alternative Text" (plus broken-image-icon in Chrome and IE).
"data:,"
is a valid URI. An empty media-type defaults to text/plain
. So it represents an empty text file and is equivalent to "data:text/plain,"
alt
. You can omit =""
, it's implicit per HTML spec.
You can just go for String
replace method.-
line1 = line1.replace("\"", "");
If you subclass Webview, you can simply override onTouchEvent to filter out the move-events that trigger scrolling.
public class SubWebView extends WebView {
@Override
public boolean onTouchEvent (MotionEvent ev) {
if(ev.getAction() == MotionEvent.ACTION_MOVE) {
postInvalidate();
return true;
}
return super.onTouchEvent(ev);
}
...
You want something like:
@echo off
setlocal
:PROMPT
SET /P AREYOUSURE=Are you sure (Y/[N])?
IF /I "%AREYOUSURE%" NEQ "Y" GOTO END
echo ... rest of file ...
:END
endlocal
This worked for me..
I was trying to automate multiple telnet logins which require a username and password. The telnet session needs to run in the background indefinitely since I am saving logs from different servers to my machine.
telnet.sh automates telnet login using the 'expect' command. More info can be found here: http://osix.net/modules/article/?id=30
telnet.sh
#!/usr/bin/expect
set timeout 20
set hostName [lindex $argv 0]
set userName [lindex $argv 1]
set password [lindex $argv 2]
spawn telnet $hostName
expect "User Access Verification"
expect "Username:"
send "$userName\r"
expect "Password:"
send "$password\r";
interact
sample_script.sh is used to create a background process for each of the telnet sessions by running telnet.sh. More information can be found in the comments section of the code.
sample_script.sh
#!/bin/bash
#start screen in detached mode with session-name 'default_session'
screen -dmS default_session -t screen_name
#save the generated logs in a log file 'abc.log'
screen -S default_session -p screen_name -X stuff "script -f /tmp/abc.log $(printf \\r)"
#start the telnet session and generate logs
screen -S default_session -p screen_name -X stuff "expect telnet.sh hostname username password $(printf \\r)"
The quick and dirty way I use to export mysql output to a file is
$ mysql <database_name> --tee=<file_path>
and then use the exported output (which you can find in <file_path>
) wherever I want.
Note that this is the only way you have in order to avoid databases running using the secure-file-priv
option, which prevents the usage of INTO OUTFILE
suggested in the previous answers:
ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
I ran into this same issue on a new install of mysql 5.5 on a mac. I tried to drop the test schema and got an errno 17 message. errno 17 is the error returned by some posix os functions indicating that a file exists where it should not. In the data directory, I found a strange file ".empty":
sh-3.2# ls -la data/test
total 0
drwxr-xr-x 3 _mysql wheel 102 Apr 15 12:36 .
drwxr-xr-x 11 _mysql wheel 374 Apr 15 12:28 ..
-rw-r--r-- 1 _mysql wheel 0 Mar 31 10:19 .empty
Once I rm'd the .empty file, the drop database command succeeded.
I don't know where the .empty file came from; as noted, this was a new mysql install. Perhaps something went wrong in the install process.
Like from any regular input/select/etc...:
$("form.my-form .chosen-select").val()
Here's an article in devx.com that says:
Creating a non-clustered index that contains all the columns used in a SQL query, a technique called index covering
I can only suppose that a covered query is a query that has an index that covers all the columns in its returned recordset. One caveat - the index and query would have to be built as to allow the SQL server to actually infer from the query that the index is useful.
For example, a join of a table on itself might not benefit from such an index (depending on the intelligence of the SQL query execution planner):
PersonID ParentID Name
1 NULL Abe
2 NULL Bob
3 1 Carl
4 2 Dave
Let's assume there's an index on PersonID,ParentID,Name
- this would be a covering index for a query like:
SELECT PersonID, ParentID, Name FROM MyTable
But a query like this:
SELECT PersonID, Name FROM MyTable LEFT JOIN MyTable T ON T.PersonID=MyTable.ParentID
Probably wouldn't benifit so much, even though all of the columns are in the index. Why? Because you're not really telling it that you want to use the triple index of PersonID,ParentID,Name
.
Instead, you're building a condition based on two columns - PersonID
and ParentID
(which leaves out Name
) and then you're asking for all the records, with the columns PersonID, Name
. Actually, depending on implementation, the index might help the latter part. But for the first part, you're better off having other indexes.
You might try turning off pooling, which is enabled by default. See this discussion for more information.
import pyodbc
pyodbc.pooling = False
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest')
csr = conn.cursor()
csr.close()
del csr
You are correct that your cTag class must implement IComparable<T>
interface. Then you can just call Sort()
on your list.
To implement IComparable<T>
interface, you must implement CompareTo(T other)
method. The easiest way to do this is to call CompareTo method of the field you want to compare, which in your case is date.
public class cTag:IComparable<cTag> {
public int id { get; set; }
public int regnumber { get; set; }
public string date { get; set; }
public int CompareTo(cTag other) {
return date.CompareTo(other.date);
}
}
However, this wouldn't sort well, because this would use classic sorting on strings (since you declared date as string). So I think the best think to do would be to redefine the class and to declare date not as string, but as DateTime. The code would stay almost the same:
public class cTag:IComparable<cTag> {
public int id { get; set; }
public int regnumber { get; set; }
public DateTime date { get; set; }
public int CompareTo(cTag other) {
return date.CompareTo(other.date);
}
}
Only thing you'd have to do when creating the instance of the class to convert your string containing the date into DateTime type, but it can be done easily e.g. by DateTime.Parse(String)
method.
$string = 'this is my world, not my world';
$find = 'world';
$replace = 'farm';
$result = preg_replace("/$find/",$replace,$string,1);
echo $result;
Similar to the answer offered by Andrew, but I use:
Select GetDate() as CurrentDate
This allows me to see if the SQL Server and the client have any time zone difference issues, in the same action.
.a
files are static libraries typically generated by the archive tool. You usually include the header files associated with that static library and then link to the library when you are compiling.
Swift 3
Orientation rotation is more complicated if a view controller is embedded in UINavigationController or UITabBarController the navigation or tab bar controller takes precedence and makes the decisions on autorotation and supported orientations.
Use the following extensions on UINavigationController and UITabBarController so that view controllers that are embedded in one of these controllers get to make the decisions:
UINavigationController extension
extension UINavigationController {
override open var shouldAutorotate: Bool {
get {
if let visibleVC = visibleViewController {
return visibleVC.shouldAutorotate
}
return super.shouldAutorotate
}
}
override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
get {
if let visibleVC = visibleViewController {
return visibleVC.preferredInterfaceOrientationForPresentation
}
return super.preferredInterfaceOrientationForPresentation
}
}
override open var supportedInterfaceOrientations: UIInterfaceOrientationMask{
get {
if let visibleVC = visibleViewController {
return visibleVC.supportedInterfaceOrientations
}
return super.supportedInterfaceOrientations
}
}}
UITabBarController extension
extension UITabBarController {
override open var shouldAutorotate: Bool {
get {
if let selectedVC = selectedViewController{
return selectedVC.shouldAutorotate
}
return super.shouldAutorotate
}
}
override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
get {
if let selectedVC = selectedViewController{
return selectedVC.preferredInterfaceOrientationForPresentation
}
return super.preferredInterfaceOrientationForPresentation
}
}
override open var supportedInterfaceOrientations: UIInterfaceOrientationMask{
get {
if let selectedVC = selectedViewController{
return selectedVC.supportedInterfaceOrientations
}
return super.supportedInterfaceOrientations
}
}}
Now you can override the supportedInterfaceOrientations, shouldAutoRotate and preferredInterfaceOrientationForPresentation in the view controller you want to lock down otherwise you can leave out the overrides in other view controllers that you want to inherit the default orientation behavior specified in your app's plist.
Lock to Specific Orientation
class YourViewController: UIViewController {
open override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
get {
return .portrait
}
}}
Disable Rotation
class YourViewController: UIViewController {
open override var shouldAutorotate: Bool {
get {
return false
}
}}
Change Preferred Interface Orientation For Presentation
class YourViewController: UIViewController {
open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
get {
return .portrait
}
}}
I suggest that you give an if to the div than:
$("#my_div_id").html();
By adding a few more headers I was able to get the data:
import urllib2,cookielib
site= "http://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/getHistoricalData.jsp?symbol=JPASSOCIAT&fromDate=1-JAN-2012&toDate=1-AUG-2012&datePeriod=unselected&hiddDwnld=true"
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'}
req = urllib2.Request(site, headers=hdr)
try:
page = urllib2.urlopen(req)
except urllib2.HTTPError, e:
print e.fp.read()
content = page.read()
print content
Actually, it works with just this one additional header:
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
You can do so by these ways.
Add watchpoint
and while debugging you can see variable in debugger window perspective under variable tab.
OR
Add System.out.println("variable = " + variable);
and see in console.
Only window is supported yes but you could use a plugin for it: http://benalman.com/projects/jquery-resize-plugin/
The error is due the fact that you are passing a wrong to strcat()
. Look at strcat()
's prototype:
char *strcat(char *dest, const char *src);
But you pass char
as the second argument, which is obviously wrong.
Use snprintf()
instead.
char str[1024] = "Hello World";
char tmp = '.';
size_t len = strlen(str);
snprintf(str + len, sizeof str - len, "%c", tmp);
As commented by OP:
That was just a example with Hello World to describe the Problem. It must be empty as first in my real program. Program will fill it later. The problem just contains to add a char/int to an char Array
In that case, snprintf()
can handle it easily to "append" integer types to a char buffer too. The advantage of snprintf()
is that it's more flexible to concatenate various types of data into a char buffer.
For example to concatenate a string, char and an int:
char str[1024];
ch tmp = '.';
int i = 5;
// Fill str here
snprintf(str + len, sizeof str - len, "%c%d", str, tmp, i);
In openCV's documentation there is an example for getting video frame by frame. It is written in c++ but it is very easy to port the example to python - you can search for each fumction documentation to see how to call them in python.
#include "opencv2/opencv.hpp"
using namespace cv;
int main(int, char**)
{
VideoCapture cap(0); // open the default camera
if(!cap.isOpened()) // check if we succeeded
return -1;
Mat edges;
namedWindow("edges",1);
for(;;)
{
Mat frame;
cap >> frame; // get a new frame from camera
cvtColor(frame, edges, CV_BGR2GRAY);
GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
Canny(edges, edges, 0, 30, 3);
imshow("edges", edges);
if(waitKey(30) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}
Might be useful to some : check for
pointer-events: none;
In the CSS. It prevents clicks from being caught by JS. I think it's relevant because the CSS might be the last place you'd look into in this kind of situation.
simple with generated links :) html:
<span class='preview' data-image-url="imageUrl.png" data-container="body" data-toggle="popover" data-placement="top" >preview</span>
js:
$('.preview').popover({
'trigger':'hover',
'html':true,
'content':function(){
return "<img src='"+$(this).data('imageUrl')+"'>";
}
});
See for the protocols HTTPS and HTTP
Sometimes if you are using mixed protocols [this happens mostly with JSONP callbacks ] you can end up in this ERROR.
Make sure both the web-page and the resource page have the same HTTP protocols.
Just to build on vinnief's hacky solution above, I use MsgBox like this:
Browser.msgBox('BorderoToMatriz', Browser.Buttons.OK_CANCEL);
and it acts kinda like a break point, stops the script and outputs whatever string you need to a pop-up box. I find especially in Sheets, where I have trouble with Logger.log, this provides an adequate workaround most times.
Hi starbeamrainbowlabs ,
You can do this with the following:
var oldValue = "pic quality, hello" ;
var newValue = "hello";
var oldValueLength = oldValue.length ;
var newValueLength = newValue.length ;
var from = oldValue.search(newValue) ;
var to = from + newValueLength ;
var nes = oldValue.substr(0,from) + oldValue.substr(to,oldValueLength);
console.log(nes);
I tested this in my javascript console so you can also check this out Thanks
In my taste, it's also very concise to combine zip()
with xrange(n)
(or range(n)
in Python3), which works nice on generators as well and seems to be more flexible for changes in general.
# Option #1: taking the first n elements as a list
[x for _, x in zip(xrange(n), generator)]
# Option #2, using 'next()' and taking care for 'StopIteration'
[next(generator) for _ in xrange(n)]
# Option #3: taking the first n elements as a new generator
(x for _, x in zip(xrange(n), generator))
# Option #4: yielding them by simply preparing a function
# (but take care for 'StopIteration')
def top_n(n, generator):
for _ in xrange(n): yield next(generator)
Make it more reusable as a function.
def createEmptyList(length,fill=None):
'''
return a (empty) list of a given length
Example:
print createEmptyList(3,-1)
>> [-1, -1, -1]
print createEmptyList(4)
>> [None, None, None, None]
'''
return [fill] * length
Javascript only :)
function isInViewport(element) {
var rect = element.getBoundingClientRect();
var html = document.documentElement;
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || html.clientHeight) &&
rect.right <= (window.innerWidth || html.clientWidth)
);
}
https://github.com/quartzjer/js0n
Ugliest interface possible, but does what you ask. Zero allocations.
http://zserge.com/jsmn.html Another zero-allocation approach.
The solutions posted above all do dynamic memory allocation, hence will be inevitably end up slower at some point, depending on the data structure - and will be dangerous to include in a heap constrained environment like an embedded system.
Benchmarks of vjson, rapidjson and sajson here : http://chadaustin.me/2013/01/json-parser-benchmarking/ if you are interested in that sort of thing.
And to answer your "writer" part of the question i doubt that you could beat an efficient
printf("{%s:%s}",name,value)
implementation with any library - assuming your printf/sprintf implementation itself is lightweight of course.
EDIT: actually let me take that back, RapidJson allows on-stack allocation only through its MemoryPoolAllocator and actually makes this a default for its GenericReader. I havent done the comparison but i would expect it to be more robust than anything else listed here. It also doesnt have any dependencies, and it doesnt throw exceptions which probably makes it ultimately suitable for embedded. Fully header based lib so, easy to include anywhere.
JSONP works by constructing a “script” element (either in HTML markup or inserted into the DOM via JavaScript), which requests to a remote data service location. The response is a javascript loaded on to your browser with name of the pre-defined function along with parameter being passed that is tht JSON data being requested. When the script executes, the function is called along with JSON data, allowing the requesting page to receive and process the data.
For Further Reading Visit: https://blogs.sap.com/2013/07/15/secret-behind-jsonp/
client side snippet of code
<!DOCTYPE html>
<html lang="en">
<head>
<title>AvLabz - CORS : The Secrets Behind JSONP </title>
<meta charset="UTF-8" />
</head>
<body>
<input type="text" id="username" placeholder="Enter Your Name"/>
<button type="submit" onclick="sendRequest()"> Send Request to Server </button>
<script>
"use strict";
//Construct the script tag at Runtime
function requestServerCall(url) {
var head = document.head;
var script = document.createElement("script");
script.setAttribute("src", url);
head.appendChild(script);
head.removeChild(script);
}
//Predefined callback function
function jsonpCallback(data) {
alert(data.message); // Response data from the server
}
//Reference to the input field
var username = document.getElementById("username");
//Send Request to Server
function sendRequest() {
// Edit with your Web Service URL
requestServerCall("http://localhost/PHP_Series/CORS/myService.php?callback=jsonpCallback&message="+username.value+"");
}
</script>
</body>
</html>
Server side piece of PHP code
<?php
header("Content-Type: application/javascript");
$callback = $_GET["callback"];
$message = $_GET["message"]." you got a response from server yipeee!!!";
$jsonResponse = "{\"message\":\"" . $message . "\"}";
echo $callback . "(" . $jsonResponse . ")";
?>
Update:
The original answer makes it difficult (and in some cases impossible) to correctly handle promise rejections. The correct solution is to use Promise.all
:
const [someResult, anotherResult] = await Promise.all([someCall(), anotherCall()]);
Original answer:
Just make sure you call both functions before you await either one:
// Call both functions
const somePromise = someCall();
const anotherPromise = anotherCall();
// Await both promises
const someResult = await somePromise;
const anotherResult = await anotherPromise;
class Element
{
public string Company;
public string TypeOfInvestment;
public decimal Worth;
}
class Program
{
static void Main(string[] args)
{
List<Element> elements = new List<Element>()
{
new Element { Company = "JPMORGAN CHASE",TypeOfInvestment = "Stocks", Worth = 96983 },
new Element { Company = "AMER TOWER CORP",TypeOfInvestment = "Securities", Worth = 17141 },
new Element { Company = "ORACLE CORP",TypeOfInvestment = "Assets", Worth = 59372 },
new Element { Company = "PEPSICO INC",TypeOfInvestment = "Assets", Worth = 26516 },
new Element { Company = "PROCTER & GAMBL",TypeOfInvestment = "Stocks", Worth = 387050 },
new Element { Company = "QUASLCOMM INC",TypeOfInvestment = "Bonds", Worth = 196811 },
new Element { Company = "UTD TECHS CORP",TypeOfInvestment = "Bonds", Worth = 257429 },
new Element { Company = "WELLS FARGO-NEW",TypeOfInvestment = "Bank Account", Worth = 106600 },
new Element { Company = "FEDEX CORP",TypeOfInvestment = "Stocks", Worth = 103955 },
new Element { Company = "CVS CAREMARK CP",TypeOfInvestment = "Securities", Worth = 171048 },
};
//Group by on multiple column in LINQ (Query Method)
var query = from e in elements
group e by new{e.TypeOfInvestment,e.Company} into eg
select new {eg.Key.TypeOfInvestment, eg.Key.Company, Points = eg.Sum(rl => rl.Worth)};
foreach (var item in query)
{
Console.WriteLine(item.TypeOfInvestment.PadRight(20) + " " + item.Points.ToString());
}
//Group by on multiple column in LINQ (Lambda Method)
var CompanyDetails =elements.GroupBy(s => new { s.Company, s.TypeOfInvestment})
.Select(g =>
new
{
company = g.Key.Company,
TypeOfInvestment = g.Key.TypeOfInvestment,
Balance = g.Sum(x => Math.Round(Convert.ToDecimal(x.Worth), 2)),
}
);
foreach (var item in CompanyDetails)
{
Console.WriteLine(item.TypeOfInvestment.PadRight(20) + " " + item.Balance.ToString());
}
Console.ReadLine();
}
}
I would personally recommend that you use os.path.isdir()
to test instead of os.path.exists()
.
>>> os.path.exists('/tmp/dirname')
True
>>> os.path.exists('/tmp/dirname/filename.etc')
True
>>> os.path.isdir('/tmp/dirname/filename.etc')
False
>>> os.path.isdir('/tmp/fakedirname')
False
If you have:
>>> dir = raw_input(":: ")
And a foolish user input:
:: /tmp/dirname/filename.etc
... You're going to end up with a directory named filename.etc
when you pass that argument to os.makedirs()
if you test with os.path.exists()
.
I wrote a tee()
implementation in Python that should work for most cases, and it works on Windows also.
https://github.com/pycontribs/tendo
Also, you can use it in combination with logging
module from Python if you want.
It is enough to use color property alongside with -webkit-text-fill-color this way:
input {_x000D_
color: red; /* color of caret */_x000D_
-webkit-text-fill-color: black; /* color of text */_x000D_
}
_x000D_
<input type="text"/>
_x000D_
Works in WebKit browsers (but not in iOS Safari, where is still used system color for caret) and also in Firefox.
The -webkit-text-fill-color CSS property specifies the fill color of characters of text. If this property is not set, the value of the color property is used. MDN
So this means we set text color with text-fill-color and caret color with standard color property. In unsupported browser, caret and text will have same color – color of the caret.
Ctrl + Alt + L works with Android Studio under xfce4 on Linux. I see that Gnome used to use this shortcut for lock screen, but in Gnome 3 it was changed to Super+L (AKA Windows+L): https://wiki.gnome.org/Design/OS/KeyboardShortcuts
I have used a similar layout with 4 TextView
s. Two TextView
s should be aligned to left and two TextView
s should be aligned to right. So, here is my solution, if you want to use LinearLayouts
alone.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:baselineAligned="false"
android:padding="10dp" >
<LinearLayout
android:layout_width="0dip"
android:layout_weight="0.50"
android:layout_height="match_parent"
android:gravity="left"
android:orientation="horizontal" >
<TextView
android:id="@+id/textview_fragment_mtfstatus_level"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/level"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/textview_fragment_mtfstatus_level_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="0dip"
android:layout_weight="0.50"
android:layout_height="match_parent"
android:gravity="right"
android:orientation="horizontal" >
<TextView
android:id="@+id/textview_fragment_mtfstatus_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/time"
android:textAppearance="?android:attr/textAppearanceMedium"
/>
<TextView
android:id="@+id/textview_fragment_mtfstatus_time_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium"
/>
</LinearLayout>
</LinearLayout>
I was having the same problem, until just now.
Removing the /
from before /css/app.css
so that its css.app.css
worked for me.
To multiply, use mult
for signed multiplication and multu
for unsigned multiplication. Note that the result of the multiplication of two 32-bit numbers yields a 64-number. If you want the result back in $v0
that means that you assume the result will fit in 32 bits.
The 32 most significant bits will be held in the HI
special register (accessible by mfhi
instruction) and the 32 least significant bits will be held in the LO
special register (accessible by the mflo
instruction):
E.g.:
li $a0, 5
li $a1, 3
mult $a0, $a1
mfhi $a2 # 32 most significant bits of multiplication to $a2
mflo $v0 # 32 least significant bits of multiplication to $v0
To divide, use div
for signed division and divu
for unsigned division. In this case, the HI
special register will hold the remainder and the LO
special register will hold the quotient of the division.
E.g.:
div $a0, $a1
mfhi $a2 # remainder to $a2
mflo $v0 # quotient to $v0
The "BIGINT(20)" specification isn't a digit limit. It just means that when the data is displayed, if it uses less than 20 digits it will be left-padded with zeros. 2^64 is the hard limit for the BIGINT type, and has 20 digits itself, hence BIGINT(20) just means everything less than 10^20 will be left-padded with spaces on display.
I would vote against display: inline-block
since its not supported across browsers, IE < 8 specifically.
.wrapper {
width:500px; /* Adjust to a total width of both .left and .right */
margin: 0 auto;
}
.left {
float: left;
width: 49%; /* Not 50% because of 1px border. */
border: 1px solid #000;
}
.right {
float: right;
width: 49%; /* Not 50% because of 1px border. */
border: 1px solid #F00;
}
<div class="wrapper">
<div class="left">Div 1</div>
<div class="right">Div 2</div>
</div>
EDIT: If no spacing between the cells is desired just change both .left
and .right
to use float: left;
fsspec is a great option for this, it offers a filesystem like implementation of sftp.
from fsspec.implementations.sftp import SFTPFileSystem
fs = SFTPFileSystem(host=host, username=username, password=password)
# list a directory
fs.ls("/")
# open a file
with fs.open(file_name) as file:
content = file.read()
Also worth noting that fsspec uses paramiko in the implementation.
Use:
:wq!
The exclamation mark is used for overriding read-only mode.
This is how I fixed my issue, I am getting data in data variable and by using above solutions I was getting error could not load results
. I had to parse the results differently in processResults.
searchBar.select2({
ajax: {
url: "/search/live/results/",
dataType: 'json',
headers : {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
delay: 250,
type: 'GET',
data: function (params) {
return {
q: params.term, // search term
};
},
processResults: function (data) {
var arr = []
$.each(data, function (index, value) {
arr.push({
id: index,
text: value
})
})
return {
results: arr
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1
});
A very important distinction, which is easy to miss, is the default bheavior of these two functions, when it comes to exceptions.
I'll use this example to simulate a coroutine that will raise exceptions, sometimes -
import asyncio
import random
async def a_flaky_tsk(i):
await asyncio.sleep(i) # bit of fuzz to simulate a real-world example
if i % 2 == 0:
print(i, "ok")
else:
print(i, "crashed!")
raise ValueError
coros = [a_flaky_tsk(i) for i in range(10)]
await asyncio.gather(*coros)
outputs -
0 ok
1 crashed!
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 20, in <module>
asyncio.run(main())
File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/runners.py", line 43, in run
return loop.run_until_complete(main)
File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
return future.result()
File "/Users/dev/PycharmProjects/trading/xxx.py", line 17, in main
await asyncio.gather(*coros)
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
As you can see, the coros after index 1
never got to execute.
But await asyncio.wait(coros)
continues to execute tasks, even if some of them fail -
0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
Task exception was never retrieved
future: <Task finished name='Task-10' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-8' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-2' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-9' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-3' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
raise ValueError
ValueError
Ofcourse, this behavior can be changed for both by using -
asyncio.gather(..., return_exceptions=True)
or,
asyncio.wait([...], return_when=asyncio.FIRST_EXCEPTION)
But it doesn't end here!
Notice:
Task exception was never retrieved
in the logs above.
asyncio.wait()
won't re-raise exceptions from the child tasks until you await
them individually. (The stacktrace in the logs are just messages, they cannot be caught!)
done, pending = await asyncio.wait(coros)
for tsk in done:
try:
await tsk
except Exception as e:
print("I caught:", repr(e))
Output -
0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
On the other hand, to catch exceptions with asyncio.gather()
, you must -
results = await asyncio.gather(*coros, return_exceptions=True)
for result_or_exc in results:
if isinstance(result_or_exc, Exception):
print("I caught:", repr(result_or_exc))
(Same output as before)
@AlexDuggleby: you don't need to copy the worksheets, you can save them directly. e.g.:
Public Sub SaveWorksheetsAsCsv()
Dim WS As Excel.Worksheet
Dim SaveToDirectory As String
SaveToDirectory = "C:\"
For Each WS In ThisWorkbook.Worksheets
WS.SaveAs SaveToDirectory & WS.Name, xlCSV
Next
End Sub
Only potential problem is that that leaves your workbook saved as the last csv file. If you need to keep the original workbook you will need to SaveAs it.
task deleteJar(type: Delete) {
delete 'libs/mylibrary.jar'
}
task exportjar(type: Copy) {
from('build/intermediates/compile_library_classes/release/')
into('libs/')
include('classes.jar')
rename('classes.jar', 'mylibrary.jar')
}
exportjar.dependsOn(deleteJar, build)
To update the listen ports for a server: 1.Click Lock & Edit in the Change Center of the webLogic Administration Console 2.expand Environment and select Server 3.click the name of the server and select Configuration > General 4.Find Listen Port to change it 5.click Save and start server.
Add an href
attribute to make it a valid link & return false;
in the event handler to prevent it from causing a navigation;
<a href="#" class="menu_links" onclick="displayData(11,1,0,'A'); return false;" onmouseover=""> A </a>
(Or make displayData()
return false and ..="return displayData(..
)
Use below code:
String html = "<a href=\"http://yourdomain.com\">Your Domain Name</a>"
TextView textview = (TextView) findViewById(R.id.your_textview_id);
textview.setMovementMethod(LinkMovementMethod.getInstance());
textview.setText(Html.fromHtml(html));
The most upvoted Override push method solution by @canon has some side-effects that were inconvenient in my case:
It makes the push property descriptor different (writable
and configurable
should be set true
instead of false
), which causes exceptions in a later point.
It raises the event multiple times when push()
is called once with multiple arguments (such as myArray.push("a", "b")
), which in my case was unnecessary and bad for performance.
So this is the best solution I could find that fixes the previous issues and is in my opinion cleaner/simpler/easier to understand.
Object.defineProperty(myArray, "push", {
configurable: true,
enumerable: false,
writable: true, // Previous values based on Object.getOwnPropertyDescriptor(Array.prototype, "push")
value: function (...args)
{
let result = Array.prototype.push.apply(this, args); // Original push() implementation based on https://github.com/vuejs/vue/blob/f2b476d4f4f685d84b4957e6c805740597945cde/src/core/observer/array.js and https://github.com/vuejs/vue/blob/daed1e73557d57df244ad8d46c9afff7208c9a2d/src/core/util/lang.js
RaiseMyEvent();
return result; // Original push() implementation
}
});
Please see comments for my sources and for hints on how to implement the other mutating functions apart from push: 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'.
UEFA or FIFA don't seem to provide any API to get the information you want. However, there are some third-party services which support that:
OPTA - Both commercial and free. They have incredible database about matches. Whoscored.com currently uses it.
Others: livescoreboards, xmlsoccer, ...
Wouldn't Collections.disjoint(A, B)
work? From the documentation:
Returns
true
if the two specified collections have no elements in common.
Thus, the method returns false
if the collections contains any common elements.
In my case I did something like this, based on Luis's answer:
...State object...
userInfo = {
name: '...',
...
}
...Reducer's code...
case CHANGED_INFO:
return {
...state,
userInfo: {
...state.userInfo,
// I'm sending the arguments like this: changeInfo({ id: e.target.id, value: e.target.value }) and use them as below in reducer!
[action.data.id]: action.data.value,
},
};
Gmail version, working with Python 3.6 (note that you will need to change your Gmail settings to be able to send email via smtp from it:
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from os.path import basename
def send_mail(send_from: str, subject: str, text: str,
send_to: list, files= None):
send_to= default_address if not send_to else send_to
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = ', '.join(send_to)
msg['Subject'] = subject
msg.attach(MIMEText(text))
for f in files or []:
with open(f, "rb") as fil:
ext = f.split('.')[-1:]
attachedfile = MIMEApplication(fil.read(), _subtype = ext)
attachedfile.add_header(
'content-disposition', 'attachment', filename=basename(f) )
msg.attach(attachedfile)
smtp = smtplib.SMTP(host="smtp.gmail.com", port= 587)
smtp.starttls()
smtp.login(username,password)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()
Usage:
username = '[email protected]'
password = 'top-secret'
default_address = ['[email protected]']
send_mail(send_from= username,
subject="test",
text="text",
send_to= None,
files= # pass a list with the full filepaths here...
)
To use with any other email provider, just change the smtp configurations.
a csv-file is just like any other file a stream of characters. the getline reads from the file up to a delimiter however in your case the delimiter for the last item is not ' ' as you assume
getline(file, genero, ' ') ;
it is newline \n
so change that line to
getline(file, genero); // \n is default delimiter
Try:
List<String> textFiles(String directory) {
List<String> textFiles = new ArrayList<String>();
File dir = new File(directory);
for (File file : dir.listFiles()) {
if (file.getName().endsWith((".txt"))) {
textFiles.add(file.getName());
}
}
return textFiles;
}
You want to do a case insensitive search in which case:
if (file.getName().toLowerCase().endsWith((".txt"))) {
If you want to recursively search for through a directory tree for text files, you should be able to adapt the above as either a recursive function or an iterative function using a stack.
A relatively newer (de)compression tool you might want to consider is zstandard. It does an excellent job of utilizing spare cores, and it has made some great trade-offs when it comes to compression ratio vs. (de)compression time. It is also highly tweak-able depending on your compression ratio needs.
Like Maiasaura, I prefer ggplot2
. The transparent reference manual is one of the reasons.
However, this is one quick way to get it done.
require(ggplot2)
data(diamonds)
qplot(carat, price, data = diamonds, colour = color)
# example taken from Hadley's ggplot2 book
And cause someone famous said, plot related posts are not complete without the plot, here's the result:
Here's a couple of references: qplot.R example, note basically this uses the same diamond dataset I use, but crops the data before to get better performance.
http://ggplot2.org/book/ the manual: http://docs.ggplot2.org/current/
In my case, the reason was very low free space in disk (only 35 Mb). I did the following -
Delete redis dump file (if existing data not needed)
sudo rm /var/lib/redis/*
Delete all the keys of all the existing databases
sudo redis-cli flushall
Here's a solution to managed your "distinct" issue, which is entirely overblown:
Create a unit sphere and drop points on it with repelling charges. Run a particle system until they no longer move (or the delta is "small enough"). At this point, each of the points are as far away from each other as possible. Convert (x, y, z) to rgb.
I mention it because for certain classes of problems, this type of solution can work better than brute force.
I originally saw this approach here for tesselating a sphere.
Again, the most obvious solutions of traversing HSL space or RGB space will probably work just fine.
Some ideas in the following answer:
Steps in creating a web service using Axis2 - The client code
Gives an example of a Groovy client invoking the ADB classes generated from the WSDL.
There are lots of web service frameworks out there...
Clone only one branch. This is the easiest way:
git clone -b BRANCH_NAME --single-branch [email protected]:___/PROJECTNAME.git
This problem, in my case, wasn't related to the Insert key. It was related to Vrapper being enabled and editing like Vim, without my knowledge.
I just toggled the Vrapper Icon in Eclipse top bar of menus and then pressed the Insert Key and the problem was solved.
Hopefully this answer will help someone in the future.
Note, adding
$.support.cors = true;
was sufficient to force $.ajax calls to work on IE8
Further refining @YoYo's correction to @a_horse_with_no_name's row_number() based approach using DECODE vs CASE (i saw here). I see that @Martin Vrbovsky also has this case approach answer.
select
col1,
listagg(col2, ',') within group (order by col2) AS col2_list,
listagg(col3, ',') within group (order by col3) AS col3_list,
SUM(col4) AS col4
from (
select
col1,
decode(row_number() over (partition by col1, col2 order by null),1,col2) as col2,
decode(row_number() over (partition by col1, col3 order by null),1,col3) as col3
from foo
)
group by col1;
looks like outerWidth is broken in the latest version of jquery.
The discrepancy happens when
the outer div is floated, the inner div has the width set (smaller than the outer div) the inner div has style="margin:auto"
yes datediff is implemented; see: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF
By the way I found this by Google-searching "hive datediff", it was the first result ;)
I just found out that the following works:
https://www.youtube.com/embed/[video_id]?start=[start_at_second]&end=[end_at_second]
Note: the time must be an integer number of seconds (e.g. 119, not 1m59s).
Same problem, but just re-installing SQL Management Studio 2008 R2 Service Pack 1 worked for me. I left my DB engine alone. The DB engine is not the problem, just SQL Management Studio getting hosed by Visual Studio SP1.
Installers here...
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=26727
I installed SQLManagementStudio_x86_ENU.exe (32 bit for my machine).
If you put the declaration in a header file, and the definition in a separate .cpp
file, and #include
the header from a different .cpp
file, you will be able to see the difference.
Specifically, suppose:
int Add(int a, int b);
int Add(int a, int b = 3) {
...
}
#include "lib.h"
int main() {
Add(4);
}
The compilation of test.cpp
will not see the default parameter declaration, and will fail with an error.
For this reason, the default parameter definition is usually specified in the function declaration:
int Add(int a, int b = 3);
If you use Grunt to build your project, there is a plugin that will automatically assemble your partials into an Angular module that primes $templateCache. You can concatenate this module with the rest of your code and load everything from one file on startup.
A Quote from : iPhone Developer Program (~8MB PDF)
A provisioning profile is a collection of digital entities that uniquely ties developers and devices to an authorized iPhone Development Team and enables a device to be used for testing. A Development Provisioning Profile must be installed on each device on which you wish to run your application code. Each Development Provisioning Profile will contain a set of iPhone Development Certificates, Unique Device Identifiers and an App ID. Devices specified within the provisioning profile can be used for testing only by those individuals whose iPhone Development Certificates are included in the profile. A single device can contain multiple provisioning profiles.
The count
method of NSArray
returns an NSUInteger
, and on the 64-bit OS X platform
NSUInteger
is defined as unsigned long
, andunsigned long
is a 64-bit unsigned integer.int
is a 32-bit integer.So int
is a "smaller" datatype than NSUInteger
, therefore the compiler warning.
See also NSUInteger in the "Foundation Data Types Reference":
When building 32-bit applications, NSUInteger is a 32-bit unsigned integer. A 64-bit application treats NSUInteger as a 64-bit unsigned integer.
To fix that compiler warning, you can either declare the local count
variable as
NSUInteger count;
or (if you are sure that your array will never contain more than 2^31-1
elements!),
add an explicit cast:
int count = (int)[myColors count];
Whatever you do to secure your secret keys is not going to be a real solution. If developer can decompile the application there is no way to secure the key, hiding the key is just security by obscurity and so is code obfuscation. Problem with securing a secret key is that in order to secure it you have to use another key and that key needs to also be secured. Think of a key hidden in a box that is locked with a key. You place a box inside a room and lock the room. You are left with another key to secure. And that key is still going to be hardcoded inside your application.
So unless the user enters a PIN or a phrase there is no way to hide the key. But to do that you would have to have a scheme for managing PINs happening out of band, which means through a different channel. Certainly not practical for securing keys for services like Google APIs.
The simplest way is to convert Date to POSIXlt format. Then perform the arithmetic operation as follows:
date_1m_fwd <- as.POSIXlt("2010-01-01")
date_1m_fwd$mon <- date_1m_fwd$mon +1
Moreover, incase you want to deal with Date columns in data.table, unfortunately, POSIXlt format is not supported.
Still you can perform the add month using basic R codes as follows:
library(data.table)
dt <- as.data.table(seq(as.Date("2010-01-01"), length.out=5, by="month"))
dt[,shifted_month:=tail(seq(V1[1], length.out=length(V1)+3, by="month"),length(V1))]
Hope it helps.
In your example a credit card is expired on 6/2008.
Without knowing what you are doing I cannot say definitively you should not be validating ahead of time but be aware that sometimes business rules defy all logic.
For example, where I used to work they often did not process a card at all or would continue on transaction failure simply so they could contact the customer and get a different card.
In Sublime Text, WHILE editing a Python file:
Sublime Text menu > Preferences > Settings - Syntax Specific :
Python.sublime-settings
{
"tab_size": 4,
"translate_tabs_to_spaces": true
}
You may have forgotten to define the Content-Type
header. For example:
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ items }),
}
Addendum to @sjngm's answer:
They both also ignore whitespace:
var foo = " 3 "; console.log(parseInt(foo)); // 3 console.log(Number(foo)); // 3
It is not exactly correct. As sjngm wrote parseInt parses string to first number. It is true. But the problem is when you want to parse number separated with whitespace ie. "12 345". In that case parseInt("12 345")
will return 12
instead of 12345
.
So to avoid that situation you must trim whitespaces before parsing to number.
My solution would be:
var number=parseInt("12 345".replace(/\s+/g, ''),10);
Notice one extra thing I used in parseInt() function. parseInt("string",10)
will set the number to decimal format. If you would parse string like "08" you would get 0 because 8 is not a octal number.Explanation is here
You have to create an item of type ListBoxItem and add that to the Items collection:
list.Items.add( new ListBoxItem("clan", "sifOsoba"));
The number is held in an int[]
- the maximum size of an array is Integer.MAX_VALUE
. So the maximum BigInteger probably is (2 ^ 32) ^ Integer.MAX_VALUE
.
Admittedly, this is implementation dependent, not part of the specification.
In Java 8, some information was added to the BigInteger javadoc, giving a minimum supported range and the actual limit of the current implementation:
BigInteger
must support values in the range-2
Integer.MAX_VALUE
(exclusive) to+2
Integer.MAX_VALUE
(exclusive) and may support values outside of that range.Implementation note:
BigInteger
constructors and operations throwArithmeticException
when the result is out of the supported range of-2
Integer.MAX_VALUE
(exclusive) to+2
Integer.MAX_VALUE
(exclusive).
Now visibility change animations should be done via Transition API
which available in support (androidx) package. Just call TransitionManager.beginDelayedTransition method with Slide transition then change visibility of the view.
import androidx.transition.Slide;
import androidx.transition.Transition;
import androidx.transition.TransitionManager;
private void toggle(boolean show) {
View redLayout = findViewById(R.id.redLayout);
ViewGroup parent = findViewById(R.id.parent);
Transition transition = new Slide(Gravity.BOTTOM);
transition.setDuration(600);
transition.addTarget(R.id.redLayout);
TransitionManager.beginDelayedTransition(parent, transition);
redLayout.setVisibility(show ? View.VISIBLE : View.GONE);
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="play" />
<LinearLayout
android:id="@+id/redLayout"
android:layout_width="match_parent"
android:layout_height="400dp"
android:background="#5f00"
android:layout_alignParentBottom="true" />
</RelativeLayout>
Check this answer with another default and custom transition examples.
The simplest way is use return View.
return View("ViewName");
Remember, the physical name of the "ViewName" should be something like ViewName.cshtml in your project, if your are using MVC C# / .NET.
Now there is already no need to use JSON.stringify
explicitly. Just execute this line of code
$.cookie.json = true;
After that you can save any object in cookie, which will be automatically converted to JSON and back from JSON when reading cookie.
var user = { name: "name", age: 25 }
$.cookie('user', user);
...
var currentUser = $.cookie('user');
alert('User name is ' + currentUser.name);
But JSON library does not come with jquery.cookie, so you have to download it by yourself and include into html page before jquery.cookie.js
git reset --hard origin/master
says: throw away all my staged and unstaged changes, forget everything on my current local branch and make it exactly the same as origin/master
.
You probably wanted to ask this before you ran the command. The destructive nature is hinted at by using the same words as in "hard reset".
For a field named isCurrent
, the correct getter / setter naming is setCurrent()
/ isCurrent()
(at least that's what Eclipse thinks), which is highly confusing and can be traced back to the main problem:
Your field should not be called isCurrent
in the first place. Is is a verb and verbs are inappropriate to represent an Object's state. Use an adjective instead, and suddenly your getter / setter names will make more sense:
private boolean current;
public boolean isCurrent(){
return current;
}
public void setCurrent(final boolean current){
this.current = current;
}
Pandas seem to be recommending df.to_numpy since
the other methods still raise a FutureWarning
: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html#pandas.DataFrame.to_numpy
So, an alternative that would work int this case is:
b=a['Names']
c = b.to_numpy().tolist()
if 'Mel' in c:
print("Mel is in the dataframe column Names")
There is a general problem: it's hard to mock time. Also, it's really bad practice to place long running/waiting code in a unit test.
So, for making a scheduling API testable, I used an interface with a real and a mock implementation like this:
public interface Clock {
public long getCurrentMillis();
public void sleep(long millis) throws InterruptedException;
}
public static class SystemClock implements Clock {
@Override
public long getCurrentMillis() {
return System.currentTimeMillis();
}
@Override
public void sleep(long millis) throws InterruptedException {
Thread.sleep(millis);
}
}
public static class MockClock implements Clock {
private final AtomicLong currentTime = new AtomicLong(0);
public MockClock() {
this(System.currentTimeMillis());
}
public MockClock(long currentTime) {
this.currentTime.set(currentTime);
}
@Override
public long getCurrentMillis() {
return currentTime.addAndGet(5);
}
@Override
public void sleep(long millis) {
currentTime.addAndGet(millis);
}
}
With this, you could imitate time in your test:
@Test
public void testExpiration() {
MockClock clock = new MockClock();
SomeCacheObject sco = new SomeCacheObject();
sco.putWithExpiration("foo", 1000);
clock.sleep(2000) // wait for 2 seconds
assertNull(sco.getIfNotExpired("foo"));
}
An advanced multi-threading mock for Clock
is much more complex, of course, but you can make it with ThreadLocal
references and a good time synchronization strategy, for example.
You have not defined the variable input_line
.
Add this:
string input_line;
And add this include.
#include <string>
Here is the full example. I also removed the semi-colon after the while loop, and you should have getline
inside the while to properly detect the end of the stream.
#include <iostream>
#include <string>
int main() {
for (std::string line; std::getline(std::cin, line);) {
std::cout << line << std::endl;
}
return 0;
}
While in Java it's indeed a bad practice to use exceptions for flow control (mainly because exceptions force the JVM to gather resources (more here)), in Python you have two important principles: duck typing and EAFP. This basically means that you are encouraged to try using an object the way you think it would work, and handle when things are not like that.
In summary, the only problem would be your code getting too much indented. If you feel like it, try to simplify some of the nestings, like lqc suggested in the suggested answer above.
Here is my solution. I first create random numbers with random.uniform, format them in to string with double precision and then convert them back to float. You can adjust the precision by changing '.2f' to '.3f' etc..
import random
from decimal import Decimal
GndSpeedHigh = float(format(Decimal(random.uniform(5, 25)), '.2f'))
GndSpeedLow = float(format(Decimal(random.uniform(2, GndSpeedHigh)), '.2f'))
GndSpeedMean = float(Decimal(format(GndSpeedHigh + GndSpeedLow) / 2, '.2f')))
print(GndSpeedMean)
Since 7-zip version 9.25 alpha there is a new -spf
switch that can be used to store the full file paths including drive letter to the archive.
7zG.exe a -spf c:\BAckup\backup.zip @c:\temp\tmpFileList.txt
should be working just fine now.
I too had that same problem.. If we think logically little bit we can get the answer.. It worked for me very well.. I hope u will get it..
listviewdemo.xml
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="30dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
listviewcontent.xml
- note that TextView
- android:id="@+id/txtLstItem"
<LinearLayout
android:id="@+id/listviewcontentlayout"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="horizontal">
<ImageView
android:id="@+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="6dp" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="@+id/txtLstItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:shadowColor="@android:color/black"
android:shadowRadius="5"
android:textColor="@android:color/white" />
</LinearLayout>
<ImageView
android:id="@+id/img2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="6dp" />
</LinearLayout>
ListViewActivity.java
- Note that view.findViewById(R.id.txtLstItem)
-
as we setting the value to TextView
by setText()
method we getting text from TextView
by View
object returned by onItemClick
method. OnItemClick()
returns the current view.
TextView v=(TextView) view.findViewById(R.id.txtLstItem);
Toast.makeText(getApplicationContext(), "selected Item Name is "+v.getText(), Toast.LENGTH_LONG).show();**
Using this simple logic we can get other values like CheckBox
, RadioButton
, ImageView
etc.
ListView List = (ListView) findViewById(R.id.listview);
cursor = cr.query(CONTENT_URI,projection,null,null,null);
adapter = new ListViewCursorAdapter(ListViewActivity.this, R.layout.listviewcontent, cursor, from, to);
cursor.moveToFirst();
// Let activity manage the cursor
startManagingCursor(cursor);
List.setAdapter(adapter);
List.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick (AdapterView < ? > adapter, View view,int position, long arg){
// TODO Auto-generated method stub
TextView v = (TextView) view.findViewById(R.id.txtLstItem);
Toast.makeText(getApplicationContext(), "selected Item Name is " + v.getText(), Toast.LENGTH_LONG).show();
}
}
);
copy *.txt all.txt
This will concatenate all text files of the folder to one text file all.txt
If you have any other type of files, like sql files
copy *.sql all.sql
ul.menu li a:before, ul.menu li .item:before, ul.menu li .separator:before {
content: "\2022";
font-family: FontAwesome;
margin-right: 10px;
display: inline;
vertical-align: middle;
font-size: 1.6em;
font-weight: normal;
}
Is present in your site's CSS, looks like it's coming from a compiled CSS file from within your application. Perhaps from a plugin. Changing the name of the "menu" class you are using should resolve the issue.
Visual for you - http://i.imgur.com/d533SQD.png
Another approach would be to leverage the INSERT ALL
syntax from oracle,
INSERT ALL
INTO table1(email, campaign_id) VALUES (email, campaign_id)
WITH source_data AS
(SELECT '[email protected]' email,100 campaign_id
FROM dual
UNION ALL
SELECT '[email protected]' email,200 campaign_id
FROM dual)
SELECT email
,campaign_id
FROM source_data src
WHERE NOT EXISTS (SELECT 1
FROM table1 dest
WHERE src.email = dest.email
AND src.campaign_id = dest.campaign_id);
INSERT ALL
also allow us to perform a conditional insert into multiple tables based on a sub query as source.
There are some really clean and nice examples are there to refer.
See svn diff
in the manual:
svn diff -r 8979:11390 http://svn.collab.net/repos/svn/trunk/fSupplierModel.php
You can do like this:
private void datagridview1_SelectionChanged(object sender, EventArgs e)
{
if (datagridview1.SelectedCells.Count > 0)
{
int selectedrowindex = datagridview1.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = datagridview1.Rows[selectedrowindex];
string cellValue = Convert.ToString(selectedRow.Cells["enter column name"].Value);
}
}
The tool that richardtz suggests is excellent.
Another one that is amazing and comes with a 30 day free trial is Araxis Merge. This one does a 3 way merge and is much more feature complete than winmerge, but it is a commercial product.
You might also like to check out Scott Hanselman's developer tool list, which mentions a couple more in addition to winmerge
new OnEditorActionListener(){
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
editText.requestFocus();
//used ******* return true ******
return **true**;
}
}
Variables can contain single quotes.
myvar=\'....$variable\'
repo forall -c $myvar
If it's a deeper key/value you're after and you're not dealing with arrays of keys/values at each level, you could recursively search the tree:
public static String recurseKeys(JSONObject jObj, String findKey) throws JSONException {
String finalValue = "";
if (jObj == null) {
return "";
}
Iterator<String> keyItr = jObj.keys();
Map<String, String> map = new HashMap<>();
while(keyItr.hasNext()) {
String key = keyItr.next();
map.put(key, jObj.getString(key));
}
for (Map.Entry<String, String> e : (map).entrySet()) {
String key = e.getKey();
if (key.equalsIgnoreCase(findKey)) {
return jObj.getString(key);
}
// read value
Object value = jObj.get(key);
if (value instanceof JSONObject) {
finalValue = recurseKeys((JSONObject)value, findKey);
}
}
// key is not found
return finalValue;
}
Usage:
JSONObject jObj = new JSONObject(jsonString);
String extract = recurseKeys(jObj, "extract");
Using Map code from https://stackoverflow.com/a/4149555/2301224
Use scrollTop() to get or set the scroll position.
How I do it with openpyxl lib:
import csv
from openpyxl import Workbook
def convert_csv_to_xlsx(self):
wb = Workbook()
sheet = wb.active
CSV_SEPARATOR = "#"
with open("my_file.csv") as f:
reader = csv.reader(f)
for r, row in enumerate(reader):
for c, col in enumerate(row):
for idx, val in enumerate(col.split(CSV_SEPARATOR)):
cell = sheet.cell(row=r+1, column=idx+1)
cell.value = val
wb.save("my_file.xlsx")
You have to define which type of exception you want to catch. So write except Exception, e:
instead of except, e:
for a general exception (that will be logged anyway).
Other possibility is to write your whole try/except code this way:
try:
with open(filepath,'rb') as f:
con.storbinary('STOR '+ filepath, f)
logger.info('File successfully uploaded to '+ FTPADDR)
except Exception, e: # work on python 2.x
logger.error('Failed to upload to ftp: '+ str(e))
in Python 3.x and modern versions of Python 2.x use except Exception as e
instead of except Exception, e
:
try:
with open(filepath,'rb') as f:
con.storbinary('STOR '+ filepath, f)
logger.info('File successfully uploaded to '+ FTPADDR)
except Exception as e: # work on python 3.x
logger.error('Failed to upload to ftp: '+ str(e))
This is also easy:
string data = "THExxQUICKxxBROWNxxFOX";
string[] arr = data.Split("xx".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
This problem occurs when you do not declare at the top of your HTML file in HEDER this tag.
<link rel="icon" href="your_address_icon" type="image/x-icon">
Do you have the required permission set in your Manifest?
<uses-permission android:name="android.permission.WAKE_LOCK" />
All tables within the bootstrap stretch according to their container, which you can easily do by placing your table inside a .span*
grid element of your choice. If you wish to remove this property you can create your own table class and simply add it to the table you want to expand with the content within:
.table-nonfluid {
width: auto !important;
}
You can add this class inside your own stylesheet and simply add it to the container of your table like so:
<table class="table table-nonfluid"> ... </table>
This way your change won't affect the bootstrap stylesheet itself (you might want to have a fluid table somewhere else in your document).
So I used to use a for loop for iterating through the dictionary as well, but one thing I've found that works much faster is to convert to a panel and then to a dataframe. Say you have a dictionary d
import pandas as pd
d
{'RAY Index': {datetime.date(2014, 11, 3): {'PX_LAST': 1199.46,
'PX_OPEN': 1200.14},
datetime.date(2014, 11, 4): {'PX_LAST': 1195.323, 'PX_OPEN': 1197.69},
datetime.date(2014, 11, 5): {'PX_LAST': 1200.936, 'PX_OPEN': 1195.32},
datetime.date(2014, 11, 6): {'PX_LAST': 1206.061, 'PX_OPEN': 1200.62}},
'SPX Index': {datetime.date(2014, 11, 3): {'PX_LAST': 2017.81,
'PX_OPEN': 2018.21},
datetime.date(2014, 11, 4): {'PX_LAST': 2012.1, 'PX_OPEN': 2015.81},
datetime.date(2014, 11, 5): {'PX_LAST': 2023.57, 'PX_OPEN': 2015.29},
datetime.date(2014, 11, 6): {'PX_LAST': 2031.21, 'PX_OPEN': 2023.33}}}
The command
pd.Panel(d)
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 2 (major_axis) x 4 (minor_axis)
Items axis: RAY Index to SPX Index
Major_axis axis: PX_LAST to PX_OPEN
Minor_axis axis: 2014-11-03 to 2014-11-06
where pd.Panel(d)[item] yields a dataframe
pd.Panel(d)['SPX Index']
2014-11-03 2014-11-04 2014-11-05 2014-11-06
PX_LAST 2017.81 2012.10 2023.57 2031.21
PX_OPEN 2018.21 2015.81 2015.29 2023.33
You can then hit the command to_frame() to turn it into a dataframe. I use reset_index as well to turn the major and minor axis into columns rather than have them as indices.
pd.Panel(d).to_frame().reset_index()
major minor RAY Index SPX Index
PX_LAST 2014-11-03 1199.460 2017.81
PX_LAST 2014-11-04 1195.323 2012.10
PX_LAST 2014-11-05 1200.936 2023.57
PX_LAST 2014-11-06 1206.061 2031.21
PX_OPEN 2014-11-03 1200.140 2018.21
PX_OPEN 2014-11-04 1197.690 2015.81
PX_OPEN 2014-11-05 1195.320 2015.29
PX_OPEN 2014-11-06 1200.620 2023.33
Finally, if you don't like the way the frame looks you can use the transpose function of panel to change the appearance before calling to_frame() see documentation here http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Panel.transpose.html
Just as an example
pd.Panel(d).transpose(2,0,1).to_frame().reset_index()
major minor 2014-11-03 2014-11-04 2014-11-05 2014-11-06
RAY Index PX_LAST 1199.46 1195.323 1200.936 1206.061
RAY Index PX_OPEN 1200.14 1197.690 1195.320 1200.620
SPX Index PX_LAST 2017.81 2012.100 2023.570 2031.210
SPX Index PX_OPEN 2018.21 2015.810 2015.290 2023.330
Hope this helps.
Does this work?
float flt = 145.664454;
Double dbl = 0.0;
dbl += flt;
A Bin file is a pure binary file with no memory fix-ups or relocations, more than likely it has explicit instructions to be loaded at a specific memory address. Whereas....
ELF files are Executable Linkable Format which consists of a symbol look-ups and relocatable table, that is, it can be loaded at any memory address by the kernel and automatically, all symbols used, are adjusted to the offset from that memory address where it was loaded into. Usually ELF files have a number of sections, such as 'data', 'text', 'bss', to name but a few...it is within those sections where the run-time can calculate where to adjust the symbol's memory references dynamically at run-time.
From your pom.xml, try to remove spring repository entries, per default will download from maven repository. I have tried with 1.5.6.RELEASE and worked very well.
I realize this is on older question but just wanted to add that
Environment.NewLine
also works if doing this through code.
Many modern browsers now support ES6 modules. As long as you import your scripts (including the entrypoint to your application) using <script type="module" src="...">
it will work.
Take a look at caniuse.com for more details: https://caniuse.com/#feat=es6-module
Just do:
document.body.innerHTML = document.body.innerHTML + '<img src="../images/loaded.gif" alt="" onload="alert(\'test\');this.parentNode.removeChild(this);" />';
The simplest method is
$dateArray = explode('/', $_POST['date']);
$date = $dateArray[2].'-'.$dateArray[0].'-'.$dateArray[1];
$sql = mysql_query("INSERT INTO user_date (column,column,column) VALUES('',$name,$date)") or die (mysql_error());
This one is great:
<style type="text/css">
textarea.test
{
width: 100%;
height: 100%;
border-color: Transparent;
}
</style>
<textarea class="test"></textarea>
To install PEAR's Mail.php in Ubuntu, run following set of commands:
sudo apt-get install php-pear
sudo pear install mail
sudo pear install Net_SMTP
sudo pear install Auth_SASL
sudo pear install mail_mime
The IE9 developer tools worked for me. Just set the "Browser Mode" menu item to IE7.
I had this issue, as well as some other issues with Brewed Python on OS X v10.9 (Mavericks).
sudo pip install --upgrade setuptools
didn't work for me, and I think my setuptools/distribute setup was botched.
I finally got it to work by running
sudo easy_install -U setuptools
I was having the same problem, the fact is that the input of lat and long should be String. Only then did I manage.
for example:
Controller.
ViewBag.Lat = object.Lat.ToString().Replace(",", ".");
ViewBag.Lng = object.Lng.ToString().Replace(",", ".");
View - function javascript
<script>
function initMap() {
var myLatLng = { lat: @ViewBag.Lat, lng: @ViewBag.Lng};
// Create a map object and specify the DOM element for display.
var map = new window.google.maps.Map(document.getElementById('map'),
{
center: myLatLng,
scrollwheel: false,
zoom: 16
});
// Create a marker and set its position.
var marker = new window.google.maps.Marker({
map: map,
position: myLatLng
//title: "Blue"
});
}
</script>
I convert the double value to string and do a Replace in the ',' to '.' And so everything works normally.
I'm facing the same problem trying to geocode 140 addresses.
My workaround was adding usleep(100000) for each loop of next geocoding request. If status of the request is OVER_QUERY_LIMIT, the usleep is increased by 50000 and request is repeated, and so on.
And of cause all received data (lat/long) are stored in XML file not to run request every time the page is loading.
If anyone is wondering how to set the heading such that it appears with a fixed distance to the left side (and not centered as presented above), I figured that out by modifying @Puigcerber's code.
h1 {
white-space: nowrap;
overflow: hidden;
}
h1:before,
h1:after {
background-color: #000;
content: "";
display: inline-block;
height: 1px;
position: relative;
vertical-align: middle;
}
h1:before {
right: 0.3em;
width: 50px;
}
h1:after {
left: 0.3em;
width: 100%;
}
Here the JSFiddle.
In more or less normal parlance: If your software can do everything the mimicked system can do, it's an emulator. If it only approximates the results of a system (IT or otherwise), it's a simulator.
I found a solution wich is to do:
<span class="visible-sm"> your code without col </span>
<span class="visible-xs"> your code with col </span>
It's not very optimized but it works. Did you find something better? It really miss a class like col-sm-0 to apply colons just to the xs size...
It can easily be done if u had declared a class that extends from Application
This class will be like a singleton, so when u need a context u can get it just like this:
I think this is the better answer and the cleaner
Here is my code from Utilities package:
public static String getAppNAme(){
return MyOwnApplication.getInstance().getString(R.string.app_name);
}
another way to check in realtime textField source :
@IBOutlet var textField1 : UITextField = UITextField()
override func viewDidLoad()
{
....
self.textField1.addTarget(self, action: Selector("yourNameFunction:"), forControlEvents: UIControlEvents.EditingChanged)
}
func yourNameFunction(sender: UITextField) {
if sender.text.isEmpty {
// textfield is empty
} else {
// text field is not empty
}
}
ASPX file:
<h2><p>Notify:</p> <asp:Literal runat="server" ID="ltNotify" /></h2>
ASPX.CS file:
ltNotify.Text = "Alert!";
I use this...but have never done any metro app development, so I don't know of any restrictions on libraries available to you. (note, you'll need to mark your classes as with DataContract and DataMember attributes)
public static class JSONSerializer<TType> where TType : class
{
/// <summary>
/// Serializes an object to JSON
/// </summary>
public static string Serialize(TType instance)
{
var serializer = new DataContractJsonSerializer(typeof(TType));
using (var stream = new MemoryStream())
{
serializer.WriteObject(stream, instance);
return Encoding.Default.GetString(stream.ToArray());
}
}
/// <summary>
/// DeSerializes an object from JSON
/// </summary>
public static TType DeSerialize(string json)
{
using (var stream = new MemoryStream(Encoding.Default.GetBytes(json)))
{
var serializer = new DataContractJsonSerializer(typeof(TType));
return serializer.ReadObject(stream) as TType;
}
}
}
So, if you had a class like this...
[DataContract]
public class MusicInfo
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Artist { get; set; }
[DataMember]
public string Genre { get; set; }
[DataMember]
public string Album { get; set; }
[DataMember]
public string AlbumImage { get; set; }
[DataMember]
public string Link { get; set; }
}
Then you would use it like this...
var musicInfo = new MusicInfo
{
Name = "Prince Charming",
Artist = "Metallica",
Genre = "Rock and Metal",
Album = "Reload",
AlbumImage = "http://up203.siz.co.il/up2/u2zzzw4mjayz.png",
Link = "http://f2h.co.il/7779182246886"
};
// This will produce a JSON String
var serialized = JSONSerializer<MusicInfo>.Serialize(musicInfo);
// This will produce a copy of the instance you created earlier
var deserialized = JSONSerializer<MusicInfo>.DeSerialize(serialized);
I drilled down the formation of the drop down list instead of using @Html.DropDownList()
. This is useful if you have to set the value of the dropdown list at runtime in razor instead of controller:
<select id="NewsCategoriesID" name="NewsCategoriesID">
@foreach (SelectListItem option in ViewBag.NewsCategoriesID)
{
<option value="@option.Value" @(option.Value == ViewBag.ValueToSet ? "selected='selected'" : "")>@option.Text</option>
}
</select>
Using awk
:
export INDEX=2
export VALUE=bar
awk -F, '$'$INDEX' ~ /^'$VALUE'$/ {print}' inputfile.csv
Edit: As per Dennis Williamson's excellent comment, this could be much more cleanly (and safely) written by defining awk variables using the -v
switch:
awk -F, -v index=$INDEX -v value=$VALUE '$index == value {print}' inputfile.csv
Jeez...with variables, and everything, awk is almost a real programming language...
As Jim Garrison said in the comment, no obvious reason why you'd make a one-element list out of drug.upper()
(which implies drug is a string).
But that's not your error, as your function medications_minimum3()
doesn't even use the second argument (something you should fix).
TypeError: unhashable type: 'list'
usually means that you are trying to use a list as a hash argument (like for accessing a dictionary). I'd look for the error in counter[row[11]]+=1
-- are you sure that row[11]
is of the right type? Sounds to me it might be a list.
Sometimes it is just how you export and import it. For this error message it could be, that the default keyword is missing.
export default SampleClass {}
Where you instantiate it:
import SampleClass from 'path/to/class';
let sampleClass = new SampleClass();
Option 2, with curly braces:
export SampleClass {}
import { SampleClass } from 'path/to/class';
let sampleClass = new SampleClass();
The answer is in the documentation for bindParam
:
Unlike PDOStatement::bindValue(), the variable is bound as a reference and will only be evaluated at the time that PDOStatement::execute() is called.
And execute
call PDOStatement::bindParam() to bind PHP variables to the parameter markers: bound variables pass their value as input and receive the output value, if any, of their associated parameter markers
Example:
$value = 'foo';
$s = $dbh->prepare('SELECT name FROM bar WHERE baz = :baz');
$s->bindParam(':baz', $value); // use bindParam to bind the variable
$value = 'foobarbaz';
$s->execute(); // executed with WHERE baz = 'foobarbaz'
or
$value = 'foo';
$s = $dbh->prepare('SELECT name FROM bar WHERE baz = :baz');
$s->bindValue(':baz', $value); // use bindValue to bind the variable's value
$value = 'foobarbaz';
$s->execute(); // executed with WHERE baz = 'foo'
If I understand what you are asking, it is a regular expression like this:
^(8768|9875|2353)
This matches the three sets of digit strings at beginning of line only.
Consider - typeof bar === "object"
to determine if bar
is an object
Although typeof bar === "object"
is a reliable way of checking if bar is an object, the surprising gotcha in JavaScript is that null is also considered an object!
Therefore, the following code will, to the surprise of most developers, log true (not false) to the console:
var bar = null;
console.log(typeof bar === "object"); // logs true!
As long as one is aware of this, the problem can easily be avoided by also checking if bar is null:
console.log((bar !== null) && (typeof bar === "object")); // logs false
To be entirely thorough in our answer, there are two other things worth noting:
First, the above solution will return false if bar is a function. In most cases, this is the desired behavior, but in situations where you want to also return true for functions, you could amend the above solution to be:
console.log((bar !== null) && ((typeof bar === "object") || (typeof bar === "function")));
Second, the above solution will return true if bar is an array (e.g., if var bar = [];
). In most cases, this is the desired behavior, since arrays are indeed objects, but in situations where you want to also false for arrays, you could amend the above solution to be:
console.log((bar !== null) && (typeof bar === "object") && (toString.call(bar) !== "[object Array]"));
However, there’s one other alternative that returns false for nulls, arrays, and functions, but true for objects:
console.log((bar !== null) && (bar.constructor === Object));
Or, if you’re using jQuery:
console.log((bar !== null) && (typeof bar === "object") && (! $.isArray(bar)));
ES5 makes the array case quite simple, including its own null check:
console.log(Array.isArray(bar));
You have two ways:
First go to the particular path of Android SDK:
1) Open your command prompt and traverse to the platform-tools directory through it such as
$ cd Frameworks\Android-Sdk\platform-tools
2) Run your adb commands now such as to know that your adb is working properly :
$ adb devices OR adb logcat OR simply adb
Second way is :
1) Right click on your My Computer.
2) Open Environment variables.
3) Add new variable to your System PATH variable(Add if not exist otherwise no need to add new variable if already exist).
4) Add path of platform-tools directory to as value of this variable such as C:\Program Files\android-sdk\platform-tools.
5) Restart your computer once.
6) Now run the above adb commands such adb devices or other adb commands from anywhere in command prompt.
Also on you can fire a command on terminal setx PATH "%PATH%;C:\Program Files\android-sdk\platform-tools"
Unsatisfied with all the replies, since most of them work very slowly and produce unnecessarily long output for large directories, I wrote my own Python script to compare two folders.
Unlike many other solutions, it doesn't compare contents of the files. Also it doesn't go inside subdirectories which are missing in another directory. So the output is quite concise and the script works fast.
#!/usr/bin/env python3
import os, sys
def compare_dirs(d1: "old directory name", d2: "new directory name"):
def print_local(a, msg):
print('DIR ' if a[2] else 'FILE', a[1], msg)
# ensure validity
for d in [d1,d2]:
if not os.path.isdir(d):
raise ValueError("not a directory: " + d)
# get relative path
l1 = [(x,os.path.join(d1,x)) for x in os.listdir(d1)]
l2 = [(x,os.path.join(d2,x)) for x in os.listdir(d2)]
# determine type: directory or file?
l1 = sorted([(x,y,os.path.isdir(y)) for x,y in l1])
l2 = sorted([(x,y,os.path.isdir(y)) for x,y in l2])
i1 = i2 = 0
common_dirs = []
while i1<len(l1) and i2<len(l2):
if l1[i1][0] == l2[i2][0]: # same name
if l1[i1][2] == l2[i2][2]: # same type
if l1[i1][2]: # remember this folder for recursion
common_dirs.append((l1[i1][1], l2[i2][1]))
else:
print_local(l1[i1],'type changed')
i1 += 1
i2 += 1
elif l1[i1][0]<l2[i2][0]:
print_local(l1[i1],'removed')
i1 += 1
elif l1[i1][0]>l2[i2][0]:
print_local(l2[i2],'added')
i2 += 1
while i1<len(l1):
print_local(l1[i1],'removed')
i1 += 1
while i2<len(l2):
print_local(l2[i2],'added')
i2 += 1
# compare subfolders recursively
for sd1,sd2 in common_dirs:
compare_dirs(sd1, sd2)
if __name__=="__main__":
compare_dirs(sys.argv[1], sys.argv[2])
Sample usage:
user@laptop:~$ python3 compare_dirs.py dir1/ dir2/
DIR dir1/out/flavor-domino removed
DIR dir2/out/flavor-maxim2 added
DIR dir1/target/vendor/flavor-domino removed
DIR dir2/target/vendor/flavor-maxim2 added
FILE dir1/tmp/.kconfig-flavor_domino removed
FILE dir2/tmp/.kconfig-flavor_maxim2 added
DIR dir2/tools/tools/LiveSuit_For_Linux64 added
Or if you want to see only files from the first directory:
user@laptop:~$ python3 compare_dirs.py dir2/ dir1/ | grep dir1
DIR dir1/out/flavor-domino added
DIR dir1/target/vendor/flavor-domino added
FILE dir1/tmp/.kconfig-flavor_domino added
P.S. If you need to compare file sizes and file hashes for potential changes, I published an updated script here: https://gist.github.com/amakukha/f489cbde2afd32817f8e866cf4abe779
If you check Thrown
for Common Language Runtime Exception
in the break when an exception window (Ctrl+Alt+E in Visual Studio), then the execution should break while you are debugging when the exception is thrown.
This will probably give you some insight into what is going on.
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values.
I didn't know about the join function - Nice! I had written a function that I placed in the code section (report properties->code tab:
Public Function ShowParmValues(ByVal parm as Parameter) as string
Dim s as String
For i as integer = 0 to parm.Count-1
s &= CStr(parm.value(i)) & IIF( i < parm.Count-1, ", ","")
Next
Return s
End Function
If you just wish to remove the zeros, leaving the non-zeros behind in a, then the very best solution is
a(a==0) = [];
This deletes the zero elements, using a logical indexing approach in MATLAB. When the index to a vector is a boolean vector of the same length as the vector, then MATLAB can use that boolean result to index it with. So this is equivalent to
a(find(a==0)) = [];
And, when you set some array elements to [] in MATLAB, the convention is to delete them.
If you want to put the zeros into a new result b, while leaving a unchanged, the best way is probably
b = a(a ~= 0);
Again, logical indexing is used here. You could have used the equivalent version (in terms of the result) of
b = a(find(a ~= 0));
but mlint will end up flagging the line as one where the purely logical index was more efficient, and thus more appropriate.
As always, beware EXACT tests for zero or for any number, if you would have accepted elements of a that were within some epsilonic tolerance of zero. Do those tests like this
b = a(abs(a) >= tol);
This retains only those elements of a that are at least as large as your tolerance.
html
<input id="something" onkeyup="key_up(this)" type="text">
script
function key_up(e){
var enterKey = 13; //Key Code for Enter Key
if (e.which == enterKey){
//Do you work here
}
}
Next time, Please try providing some code.
The error implies that this subquery is returning more than 1 row:
(Select Supplier_Item.Price from Supplier_Item,orderdetails,Supplier where Supplier_Item.SKU=OrderDetails.Sku and Supplier_Item.SupplierId=Supplier.SupplierID )
You probably don't want to include the orderdetails and supplier tables in the subquery, because you want to reference the values selected from those tables in the outer query. So I think you want the subquery to be simply:
(Select Supplier_Item.Price from Supplier_Item where Supplier_Item.SKU=OrderDetails.Sku and Supplier_Item.SupplierId=Supplier.SupplierID )
I suggest you read up on correlated vs. non-correlated subqueries.
As far as I know, there is no such a thing as iOS emulator on windows or linux, there are only some gameengines that enable you to compile same code for both iOS and windows or linux and there is a toolchain to compile iOS application using linux. none of them are realy emulator/simulator things. and to use that toolchain you need a jailbreaked iOS device to test binary file created using toolchain. I mean linux itself can't run the binary created itself. and by the way even in mac simulator is just an intermediate program which runs mac-compiled binary, since if you change compiling for iOS from simulator or the other way, all the files are rebuild. and also there are some real differences, like iOS is a case-sensitive operation while simulator is not.
so the best solution is to buy an iOS device yourself.
Check out this one:
https://github.com/VBA-tools/VBA-Web
It's a high level library for dealing with REST. It's OOP, works with JSON, but also works with any other format.
Yes, you can do the same in JavaScript using a loop, but not limited to that. There are many ways to do a loop over arrays in JavaScript. Imagine you have this array below, and you'd like to do a loop over it:
var arr = [1, 2, 3, 4, 5];
These are the solutions:
1) For loop
A for
loop is a common way looping through arrays in JavaScript, but it is no considered as the fastest solutions for large arrays:
for (var i=0, l=arr.length; i<l; i++) {
console.log(arr[i]);
}
2) While loop
A while loop is considered as the fastest way to loop through long arrays, but it is usually less used in the JavaScript code:
let i=0;
while (arr.length>i) {
console.log(arr[i]);
i++;
}
3) Do while
A do while
is doing the same thing as while
with some syntax difference as below:
let i=0;
do {
console.log(arr[i]);
i++;
}
while (arr.length>i);
These are the main ways to do JavaScript loops, but there are a few more ways to do that.
Also we use a for in
loop for looping over objects in JavaScript.
Also look at the map()
, filter()
, reduce()
, etc. functions on an Array in JavaScript. They may do things much faster and better than using while
and for
.
This is a good article if you like to learn more about the asynchronous functions over arrays in JavaScript.
Functional programming has been making quite a splash in the development world these days. And for good reason: Functional techniques can help you write more declarative code that is easier to understand at a glance, refactor, and test.
One of the cornerstones of functional programming is its special use of lists and list operations. And those things are exactly what the sound like they are: arrays of things, and the stuff you do to them. But the functional mindset treats them a bit differently than you might expect.
This article will take a close look at what I like to call the "big three" list operations: map, filter, and reduce. Wrapping your head around these three functions is an important step towards being able to write clean functional code, and opens the doors to the vastly powerful techniques of functional and reactive programming.
It also means you'll never have to write a for loop again.
Read more>> here:
dataframe.limit(1).count > 0
This also triggers a job but since we are selecting single record, even in case of billion scale records the time consumption could be much lower.
First, convert the timespan to a string, then to DateTime, then back to a string:
Convert.ToDateTime(timespan.SelectedTime.ToString()).ToShortTimeString();
Just look in to your header files there will be:
import somefile.R;
Just remove that line and that's it.
yourTextField.tintColor = [UIColor whiteColor];
It works if you set it in code, 'cos somehow color trigger doesn't do it in the Interface Builder (Xcode 6.1.1). It suited well without a need to change any appearance proxy.
You can use RegEdit to export the following two keys:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
HKEY_CURRENT_USER\Environment
The first set are system/global environment variables; the second set are user-level variables. Edit as needed and then import the .reg files on the new machine.
While the suggested solution works fine, there is another way to return a byte array from the controller, with response stream properly formatted :
Unfortunately, WebApi does not include any formatter for "application/octet-stream". There is an implementation here on GitHub: BinaryMediaTypeFormatter (there are minor adaptations to make it work for webapi 2, method signatures changed).
You can add this formatter into your global config :
HttpConfiguration config;
// ...
config.Formatters.Add(new BinaryMediaTypeFormatter(false));
WebApi should now use BinaryMediaTypeFormatter
if the request specifies the correct Accept header.
I prefer this solution because an action controller returning byte[] is more comfortable to test. Though, the other solution allows you more control if you want to return another content-type than "application/octet-stream" (for example "image/gif").
Create an another <tr>
just below and add some space or height to content of <td>
Checkout the fiddle for example
NSDate
is a specific point in time without a time zone. Think of it as the number of seconds that have passed since a reference date. How many seconds have passed in one time zone vs. another since a particular reference date? The answer is the same.
Depending on how you output that date (including looking at the debugger), you may get an answer in a different time zone.
If they ran at the same moment, the values of these are the same. They're both the number of seconds since the reference date, which may be formatted on output to UTC or local time. Within the date variable, they're both UTC.
Objective-C:
NSDate *UTCDate = [NSDate date]
Swift:
let UTCDate = NSDate.date()
To explain this, we can use a NSDateFormatter in a playground:
import UIKit
let date = NSDate.date()
// "Jul 23, 2014, 11:01 AM" <-- looks local without seconds. But:
var formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
let defaultTimeZoneStr = formatter.stringFromDate(date)
// "2014-07-23 11:01:35 -0700" <-- same date, local, but with seconds
formatter.timeZone = NSTimeZone(abbreviation: "UTC")
let utcTimeZoneStr = formatter.stringFromDate(date)
// "2014-07-23 18:01:41 +0000" <-- same date, now in UTC
The date output varies, but the date is constant. This is exactly what you're saying. There's no such thing as a local NSDate.
As for how to get microseconds out, you can use this (put it at the bottom of the same playground):
let seconds = date.timeIntervalSince1970
let microseconds = Int(seconds * 1000) % 1000 // chops off seconds
To compare two dates, you can use date.compare(otherDate)
.
Components can be extended as same as a typescript class inheritance, just that you have to override the selector with a new name. All Input() and Output() Properties from the Parent Component works as normal
Update
@Component is a decorator,
Decorators are applied during the declaration of class not on objects.
Basically, decorators add some metadata to the class object and that cannot be accessed via inheritance.
If you want to achieve the Decorator Inheritance I would Suggest writing a custom decorator. Something like below example.
export function CustomComponent(annotation: any) {
return function (target: Function) {
var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
var parentAnnotations = Reflect.getMetadata('annotations', parentTarget);
var parentParamTypes = Reflect.getMetadata('design:paramtypes', parentTarget);
var parentPropMetadata = Reflect.getMetadata('propMetadata', parentTarget);
var parentParameters = Reflect.getMetadata('parameters', parentTarget);
var parentAnnotation = parentAnnotations[0];
Object.keys(parentAnnotation).forEach(key => {
if (isPresent(parentAnnotation[key])) {
if (!isPresent(annotation[key])) {
annotation[key] = parentAnnotation[key];
}
}
});
// Same for the other metadata
var metadata = new ComponentMetadata(annotation);
Reflect.defineMetadata('annotations', [ metadata ], target);
};
};
Refer: https://medium.com/@ttemplier/angular2-decorators-and-class-inheritance-905921dbd1b7
You had selected the time format wrong
<?php
date_default_timezone_set('GMT');
echo date("Y-m-d,h:m:s");
?>
Done
I just encountered the same issue but here it seemed to come from the fact that I declared the ID-column to be UNsigned and that in combination with an ID-value of '0' (zero) caused the import to fail...
So by changing the value of every ID (PK-column) that I'd declared '0' and every corresponding FK to the new value, my issue was solved.
It's a kludge, but assuming there's a minimum length for SEARCHSTRING
, for example 2 characters, substring
the SEARCHSTRING
parameter at the second character and pass it as two parameters instead: SEARCHSTRING1 ("Nu")
and SEARCHSTRING2 ("ll").
Concatenate
them back together when executing the query to the database.
Also check out :undolist
, which offers multiple paths through the undo history. This is useful if you accidentally type something after undoing too much.
mysqli executable sample code:
<?php
$db = new mysqli("localhost", "user", "password", "YourDatabaseName");
if ($db->connect_errno) die ($db->connect_error);
$table=$db->prepare("SHOW TABLE STATUS FROM YourDatabaseName");
$table->execute();
$sonuc = $table->get_result();
while ($satir=$sonuc->fetch_assoc()){
if ($satir["Name"]== "YourTableName"){
$ai[$satir["Name"]]=$satir["Auto_increment"];
}
}
$LastAutoIncrement=$ai["YourTableName"];
echo $LastAutoIncrement;
?>
$('html').keyup(function(e){
if(e.keyCode == 46) {
alert('Delete key released');
}
});
Source: javascript char codes key codes from www.cambiaresearch.com
Why not making your form a dialogue box:
myForm.ShowDialog();
Try this code
SELECT REPLACE([Column], char(9), '') From [dbo.Table]
char(9) is the TAB character
The same problem was coming for my phone and this resolved the problem:
Go to Application Manager
/ Apps
from Settings.
Select Google Play Services
.
Click Uninstall Updates
button to the right of the Force Stop
button.
Once the updates are uninstalled, you should see Disable
button
which means you are done.
You will see lots of free space available now.
Are there situations in which sys.stdout.write() is preferable to print?
For example I'm working on small function which prints stars in pyramid format upon passing the number as argument, although you can accomplish this using end="" to print in a separate line, I used sys.stdout.write in co-ordination with print to make this work. To elaborate on this stdout.write prints in the same line where as print always prints its contents in a separate line.
import sys
def printstars(count):
if count >= 1:
i = 1
while (i <= count):
x=0
while(x<i):
sys.stdout.write('*')
x = x+1
print('')
i=i+1
printstars(5)
You can’t really — background colours apply to the entirely of element backgrounds. Keeps ’em simple.
You could define a CSS gradient with sharp colour boundaries for the background instead, e.g.
background: -webkit-linear-gradient(left, grey, grey 30%, white 30%, white);
But only a few browsers support that at the moment. See http://jsfiddle.net/UES6U/2/
(See also http://www.webkit.org/blog/1424/css3-gradients/ for an explanation CSS3 gradients, including the sharp colour boundary trick.)