alternatively you can try this:
<?php echo (new DateTime("now", new DateTimeZone('Asia/Singapore')))->format("Y-m-d H:i:s e"); ?>
this will output :
2017-10-25 17:13:20 Asia/Singapore
you can use this inside the value attribute of a text input box if you only want to display a read-only date.
remove the 'e' if you do not wish to show your region/country.
If you just want to disable the rule once, you want to look at Exception's answer.
You can improve this by only disabling the rule for one line only:
... on the current line:
console.log(someThing); /* eslint-disable-line no-console */
... or on the next line:
/* eslint-disable-next-line no-console */
console.log(someThing);
Bootstrap styling for jQuery UI Autocomplete
.ui-autocomplete {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
float: left;
display: none;
min-width: 160px;
padding: 4px 0;
margin: 0 0 10px 25px;
list-style: none;
background-color: #ffffff;
border-color: #ccc;
border-color: rgba(0, 0, 0, 0.2);
border-style: solid;
border-width: 1px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
-webkit-background-clip: padding-box;
-moz-background-clip: padding;
background-clip: padding-box;
*border-right-width: 2px;
*border-bottom-width: 2px;
}
.ui-menu-item > a.ui-corner-all {
display: block;
padding: 3px 15px;
clear: both;
font-weight: normal;
line-height: 18px;
color: #555555;
white-space: nowrap;
text-decoration: none;
}
.ui-state-hover, .ui-state-active {
color: #ffffff;
text-decoration: none;
background-color: #0088cc;
border-radius: 0px;
-webkit-border-radius: 0px;
-moz-border-radius: 0px;
background-image: none;
}
I've seen many variants of this problem. One of the main differences (that determines the difficulty) is whether there is some centralized attempt to have a "smart and efficient system" that would have load balancing (e.g., send more idle elevators to lobby in morning). If that is the case, the design will include a whole subsystem with really fun design.
A full design is obviously too much to present here and there are many altenatives. The breadth is also not clear. In an interview, they'll try to figure out how you would think. However, these are some of the things you would need:
Representation of the central controller (assuming there is one).
Representations of elevators
Representations of the interface units of the elevator (these may be different from elevator to elevator). Obviously also call buttons on every floor, etc.
Representations of the arrows or indicators on each floor (almost a "view" of the elevator model).
Representation of a human and cargo (may be important for factoring in maximal loads)
Representation of the building (in some cases, as certain floors may be blocked at times, etc.)
Old thread, I know, but for future reference, the --proxy option is now passed with an "="
Example:
$ sudo pip install --proxy=http://yourproxy:yourport package_name
<?php $date= date("Y-m-d");
$time=date("H:m");
$datetime=$date."T".$time;
mysql_query(INSERT INTO table (`dateposted`) VALUES ($datetime));
?>
<form action="form.php" method="get">
<input type="datetime-local" name="date" value="<?php echo $datetime; ?>">
<input type="submit" name="submit" value="submit">
Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal (i.e. the first is greater or smaller than the second) then that's the result of the comparison, else the second item is considered, then the third and so on.
See Common Sequence Operations:
Sequences of the same type also support comparisons. In particular, tuples and lists are compared lexicographically by comparing corresponding elements. This means that to compare equal, every element must compare equal and the two sequences must be of the same type and have the same length.
Also Value Comparisons for further details:
Lexicographical comparison between built-in collections works as follows:
- For two collections to compare equal, they must be of the same type, have the same length, and each pair of corresponding elements must compare equal (for example,
[1,2] == (1,2)
is false because the type is not the same).- Collections that support order comparison are ordered the same as their first unequal elements (for example,
[1,2,x] <= [1,2,y]
has the same value asx <= y
). If a corresponding element does not exist, the shorter collection is ordered first (for example,[1,2] < [1,2,3]
is true).
If not equal, the sequences are ordered the same as their first differing elements. For example, cmp([1,2,x], [1,2,y]) returns the same as cmp(x,y). If the corresponding element does not exist, the shorter sequence is considered smaller (for example, [1,2] < [1,2,3] returns True).
Note 1: <
and >
do not mean "smaller than" and "greater than" but "is before" and "is after": so (0, 1) "is before" (1, 0).
Note 2: tuples must not be considered as vectors in a n-dimensional space, compared according to their length.
Note 3: referring to question https://stackoverflow.com/questions/36911617/python-2-tuple-comparison: do not think that a tuple is "greater" than another only if any element of the first is greater than the corresponding one in the second.
You can use the response.text
to write to a file:
import requests
files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("resp_text.txt", "w")
file.write(response.text)
file.close()
file = open("resp_content.txt", "w")
file.write(response.text)
file.close()
$string_val = 'a.b';
$parts = explode('.', $string_val);
print_r($parts);
In unix (mac os X included) terminal you can do
which python
and it will tell you.
Found a good explanation with solutions: https://vcfvct.wordpress.com/2016/12/15/spring-nested-transactional-rollback-only/
1) remove the @Transacional from the nested method if it does not really require transaction control. So even it has exception, it just bubbles up and does not affect transactional stuff.
OR:
2) if nested method does need transaction control, make it as REQUIRE_NEW for the propagation policy that way even if throws exception and marked as rollback only, the caller will not be affected.
new Date().toString();
http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/
Dateformatter can make it to any string you want
A bit surprised to see None of the above answers considers it can be multiple times faster using a thread pool. Here, parallel
uses a fork-join thread pool and automatically break the stream in multiple parts and run them parallel and then merge. If you just remember the following line of code you can use it many places.
So the award for the fastest short and sweet code goes to -
int[] nums = {1,2,3};
int sum = Arrays.stream(nums).parallel().reduce(0, (a,b)-> a+b);
Lets say you want to do sum of squares
, then Arrays.stream(nums).parallel().map(x->x*x).reduce(0, (a,b)-> a+b). Idea is you can still perform reduce , without map .
Possible solution
I had to use Debug.print
instead of Print
, which works in the Immediate window.
Sub SendEmail()
'Dim objHTTP As New MSXML2.XMLHTTP
'Set objHTTP = New MSXML2.XMLHTTP60
'Dim objHTTP As New MSXML2.XMLHTTP60
Dim objHTTP As New WinHttp.WinHttpRequest
'Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
'Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
URL = "http://localhost:8888/rest/mail/send"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "Content-Type", "application/json"
objHTTP.send ("{""key"":null,""from"":""[email protected]"",""to"":null,""cc"":null,""bcc"":null,""date"":null,""subject"":""My Subject"",""body"":null,""attachments"":null}")
Debug.Print objHTTP.Status
Debug.Print objHTTP.ResponseText
End Sub
Make sure to target x86 on your project in Visual Studio. This should fix your trouble.
While all the suggestions above are working, sometimes I need to have an empty selection (showing placeholder text) when initially enter my screen. So, to prevent select box from adding this empty selection at the beginning (or sometimes at the end) of my list I am using this trick:
<div ng-app="MyApp1">
<div ng-controller="MyController">
<input type="text" ng-model="feed.name" placeholder="Name" />
<select ng-model="feed.config" ng-options="template.value as template.name for template in feed.configs" placeholder="Config">
<option value="" selected hidden />
</select>
</div>
</div>
Now you have defined this empty option, so select box is happy, but you keep it hidden.
Using the Windows Command Prompt you can increase the buffer size of the window as much you want to see the number of columns. This depends on the no of columns in the table.
You can access this list everytime you want (even if you don't have Internet access) through:
rails generate model -h
Problem is your Xcode version is not set on Command Line Tools, to solve this problem open Xcode>Menu>preferences> location> here for Command Line tools select your Xcode version, that's it.
Even i have enable VT-X tech and disabled secure boot. My Android Studio failed to load emulator saying dev/kvm not found
.
After doing some research on this. Finally i solved it out.
This issue came after updating HAXM. I found some useful answers. which tell this issue is in HAXM 7.2.0. See this issue on github
Steps to solve:
Now everything should work fine as before.
This is part of UIDevice as of iOS 3.2, e.g.:
[UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad
I had the same issue, the easiest way i found to insert the current date into a prepared statement is this one:
preparedStatement.setDate(1, new java.sql.Date(new java.util.Date().getTime()));
var config = {
'.chosen-select' : {},
'.chosen-select-deselect' : {allow_single_deselect:true},
'.chosen-select-no-single' : {disable_search_threshold:10},
'.chosen-select-no-results': {no_results_text:'Oops, nothing found!'},
'.chosen-select-width' : {width:"95%"}
}
for (var selector in config) {
$(selector).chosen(config[selector]);
}
Use above config and apply class='chosen-select-deselect'
for manually deselect and set the value empty
or if you want deselect option in all combo then apply config like below
var config = {
'.chosen-select' : {allow_single_deselect:true},//Remove if you do not need X button in combo
'.chosen-select-deselect' : {allow_single_deselect:true},
'.chosen-select-no-single' : {disable_search_threshold:10},
'.chosen-select-no-results': {no_results_text:'Oops, nothing found!'},
'.chosen-select-width' : {width:"95%"}
}
for (var selector in config) {
$(selector).chosen(config[selector]);
}
You can't do it easily with cut if the data has for example multiple spaces. I have found it useful to normalize input for easier processing. One trick is to use sed for normalization as below.
echo -e "foor\t \t bar" | sed 's:\s\+:\t:g' | cut -f2 #bar
As far as I know, a forced update like this is not directly possible. You might be able to reduce the DNS downtime by reducing the TTL (Time-To-Live) value of the entries before changing them, if your name server service provider allows that.
Here's a guide for less painful DNS changes.
A fair warning, though - not all name servers between your client and the authoritative (origin) name server will enforce your TTL, they might have their own caching time.
I face this problem but resolution is very simple. I am writing the 1 MB file in 1024 Byte Buffer causing this issue. To Understand refer code before and After Fix.
Code with Excepion
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
while (fis.read(buffer) > 0) {
dos.write(buffer);
}
After Fixes:
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[102400];
while (fis.read(buffer) > 0) {
dos.write(buffer);
}
You have to create a separate volume for mysql data.
So it will look like this:
volumes_from:
- data
volumes:
- ./mysql-data:/var/lib/mysql
And no, /var/lib/mysql
is a path inside your mysql container and has nothing to do with a path on your host machine. Your host machine may even have no mysql at all. So the goal is to persist an internal folder from a mysql container.
import swineflu
x = swineflu.fibo() # create an object `x` of class `fibo`, an instance of the class
x.f() # call the method `f()`, bound to `x`.
Here is a good tutorial to get started with classes in Python.
You may want to use:
SELECT Name, 'Unpaid' AS Status FROM table;
The SELECT
clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:
SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ]
<select_list>
Where the expression
can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.
I had a similarly strange problem with a file from the program e-prime (edat -> SPSS conversion), but then I discovered that there are many additional encodings you can use. this did the trick for me:
tbl <- read.delim("dir/file.txt", fileEncoding="UCS-2LE")
Starting with Google Play 4.9, the app info display has been changed and the promo graphic is displayed at the top.
The promo graphic will be required soon.
The promo text has turned into a short description and is now shown on the main info page, before the user presses it to view the full description.
Based on answers of neeraj t and Everton Fernandes Rosario I wrote in Kotlin, where password
is an id of an EditText in your layout.
// Show passwords' symbols.
private fun showPassword() {
password.run {
val cursorPosition = selectionStart
transformationMethod = HideReturnsTransformationMethod.getInstance()
setSelection(cursorPosition)
}
}
// Show asterisks.
private fun hidePassword() {
password.run {
val cursorPosition = selectionStart
transformationMethod = PasswordTransformationMethod.getInstance()
setSelection(cursorPosition)
}
}
Warning: This solution is deprecated since Angular 5.5, please refer to Trent's answer below
=====================
Yes, you need to import the operator:
import 'rxjs/add/operator/catch';
Or import Observable
this way:
import {Observable} from 'rxjs/Rx';
But in this case, you import all operators.
See this question for more details:
ghostdog74's example provided the core of what I needed, since I've never written any vbs before and needed to do that. It's not perfect, but I fleshed out the example into a full script in case anyone finds it useful.
'ReplaceText.vbs
Option Explicit
Const ForAppending = 8
Const TristateFalse = 0 ' the value for ASCII
Const Overwrite = True
Const WindowsFolder = 0
Const SystemFolder = 1
Const TemporaryFolder = 2
Dim FileSystem
Dim Filename, OldText, NewText
Dim OriginalFile, TempFile, Line
Dim TempFilename
If WScript.Arguments.Count = 3 Then
Filename = WScript.Arguments.Item(0)
OldText = WScript.Arguments.Item(1)
NewText = WScript.Arguments.Item(2)
Else
Wscript.Echo "Usage: ReplaceText.vbs <Filename> <OldText> <NewText>"
Wscript.Quit
End If
Set FileSystem = CreateObject("Scripting.FileSystemObject")
Dim tempFolder: tempFolder = FileSystem.GetSpecialFolder(TemporaryFolder)
TempFilename = FileSystem.GetTempName
If FileSystem.FileExists(TempFilename) Then
FileSystem.DeleteFile TempFilename
End If
Set TempFile = FileSystem.CreateTextFile(TempFilename, Overwrite, TristateFalse)
Set OriginalFile = FileSystem.OpenTextFile(Filename)
Do Until OriginalFile.AtEndOfStream
Line = OriginalFile.ReadLine
If InStr(Line, OldText) > 0 Then
Line = Replace(Line, OldText, NewText)
End If
TempFile.WriteLine(Line)
Loop
OriginalFile.Close
TempFile.Close
FileSystem.DeleteFile Filename
FileSystem.MoveFile TempFilename, Filename
Wscript.Quit
The following should suffice:
[^ ]
If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):
[^\s]
or
\S # Note this is a CAPITAL 'S'!
Jupyter under the WinPython environment has a batch file in the scripts
folder called:
make_working_directory_be_not_winpython.bat
You need to edit the following line in it:
echo WINPYWORKDIR = %%HOMEDRIVE%%%%HOMEPATH%%\Documents\WinPython%%WINPYVER%%\Notebooks>>"%winpython_ini%"
replacing the Documents\WinPython%%WINPYVER%%\Notebooks
part with your folder address.
Notice that the %%HOMEDRIVE%%%%HOMEPATH%%\
part will identify the root and user folders (i.e. C:\Users\your_name\
) which will allow you to point different WinPython installations on separate computers to the same cloud storage folder (e.g. OneDrive), accessing and working with the same files from different machines. I find that very useful.
#include<stdio.h>
#include<string.h>
#define filename "somefile.txt"
int main()
{
FILE *fp;
int count[26] = {0}, i, c;
char ch;
char alpha[27] = "abcdefghijklmnopqrstuwxyz";
fp = fopen(filename,"r");
if(fp == NULL)
printf("file not found\n");
while( (ch = fgetc(fp)) != EOF) {
c = 0;
while(alpha[c] != '\0') {
if(alpha[c] == ch) {
count[c]++;
}
c++;
}
}
for(i = 0; i<26;i++) {
printf("character %c occured %d number of times\n",alpha[i], count[i]);
}
return 0;
}
it can be done by using this command: tcptraceroute -p destination port destination IP
. like: tcptraceroute -p 9100 10.0.0.50
but don't forget to install tcptraceroute package on your system. tcpdump and nc by default installed on the system. regards
The Angular microsyntax lets you configure a directive in a compact, friendly string. The microsyntax parser translates that string into attributes on the <ng-template>
. The let keyword declares a template input variable that you reference within the template.
UrlConnection is an awkward API to work with. HttpClient is by far the better API and it'll spare you from loosing time searching how to achieve certain things like this stackoverflow question illustrates perfectly. I write this after having used the jdk HttpUrlConnection in several REST clients. Furthermore when it comes to scalability features (like threadpools, connection pools etc.) HttpClient is superior
TableA LEFT OUTER JOIN TableB
is equivalent to TableB RIGHT OUTER JOIN Table A
.
In Oracle, (+)
denotes the "optional" table in the JOIN. So in your first query, it's a P LEFT OUTER JOIN S
. In your second query, it's S RIGHT OUTER JOIN P
. They're functionally equivalent.
In the terminology, RIGHT or LEFT specify which side of the join always has a record, and the other side might be null. So in a P LEFT OUTER JOIN S
, P
will always have a record because it's on the LEFT
, but S
could be null.
See this example from java2s.com for additional explanation.
To clarify, I guess I'm saying that terminology doesn't matter, as it's only there to help visualize. What matters is that you understand the concept of how it works.
I've seen some confusion about what matters in determining RIGHT vs LEFT in implicit join syntax.
LEFT OUTER JOIN
SELECT *
FROM A, B
WHERE A.column = B.column(+)
RIGHT OUTER JOIN
SELECT *
FROM A, B
WHERE B.column(+) = A.column
All I did is swap sides of the terms in the WHERE clause, but they're still functionally equivalent. (See higher up in my answer for more info about that.) The placement of the (+)
determines RIGHT or LEFT. (Specifically, if the (+)
is on the right, it's a LEFT JOIN. If (+)
is on the left, it's a RIGHT JOIN.)
The two styles of JOIN are implicit JOINs and explicit JOINs. They are different styles of writing JOINs, but they are functionally equivalent.
See this SO question.
Implicit JOINs simply list all tables together. The join conditions are specified in a WHERE clause.
Implicit JOIN
SELECT *
FROM A, B
WHERE A.column = B.column(+)
Explicit JOINs associate join conditions with a specific table's inclusion instead of in a WHERE clause.
Explicit JOIN
SELECT *
FROM A
LEFT OUTER JOIN B ON A.column = B.column
These Implicit JOINs can be more difficult to read and comprehend, and they also have a few limitations since the join conditions are mixed in other WHERE conditions. As such, implicit JOINs are generally recommended against in favor of explicit syntax.
I got this error when I created an 'Empty' console application in Visual Studio 2015. I re-created the application, leaving the 'Empty' box unchecked, it added all of the necessary libraries.
The issue is how you're attempting to get the value. Things like...
if ( document.frm_new_user_request.u_isid.value == '' )
won't work. You need to find the element you want to get the value of first. It's not quite like a server side language where you can type in an object's reference name and a period to get or assign values.
document.getElementById('[id goes here]').value;
will work. Note: JavaScript is case-sensitive
I would recommend using:
var variablename = document.getElementById('[id goes here]');
or
var variablename = document.getElementById('[id goes here]').value;
Improving on @deepakssn answer. There is a possibility that you want the data to load a bit before we actually scroll to the bottom.
var scrollLoad = true;
$(window).scroll(function(){
if (scrollLoad && ($(document).height() - $(window).height())-$(window).scrollTop()<=800){
// fetch data when we are 800px above the document end
scrollLoad = false;
}
});
[var scrollLoad] is used to block the call until one new data is appended.
Hope this helps.
You can use simple date format in Java using the code below
SimpleDateFormat simpledatafo = new SimpleDateFormat("dd/MM/yyyy");
Date newDate = new Date();
String expectedDate= simpledatafo.format(newDate);
You will have to override the equals function (along with others) to use this with custom classes.
The equals method compares the objects.
The ==
binary operator compares memory addresses.
I think the given answers miss the point of the original question, which is how much space needs to be allocated to fit the base64 encoding for a given binary string of length n bytes.
The answer is (floor(n / 3) + 1) * 4 + 1
This includes padding and a terminating null character. You may not need the floor call if you are doing integer arithmetic.
Including padding, a base64 string requires four bytes for every three-byte chunk of the original string, including any partial chunks. One or two bytes extra at the end of the string will still get converted to four bytes in the base64 string when padding is added. Unless you have a very specific use, it is best to add the padding, usually an equals character. I added an extra byte for a null character in C, because ASCII strings without this are a little dangerous and you'd need to carry the string length separately.
Using Google Collections:
class Person {
private int age;
public static Function<Person, Integer> GET_AGE =
new Function<Person, Integer> {
public Integer apply(Person p) { return p.age; }
};
}
public static void main(String[] args) {
ArrayList<Person> people;
// Populate the list...
Collections.sort(people, Ordering.natural().onResultOf(Person.GET_AGE).reverse());
}
I've used py2exe in the past and have been very happy with it. I didn't particularly enjoy using cx-freeze as much, though
to search every column of every table for a particular value
This does not define how to match exactly.
Nor does it define what to return exactly.
Assuming:
regclass
) and the tuple ID (ctid
), because that's simplest.Here is a dead simple, fast and slightly dirty way:
CREATE OR REPLACE FUNCTION search_whole_db(_like_pattern text)
RETURNS TABLE(_tbl regclass, _ctid tid) AS
$func$
BEGIN
FOR _tbl IN
SELECT c.oid::regclass
FROM pg_class c
JOIN pg_namespace n ON n.oid = relnamespace
WHERE c.relkind = 'r' -- only tables
AND n.nspname !~ '^(pg_|information_schema)' -- exclude system schemas
ORDER BY n.nspname, c.relname
LOOP
RETURN QUERY EXECUTE format(
'SELECT $1, ctid FROM %s t WHERE t::text ~~ %L'
, _tbl, '%' || _like_pattern || '%')
USING _tbl;
END LOOP;
END
$func$ LANGUAGE plpgsql;
Call:
SELECT * FROM search_whole_db('mypattern');
Provide the search pattern without enclosing %
.
Why slightly dirty?
If separators and decorators for the row in text
representation can be part of the search pattern, there can be false positives:
,
by default()
"
\
may be added as escape charAnd the text representation of some columns may depend on local settings - but that ambiguity is inherent to the question, not to my solution.
Each qualifying row is returned once only, even when it matches multiple times (as opposed to other answers here).
This searches the whole DB except for system catalogs. Will typically take a long time to finish. You might want to restrict to certain schemas / tables (or even columns) like demonstrated in other answers. Or add notices and a progress indicator, also demonstrated in another answer.
The regclass
object identifier type is represented as table name, schema-qualified where necessary to disambiguate according to the current search_path
:
What is the ctid
?
You might want to escape characters with special meaning in the search pattern. See:
Goto:
project>Properties>Android> select: google APIs Android 4.0.3
Click Icon:
Android Virtual Device Manager>Edit> Slect box in Tabget>Google APIs APIsLevel15
and select Built-in: is WQVGA400 > Edit AVD > Start
TLDR;
use location.href
or better use window.location.href
;
However if you read this you will gain undeniable proof.
The truth is it's fine to use but why do things that are questionable. You should take the higher road and just do it the way that it probably should be done.
location = "#/mypath/otherside"
var sections = location.split('/')
This code is perfectly correct syntax-wise, logic wise, type-wise you know the only thing wrong with it?
it has location
instead of location.href
what about this
var mystring = location = "#/some/spa/route"
what is the value of mystring
? does anyone really know without doing some test. No one knows what exactly will happen here. Hell I just wrote this and I don't even know what it does. location
is an object but I am assigning a string will it pass the string or pass the location object. Lets say there is some answer to how this should be implemented. Can you guarantee all browsers will do the same thing?
This i can pretty much guess all browsers will handle the same.
var mystring = location.href = "#/some/spa/route"
What about if you place this into typescript will it break because the type compiler will say this is suppose to be an object?
This conversation is so much deeper than just the location
object however. What this conversion is about what kind of programmer you want to be?
If you take this short-cut, yea it might be okay today, ye it might be okay tomorrow, hell it might be okay forever, but you sir are now a bad programmer. It won't be okay for you and it will fail you.
There will be more objects. There will be new syntax.
You might define a getter that takes only a string but returns an object and the worst part is you will think you are doing something correct, you might think you are brilliant for this clever method because people here have shamefully led you astray.
var Person.name = {first:"John":last:"Doe"}
console.log(Person.name) // "John Doe"
With getters and setters this code would actually work, but just because it can be done doesn't mean it's 'WISE' to do so.
Most people who are programming love to program and love to get better. Over the last few years I have gotten quite good and learn a lot. The most important thing I know now especially when you write Libraries is consistency and predictability.
Do the things that you can consistently do.
+"2"
<-- this right here parses the string to a number. should you use it?
or should you use parseInt("2")
?
what about var num =+"2"
?
From what you have learn, from the minds of stackoverflow i am not too hopefully.
If you start following these 2 words consistent and predictable. You will know the right answer to a ton of questions on stackoverflow.
Let me show you how this pays off.
Normally I place ;
on every line of javascript i write. I know it's more expressive. I know it's more clear. I have followed my rules. One day i decided not to. Why? Because so many people are telling me that it is not needed anymore and JavaScript can do without it. So what i decided to do this. Now because I have become sure of my self as a programmer (as you should enjoy the fruit of mastering a language) i wrote something very simple and i didn't check it. I erased one comma and I didn't think I needed to re-test for such a simple thing as removing one comma.
I wrote something similar to this in es6 and babel
var a = "hello world"
(async function(){
//do work
})()
This code fail and took forever to figure out. For some reason what it saw was
var a = "hello world"(async function(){})()
hidden deep within the source code it was telling me "hello world" is not a function.
For more fun node doesn't show the source maps of transpiled code.
Wasted so much stupid time. I was presenting to someone as well about how ES6 is brilliant and then I had to start debugging and demonstrate how headache free and better ES6 is. Not convincing is it.
I hope this answered your question. This being an old question it's more for the future generation, people who are still learning.
Question when people say it doesn't matter either way works. Chances are a wiser more experienced person will tell you other wise.
what if someone overwrite the location object. They will do a shim for older browsers. It will get some new feature that needs to be shimmed and your 3 year old code will fail.
My last note to ponder upon.
Writing clean, clear purposeful code does something for your code that can't be answer with right or wrong. What it does is it make your code an enabler.
You can use more things plugins, Libraries with out fear of interruption between the codes.
for the record. use
window.location.href
If you want to clear the data but keep the headers:
$('#myTableId tbody').empty();
The table must be formatted in this manner:
<table id="myTableId">
<thead>
<tr>
<th>header1</th><th>header2</th>
</tr>
</thead>
<tbody>
<tr>
<td>data1</td><td>data2</td>
</tr>
</tbody>
</table>
You can rather use a List, so you can check the existence.
List<int> l = new List<int>();
l.Add(45);
...
...
if (l.Count == 25) {
doStuff();
}
int num = 45;
if (l.Contains(num)) {
doMoreStuff();
}
Just click the left mouse button for 2 or 3 seconds, paste button will be appear. Click the paste button and the test will be copied smoothly.
Look at the WSGI reference implementation. You already have it in your Python libraries. It's quite simple.
$("#button_id").click(function(){ $("#detailInfo").html("WHAT YOU WANT") })
You are comparing a jQuery object (jQuery('input:first')
) to strings (the elements of the array).
Change the code in order to compare the input's value (wich is a string) to the array elements:
if (jQuery.inArray(jQuery("input:first").val(), ar) != -1)
The inArray
method returns -1
if the element wasn't found in the array, so as your bonus answer to how to determine if an element is not in an array, use this :
if(jQuery.inArray(el,arr) == -1){
// the element is not in the array
};
I have a very simple solution which worked for me instantly. Takes some 10 sec to do:
1) Go to Window -> Devices & Simulators
and untick Show as run destination
2) Unplug the cable and plug it back in.
3) Run the project.
This should be solving your problem!
You can use underscore.js "debounce"
$('input#username').keypress( _.debounce( function(){<your ajax call here>}, 500 ) );
This means that your function call will execute after 500ms of pressing a key. But if you press another key (another keypress event is fired) before the 500ms, the previous function execution will be ignored (debounced) and the new one will execute after a fresh 500ms timer.
For extra info, using _.debounce(func,timer,true) would mean that the first function will execute and all other keypress events withing subsequent 500ms timers would be ignored.
To accomplish what you want, use an array Like Rabbot said (though this can become a pain to document/maintain if used excessively). Or just use the traditional optional args.
//My function with tons of optional params
function my_func($req_a, $req_b, $opt_a = NULL, $opt_b = NULL, $opt_c = NULL)
{
//Do stuff
}
my_func('Hi', 'World', null, null, 'Red');
However, I usually find that when I start writing a function/method with that many arguments - more often than not it is a code smell, and can be re-factored/abstracted into something much cleaner.
//Specialization of my_func - assuming my_func itself cannot be refactored
function my_color_func($reg_a, $reg_b, $opt = 'Red')
{
return my_func($reg_a, $reg_b, null, null, $opt);
}
my_color_func('Hi', 'World');
my_color_func('Hello', 'Universe', 'Green');
I had the same problem. In my case cordova platform update ios
helped. The reason was in outdated version.
I'm not an attorney, but clicking the like button without the express permission of a facebook user might be a violation of facebook policy. You should have your corporate attorney check out the facebook policy.
You should encode the url to a page with a like button, so when scanned by the phone, it opens up a browser window to the like page, where now the user has the option to like it or not.
I found same problem, we can resolve in three steps:-
Step 1
sudo chown -R $(whoami) $(brew --prefix)/*
Step 2
brew doctor
Step 3
brew prune
If you still get any linking problem, lets say for mysql
, just write
brew link mysql
This will work.
jQuery code uses it's own data()
method as such id.
var id = $.data(object);
At the backstage method data
creates a very special field in object
called "jQuery" + now()
put there next id of a stream of unique ids like
id = elem[ expando ] = ++uuid;
I'd suggest you use the same method as John Resig obviously knows all there is about JavaScript and his method is based on all that knowledge.
I got the same error with a class like the following StockPickBean
. Called from this code:
List<StockPickBean> beansListcatMap.getValue();
beansList.sort(StockPickBean.Comparators.VALUE);
public class StockPickBean implements Comparable<StockPickBean> {
private double value;
public double getValue() { return value; }
public void setValue(double value) { this.value = value; }
@Override
public int compareTo(StockPickBean view) {
return Comparators.VALUE.compare(this,view); //return
Comparators.SYMBOL.compare(this,view);
}
public static class Comparators {
public static Comparator<StockPickBean> VALUE = (val1, val2) ->
(int)
(val1.value - val2.value);
}
}
After getting the same error:
java.lang.IllegalArgumentException: Comparison method violates its general contract!
I changed this line:
public static Comparator<StockPickBean> VALUE = (val1, val2) -> (int)
(val1.value - val2.value);
to:
public static Comparator<StockPickBean> VALUE = (StockPickBean spb1,
StockPickBean spb2) -> Double.compare(spb2.value,spb1.value);
That fixes the error.
I appreciate all the answers above. However, like some answers and comments pointed out, the axes_grid1
module cannot address GeoAxes, whereas adjusting fraction
, pad
, shrink
, and other similar parameters cannot necessarily give the very precise order, which really bothers me. I believe that giving the colorbar
its own axes
might be a better solution to address all the issues that have been mentioned.
import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure()
ax = plt.axes()
im = ax.imshow(np.arange(100).reshape((10,10)))
# Create an axes for colorbar. The position of the axes is calculated based on the position of ax.
# You can change 0.01 to adjust the distance between the main image and the colorbar.
# You can change 0.02 to adjust the width of the colorbar.
# This practice is universal for both subplots and GeoAxes.
cax = fig.add_axes([ax.get_position().x1+0.01,ax.get_position().y0,0.02,ax.get_position().height])
plt.colorbar(im, cax=cax) # Similar to fig.colorbar(im, cax = cax)
Later on, I find matplotlib.pyplot.colorbar
official documentation also gives ax
option, which are existing axes that will provide room for the colorbar. Therefore, it is useful for multiple subplots, see following.
fig, ax = plt.subplots(2,1,figsize=(12,8)) # Caution, figsize will also influence positions.
im1 = ax[0].imshow(np.arange(100).reshape((10,10)), vmin = -100, vmax =100)
im2 = ax[1].imshow(np.arange(-100,0).reshape((10,10)), vmin = -100, vmax =100)
fig.colorbar(im1, ax=ax)
Again, you can also achieve similar effects by specifying cax, a more accurate way from my perspective.
fig, ax = plt.subplots(2,1,figsize=(12,8))
im1 = ax[0].imshow(np.arange(100).reshape((10,10)), vmin = -100, vmax =100)
im2 = ax[1].imshow(np.arange(-100,0).reshape((10,10)), vmin = -100, vmax =100)
cax = fig.add_axes([ax[1].get_position().x1-0.25,ax[1].get_position().y0,0.02,ax[0].get_position().y1-ax[1].get_position().y0])
fig.colorbar(im1, cax=cax)
Examine error log (start eventvwr.msc). MySQL typically writes something to the Application log.
In very rare cases it does not write anything (I'm only aware of one particular bug http://bugs.mysql.com/bug.php?id=56821, where services did not work at all). There is also error log file, normally named .err in the data directory that has the same info as written to windows error log.
Use copy()
instead, which is willing to overwrite destination files. If you then want the first tree to go away, just rmtree()
it separately once you are done iterating over it.
http://docs.python.org/library/shutil.html#shutil.copy
http://docs.python.org/library/shutil.html#shutil.rmtree
Update:
Do an os.walk()
over the source tree. For each directory, check if it exists on the destination side, and os.makedirs()
it if it is missing. For each file, simply shutil.copy()
and the file will be created or overwritten, whichever is appropriate.
profile name is not valid [SQLSTATE 42000] (Error 14607)
This happened to me after I copied job script from old SQL server to new SQL server. In SSMS, under Management, the Database Mail profile name was different in the new SQL Server. All I had to do was update the name in job script.
You should use abstract class to initialize a property. You can't inititalize in Inteface .
This function creates a temporary form, then send data using jQuery :
function postToIframe(data,url,target){
$('body').append('<form action="'+url+'" method="post" target="'+target+'" id="postToIframe"></form>');
$.each(data,function(n,v){
$('#postToIframe').append('<input type="hidden" name="'+n+'" value="'+v+'" />');
});
$('#postToIframe').submit().remove();
}
target is the 'name' attr of the target iFrame, and data is a JS object :
data={last_name:'Smith',first_name:'John'}
You can only use await
in an async
method, and Main
cannot be async
.
You'll have to use your own async
-compatible context, call Wait
on the returned Task
in the Main
method, or just ignore the returned Task
and just block on the call to Read
. Note that Wait
will wrap any exceptions in an AggregateException
.
If you want a good intro, see my async
/await
intro post.
As of now (NOV-2019), graph.api V5.0
graph API says, refer graph api
A link to the person's Timeline. The link will only resolve if the person clicking the link is logged into Facebook and is a friend of the person whose profile is being viewed.
Wrap your OutputStream with a PrintWriter and use the print methods on that class. They take in a String and do the work for you.
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=8080
DB_DATABASE=flap_safety
DB_USERNAME=root
DB_PASSWORD=mysql
the above given is my .env
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', 'mysql'),
// 'port' => env('DB_PORT', '8080'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', 'mysql'),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
the above given is my database.php file. i just commented out port from database.php and it worked for me.
The element hasn't been appended yet, therefore it is equal to null. The Id will never = 0. When you call getElementById(id), it is null since it is not a part of the dom yet unless your static id is already on the DOM. Do a call through the console to see what it returns.
Yes, it can be done as long as both windows are on the same domain. The window.open() function will return a handle to the new window. The child window can access the parent window using the DOM element "opener".
function doSomething(){
if ($(this).hasClass('clickedTag')){
// code here
}
else {
// and here
}
}
$('.tag1').click(doSomething);
$('.tag2').click(doSomething);
// or, simplifying further
$(".tag1, .tag2").click(doSomething);
This will also work:
?$(".tag1, .tag2").click(function(){
alert("clicked");
});?
I prefer a separate function (approach #1) if there is a chance that logic will be reused.
See also How can I select an element with multiple classes? for handling multiple classes on the same item.
To add to Oleg's answer:
I was able to find the DLL at runtime by appending Visual Studio's $(ExecutablePath)
to the PATH environment variable in Configuration Properties->Debugging. This macro is exactly what's defined in the Configuration Properties->VC++ Directories->Executable Directories field*, so if you have that setup to point to any DLLs you need, simply adding this to your PATH makes finding the DLLs at runtime easy!
* I actually don't know if the $(ExecutablePath)
macro uses the project's Executable Directories setting or the global Property Pages' Executable Directories setting. Since I have all of my libraries that I often use configured through the Property Pages, these directories show up as defaults for any new projects I create.
On top of the more direct answers, I'd be remiss if I didn't mention IPython.
Hit Tab to see the available methods, with autocompletion.
And once you've found a method, try:
help(object.method)
to see the pydocs, method signature, etc.
Ahh... REPL.
I think you may need to define the handler function ahead of time, like so:
var myHandler = function(event) {
click++;
if(click == 50) {
this.removeEventListener('click', myHandler);
}
}
canvas.addEventListener('click', myHandler);
This will allow you to remove the handler by name from within itself.
You can use JQuery(jquery.validate.js) to make it work easily.
$.validator.format("My name is {0}, I'm {1} years old",["Bob","23"]);
Or if you want to use just that feature you can define that function and just use it like
function format(source, params) {
$.each(params,function (i, n) {
source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
})
return source;
}
alert(format("{0} is a {1}", ["Michael", "Guy"]));
credit to jquery.validate.js team
I used numpy to generate the array, but list of lists array should work similarly.
import numpy as np
def printArray(args):
print "\t".join(args)
n = 10
Array = np.zeros(shape=(n,n)).astype('int')
for row in Array:
printArray([str(x) for x in row])
If you want to only print certain indices:
import numpy as np
def printArray(args):
print "\t".join(args)
n = 10
Array = np.zeros(shape=(n,n)).astype('int')
i_indices = [1,2,3]
j_indices = [2,3,4]
for i in i_indices:printArray([str(Array[i][j]) for j in j_indices])
You cannot concatenate a string
with an int
. You would need to convert your int
to a string
using the str
function, or use formatting
to format your output.
Change: -
print("Ok. Your balance is now at " + balanceAfterStrength + " skill points.")
to: -
print("Ok. Your balance is now at {} skill points.".format(balanceAfterStrength))
or: -
print("Ok. Your balance is now at " + str(balanceAfterStrength) + " skill points.")
or as per the comment, use ,
to pass different strings to your print
function, rather than concatenating using +
: -
print("Ok. Your balance is now at ", balanceAfterStrength, " skill points.")
I think you really need pandoc, which great software was designed and built just for this task :) Besides pdf, you could convert your md file to e.g. docx or odt among others.
Well, installing an up-to-date version of Pandoc might be challanging on Linux (as you would need the entire haskell-platform
?to build from the sources), but really easy on Windows/Mac with only a few megabytes of download.
If you have the brewed/knitted markdown file you can just call pandoc
in e.g bash or with the system
function within R. A POC demo of that latter is implemented in the ?andoc.convert
function of my little package (which you must be terribly bored of as I try to point your attention there at every opportunity).
Provide the directory on the command line:
svn checkout file:///home/landonwinters/svn/waterproject/trunk public_html
Easy Solution
Got to Start->All Programs-> Microsoft SQL Server 2012-> Configuration Tool -> Click SQL Server Configuration Manager ->Expand SQL Server Network Configuration-> Protocol ->Enable TCP/IP Right box
Double Click on TCP/IP and go to IP Adresses Tap and Put port 1433 under TCP port.
The Request Payload - or to be more precise: payload body of a HTTP Request
- is the data normally send by a POST or PUT Request.
It's the part after the headers and the CRLF
of a HTTP Request.
A request with Content-Type: application/json
may look like this:
POST /some-path HTTP/1.1
Content-Type: application/json
{ "foo" : "bar", "name" : "John" }
If you submit this per AJAX the browser simply shows you what it is submitting as payload body. That’s all it can do because it has no idea where the data is coming from.
If you submit a HTML-Form with method="POST"
and Content-Type: application/x-www-form-urlencoded
or Content-Type: multipart/form-data
your request may look like this:
POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded
foo=bar&name=John
In this case the form-data is the request payload. Here the Browser knows more: it knows that bar is the value of the input-field foo of the submitted form. And that’s what it is showing to you.
So, they differ in the Content-Type
but not in the way data is submitted. In both cases the data is in the message-body. And Chrome distinguishes how the data is presented to you in the Developer Tools.
$('#txtConfirmPassword').keyup(function(){
if($(this).val() != $('#txtNewPassword').val().substr(0,$(this).val().length))
{
alert('confirm password not match');
}
});
To check the class in Swift, use "is" (as explained under "checking Type" in the chapter called Type Casting in the Swift Programming Guide)
if self.window.rootViewController is MyViewController {
//do something if it's an instance of that class
}
my mistake was making the target name "filename.c:" instead of just "filename:"
You can run build
for a specific service by running docker-compose up --build <service name>
where the service name must match how did you call it in your docker-compose file.
Example
Let's assume that your docker-compose file contains many services (.net app - database - let's encrypt... etc) and you want to update only the .net app which named as application
in docker-compose file.
You can then simply run docker-compose up --build application
Extra parameters
In case you want to add extra parameters to your command such as -d
for running in the background, the parameter must be before the service name:
docker-compose up --build -d application
It seems that the struct
datatype is commonly used in SOAP:
var_dump($client->__getTypes());
array(52) {
[0] =>
string(43) "struct Bank {\n string Code;\n string Name;\n}"
}
This is not a native PHP datatype!
It seems that the properties of the struct
type referred to in SOAP can be accessed as a simple PHP stdClass
object:
$some_struct = $client->SomeMethod();
echo 'Name: ' . $some_struct->Name;
In Python 3.6+:
import datetime
timestamp = 1579117901
value = datetime.datetime.fromtimestamp(timestamp)
print(f"{value:%Y-%m-%d %H:%M:%S}")
2020-01-15 19:51:41
type(value)
To save the date to a string then print it, use this:
my_date = f"{value:%Y-%m-%d %H:%M:%S}"
print(my_date)
This is a very old question but I came here due to the same issue, so I am leaving this here to help any others.
I was trying to optimize the query because it was taking over 5 minutes to query the DB due to the amount of data. My query was similar to the accepted answer's query. Pablo's comment pushed me in the right direction and my 5 minute query became 0.016 seconds. So to help any others that are having very long query times try using an uncorrelated subquery.
The example for the OP would be:
SELECT
a.report_id,
a.computer_id,
a.date_entered
FROM reports AS a
JOIN (
SELECT report_id, computer_id, MAX(date_entered) as max_date_entered
FROM reports
GROUP BY report_id, computer_id
) as b
WHERE a.report_id = b.report_id
AND a.computer_id = b.computer_id
AND a.date_entered = b.max_date_entered
Thank you Pablo for the comment. You saved me big time!
If someone is still struggling to make predictions on images, here is the optimized code to load the saved model and make predictions:
# Modify 'test1.jpg' and 'test2.jpg' to the images you want to predict on
from keras.models import load_model
from keras.preprocessing import image
import numpy as np
# dimensions of our images
img_width, img_height = 320, 240
# load the model we saved
model = load_model('model.h5')
model.compile(loss='binary_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
# predicting images
img = image.load_img('test1.jpg', target_size=(img_width, img_height))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])
classes = model.predict_classes(images, batch_size=10)
print classes
# predicting multiple images at once
img = image.load_img('test2.jpg', target_size=(img_width, img_height))
y = image.img_to_array(img)
y = np.expand_dims(y, axis=0)
# pass the list of multiple images np.vstack()
images = np.vstack([x, y])
classes = model.predict_classes(images, batch_size=10)
# print the classes, the images belong to
print classes
print classes[0]
print classes[0][0]
I had some malware that marked all files in a directory as hidden/system/readonly. If anyone else finds themselves in this situation, cd into the directory and run for /f "delims=|" %f in ('forfiles') do attrib -s -h -r %f
.
You can use on another class
public ArrayList<Integer> myNumbers = new Foo().myNumbers();
or
Foo myClass = new Foo();
public ArrayList<Integer> myNumbers = myclass.myNumbers();
You are correct that this is currently not natively supported in Android, although Google has been saying it will be coming ever since Android was officially launched.
While not natively supported, the hardware on every android device released to date do support it. It is just disabled in software, and you would need to enable it in order to use these features.
It is however, fairly easy to do this, but you need to be root, and the specifics may be slightly different between different devices. Your best source for more informationa about this, would be XDA developers: http://forum.xda-developers.com/forumdisplay.php?f=564. Most of the existing solutions are based on replacing wpa_supplicant, and is the method I would recommend if possible on your device. For more details, see http://szym.net/2010/12/adhoc-wifi-in-android/.
Update: Its been a few years now, and whenever I need an ad hoc network connection on my phone I use CyanogenMod. It gives you both programmatic and scripted access to these functions, and the ability to create ad hoc (ibss) networks in the WiFi settings menu.
They're not bad practice, they're just another tool and they add flexibility.
For use as a standard page element... they're good, because they're a simple and reliable way to separate content onto several pages. Especially for user-generated content, it may be useful to "sandbox" internal pages into an iframe
so poor markup doesn't affect the main page. The downside is that if you introduce multiple layers of scrolling (one for the browser, one for the iframe
) your users will get frustrated. Like adzm said, you don't want to use an iframe
for primary navigation, but think about them as a text/markup equivalent to the way a video or another media file would be embedded.
For scripting background events, the choice is generally between a hidden iframe
and XmlHttpRequest
to load content for the current page. The difference there is that an iframe
generates a page load, so you can move back and forward in browser cache with most browsers. Notice that Google, who uses XmlHttpRequest
all over the place, also uses iframe
s in certain cases to allow a user to move back and forward in browser history.
theoretically it could be done by defining a custom build step to the VS project. And you can make a file template to create a new java file, don't know if you could have it throw things in the right package or not, so you may end up writing quite a bit of the stuff a java ide would throw in already. it's not impossible, but from experience (I've used xcode on mac, vs in windows, eclipse, netbeans, code::blocks, and ended up compiling from command line for both java and c++ a lot) it's easier just to learn the new ide.
if you are insistent, i found this: http://improve.dk/compiling-java-in-visual-studio/
i plan on following and trying to modify it to create a general template for java
if possible (meaning if i understand enough of what im doing) im goint to implement a custom wizard for java projects and files.
No need for a StringBuilder
:
string path = @"c:\hereIAm.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Here");
sw.WriteLine("I");
sw.WriteLine("am.");
}
}
But of course you can use the StringBuilder
to create all lines and write them to the file at once.
sw.Write(stringBuilder.ToString());
StreamWriter.Write
Method (String) (.NET Framework 1.1)
Are you looking for a Windows API?
Just use SHGetFolderPath function with CSIDL_INTERNET_CACHE flag or SHGetKnownFolderPath with FOLDERID_InternetCache flag to get the exact location. This way you don't have to worry about the OS. The former function works in Windows XP. The latter one works in Windows Vista+.
Not as bulletproof as the above answer, however still effective:
#!/bin/bash
if [ "$1" = "" ]
then
echo "Usage: $0 <id number to be cleaned up>"
exit
fi
# rm commands go here
$ git clone --bare https://github.com/example
This command will make the new "example
" directory itself the $GIT_DIR (instead of example/.git
). Also the branch heads at the remote are copied directly to corresponding local branch heads, without mapping. When this option is used, neither remote-tracking branches nor the related configuration variables are created.
$ git clone --mirror https://github.com/example
As with a bare clone, a mirrored clone includes all remote branches and tags, but all local references (including remote-tracking branches, notes etc.) will be overwritten each time you fetch, so it will always be the same as the original repository.
In some cases it is tied to how the field is used. In some DB engines the field differences determine how (and if) you search for text in the field. CharFields are typically used for things that are searchable, like if you want to search for "one" in the string "one plus two". Since the strings are shorter they are less time consuming for the engine to search through. TextFields are typically not meant to be searched through (like maybe the body of a blog) but are meant to hold large chunks of text. Now most of this depends on the DB Engine and like in Postgres it does not matter.
Even if it does not matter, if you use ModelForms you get a different type of editing field in the form. The ModelForm will generate an HTML form the size of one line of text for a CharField and multiline for a TextField.
It might be easier with vlookup. Try this:
=IFERROR(VLOOKUP(D2,G:H,2,0),"")
The IFERROR()
is for no matches, so that it throws ""
in such cases.
VLOOKUP
's first parameter is the value to 'look for' in the reference table, which is column G and H.
VLOOKUP
will thus look for D2
in column G and return the value in the column index 2
(column G has column index 1, H will have column index 2), meaning that the value from column H will be returned.
The last parameter is 0
(or equivalently FALSE
) to mean an exact match. That's what you need as opposed to approximate match.
It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.
It is indeed possible to have PHP render partials and whole views, but I would not recommend it.
To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.
I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.
Using PHP to render the view:
/user/account
if($loggedIn)
{
echo "<p>Logged in as ".$user."</p>";
}
else
{
echo "Please log in.";
}
How the same problem can be solved with an API centric approach by outputting JSON like this:
api/auth/
{
authorized:true,
user: {
username: 'Joe',
securityToken: 'secret'
}
}
and in Angular you could do a get, and handle the response client side.
$http.post("http://example.com/api/auth", {})
.success(function(data) {
$scope.isLoggedIn = data.authorized;
});
To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.
This is default database :
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'mydatabase',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => TRUE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
Add another database at the bottom of database.php file
$db['second'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'mysecond',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => TRUE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
In autoload.php config file
$autoload['libraries'] = array('database', 'email', 'session');
The default database is worked fine by autoload the database library but second database load and connect by using constructor in model and controller...
<?php
class Seconddb_model extends CI_Model {
function __construct(){
parent::__construct();
//load our second db and put in $db2
$this->db2 = $this->load->database('second', TRUE);
}
public function getsecondUsers(){
$query = $this->db2->get('members');
return $query->result();
}
}
?>
t=$(mktemp) && export -p > "$t" && set -a && . ./.env && set +a && . "$t" && rm "$t" && unset t
How it works
.env
file. All variables will be exported into current environment.declare -x VAR="val"
that would export each of the variables into environment.Features
.env
can have comments.env
can have empty lines.env
does not require special header or footer like in the other answers (set -a
and set +a
).env
does not require to have export
for every valueThe syntax is wrong. The typedef
should be removed.
Had issues using most of the mentioned methods since textfield had not accepted keyboard input, and the mouse solution seem not complete.
This worked for to simulate a click in the field, selecting the content and replacing it with new.
Actions actionList = new Actions(driver);
actionList.clickAndHold(WebElement).sendKeys(newTextFieldString).
release().build().perform();
TEXT
is used for large pieces of string data. If the length of the field exceeed a certain threshold, the text is stored out of row.
VARCHAR
is always stored in row and has a limit of 8000 characters. If you try to create a VARCHAR(x)
, where x > 8000, you get an error:
Server: Msg 131, Level 15, State 3, Line 1
The size () given to the type ‘varchar’ exceeds the maximum allowed for any data type (8000)
These length limitations do not concern VARCHAR(MAX)
in SQL Server 2005, which may be stored out of row, just like TEXT
.
Note that MAX
is not a kind of constant here, VARCHAR
and VARCHAR(MAX)
are very different types, the latter being very close to TEXT
.
In prior versions of SQL Server you could not access the TEXT
directly, you only could get a TEXTPTR
and use it in READTEXT
and WRITETEXT
functions.
In SQL Server 2005 you can directly access TEXT
columns (though you still need an explicit cast to VARCHAR
to assign a value for them).
TEXT
is good:
VARCHAR
is good:
By selecting here I mean issuing any queries that return the value of the column.
By searching here I mean issuing any queries whose result depends on the value of the TEXT
or VARCHAR
column. This includes using it in any JOIN
or WHERE
condition.
As the TEXT
is stored out of row, the queries not involving the TEXT
column are usually faster.
Some examples of what TEXT
is good for:
Some examples of what VARCHAR
is good for:
As a rule of thumb, if you ever need you text value to exceed 200 characters AND do not use join on this column, use TEXT
.
Otherwise use VARCHAR
.
P.S. The same applies to UNICODE
enabled NTEXT
and NVARCHAR
as well, which you should use for examples above.
P.P.S. The same applies to VARCHAR(MAX)
and NVARCHAR(MAX)
that SQL Server 2005+ uses instead of TEXT
and NTEXT
. You'll need to enable large value types out of row
for them with sp_tableoption
if you want them to be always stored out of row.
As mentioned above and here, TEXT
is going to be deprecated in future releases:
The
text in row
option will be removed in a future version of SQL Server. Avoid using this option in new development work, and plan to modify applications that currently usetext in row
. We recommend that you store large data by using thevarchar(max)
,nvarchar(max)
, orvarbinary(max)
data types. To control in-row and out-of-row behavior of these data types, use thelarge value types out of row
option.
I prefer this method as it doesn't require manually emitting markup. I use this because I'm rendering Razor Pages to strings and sending them out via email, which is an environment where the white-space styling won't always work.
public static IHtmlContent RenderNewlines<TModel>(this IHtmlHelper<TModel> html, string content)
{
if (string.IsNullOrEmpty(content) || html is null)
{
return null;
}
TagBuilder brTag = new TagBuilder("br");
IHtmlContent br = brTag.RenderSelfClosingTag();
HtmlContentBuilder htmlContent = new HtmlContentBuilder();
// JAS: On the off chance a browser is using LF instead of CRLF we strip out CR before splitting on LF.
string lfContent = content.Replace("\r", string.Empty, StringComparison.InvariantCulture);
string[] lines = lfContent.Split('\n', StringSplitOptions.None);
foreach(string line in lines)
{
_ = htmlContent.Append(line);
_ = htmlContent.AppendHtml(br);
}
return htmlContent;
}
If your environment supports ECMAScript 6 Set, one simple and supposedly efficient (see specification link) way:
function intersect(a, b) {
var setA = new Set(a);
var setB = new Set(b);
var intersection = new Set([...setA].filter(x => setB.has(x)));
return Array.from(intersection);
}
Shorter, but less readable (also without creating the additional intersection Set
):
function intersect(a, b) {
var setB = new Set(b);
return [...new Set(a)].filter(x => setB.has(x));
}
Note that when using sets you will only get distinct values, thus new Set([1, 2, 3, 3]).size
evaluates to 3
.
Suppose you need a car as we all know their are several A class manufacturer like MERCEDES, BMW , AUDI etc.
Now in above statement CAR(is a specification) as every car have common features like thing with 4 wheels and can be driven on road is car...so its like JPA. And MERCEDES, BMW , AUDI etc are just using common car feature and adding functionality according to their customer base so they are implementing the car specification like hibernate , iBATIS etc.
So by this common features goes to jpa and hibernate is just an implementation according to their jboss need.
JPA includes some basic properties so in future if you want to change hibernate to any other implementation you can easily switch without much headache and for those basic properties includes JPA annotations which can work for any implementation technology, JPQL queries.
So mainly we implement hibernate with JPA type technology just for in case we want to switch our implementation according to client need plus you will write less code as some common features are involved in JPA. If someone still not clear then you can comment as i m new on stack overflow.
I found mongo-connector useful. It is form Mongo Labs (MongoDB Inc.) and can be used now with Elasticsearch 2.x
Elastic 2.x doc manager: https://github.com/mongodb-labs/elastic2-doc-manager
mongo-connector creates a pipeline from a MongoDB cluster to one or more target systems, such as Solr, Elasticsearch, or another MongoDB cluster. It synchronizes data in MongoDB to the target then tails the MongoDB oplog, keeping up with operations in MongoDB in real-time. It has been tested with Python 2.6, 2.7, and 3.3+. Detailed documentation is available on the wiki.
https://github.com/mongodb-labs/mongo-connector https://github.com/mongodb-labs/mongo-connector/wiki/Usage%20with%20ElasticSearch
To read the result you can read it like a simple php array.
For example, getting the name
can be done like $user['name']
, and so on. The method fetch(PDO::FETCH_ASSOC)
will only return 1 tuple tho. If you want to get all tuples, you can use fetchall(PDO::FETCH_ASSOC)
. You can go through the multidimensional array and get the values just the same.
you can render the page in express more easily
var app = require('express')();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.get('/signup',function(req,res){
res.sendFile(path.join(__dirname,'/signup.html'));
});
so if u request like http://127.0.0.1:8080/signup
that it will render signup.html page under views folder.
1) Your existing web.config: you have declared rewrite map .. but have not created any rules that will use it. RewriteMap on its' own does absolutely nothing.
2) Below is how you can do it (it does not utilise rewrite maps -- rules only, which is fine for small amount of rewrites/redirects):
This rule will do SINGLE EXACT rewrite (internal redirect) /page
to /page.html
. URL in browser will remain unchanged.
<system.webServer>
<rewrite>
<rules>
<rule name="SpecificRewrite" stopProcessing="true">
<match url="^page$" />
<action type="Rewrite" url="/page.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
This rule #2 will do the same as above, but will do 301 redirect (Permanent Redirect) where URL will change in browser.
<system.webServer>
<rewrite>
<rules>
<rule name="SpecificRedirect" stopProcessing="true">
<match url="^page$" />
<action type="Redirect" url="/page.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
Rule #3 will attempt to execute such rewrite for ANY URL if there are such file with .html extension (i.e. for /page
it will check if /page.html
exists, and if it does then rewrite occurs):
<system.webServer>
<rewrite>
<rules>
<rule name="DynamicRewrite" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{REQUEST_FILENAME}\.html" matchType="IsFile" />
</conditions>
<action type="Rewrite" url="/{R:1}.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
You can think of a MySQL "database" as a schema/user in Oracle. If you have the privileges, you can query the DBA_USERS
view to see the list of schemas:
SELECT * FROM DBA_USERS;
I resolve this problem with following function. I use Visual Studio 2019.
FILE* __cdecl __iob_func(void)
{
FILE _iob[] = { *stdin, *stdout, *stderr };
return _iob;
}
because stdin Macro defined function call, "*stdin" expression is cannot used global array initializer. But local array initialier is possible. sorry, I am poor at english.
Simple :::
scp remoteusername@remoteIP:/path/of/file /Local/path/to/copy
scp -r remoteusername@remoteIP:/path/of/folder /Local/path/to/copy
With booleans, there is no output difference between the two. You can swap && and & or || and | and it will never change the result of your expression.
The difference lies behind the scene where the information is being processed. When you right an expression "(a != 0) & ( b != 0)" for a= 0 and b = 1, The following happens:
left side: a != 0 --> false
right side: b 1= 0 --> true
left side and right side are both true? --> false
expression returns false
When you write an expression (a != 0) && ( b != 0)
when a= 0 and b = 1, the following happens:
a != 0 -->false
expression returns false
Less steps, less processing, better coding, especially when doing many boolean expression or complicated arguments.
No NSString
required!
String(format: "Value: %3.2f\tResult: %3.2f", arguments: [2.7, 99.8])
or
String(format:"Value: %3.2f\tResult: %3.2f", 2.7, 99.8)
if you want to run app in debug mode
1) Look at Left Side bottom, above Favorites there is Build Variants
2) Click on Build Variants. Click on release and choose debug
it works perfect !!!
if you don't have a good copy of your php5.ini
file in your home directory (a predicament that I recently found myself in), you'll need to follow a little multi-step process to make your changes.
Create a little code snippet to look at the output of the phpinfo()
call. This is simple, and there are multiple web-sites that describe this process.
Examine the output of phpinfo()
for the row which contains Configuration File (php.ini) Path
. Mine was in /usr/local/lib
, but your's may be a different path (depends on hosting level purchased).
GoDaddy will NOT simply copy this file into your home directory for you --as silly as that sounds! But, you can write a little php program to copy this php.ini file into your home directory. The guy at https://www.jabari-holder.com/blog/how-to-get-godaddys-php5-ini-file/ has a drop-box with this code snippet, if you care to use it. Just take care to modify two things:
a. change the path you read 'from' to match the path you uncovered in Step 2.
b. change the output file-name to something of your choosing. You're going to re-name this file in a later step anyway. Let's call our copied file Foo.ini
(but it can be anything).
Rename Foo.ini
to .user.ini
(for most GoDaddy account types).
It is possible on your restart some shards were not recovered, causing the cluster to stay red.
If you hit:
http://<yourhost>:9200/_cluster/health/?level=shards
you can look for red shards.
I have had issues on restart where shards end up in a non recoverable state. My solution was to simply delete that index completely. That is not an ideal solution for everyone.
It is also nice to visualize issues like this with a plugin like:
Elasticsearch Head
<html>
<style>
.selectBox{
color:White;
}
.optionBox{
color:black;
}
</style>
<body>
<select class = "selectBox">
<option class = "optionBox">One</option>
<option class = "optionBox">Two</option>
<option class = "optionBox">Three</option>
</select>
You can simply hide the <td>
tag content by just including a style attribute: style = "display:none"
For e.g
<td style = "display:none" >
<p> I'm invisible </p>
</td>
If you're trying to serialize a list of object and one of them is null you'll end up including the null item in the JSON even with
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
will result in:
[{myObject},null]
to get this:
[{myObject}]
one can do something like:
mapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
@Override
public void serialize(Object obj, JsonGenerator jsonGen, SerializerProvider unused)
throws IOException
{
//IGNORES NULL VALUES!
}
});
TIP: If you're using DropWizard you can retrieve the ObjectMapper
being used by Jersey using environment.getObjectMapper()
For c++ use std::array<int/*type*/, 10/*size*/>
instead of c-style array. This is available with c++11 standard, and which is a good practice. See it here for standard and examples. If you want to stick to old c-style arrays for reasons, there two possible ways:
int *a = new int[5]();
Here leave the parenthesis empty, otherwise it will give compile error. This will initialize all the elements in the allocated array. Here if you don't use the parenthesis, it will still initialize the integer values with zeros because new will call the constructor, which is in this case int()
.int *a = new int[5] {0, 0, 0};
This is allowed in c++11 standard. Here you can initialize array elements with any value you want. Here make sure your initializer list(values in {}) size should not be greater than your array size. Initializer list size less than array size is fine. Remaining values in array will be initialized with 0.I tried all of the suggestions above and none of them worked for me, they changed the clientWidth and clientHeight not the actual width and height.
The jQuery docs for $().width and height methods says: "Note that .width("value") sets the content width of the box regardless of the value of the CSS box-sizing property."
The css approach did the same thing so I had to use the $().attr() methods instead.
_canvas.attr('width', 100);
_canvas.attr('height', 200);
I don't know is this affect me because I was trying to resize a element and it is some how different or not.
You could use x ** (1. / 3)
to compute the (floating-point) cube root of x
.
The slight subtlety here is that this works differently for negative numbers in Python 2 and 3. The following code, however, handles that:
def is_perfect_cube(x):
x = abs(x)
return int(round(x ** (1. / 3))) ** 3 == x
print(is_perfect_cube(63))
print(is_perfect_cube(64))
print(is_perfect_cube(65))
print(is_perfect_cube(-63))
print(is_perfect_cube(-64))
print(is_perfect_cube(-65))
print(is_perfect_cube(2146689000)) # no other currently posted solution
# handles this correctly
This takes the cube root of x
, rounds it to the nearest integer, raises to the third power, and finally checks whether the result equals x
.
The reason to take the absolute value is to make the code work correctly for negative numbers across Python versions (Python 2 and 3 treat raising negative numbers to fractional powers differently).
The commands module is a reasonably high-level way to do this:
import commands
status, output = commands.getstatusoutput("cat /etc/services")
status is 0, output is the contents of /etc/services.
I created this based on the input from this thread. I need to use odict though, so I had to override get and set attr. I think this should work for the majority of special uses.
Usage looks like this:
# Create an ordered dict normally...
>>> od = OrderedAttrDict()
>>> od["a"] = 1
>>> od["b"] = 2
>>> od
OrderedAttrDict([('a', 1), ('b', 2)])
# Get and set data using attribute access...
>>> od.a
1
>>> od.b = 20
>>> od
OrderedAttrDict([('a', 1), ('b', 20)])
# Setting a NEW attribute only creates it on the instance, not the dict...
>>> od.c = 8
>>> od
OrderedAttrDict([('a', 1), ('b', 20)])
>>> od.c
8
The class:
class OrderedAttrDict(odict.OrderedDict):
"""
Constructs an odict.OrderedDict with attribute access to data.
Setting a NEW attribute only creates it on the instance, not the dict.
Setting an attribute that is a key in the data will set the dict data but
will not create a new instance attribute
"""
def __getattr__(self, attr):
"""
Try to get the data. If attr is not a key, fall-back and get the attr
"""
if self.has_key(attr):
return super(OrderedAttrDict, self).__getitem__(attr)
else:
return super(OrderedAttrDict, self).__getattr__(attr)
def __setattr__(self, attr, value):
"""
Try to set the data. If attr is not a key, fall-back and set the attr
"""
if self.has_key(attr):
super(OrderedAttrDict, self).__setitem__(attr, value)
else:
super(OrderedAttrDict, self).__setattr__(attr, value)
This is a pretty cool pattern already mentioned in the thread, but if you just want to take a dict and convert it to an object that works with auto-complete in an IDE, etc:
class ObjectFromDict(object):
def __init__(self, d):
self.__dict__ = d
In my case, stopping Proxifier fixed it. I added a rule to route any connections from vpnkit.exe
as Direct
and it now works.
Here is Bjarne Stroustrup's wordings,
In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.
If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, "nullptr" will be a keyword.
You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.
Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String
'Assign data to first item in array
compArray(1) = "asdf"
'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"
'Prints "ErrorState"
Debug.Print Computers("Computer Name")
Collections cannot be sorted so if you need to sort data you will probably want to use an array.
Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx
Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx
Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!
Edit:
Sub ArrayExample()
Dim subject As String
Dim TestArray() As String
Dim counter As Long
subject = "Example"
counter = Len(subject)
ReDim TestArray(1 To counter) As String
For counter = 1 To Len(subject)
TestArray(counter) = Right(Left(subject, counter), 1)
Next
End Sub
I don't think the problem lies in the sample you posted - we'd need to see the CSS, or verify its location etc!
But why not try stripping it down to one CSS rule - put it in the HEAD section, then if it works, move that rule to the external file. Then re-introduce the other rules to make sure there's nothing missing or taking precedence over your CSS.
It depends on your definition of "inherit". Does the subclass still have the fields in memory? Definitely. Can it access them directly? No. It's just subtleties of the definition; the point is to understand what's really happening.
In order to read data from microsoft excel 2007 by codeigniter just create a helper function excel_helper.php and add the following in:
require_once APPPATH.'libraries/phpexcel/PHPExcel.php';
require_once APPPATH.'libraries/phpexcel/PHPExcel/IOFactory.php';
in controller add the following code to read spread sheet by active sheet
//initialize php excel first
ob_end_clean();
//define cachemethod
$cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
$cacheSettings = array('memoryCacheSize' => '20MB');
//set php excel settings
PHPExcel_Settings::setCacheStorageMethod(
$cacheMethod,$cacheSettings
);
$arrayLabel = array("A","B","C","D","E");
//=== set object reader
$objectReader = PHPExcel_IOFactory::createReader('Excel2007');
$objectReader->setReadDataOnly(true);
$objPHPExcel = $objectReader->load("./forms/test.xlsx");
$objWorksheet = $objPHPExcel->setActiveSheetIndexbyName('Sheet1');
$starting = 1;
$end = 3;
for($i = $starting;$i<=$end; $i++)
{
for($j=0;$j<count($arrayLabel);$j++)
{
//== display each cell value
echo $objWorksheet->getCell($arrayLabel[$j].$i)->getValue();
}
}
//or dump data
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
var_dump($sheetData);
//see also the following link
http://blog.mayflower.de/561-Import-and-export-data-using-PHPExcel.html
----------- import in another style around 5000 records ------
$this->benchmark->mark('code_start');
//=== change php ini limits. =====
$cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_phpTemp;
$cacheSettings = array( ' memoryCacheSize ' => '50MB');
PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
//==== create excel object of reader
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
//$objReader->setReadDataOnly(true);
//==== load forms tashkil where the file exists
$objPHPExcel = $objReader->load("./forms/5000records.xlsx");
//==== set active sheet to read data
$worksheet = $objPHPExcel->setActiveSheetIndexbyName('Sheet1');
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns = ord($highestColumn) - 64;
$worksheetTitle = $worksheet->getTitle();
echo "<br>The worksheet ".$worksheetTitle." has ";
echo $nrColumns . ' columns (A-' . $highestColumn . ') ';
echo ' and ' . $highestRow . ' row.';
echo '<br>Data: <table border="1"><tr>';
//----- loop from all rows -----
for ($row = 1; $row <= $highestRow; ++ $row)
{
echo '<tr>';
echo "<td>".$row."</td>";
//--- read each excel column for each row ----
for ($col = 0; $col < $highestColumnIndex; ++ $col)
{
if($row == 1)
{
// show column name with the title
//----- get value ----
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
//$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val);
echo '<td>' . $val ."(".$row." X ".$col.")".'</td>';
}
else
{
if($col == 9)
{
//----- get value ----
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
//$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val);
echo '<td>zone ' . $val .'</td>';
}
else if($col == 13)
{
$date = PHPExcel_Shared_Date::ExcelToPHPObject($worksheet->getCellByColumnAndRow($col, $row)->getValue())->format('Y-m-d');
echo '<td>' .dateprovider($date,'dr') .'</td>';
}
else
{
//----- get value ----
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
//$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val);
echo '<td>' . $val .'</td>';
}
}
}
echo '</tr>';
}
echo '</table>';
$this->benchmark->mark('code_end');
echo "Total time:".$this->benchmark->elapsed_time('code_start', 'code_end');
$this->load->view("error");
Another helpful note to add to the above responses is to add some flexbox styling. This will keep the text on one line and will make sure the text doesn't overlap the screen.
<View style={{ display: "flex", flexDirection: "row", flex: 1, flexWrap: 'wrap', margin: 10 }}>
<Text>Add your </Text>
<TouchableOpacity>
<Text style={{ color: 'blue' }} onpress={() => Linking.openURL('https://www.google.com')} >
link
</Text>
</TouchableOpacity>
<Text>here.
</Text>
</View>
You should also consider using libraries to do that: they allow limiting and much more:
FineUploader. Demo using validation.itemLimit
as of 5.16.2:
var restrictedUploader = new qq.FineUploader({
validation: {
itemLimit: 3,
}
});
bluimp's jQuery File Upload Plugin. Usage: jquery file upload restricting number of files using maxNumberOfFiles
as of v9.22.0:
$('#fileuploadbasic').fileupload({
maxNumberOfFiles: 6
});
They are also available at https://cdnjs.com/
Basically it's because MS Excel can't decide how to open the file with such content.
When you put ID
as the first character in a Spreadsheet type file, it matches the specification of a SYLK file and MS Excel (and potentially other Spreadsheet Apps) try to open it as a SYLK file. But at the same time, it does not meet the complete specification of a SYLK file since rest of the values in the file are comma separated. Hence, the error is shown.
To solve the issue, change "ID"
to "id"
and it should work as expected.
This is weird. But, yeah!
Also trying to minimize file access by using file object less.
I tested and the code below works perfect.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class CsvWriter {
public static void main(String[] args) {
try (PrintWriter writer = new PrintWriter(new File("test.csv"))) {
StringBuilder sb = new StringBuilder();
sb.append("id,");
sb.append(',');
sb.append("Name");
sb.append('\n');
sb.append("1");
sb.append(',');
sb.append("Prashant Ghimire");
sb.append('\n');
writer.write(sb.toString());
System.out.println("done!");
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
}
}
}
I have encountered similar problem and my solution is much clear than above.
I simply used the pattern in @JsonFormat
annotation
Basically my class has a DateTime
field, so I put an annotation around the getter:
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public DateTime getDate() {
return date;
}
I serialize the class with ObjectMapper
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
ObjectWriter ow = mapper.writer();
try {
String logStr = ow.writeValueAsString(log);
outLogger.info(logStr);
} catch (IOException e) {
logger.warn("JSON mapping exception", e);
}
We use Jackson 2.5.4
The $.fn.equals(...)
solution is probably the cleanest and most elegant one.
I have tried something quick and dirty like this:
JSON.stringify(a) == JSON.stringify(b)
It is probably expensive, but the comfortable thing is that it is implicitly recursive, while the elegant solution is not.
Just my 2 cents.
If you could reload this, you might be able to use dtypes argument.
pd.read_csv(..., dtype={'COL_NAME':'str'})
If you need to use trim in select query, you can also use regular expressions
SELECT * FROM table_name WHERE field RLIKE ' * query-string *'
return rows with field like ' query-string '
public void run(final String scriptSrc) {
webView.post(new Runnable() {
@Override
public void run() {
webView.loadUrl("javascript:" + scriptSrc);
}
});
}
You should use "r"
for opening text files. Different operating systems have slightly different ways of storing text, and this will perform the correct translations so that you don't need to know about the idiosyncracies of the local operating system. For example, you will know that newlines will always appear as a simple "\n"
, regardless of where the code runs.
You should use "rb"
if you're opening non-text files, because in this case, the translations are not appropriate.
Websocket and WebRTC can be used together, Websocket as a signal channel of WebRTC, and webrtc is a video/audio/text channel, also WebRTC can be in UDP also in TURN relay, TURN relay support TCP HTTP also HTTPS. Many projects use Websocket and WebRTC together.
The case (single page style) for browser history
HttpContext.Request.UrlReferrer
Using MySql and Entity framework code first Approach:
public class Vw_EMIcount
{
public int EmiCount { get; set; }
public string Satus { get; set; }
}
var result = context.Database.SqlQuery<Vw_EMIcount>("call EMIStatus('2018-3-01' ,'2019-05-30')").ToList();
The asynchronous solution from Edward:
is simple and might just work for you.
I would also like to give a more advanced version which has these advantages:
This might be in particular useful in large software projects where you have many task executed repetitively in your process and you care about resource usage (threads) and also startup overhead.
Idea: Have one service thread which processes all registered timed tasks. Use boost io_service for that.
Code similar to: http://www.boost.org/doc/libs/1_65_1/doc/html/boost_asio/tutorial/tuttimer2/src.html
#include <cstdio>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
int main()
{
boost::asio::io_service io;
boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
t.async_wait([](const boost::system::error_code& /*e*/){
printf("Printed after 1s\n"); });
boost::asio::deadline_timer t2(io, boost::posix_time::seconds(1));
t2.async_wait([](const boost::system::error_code& /*e*/){
printf("Printed after 1s\n"); });
// both prints happen at the same time,
// but only a single thread is used to handle both timed tasks
// - namely the main thread calling io.run();
io.run();
return 0;
}
Better make the google object convert as a javascript readable object first.
Create two functions like below and call it passing google map return object.
function getShortAddressObject(object) {
let address = {};
const address_components = object[0].address_components;
address_components.forEach(element => {
address[element.types[0]] = element.short_name;
});
return address;
}
function getLongAddressObject(object) {
let address = {};
const address_components = object[0].address_components;
address_components.forEach(element => {
address[element.types[0]] = element.long_name;
});
return address;
}
Then user can access names like below.
var addressObj = getLongAddressObject(object);
var country = addressObj.country; //Sri Lanka
All address parts are like below.
administrative_area_level_1: "Western Province"
administrative_area_level_2: "Colombo"
country: "Sri Lanka"
locality: "xxxx xxxxx"
political: "xxxxx"
route: "xxxxx - xxxxx Road"
street_number: "No:00000"
i also got same error , i just change the java version in pom.xml from 11 to 1.8 and it's work fine.
This is how I set it up:
Export the proxy settings :
set http_proxy=http://username:password@proxyAddress:port
set https_proxy=https://username:password@proxyAddress:port
Install the package you want to install:
pip install PackageName
For example:
You can do a serialization-based deep clone using org.apache.commons.lang3.SerializationUtils.clone(T)
in Apache Commons Lang, but be careful—the performance is abysmal.
In general, it is best practice to write your own clone methods for each class of an object in the object graph needing cloning.
// GET: api/GetStudent
public Response Get() {
return StoredProcedure.GetStudent();
}
public static Response GetStudent() {
using (var db = new dal()) {
var student = db.Database.SqlQuery<GetStudentVm>("GetStudent").ToList();
return new Response {
Sucess = true,
Message = student.Count() + " Student found",
Data = student
};
}
}
Typically we would place one of these at or near the top of the script. Scripts that parse their command lines would do the redirection after parsing.
Send stdout to a file
exec > file
with stderr
exec > file
exec 2>&1
append both stdout and stderr to file
exec >> file
exec 2>&1
As Jonathan Leffler mentioned in his comment:
exec
has two separate jobs. The first one is to replace the currently executing shell (script) with a new program. The other is changing the I/O redirections in the current shell. This is distinguished by having no argument to exec
.
If none of them are working then check this.. say if you have x and y arrays of data along respective axis. Then check in which cell(jupyter) you have initialized x and y to empty. This is because , maybe you are appending data to x and y without re-initializing them. So plot has old data too. So check that..
Use PHP's $_POST
or $_GET
superglobals to retrieve the value of the input tag via the name of the HTML tag.
For Example, change the method in your form and then echo out the value by the name of the input:
Using $_GET
method:
<form name="form" action="" method="get">
<input type="text" name="subject" id="subject" value="Car Loan">
</form>
To show the value:
<?php echo $_GET['subject']; ?>
Using $_POST
method:
<form name="form" action="" method="post">
<input type="text" name="subject" id="subject" value="Car Loan">
</form>
To show the value:
<?php echo $_POST['subject']; ?>
On Mac Os High Sierra, I installed jupyter with
python3 -m pip install jupyter
And then, binary were installed in:
/Library/Frameworks/Python.framework/Versions/3.6/bin/jupyter-notebook
SELECT
CASE
WHEN course_enrollment_settings.base_price = 0 THEN 1
WHEN course_enrollment_settings.base_price>0 AND
course_enrollment_settings.base_price<=100 THEN 2
WHEN course_enrollment_settings.base_price>100 AND
course_enrollment_settings.base_price<201 THEN 3
ELSE 6
END AS 'calc_base_price',
course_enrollment_settings.base_price
FROM
course_enrollment_settings
WHERE course_enrollment_settings.base_price = 0
This question is old and Carlos Rojas's answer is good, but I think I should post few things which should be kept in mind while trying to open the ports.
The first thing to remember is that Networking section is renamed to VPC Networking. So if you're trying to find out where Firewall Rules option is available, go look at VPC Networking.
The second thing is, if you're trying to open ports on a Linux VM, make sure under no circumstances should you try to open port using ufw
command. I tried using that and lost ssh access to the VM. So don't repeat my mistake.
The third thing is, if you're trying to open ports on a Windows VM, you'll need to create Firewall rules inside the VM also in Windows Firewall along with VPC Networking -> Firewall Rules. The port needs to be opened in both firewall rules, unlike Linux VM. So if you're not getting access to the port from outside the VM, check if you've opened the port in both GCP console and Windows Firewall.
The last (obvious) thing is, do not open ports unnecessarily. Close the ports, as soon as you no longer need it.
I hope this answer is useful.
If Perl is an option:
perl -F, -lane 'print join ",",@F[0,1,2,3,4,5,6,7,8,9,19,20,21,22,23,24,29,32]'
-a
autosplits line into @F
fields array. Indices start at 0 (not 1 as in awk)
-F,
field separator is ,
If your CSV file contains commas within quotes, fully fledged CSV parsers such as Perl's Text::CSV_XS
are purpose-built to handle that kind of weirdness.
perl -MText::CSV_XS -lne 'BEGIN{$csv=Text::CSV_XS->new()} if($csv->parse($_)){@f=$csv->fields();print (join ",",@f[0,1,2,3,4,5,6,7,8,9,19,20,21,22,23,24,29,32])}'
I provided more explanation within my answer here: parse csv file using gawk
Off the top of my head, Set is used to assign COM objects to variables. By doing a Set I suspect that under the hood it's doing an AddRef() call on the object to manage it's lifetime.
I believe that in the book class all \part and \chapter are set to start on a recto page.
from book.cls:
\newcommand\part{%
\if@openright
\cleardoublepage
\else
\clearpage
\fi
\thispagestyle{plain}%
\if@twocolumn
\onecolumn
\@tempswatrue
\else
\@tempswafalse
\fi
\null\vfil
\secdef\@part\@spart}
you should be able to renew that command, and something similar for the \chapter.
TRAC. Open source, Python-based
SelectedItem
is an object
.
SelectedValue
and SelectedValuePath
are string
s.
for example using the ListBox:
if you say give me listbox1.SelectedValue
it will return the text of the currently selected item.
string value = listbox1.SelectedValue;
if you say give me listbox1.SelectedItem
it will give you the entire object.
ListItem item = listbox1.SelectedItem;
string value = item.value;
I know this has been answered with a very high-quality answer. But, in short, you cant have spaces.
#!/bin/bash
STR = "Hello World"
echo $STR
Didn't work because of the spaces around the equal sign. If you were to run...
#!/bin/bash
STR="Hello World"
echo $STR
It would work
Try setting position to absolute, ie.
#yourDiv{
position: absolute;
z-index: 10;
};
If you want to merge the filters (eg. CSV and Excel files), use this formula:
OpenFileDialog of = new OpenFileDialog();
of.Filter = "CSV files (*.csv)|*.csv|Excel Files|*.xls;*.xlsx";
Or if you want to see XML or PDF files in one time use this:
of.Filter = @" XML or PDF |*.xml;*.pdf";
If it's possible to sort your items then there is a much faster way to do this then doing key lookups into a hashtable or b-tree. Though if you're items aren't sortable you can't really put them into a b-tree anyway.
Anyway, if sortable sort both lists then it's just a matter of walking the lookup list in order.
Walk lookup list
While items in check list <= lookup list item
if check list item = lookup list item do something
Move to next lookup list item
This is basically @lengxuehx's answer, but updated for Win 10, and it assumes your bash installation is from Git Bash for Windows from git's official downloads.
cmd /c (start /b "%cd%" "C:\Program Files\GitW\git-bash.exe") && exit
I ended up using this after I lost my context-menu items for Git Bash as my command to run from the registry settings. In case you're curious about that, I did this:
Bash
in the shell
key at HKEY_CLASSES_ROOT\Directory\Background\shell
Icon
(not a new key!) that is the full path to your git-bash.exe, including the git-bash.exe part. You might need to wrap this in quotes.Bash
to the text you want to use in the context menu
Bash
called command
command
's default value to cmd /c (start /b "%cd%" "C:\Program Files\GitW\git-bash.exe") && exit
Then you should be able to close the registry and start using Git Bash from anywhere that's a real directory. For example, This PC
is not a real directory.
No, this is not possible. The closest you can get is:
switch(this.dealer) {
case 1:
case 2:
case 3:
case 4:
// DO SOMETHING
break;
case 5:
case 6:
case 7:
case 8:
// DO SOMETHING
break;
But this very unwieldly.
For cases like this it's usually better just to use a if
/else if
structure.
This script runs on Git Bash (MINGW64) on Windows and return a messages depending of the ping result.
#!/bin/bash
#$1 should be something like "19.62.55"
if [ -z "$1" ]
then
echo "No identify of the network supplied, i.e. 19.62.55"
else
ipAddress=$1
for i in {1..256} ;do
(
{
ping -w 5 $ipAddress.$i ;
result=$(echo $?);
} &> /dev/null
if [ $result = 0 ]; then
echo Successful Ping From : $ipAddress.$i
else
echo Failed Ping From : $ipAddress.$i
fi &);
done
fi
As an unordered collection type, set([8, 1, 6])
is equivalent to set([1, 6, 8])
.
While it might be nicer to display the set contents in sorted order, that would make the repr()
call more expensive.
Internally, the set
type is implemented using a hash table: a hash function is used to separate items into a number of buckets to reduce the number of equality operations needed to check if an item is part of the set.
To produce the repr()
output it just outputs the items from each bucket in turn, which is unlikely to be the sorted order.
I made a really dumb mistake and forgot to define name
attributes for inputs in my html file.
So instead of
<input type="password" class="form-control" id="password">
I have this.
<input type="password" class="form-control" id="password" name="password">
Now request.body
is populated like this: { password: 'hhiiii' }
If your classes are in the same package, you won't need to import. To call a method from class B in class A, you should use classB.methodName(arg)
Swift 2.0
Well I worked out. Have a look. Made a ViewController in StoryBoard. Associated with PopOverViewController class.
import UIKit
class PopOverViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.preferredContentSize = CGSizeMake(200, 200)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "dismiss:")
}
func dismiss(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
See ViewController:
// ViewController.swift
import UIKit
class ViewController: UIViewController, UIPopoverPresentationControllerDelegate
{
func showPopover(base: UIView)
{
if let viewController = self.storyboard?.instantiateViewControllerWithIdentifier("popover") as? PopOverViewController {
let navController = UINavigationController(rootViewController: viewController)
navController.modalPresentationStyle = .Popover
if let pctrl = navController.popoverPresentationController {
pctrl.delegate = self
pctrl.sourceView = base
pctrl.sourceRect = base.bounds
self.presentViewController(navController, animated: true, completion: nil)
}
}
}
override func viewDidLoad(){
super.viewDidLoad()
}
@IBAction func onShow(sender: UIButton)
{
self.showPopover(sender)
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .None
}
}
Note: The func showPopover(base: UIView) method should be placed before ViewDidLoad. Hope it helps !
If you are using virtualenv, it is fine to install tkinter using sudo apt-get install python-tk
(python2), sudo apt-get install python3-tk
(python3), and and it will work fine in the virtual environment
found a working solution here: https://codepen.io/hoanghals/pen/dZrWLZ
JS here:
var gifElements = document.querySelectorAll('img.gif');
for(var e in gifElements) {
var element = gifElements[e];
if(element.nodeName == 'IMG') {
var supergif = new SuperGif({
gif: element,
progressbar_height: 0,
auto_play: false,
});
var controlElement = document.createElement("div");
controlElement.className = "gifcontrol loading g"+e;
supergif.load((function(controlElement) {
controlElement.className = "gifcontrol paused";
var playing = false;
controlElement.addEventListener("click", function(){
if(playing) {
this.pause();
playing = false;
controlElement.className = "gifcontrol paused";
} else {
this.play();
playing = true;
controlElement.className = "gifcontrol playing";
}
}.bind(this, controlElement));
}.bind(supergif))(controlElement));
var canvas = supergif.get_canvas();
controlElement.style.width = canvas.width+"px";
controlElement.style.height = canvas.height+"px";
controlElement.style.left = canvas.offsetLeft+"px";
var containerElement = canvas.parentNode;
containerElement.appendChild(controlElement);
}
}
There could be one of the following reasons:
Please go through following link: How Do I Enable Remote Access To MySQL Database Server?
test.Substring(test.LastIndexOf("-"))
The constant values (uses in fixtures or assertions) should be initialized in their declarations and final
(as never change)
the object under test should be initialized in the setup method because we may set things on. Of course we may not set something now but we could set it later. Instantiating in the init method would ease the changes.
dependencies of the object under test if these are mocked, should not even be instantiated by yourself : today the mock frameworks can instantiate it by reflection.
A test without dependency to mock could look like :
public class SomeTest {
Some some; //instance under test
static final String GENERIC_ID = "123";
static final String PREFIX_URL_WS = "http://foo.com/ws";
@Before
public void beforeEach() {
some = new Some(new Foo(), new Bar());
}
@Test
public void populateList()
...
}
}
A test with dependencies to isolate could look like :
@RunWith(org.mockito.runners.MockitoJUnitRunner.class)
public class SomeTest {
Some some; //instance under test
static final String GENERIC_ID = "123";
static final String PREFIX_URL_WS = "http://foo.com/ws";
@Mock
Foo fooMock;
@Mock
Bar barMock;
@Before
public void beforeEach() {
some = new Some(fooMock, barMock);
}
@Test
public void populateList()
...
}
}
If you're using underscore.js then you can use the _.isEmpty function:
var obj = {};
var emptyObject = _.isEmpty(obj);
I fixed this by adding the following into MainApplication.onCreate
:
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.genolingo.genolingo",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String hash = Base64.encodeToString(md.digest(), Base64.DEFAULT);
KeyHash.addKeyHash(hash);
}
}
catch (PackageManager.NameNotFoundException e) {
Log.e("PackageInfoError:", "NameNotFoundException");
}
catch (NoSuchAlgorithmException e) {
Log.e("PackageInfoError:", "NoSuchAlgorithmException");
}
I then uploaded this to the Google developer console and then downloaded the derived APK which, for whatever reason, has a totally different key hash.
I then used LogCat to determine the new key hash and added it Facebook as other users have outlined.
If you want to ask based on condition:
var ask = true
window.onbeforeunload = function (e) {
if(!ask) return null
e = e || window.event;
//old browsers
if (e) {e.returnValue = 'Sure?';}
//safari, chrome(chrome ignores text)
return 'Sure?';
};