If you want to check whether sessions are available, you probably want to use the session_id()
function:
session_id() returns the session id for the current session or the empty string ("") if there is no current session (no current session id exists).
You don't need much math. Some combinatorial thinking can help you frame and reduce a problem for fast execution. Being able to multiply is good. You're an engineer, approximations are fine.
In response to the post starting:
If you want to use this with command line or function arguments...
with the code:
size=${#1}
There might be the case where you just want to check for a zero length argument and have no need to store a variable. I believe you can use this sort of syntax:
if [ -z "$1" ]; then
#zero length argument
else
#non-zero length
fi
See GNU and wooledge for a more complete list of Bash conditional expressions.
It's just more convenient to reason about in many cases.
Basically, we could think of a range as an interval between start
and end
. If start <= end
, the length of the interval between them is end - start
. If len
was actually defined as the length, you'd have:
len(range(start, end)) == start - end
However, we count the integers included in the range instead of measuring the length of the interval. To keep the above property true, we should include one of the endpoints and exclude the other.
Adding the step
parameter is like introducing a unit of length. In that case, you'd expect
len(range(start, end, step)) == (start - end) / step
for length. To get the count, you just use integer division.
In windows it is
java -cp .;/path/junit.jar org.junit.runner.JUnitCore TestClass
[test class name without .class extension]
for example:
c:\>java -cp .;f:/libraries/junit-4.8.2 org.junit.runner.JUnitCore TestSample1 TestSample2 ...
and so on, if one has more than one test classes.
-cp stands for class path and the dot (.) represents the existing classpath while semi colon (;) appends the additional given jar to the classpath , as in above example junit-4.8.2 is now available in classpath to execute JUnitCore class that here we have used to execute our test classes.
Above command line statement helps you to execute junit (version 4+) tests from command prompt(i-e MSDos).
Note: JUnitCore is a facade to execute junit tests, this facade is included in 4+ versions of junit.
If the string is empty, comboBox.getSelectedItem().toString()
will give a NullPointerException
. So better to typecast by (String)
.
you can also check this link
SELECT * FROM master_question
WHERE 1 ORDER BY question_id
ASC LIMIT 20
Well, I like MONEY
! It's a byte cheaper than DECIMAL
, and the computations perform quicker because (under the covers) addition and subtraction operations are essentially integer operations. @SQLMenace's example—which is a great warning for the unaware—could equally be applied to INT
egers, where the result would be zero. But that's no reason not to use integers—where appropriate.
So, it's perfectly 'safe' and appropriate to use MONEY
when what you are dealing with is MONEY
and use it according to mathematical rules that it follows (same as INT
eger).
Would it have been better if SQL Server promoted division and multiplication of MONEY
's into DECIMAL
s (or FLOAT
s?)—possibly, but they didn't choose to do this; nor did they choose to promote INT
egers to FLOAT
s when dividing them.
MONEY
has no precision issue; that DECIMAL
s get to have a larger intermediate type used during calculations is just a 'feature' of using that type (and I'm not actually sure how far that 'feature' extends).
To answer the specific question, a "compelling reason"? Well, if you want absolute maximum performance in a SUM(x)
where x
could be either DECIMAL
or MONEY
, then MONEY
will have an edge.
Also, don't forget it's smaller cousin, SMALLMONEY
—just 4 bytes, but it does max out at 214,748.3647
- which is pretty small for money—and so is not often a good fit.
To prove the point around using larger intermediate types, if you assign the intermediate explicitly to a variable, DECIMAL
suffers the same problem:
declare @a decimal(19,4)
declare @b decimal(19,4)
declare @c decimal(19,4)
declare @d decimal(19,4)
select @a = 100, @b = 339, @c = 10000
set @d = @a/@b
set @d = @d*@c
select @d
Produces 2950.0000
(okay, so at least DECIMAL
rounded rather than MONEY
truncated—same as an integer would.)
From Effective Go:
Constants in Go are just that—constant. They are created at compile time, even when defined as locals in functions, and can only be numbers, characters (runes), strings or booleans. Because of the compile-time restriction, the expressions that define them must be constant expressions, evaluatable by the compiler. For instance,
1<<3
is a constant expression, whilemath.Sin(math.Pi/4)
is not because the function call tomath.Sin
needs to happen at run time.
Slices and arrays are always evaluated during runtime:
var TestSlice = []float32 {.03, .02}
var TestArray = [2]float32 {.03, .02}
var TestArray2 = [...]float32 {.03, .02}
[...]
tells the compiler to figure out the length of the array itself. Slices wrap arrays and are easier to work with in most cases. Instead of using constants, just make the variables unaccessible to other packages by using a lower case first letter:
var ThisIsPublic = [2]float32 {.03, .02}
var thisIsPrivate = [2]float32 {.03, .02}
thisIsPrivate
is available only in the package it is defined. If you need read access from outside, you can write a simple getter function (see Getters in golang).
I could not made your code to do the desired query, the AS is an alias only for the table abc
, not for the derived table.
Laravel Query Builder does not implicitly support derived table aliases, DB::raw is most likely needed for this.
The most straight solution I could came up with is almost identical to yours, however produces the query as you asked for:
$sql = Abc::groupBy('col1')->toSql();
$count = DB::table(DB::raw("($sql) AS a"))->count();
The produced query is
select count(*) as aggregate from (select * from `abc` group by `col1`) AS a;
You can use the following nginx configuration example:
upstream adminhost {
server adminhostname:8080;
}
server {
listen 80;
location ~ ^/admin/(.*)$ {
proxy_pass http://adminhost/$1$is_args$args;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
}
}
Use npm outdated
to see Current and Latest version of all packages.
Then npm i packageName@versionNumber
to install specific version : example npm i [email protected]
.
Or npm i packageName@latest
to install latest version : example npm i browser-sync@latest
.
You are almost always better off using an options hash.
def ldap_get(base_dn, filter, options = {})
options[:scope] ||= LDAP::LDAP_SCOPE_SUBTREE
...
end
ldap_get(base_dn, filter, :attrs => X)
Also just though I'd post the answer to another related question I had,
a = x ? : y;
Is equivalent to:
a = x ? x : y;
If x is false or null then the value of y is taken.
I wrote a function wrapper called bar()
for barplot()
to do what you are trying to do here, since I need to do similar things frequently. The Github link to the function is here. After copying and pasting it into R, you do
bar(dv = Species,
factors = c(Category, Reason),
dataframe = Reasonstats,
errbar = FALSE,
ylim=c(0, 140)) #I increased the upper y-limit to accommodate the legend.
The one convenience is that it will put a legend on the plot using the names of the levels in your categorical variable (e.g., "Decline" and "Improved"). If each of your levels has multiple observations, it can also plot the error bars (which does not apply here, hence errbar=FALSE
Below script gets job status for every job on the server. It also tells how many steps are there and what is the currently running step and elasped time.
SELECT sj.Name,
CASE
WHEN sja.start_execution_date IS NULL THEN 'Never ran'
WHEN sja.start_execution_date IS NOT NULL AND sja.stop_execution_date IS NULL THEN 'Running'
WHEN sja.start_execution_date IS NOT NULL AND sja.stop_execution_date IS NOT NULL THEN 'Not running'
END AS 'RunStatus',
CASE WHEN sja.start_execution_date IS NOT NULL AND sja.stop_execution_date IS NULL then js.StepCount else null end As TotalNumberOfSteps,
CASE WHEN sja.start_execution_date IS NOT NULL AND sja.stop_execution_date IS NULL then ISNULL(sja.last_executed_step_id+1,js.StepCount) else null end as currentlyExecutingStep,
CASE WHEN sja.start_execution_date IS NOT NULL AND sja.stop_execution_date IS NULL then datediff(minute, sja.run_requested_date, getdate()) ELSE NULL end as ElapsedTime
FROM msdb.dbo.sysjobs sj
JOIN msdb.dbo.sysjobactivity sja
ON sj.job_id = sja.job_id
CROSS APPLY (SELECT COUNT(*) FROM msdb.dbo.sysjobsteps as js WHERE js.job_id = sj.job_id) as js(StepCount)
WHERE session_id = (
SELECT MAX(session_id) FROM msdb.dbo.sysjobactivity)
ORDER BY RunStatus desc
Recently have the issue. The fix which work for me was to added this to babel.config.json in the plugins section
["@babel/plugin-transform-modules-commonjs", {
"allowTopLevelThis": true,
"loose": true,
"lazy": true
}],
I had some imported module with // and the error "cannot use import outside a module".
If you're feeling lazy, here's a terse method of handling conditions using ||
(or) and &&
(and) after the operation:
wget -q --tries=10 --timeout=20 --spider http://google.com || \
{ echo "Sorry you are Offline" && exit 1; }
in Swift 4
in cellForRowAt indexPath:
cell.prescriptionButton.addTarget(self, action: Selector("onClicked:"), for: .touchUpInside)
function that run after user pressed button:
@objc func onClicked(sender: UIButton){
let tag = sender.tag
}
I found that xfig
did an excellent job:
pstoedit -f fig foo.pdf foo.fig
xfig foo.fig
export to svg
It did much better job than inkscape. Actually it was probably pdtoedit that did it.
I use this way in work life: "Forget common loops" in this case and use this combination of "setInterval" includes "setTimeOut"s:
function iAsk(lvl){
var i=0;
var intr =setInterval(function(){ // start the loop
i++; // increment it
if(i>lvl){ // check if the end round reached.
clearInterval(intr);
return;
}
setTimeout(function(){
$(".imag").prop("src",pPng); // do first bla bla bla after 50 millisecond
},50);
setTimeout(function(){
// do another bla bla bla after 100 millisecond.
seq[i-1]=(Math.ceil(Math.random()*4)).toString();
$("#hh").after('<br>'+i + ' : rand= '+(Math.ceil(Math.random()*4)).toString()+' > '+seq[i-1]);
$("#d"+seq[i-1]).prop("src",pGif);
var d =document.getElementById('aud');
d.play();
},100);
setTimeout(function(){
// keep adding bla bla bla till you done :)
$("#d"+seq[i-1]).prop("src",pPng);
},900);
},1000); // loop waiting time must be >= 900 (biggest timeOut for inside actions)
}
PS: Understand that the real behavior of (setTimeOut): they all will start in same time "the three bla bla bla will start counting down in the same moment" so make a different timeout to arrange the execution.
PS 2: the example for timing loop, but for a reaction loops you can use events, promise async await ..
I have used the above option to .hide entries from 2 drops down boxes (first you select the city, then you selected the area within that city). It works fine on screen but the hidden options are still selectable via keyboard inputs.
Thanks Andy W
I found that the mid() did not quite work as I expected and I modified as follows:
def mid(s, offset, amount):
return s[offset-1:offset+amount-1]
I performed the following test:
print('[1]23', mid('123', 1, 1))
print('1[2]3', mid('123', 2, 1))
print('12[3]', mid('123', 3, 1))
print('[12]3', mid('123', 1, 2))
print('1[23]', mid('123', 2, 2))
Which resulted in:
[1]23 1
1[2]3 2
12[3] 3
[12]3 12
1[23] 23
Which was what I was expecting. The original mid() code produces this:
[1]23 2
1[2]3 3
12[3]
[12]3 23
1[23] 3
But the left() and right() functions work fine. Thank you.
As far as I understand, you want to prepend column1, column2, column3
to your existing one, two, three
.
I would use ed
in place of sed
, since sed
write on the standard output and not in the file.
The command:
printf '0a\ncolumn1, column2, column3\n.\nw\n' | ed testfile.csv
should do the work.
perl -i
is worth taking a look as well.
In general suppressing warnings is not the best solution as you may want to be warned when some unexpected input will be provided.
Solution below is wrapper for maintaining just NA during data type conversion. Doesn't require any package.
as.num = function(x, na.strings = "NA") {
stopifnot(is.character(x))
na = x %in% na.strings
x[na] = 0
x = as.numeric(x)
x[na] = NA_real_
x
}
as.num(c("1", "2", "X"), na.strings="X")
#[1] 1 2 NA
Use your code
public class FragmentOne extends Fragment implements OnClickListener{
View view;
Fragment fragmentTwo;
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
Button buttonSayHi = (Button) view.findViewById(R.id.buttonSayHi);
buttonSayHi.setOnClickListener(this);
return view;
}
But I think is better handle the buttons in this way:
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonSayHi:
/** Do things you need to..
fragmentTwo = new FragmentTwo();
fragmentTransaction.replace(R.id.frameLayoutFragmentContainer, fragmentTwo);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
*/
break;
}
}
I've had problems in the past calling iframe.onload for dynamically created iframes, so I went with this approach for setting the iframe size:
iFrame View
var height = $("body").outerHeight();
parent.SetIFrameHeight(height);
Main View
SetIFrameHeight = function(height) {
$("#iFrameWrapper").height(height);
}
(this is only going to work if both views are in the same domain)
Put them in brackets []
:
var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");
There is a much easier solution, if you take advantage of the built-in reverseObjectEnumerator
method on NSArray
, and the allObjects
method of NSEnumerator
:
NSArray* reversedArray = [[startArray reverseObjectEnumerator] allObjects];
allObjects
is documented as returning an array with the objects that have not yet been traversed with nextObject
, in order:
This array contains all the remaining objects of the enumerator in enumerated order.
We use this code to check if the string is a valid date
var dt = new Date(txtDate.value)
if (isNaN(dt))
If the types of the parameters are all the same (varchar2
for example), you can have a package like this which will do the following:
CREATE OR REPLACE PACKAGE testuser.test_pkg IS
TYPE assoc_array_varchar2_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;
PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t);
END test_pkg;
CREATE OR REPLACE PACKAGE BODY testuser.test_pkg IS
PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t) AS
BEGIN
FOR i IN p_parm.first .. p_parm.last
LOOP
dbms_output.put_line(p_parm(i));
END LOOP;
END;
END test_pkg;
Then, to call it you'd need to set up the array and pass it:
DECLARE
l_array testuser.test_pkg.assoc_array_varchar2_t;
BEGIN
l_array(0) := 'hello';
l_array(1) := 'there';
testuser.test_pkg.your_proc(l_array);
END;
/
public static DateTime ConvertDateTime(string Date)
{
DateTime date=new DateTime();
try
{
string CurrentPattern = Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern;
string[] Split = new string[] {"-","/",@"\","."};
string[] Patternvalue = CurrentPattern.Split(Split,StringSplitOptions.None);
string[] DateSplit = Date.Split(Split,StringSplitOptions.None);
string NewDate = "";
if (Patternvalue[0].ToLower().Contains("d") == true && Patternvalue[1].ToLower().Contains("m")==true && Patternvalue[2].ToLower().Contains("y")==true)
{
NewDate = DateSplit[1] + "/" + DateSplit[0] + "/" + DateSplit[2];
}
else if (Patternvalue[0].ToLower().Contains("m") == true && Patternvalue[1].ToLower().Contains("d")==true && Patternvalue[2].ToLower().Contains("y")==true)
{
NewDate = DateSplit[0] + "/" + DateSplit[1] + "/" + DateSplit[2];
}
else if (Patternvalue[0].ToLower().Contains("y") == true && Patternvalue[1].ToLower().Contains("m")==true && Patternvalue[2].ToLower().Contains("d")==true)
{
NewDate = DateSplit[2] + "/" + DateSplit[0] + "/" + DateSplit[1];
}
else if (Patternvalue[0].ToLower().Contains("y") == true && Patternvalue[1].ToLower().Contains("d")==true && Patternvalue[2].ToLower().Contains("m")==true)
{
NewDate = DateSplit[2] + "/" + DateSplit[1] + "/" + DateSplit[0];
}
date = DateTime.Parse(NewDate, Thread.CurrentThread.CurrentCulture);
}
catch (Exception ex)
{
}
finally
{
}
return date;
}
You are not getting value of $id=$_GET['id'];
And you are using it (before it gets initialised).
Use php's in built isset() function to check whether the variable is defied or not.
So, please update the line to:
$id = isset($_GET['id']) ? $_GET['id'] : '';
You want to use transform
this will return a Series with the index aligned to the df so you can then add it as a new column:
In [74]:
df = pd.DataFrame({'Date': ['2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05', '2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05'], 'Sym': ['aapl', 'aapl', 'aapl', 'aapl', 'aaww', 'aaww', 'aaww', 'aaww'], 'Data2': [11, 8, 10, 15, 110, 60, 100, 40],'Data3': [5, 8, 6, 1, 50, 100, 60, 120]})
?
df['Data4'] = df['Data3'].groupby(df['Date']).transform('sum')
df
Out[74]:
Data2 Data3 Date Sym Data4
0 11 5 2015-05-08 aapl 55
1 8 8 2015-05-07 aapl 108
2 10 6 2015-05-06 aapl 66
3 15 1 2015-05-05 aapl 121
4 110 50 2015-05-08 aaww 55
5 60 100 2015-05-07 aaww 108
6 100 60 2015-05-06 aaww 66
7 40 120 2015-05-05 aaww 121
In my case, the problem was that the phpMyAdmin version was specified wrongly in the phpmyadmin.conf
file. You may check that:
Go to wamp/apps/phpmyadmin3.x.x: notice the file name - what version you are currently using?
Open file wamp/alias/phpmyadmin.conf:
Options Indexes FollowSymLinks MultiViews AllowOverride all Order Deny,Allow Allow from all
Check the first line (directory "c:/wamp/apps/phpmyadmin3.x.x/") is the file name exactly the same as your actual file name.
Make sure the directory file name is absolutely correct.
Would implementing ThreeDBoard in terms of an array of Board be that useful?
Perhaps you may want to treat slices of ThreeDBoard in various planes as a Board. In that case you may want to abstract out an interface (or abstract class) for Board to allow for multiple implementations.
In terms of external interface, you might want to factor out a Board interface for both TwoDBoard and ThreeDBoard (although none of the above methods fit).
You need to subscribe to a SMS gateway. There are thousands of those (try searching with google) and they are usually not free. For example this one has support for PHP.
Well it does not work if the XML file (starting by the standard PI:
<?xml-stylesheet type="text/xsl" href="..."?>
for referencing the XSL stylesheet) is served as "application/xml". In that case, Chrome will still download the referenced XSL stylesheet, but nothing will be rendered, as it will silently change the document types from "application/xml" into "Document" (!??) and "text/xsl" into "Stylesheet" (!??), and then will attempt to render the XML document as if it was an HTML(5) document, without running first its XSLT processor. And Nothing at all will be displayed in the screen (whose content will continue to show the previous page from which the XML page was referenced, and will continue spinning the icon, as if the document was never completely loaded.
You can perfectly use the Chrome console, that shows that all resources are loaded, but they are incorrectly interpreted.
So yes, Chrome currently only render XML files (with its optional leading XSL stylesheet declaration), only if it is served as "text/xml", but not as "application/xml" as it should for client-side rendered XML with an XSL declaration.
For XML files served as "text/xml" or "application/xml" and that do not contain an XSL stylesheet declaration, Chrome should still use a default stylesheet to render it as a DOM tree, or at least as its text source. But it does not, and here again it attempts to render it as if it was HTML, and bugs immediately on many scripts (including a default internal one) that attempt to access to "document.body" for handling onLoad events and inject some javascript handler in it.
An example of site that does not work as expected (the Common Lisp documentation) in Chrome, but works in IE which supports client-side XSLT:
http://common-lisp.net/project/bknr/static/lmman/toc.html
This index page above is displayed correctly, but all links will drive to XML documents with a basic XSL declaration to an existing XSL stylesheet document, and you can wait indefinitely, thinking that the chapters have problems to be downloaded. All you can do to read the docuemntation is to open the console and read the source code in the Resources tab.
First declare your timer
var timer: Timer?
Then add line in viewDidLoad() or in any function you want to start the timer
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(action), userInfo: nil, repeats: false)
This is the func you will callback it to do something it must be @objc
@objc func action () {
print("done")
}
In my case this worked (Mac, Excel 2011, both Cyrillic and Latin characters with Czech diacritics):
We offer a tool called DocFlex/XML XSDDoc that allows you to enjoy both things at once:
The diagrams in fact are generated not by us, but by Altova XMLSpy. We implemented an Integration with XMLSpy (with the full support of all diagram hyperlinks):
Here you can see the full this doc: http://www.filigris.com/docflex-xml/xsddoc/examples/html/XMLSchema/index.html
The whole thing provides a functionality not offered by any single vendor right now on the market!
Some our customers were so impressed that they purchased an extra license for XMLSpy only because of our tool. (That's no joke!)
Currently, we've also implemented similar integrations with other XML editors:
See: http://www.filigris.com/docflex-xml/OxygenXML/demo/html/xslt20/index.html
See: http://www.filigris.com/docflex-xml/LiquidXML/demo/html/XMLSchema/index.html
Concerning what all those diagrams depict... Essentially, they are all about content model of XSD elements (as well as other XSD components that lead to elements: complexTypes, element/attribute groups). It seems, there are two approaches here:
I personally believe that the diagrams generated by XMLSpy are more useful.
Yet, there were no attempts so far (at least known to me) to depict graphically anything else contained in XML schemas, although one can imagine many...
I found AlecRust's solution quite helpful, but I add something to resolve one problem: When you click on a single accordion to expand it and then you click on the button to expand, they will all be opened. But, if you click again on the button to collapse, the single accordion expand before won't be collapse.
I've used imageButton, but you can also apply that logic to buttons.
/*** Expand all ***/
$(".expandAll").click(function (event) {
$('.accordion .ui-accordion-header:not(.ui-state-active)').next().slideDown();
return false;
});
/*** Collapse all ***/
$(".collapseAll").click(function (event) {
$('.accordion').accordion({
collapsible: true,
active: false
});
$('.accordion .ui-accordion-header').next().slideUp();
return false;
});
Also, if you have accordions inside an accordion and you want to expand all only on that second level, you can add a query:
/*** Expand all Second Level ***/
$(".expandAll").click(function (event) {
$('.accordion .ui-accordion-header:not(.ui-state-active)').nextAll(':has(.accordion .ui-accordion-header)').slideDown();
return false;
});
This thread is old but since no one posted about require.context I'm going to mention it:
You can use require.context to set the folder to look through like this:
var req = require.context('../../mydir/', true)
// true here is for use subdirectories, you can also specify regex as third param
return req('./myfile.js')
This can also be used
$('#name2').change(function(){
$('#name').val('');//You can set the first value of first one if that is not empty
});
$('#name').change(function(){
$('#name2').val('');
});
Reading Data From The Console
BufferedReader
is synchronized, so read operations on a BufferedReader can be safely done from multiple threads. The buffer size may be specified, or the default size(8192) may be used. The default is large enough for most purposes.
readLine() « just reads data line by line from the stream or source. A line is considered to be terminated by any one these: \n, \r (or) \r\n
Scanner
breaks its input into tokens using a delimiter pattern, which by default matches whitespace(\s) and it is recognised by Character.isWhitespace
.
« Until the user enters data, the scanning operation may block, waiting for input. « Use Scanner(BUFFER_SIZE = 1024) if you want to parse a specific type of token from a stream. « A scanner however is not thread safe. It has to be externally synchronized.
next() « Finds and returns the next complete token from this scanner. nextInt() « Scans the next token of the input as an int.
Code
String name = null;
int number;
java.io.BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
name = in.readLine(); // If the user has not entered anything, assume the default value.
number = Integer.parseInt(in.readLine()); // It reads only String,and we need to parse it.
System.out.println("Name " + name + "\t number " + number);
java.util.Scanner sc = new Scanner(System.in).useDelimiter("\\s");
name = sc.next(); // It will not leave until the user enters data.
number = sc.nextInt(); // We can read specific data.
System.out.println("Name " + name + "\t number " + number);
// The Console class is not working in the IDE as expected.
java.io.Console cnsl = System.console();
if (cnsl != null) {
// Read a line from the user input. The cursor blinks after the specified input.
name = cnsl.readLine("Name: ");
System.out.println("Name entered: " + name);
}
Reader Input: Output:
Yash 777 Line1 = Yash 777
7 Line1 = 7
Scanner Input: Output:
Yash 777 token1 = Yash
token2 = 777
I prefer to stop the MongoDB server using the port
command itself.
sudo port unload mongodb
And to start it again.
sudo port load mongodb
Aggregation and composition are terms that most people in the OO world have acquired via UML. And UML does a very poor job at defining these terms, as has been demonstrated by, for example, Henderson-Sellers and Barbier ("What is This Thing Called Aggregation?", "Formalization of the Whole-Part Relationship in the Unified Modeling Language"). I don't think that a coherent definition of aggregation and composition can be given if you are interested in being UML-compliant. I suggest you look at the cited works.
Regarding dependency, that's a highly abstract relationship between types (not objects) that can mean almost anything.
This is a good way of counting entries within .pivot_table
:
df2.pivot_table(values='X', index=['Y','Z'], columns='X', aggfunc='count')
X1 X2
Y Z
Y1 Z1 1 1
Z2 1 NaN
Y2 Z3 1 NaN
class FormClass(forms.ModelForm):
class Meta:
model = Book
fields = '__all__'
widgets = {
'field_name': forms.TextInput(attrs={'placeholder': 'Type placeholder text here..'}),
}
I resolved this by editing the svg file too.
I wrapped the xml of the whole svg graphic in a group tag that has a click event as follows:
<svg .....>
<g id="thefix" onclick="window.top.location.href='http://www.google.com/';">
<!-- ... your graphics ... -->
</g>
</svg>
Solution works in all browsers that support object svg script. (default a img tag inside your object element for browsers that don't support svg and you'll cover the gamut of browsers)
The formula
=OFFSET(Sheet1!$A$1,MOD(ROW()-1,COUNT(Sheet1!$A$1:$A$20000)),
(ROW()-1)/COUNT(Sheet1!$A$1:$A$20000))
placed into each cell of your second workbook will retrieve the appropriate cell from the source sheet. No macros, simple copying from one sheet to another to reformat the results.
You will need to modify the ranges in the COUNT function to match the maximum number of rows in the source sheet. Adjust for column headers as required.
If you need something other than a 0 for empty cells, you may prefer to include a conditional.
A script to reformat the data may well be more efficient, but 20k rows is no longer a real limit in a modern Excel workbook.
try this=> numpy.array(r) or numpy.array(yourvariable) followed by the command to compare whatever you wish to.
It is not good to use this method but if you really want to split it with regex
<primaryAddress.*>((.|\n)*?)<\/primaryAddress>
the verified answer returns the tags but this just return the value between tags.
You declare a delegate for the parameters:
public enum MyEvents { Event1 }
public delegate void MyEventHandler(MyEvents e);
public static event MyEventHandler EventTriggered;
Although all events in the framework takes a parameter that is or derives from EventArgs
, you can use any parameters you like. However, people are likely to expect the pattern used in the framework, which might make your code harder to follow.
Like said in docs, use
<meta property="og:url" content="http://www.your-domain.com/your-page.html" />
<meta property="og:type" content="website" />
<meta property="og:title" content="Your Website Title" />
<meta property="og:description" content="Your description" />
<meta property="og:image" content="http://www.your-domain.com/path/image.jpg" />
image size recommended: 1 200 x 630
The word "canonical" is just a synonym for "standard" or "usual". It doesn`t have any Java-specific meaning.
Super-brief summary from what Professor Brasilford explains in this video.
Turing Complete ? do anything that a Turing Machine can do.
It has conditional branching (i.e. "if statement"). Also, implies "go to" and thus permitting loop.
It has arbitrary amount of memory (e.g. long enough tape) that the program needs.
Just in case if anyone is interested in labeling horizontal barplot graph, I modified Sharon's answer as below:
def show_values_on_bars(axs, h_v="v", space=0.4):
def _show_on_single_plot(ax):
if h_v == "v":
for p in ax.patches:
_x = p.get_x() + p.get_width() / 2
_y = p.get_y() + p.get_height()
value = int(p.get_height())
ax.text(_x, _y, value, ha="center")
elif h_v == "h":
for p in ax.patches:
_x = p.get_x() + p.get_width() + float(space)
_y = p.get_y() + p.get_height()
value = int(p.get_width())
ax.text(_x, _y, value, ha="left")
if isinstance(axs, np.ndarray):
for idx, ax in np.ndenumerate(axs):
_show_on_single_plot(ax)
else:
_show_on_single_plot(axs)
Two parameters explained:
h_v
- Whether the barplot is horizontal or vertical. "h"
represents the horizontal barplot, "v"
represents the vertical barplot.
space
- The space between value text and the top edge of the bar. Only works for horizontal mode.
Example:
show_values_on_bars(sns_t, "h", 0.3)
Instead of formatting namenode, may be you can use the below command to restart the namenode. It worked for me:
sudo service hadoop-master restart
So there is two ways to pass values from fragment/activity to dialog fragment:-
Create dialog fragment object with make setter method and pass value/argument.
Pass value/argument through bundle.
// Fragment or Activity
@Override
public void onClick(View v) {
DialogFragmentWithSetter dialog = new DialogFragmentWithSetter();
dialog.setValue(header, body);
dialog.show(getSupportFragmentManager(), "DialogFragmentWithSetter");
}
// your dialog fragment
public class MyDialogFragment extends DialogFragment {
String header;
String body;
public void setValue(String header, String body) {
this.header = header;
this.body = body;
}
// use above variable into your dialog fragment
}
Note:- This is not best way to do
// Fragment or Activity
@Override
public void onClick(View v) {
DialogFragmentWithSetter dialog = new DialogFragmentWithSetter();
Bundle bundle = new Bundle();
bundle.putString("header", "Header");
bundle.putString("body", "Body");
dialog.setArguments(bundle);
dialog.show(getSupportFragmentManager(), "DialogFragmentWithSetter");
}
// your dialog fragment
public class MyDialogFragment extends DialogFragment {
String header;
String body;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
header = getArguments().getString("header","");
body = getArguments().getString("body","");
}
}
// use above variable into your dialog fragment
}
Note:- This is the best way to do.
According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators.
Further to this, if you're using a code style check such as pycodestyle, the next logical line needs to have different indentation to your code block.
For example:
if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
here_is_another_long_identifier != and_finally_another_long_name):
# ... your code here ...
pass
repalce content with the CSS
h1{ font-size: 0px;}
h1:after {
content: "new content";
font-size: 15px;
}
To answer this question from my understanding...
An authentication system that uses REST so that you do not need to actually track or manage the users in your system. This is done by using the HTTP methods POST, GET, PUT, DELETE. We take these 4 methods and think of them in terms of database interaction as CREATE, READ, UPDATE, DELETE (but on the web we use POST and GET because that is what anchor tags support currently). So treating POST and GET as our CREATE/READ/UPDATE/DELETE (CRUD) then we can design routes in our web application that will be able to deduce what action of CRUD we are achieving.
For example, in a Ruby on Rails application we can build our web app such that if a user who is logged in visits http://store.com/account/logout then the GET of that page can viewed as the user attempting to logout. In our rails controller we would build an action in that logs the user out and sends them back to the home page.
A GET on the login page would yield a form. a POST on the login page would be viewed as a login attempt and take the POST data and use it to login.
To me, it is a practice of using HTTP methods mapped to their database meaning and then building an authentication system with that in mind you do not need to pass around any session id's or track sessions.
I'm still learning -- if you find anything I have said to be wrong please correct me, and if you learn more post it back here. Thanks.
Try this
boxValue = boxValue.replace(/[^0-9\.]/g,"");
This Regular Expression will allow only digits and dots in the value of text box.
Expanding on Adis H's example to include the null case (got bit on this one)
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings["HostName"] != null)
config.AppSettings.Settings["HostName"].Value = hostName;
else
config.AppSettings.Settings.Add("HostName", hostName);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
From PHP's manual :
Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported.
So you have it. The error message is not really helpful, I give you that though.
PHP7 introduced more function data type declarations, and the aforementioned link has been moved to Function arguments : Type declarations. From that page :
Valid types
Warning
Aliases for the above scalar types are not supported. Instead, they are treated as class or interface names. For example, using boolean as a parameter or return type will require an argument or return value that is an instanceof the class or interface boolean, rather than of type bool:
<?php function test(boolean $param) {} test(true); ?>
The above example will output:
Fatal error: Uncaught TypeError: Argument 1 passed to test() must be an instance of boolean, boolean given, called in - on line 1 and defined in -:1
The last warning is actually significant to understand the error "Argument must of type string, string given"; since mostly only class/interface names are allowed as argument type, PHP tries to locate a class name "string", but can't find any because it is a primitive type, thus fail with this awkward error.
You just needed to cast the unsigned char
into a char
as the string
class doesn't have a constructor that accepts unsigned char
:
unsigned char* uc;
std::string s( reinterpret_cast< char const* >(uc) ) ;
However, you will need to use the length argument in the constructor if your byte array contains nulls, as if you don't, only part of the array will end up in the string (the array up to the first null)
size_t len;
unsigned char* uc;
std::string s( reinterpret_cast<char const*>(uc), len ) ;
Your server process has received a SIGPIPE
writing to a socket. This usually happens when you write to a socket fully closed on the other (client) side. This might be happening when a client program doesn't wait till all the data from the server is received and simply closes a socket (using close
function).
In a C program you would normally try setting to ignore SIGPIPE
signal or setting a dummy signal handler for it. In this case a simple error will be returned when writing to a closed socket. In your case a python seems to throw an exception that can be handled as a premature disconnect of the client.
We have tried custom search box with the pasted snippet. This code will useful for all kind of TextFiled
decoration in Flutter. Hope this snippet will helpful for others.
Container(
margin: EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 10.0),
child: new Theme(
data: new ThemeData(
hintColor: Colors.white,
primaryColor: Colors.white,
primaryColorDark: Colors.white,
),
child:Padding(
padding: EdgeInsets.all(10.0),
child: TextField(
style: TextStyle(color: Colors.white),
onChanged: (value) {
filterSearchResults(value);
},
controller: editingController,
decoration: InputDecoration(
labelText: "Search",
hintText: "Search",
prefixIcon: Icon(Icons.search,color: Colors.white,),
enabled: true,
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.white),
borderRadius: BorderRadius.all(Radius.circular(25.0))),
border: OutlineInputBorder(
borderSide: const BorderSide(color: Colors.white, width: 0.0),
borderRadius: BorderRadius.all(Radius.circular(25.0)))),
),
),
),
),
Yet another node based simple command line server
https://github.com/greggman/servez-cli
Written partly in response to http-server having issues, particularly on windows.
Install node.js then
npm install -g servez
servez [options] [path]
With no path it serves the current folder.
By default it serves index.html
for folder paths if it exists. It serves a directory listing for folders otherwise. It also serves CORS headers. You can optionally turn on basic authentication with --username=somename --password=somepass
and you can serve https.
There are a couple of important things to know about bash's [[ ]]
construction. The first:
Word splitting and pathname expansion are not performed on the words between the
[[
and]]
; tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal are performed.
The second thing:
An additional binary operator, ‘=~’, is available,... the string to the right of the operator is considered an extended regular expression and matched accordingly... Any part of the pattern may be quoted to force it to be matched as a string.
Consequently, $v
on either side of the =~
will be expanded to the value of that variable, but the result will not be word-split or pathname-expanded. In other words, it's perfectly safe to leave variable expansions unquoted on the left-hand side, but you need to know that variable expansions will happen on the right-hand side.
So if you write: [[ $x =~ [$0-9a-zA-Z] ]]
, the $0
inside the regex on the right will be expanded before the regex is interpreted, which will probably cause the regex to fail to compile (unless the expansion of $0
ends with a digit or punctuation symbol whose ascii value is less than a digit). If you quote the right-hand side like-so [[ $x =~ "[$0-9a-zA-Z]" ]]
, then the right-hand side will be treated as an ordinary string, not a regex (and $0
will still be expanded). What you really want in this case is [[ $x =~ [\$0-9a-zA-Z] ]]
Similarly, the expression between the [[
and ]]
is split into words before the regex is interpreted. So spaces in the regex need to be escaped or quoted. If you wanted to match letters, digits or spaces you could use: [[ $x =~ [0-9a-zA-Z\ ] ]]
. Other characters similarly need to be escaped, like #
, which would start a comment if not quoted. Of course, you can put the pattern into a variable:
pat="[0-9a-zA-Z ]"
if [[ $x =~ $pat ]]; then ...
For regexes which contain lots of characters which would need to be escaped or quoted to pass through bash's lexer, many people prefer this style. But beware: In this case, you cannot quote the variable expansion:
# This doesn't work:
if [[ $x =~ "$pat" ]]; then ...
Finally, I think what you are trying to do is to verify that the variable only contains valid characters. The easiest way to do this check is to make sure that it does not contain an invalid character. In other words, an expression like this:
valid='0-9a-zA-Z $%&#' # add almost whatever else you want to allow to the list
if [[ ! $x =~ [^$valid] ]]; then ...
!
negates the test, turning it into a "does not match" operator, and a [^...]
regex character class means "any character other than ...
".
The combination of parameter expansion and regex operators can make bash regular expression syntax "almost readable", but there are still some gotchas. (Aren't there always?) One is that you could not put ]
into $valid
, even if $valid
were quoted, except at the very beginning. (That's a Posix regex rule: if you want to include ]
in a character class, it needs to go at the beginning. -
can go at the beginning or the end, so if you need both ]
and -
, you need to start with ]
and end with -
, leading to the regex "I know what I'm doing" emoticon: [][-]
)
It's not that much work to make a function that's allocating the needed memory for your string. That's a little c-function i wrote some time ago, i always use it to read in strings.
It will return the read string or if a memory error occurs NULL. But be aware that you have to free() your string and always check for it's return value.
#define BUFFER 32
char *readString()
{
char *str = malloc(sizeof(char) * BUFFER), *err;
int pos;
for(pos = 0; str != NULL && (str[pos] = getchar()) != '\n'; pos++)
{
if(pos % BUFFER == BUFFER - 1)
{
if((err = realloc(str, sizeof(char) * (BUFFER + pos + 1))) == NULL)
free(str);
str = err;
}
}
if(str != NULL)
str[pos] = '\0';
return str;
}
I believe java gleans this from the environment variables in which it was launched, so you'll need to make sure your LANG and LC_* environment variables are set appropriately.
The locale manpage has full info on said environment variables.
I got the same error while using other one entity, He was annotating the class wrongly by using the table name inside the @Entity annotation without using the @Table annotation
The correct format should be
@Entity //default name similar to class name 'FooBar' OR @Entity( name = "foobar" ) for differnt entity name
@Table( name = "foobar" ) // Table name
public class FooBar{
Actually your $product
has no data because the Eloquent
model returns NULL. It's probably because you have used whereOwnerAndStatus
which seems wrong and if there were data in $product
then it would not work in your first example because get()
returns a collection of multiple models but that is not the case. The second example throws error because foreach
didn't get any data. So I think it should be something like this:
$owner = Input::get('owner');
$count = Input::get('count');
$products = Product::whereOwner($owner, 0)->take($count)->get();
Further you may also make sure if $products
has data:
if($product) {
return View:make('viewname')->with('products', $products);
}
Then in the view
:
foreach ($products as $product) {
// If Product has sku (collection object, probably related models)
foreach ($product->sku as $sku) {
// Code Here
}
}
The only real use case for GROUP BY without aggregation is when you GROUP BY more columns than are selected, in which case the selected columns might be repeated. Otherwise you might as well use a DISTINCT.
It's worth noting that other RDBMS's do not require that all non-aggregated columns be included in the GROUP BY. For example in PostgreSQL if the primary key columns of a table are included in the GROUP BY then other columns of that table need not be as they are guaranteed to be distinct for every distinct primary key column. I've wished in the past that Oracle did the same as it would have made for more compact SQL in many cases.
Maybe not as elegant but another possibility would be to write a formula to do the check and fill it in an adjacent column. You could then filter on that column.
The following looks in cell b14 and would return true for all the file types you mention. This assumes that the file extension is by itself in the column. If it's not it would be a little more complicated but you could still do it this way.
=OR(B14=".pdf",B14=".doc",B14=".docx",B14=".xls",B14=".xlsx",B14=".rtf",B14=".txt",B14=".csv",B14=".pps")
Like I said, not as elegant as the advanced filters but options are always good.
If you need something to be able to added dynamically, c# attributes aren't the way. Look into storing the data in xml. I recently did a project that i started w/ attributes, but eventually moved to serialization w/ xml.
The problem in your code is that you can't store the memory address of a local variable (local to a function, for example) in a globlar variable:
RectInvoice rect(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(&rect);
There, &rect
is a temporary address (stored in the function's activation registry) and will be destroyed when that function end.
The code should create a dynamic variable:
RectInvoice *rect = new RectInvoice(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(rect);
There you are using a heap address that will not be destroyed in the end of the function's execution. Tell me if it worked for you.
Cheers
I agree with the current answers, I just wanna add little more information, Here's a good functionality
if you want to require just zip file but the owner has not prepared a zip file,
To simply download a repository as a zip file: add the extra path /zipball/master/ to the end of the repository URL, This will give you a full ZIP file
For example, here is your repository
https://github.com/spring-projects/spring-data-graph-examples
Add zipball/master/ in your repository link
https://github.com/spring-projects/spring-data-graph-examples/zipball/master/
Paste the URL into your browser and it will give you a zip file to download
If you are facing an error like that on new MacOS version.
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun
It means that you need to install XCode command line, open a Terminal and run this command:
$ xcode-select --install
Get all classes by part of Namespace name in just one row:
var allClasses = Assembly.GetExecutingAssembly().GetTypes().Where(a => a.IsClass && a.Namespace != null && a.Namespace.Contains(@"..your namespace...")).ToList();
You can just call it.
function test(){
print_r(func_get_args());
}
test("blah");
test("blah","blah");
Output:
Array ( [0] => blah ) Array ( [0] => blah [1] => blah )
If you are given this format it takes like a link to another page or another link.partial view majorly used for renduring the html files from one place to another.
I don't know I used random.shuffle()
but it return 'None' to me, so I wrote this, might helpful to someone
def shuffle(arr):
for n in range(len(arr) - 1):
rnd = random.randint(0, (len(arr) - 1))
val1 = arr[rnd]
val2 = arr[rnd - 1]
arr[rnd - 1] = val1
arr[rnd] = val2
return arr
An md5 encryption is one of the worst, because you have to turn the code and it is already decrypted. I would recommend you the SHA256. I'm programming a bit longer and have had a good experience. Below would also be an encryption.
password_hash() example using Argon2i
<?php
echo 'Argon2i hash: ' . password_hash('rasmuslerdorf', PASSWORD_ARGON2I);
?>
The above example will output something similar to:
Argon2i hash: $argon2i$v=19$m=1024,t=2,p=2$YzJBSzV4TUhkMzc3d3laeg$zqU/1IN0/AogfP4cmSJI1vc8lpXRW9/S0sYY2i2jHT0
How does the server know that it should pull image.png from the /pictures folder when you visit the website and browse to the /system/files/images folder in your web browser? A so-called symbolic link is the guy that is responsible for this behavior. Somewhere in your system, there is a symlink that tells your server "If a visitor requests /system/files/images/image.png then show him /pictures/image.png."
And what is the role of the FollowSymLinks setting in this?
FollowSymLinks relates to server security. When dealing with web servers, you can't just leave things undefined. You have to tell who has access to what. The FollowSymLinks setting tells your server whether it should or should not follow symlinks. In other words, if FollowSymLinks was disabled in our case, browsing to the /system/files/images/image.png file would return depending on other settings either the 403 (access forbidden) or 404 (not found) error.
You can use Manifold's @Jailbreak for direct, type-safe Java reflection:
@Jailbreak Foo foo = new Foo();
foo.callMe();
public class Foo {
private void callMe();
}
@Jailbreak
unlocks the foo
local variable in the compiler for direct access to all the members in Foo
's hierarchy.
Similarly you can use the jailbreak() extension method for one-off use:
foo.jailbreak().callMe();
Through the jailbreak()
method you can access any member in Foo
's hierarchy.
In both cases the compiler resolves the method call for you type-safely, as if a public method, while Manifold generates efficient reflection code for you under the hood.
Alternatively, if the type is not known statically, you can use Structural Typing to define an interface a type can satisfy without having to declare its implementation. This strategy maintains type-safety and avoids performance and identity issues associated with reflection and proxy code.
Discover more about Manifold.
to_char(tran_date, 'yyyy-mm-dd') = to_char(sysdate-1, 'yyyy-mm-dd')
This is answered in the documentation:
Where MySQL Stores Temporary Files
On Unix, MySQL uses the value of the TMPDIR environment variable as the path name of the directory in which to store temporary files. If TMPDIR is not set, MySQL uses the system default, which is usually /tmp, /var/tmp, or /usr/tmp.
On Windows, Netware and OS2, MySQL checks in order the values of the TMPDIR, TEMP, and TMP environment variables. For the first one found to be set, MySQL uses it and does not check those remaining. If none of TMPDIR, TEMP, or TMP are set, MySQL uses the Windows system default, which is usually C:\windows\temp.
you dont need to change your JSON format.
replace:
console.log(data.phones.length);
with:
console.log( Object.keys( data.phones ).length ) ;
import java.io.IOException;
class Super {
protected Super getClassName(Super s) throws IOException {
System.out.println(this.getClass().getSimpleName() + " - I'm parent");
return null;
}
}
class SubOne extends Super {
@Override
protected Super getClassName(Super s) {
System.out.println(this.getClass().getSimpleName() + " - I'm Perfect Overriding");
return null;
}
}
class SubTwo extends Super {
@Override
protected Super getClassName(Super s) throws NullPointerException {
System.out.println(this.getClass().getSimpleName() + " - I'm Overriding and Throwing Runtime Exception");
return null;
}
}
class SubThree extends Super {
@Override
protected SubThree getClassName(Super s) {
System.out.println(this.getClass().getSimpleName()+ " - I'm Overriding and Returning SubClass Type");
return null;
}
}
class SubFour extends Super {
@Override
protected Super getClassName(Super s) throws IOException {
System.out.println(this.getClass().getSimpleName()+ " - I'm Overriding and Throwing Narrower Exception ");
return null;
}
}
class SubFive extends Super {
@Override
public Super getClassName(Super s) {
System.out.println(this.getClass().getSimpleName()+ " - I'm Overriding and have broader Access ");
return null;
}
}
class SubSix extends Super {
public Super getClassName(Super s, String ol) {
System.out.println(this.getClass().getSimpleName()+ " - I'm Perfect Overloading ");
return null;
}
}
class SubSeven extends Super {
public Super getClassName(SubSeven s) {
System.out.println(this.getClass().getSimpleName()+ " - I'm Perfect Overloading because Method signature (Argument) changed.");
return null;
}
}
public class Test{
public static void main(String[] args) throws Exception {
System.out.println("Overriding\n");
Super s1 = new SubOne(); s1.getClassName(null);
Super s2 = new SubTwo(); s2.getClassName(null);
Super s3 = new SubThree(); s3.getClassName(null);
Super s4 = new SubFour(); s4.getClassName(null);
Super s5 = new SubFive(); s5.getClassName(null);
System.out.println("Overloading\n");
SubSix s6 = new SubSix(); s6.getClassName(null, null);
s6 = new SubSix(); s6.getClassName(null);
SubSeven s7 = new SubSeven(); s7.getClassName(s7);
s7 = new SubSeven(); s7.getClassName(new Super());
}
}
The reason is your base class is not public-ed, then Mockito cannot intercept it due to visibility, if you change base class as public, or @Override in sub class (as public), then Mockito can mock it correctly.
public class BaseService{
public boolean foo(){
return true;
}
}
public ChildService extends BaseService{
}
@Test
@Mock ChildService childService;
public void testSave() {
Mockito.when(childService.foo()).thenReturn(false);
// When
assertFalse(childService.foo());
}
In Python, Storing a bare python list as a numpy.array and then saving it out to file, then loading it back, and converting it back to a list takes some conversion tricks. The confusion is because python lists are not at all the same thing as numpy.arrays:
import numpy as np
foods = ['grape', 'cherry', 'mango']
filename = "./outfile.dat.npy"
np.save(filename, np.array(foods))
z = np.load(filename).tolist()
print("z is: " + str(z))
This prints:
z is: ['grape', 'cherry', 'mango']
Which is stored on disk as the filename: outfile.dat.npy
The important methods here are the tolist()
and np.array(...)
conversion functions.
getline(fin, buffer, '\n')
where fin
is opened file(ifstream object) and buffer
is of string/char
type where you want to copy line.
I don't have to many bulky code to give out just a little snippet solved the issue for me.
i have https://example.com/entitlements/index.php rather i want anyone that types it to get error on request event if you type https://example.com/entitlements/index you will still get error since there's this word "index" is contained there will always be an error thrown back though the content of index.php will still be displayed properly
cletus post on "https://stackoverflow.com/a/1055655/12192635" which solved it
Edit your .htaccess file with the below to redirect people visiting https://example.com/entitlements/index.php to 404 page
RewriteCond %{THE_REQUEST} \.php[\ /?].*HTTP/
RewriteRule ^.*$ - [R=404,L]
to redirect people visiting https://example.com/entitlements/index to 404 page
RewriteCond %{THE_REQUEST} \index[\ /?].*HTTP/
RewriteRule ^.*$ - [R=404,L]
Not withstanding we have already known that the above code works with already existing codes on stack see where i applied the code above just below the all codes at it end.
# The following will allow you to use URLs such as the following:
#
# example.com/anything
# example.com/anything/
#
# Which will actually serve files such as the following:
#
# example.com/anything.html
# example.com/anything.php
#
# But *only if they exist*, otherwise it will report the usual 404 error.
Options +FollowSymLinks
RewriteEngine On
# Remove trailing slashes.
# e.g. example.com/foo/ will redirect to example.com/foo
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [R=permanent,QSA]
# Redirect to HTML if it exists.
# e.g. example.com/foo will display the contents of example.com/foo.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.+)$ $1.html [L,QSA]
# Redirect to PHP if it exists.
# e.g. example.com/foo will display the contents of example.com/foo.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)$ $1.php [L,QSA]
RewriteCond %{THE_REQUEST} \.php[\ /?].*HTTP/
RewriteRule ^.*$ - [R=404,L]
RewriteCond %{THE_REQUEST} \index[\ /?].*HTTP/
RewriteRule ^.*$ - [R=404,L]
GAC (Global Assembly Cache) is where all shared .NET assembly reside.
echo "12|23|11" | awk '{split($0,a,"|"); print a[3] a[2] a[1]}'
should work.
/* 1 */ Foo* foo1 = new Foo ();
Creates an object of type Foo
in dynamic memory. foo1
points to it. Normally, you wouldn't use raw pointers in C++, but rather a smart pointer. If Foo
was a POD-type, this would perform value-initialization (it doesn't apply here).
/* 2 */ Foo* foo2 = new Foo;
Identical to before, because Foo
is not a POD type.
/* 3 */ Foo foo3;
Creates a Foo
object called foo3
in automatic storage.
/* 4 */ Foo foo4 = Foo::Foo();
Uses copy-initialization to create a Foo
object called foo4
in automatic storage.
/* 5 */ Bar* bar1 = new Bar ( *new Foo() );
Uses Bar
's conversion constructor to create an object of type Bar
in dynamic storage. bar1
is a pointer to it.
/* 6 */ Bar* bar2 = new Bar ( *new Foo );
Same as before.
/* 7 */ Bar* bar3 = new Bar ( Foo foo5 );
This is just invalid syntax. You can't declare a variable there.
/* 8 */ Bar* bar3 = new Bar ( Foo::Foo() );
Would work and work by the same principle to 5 and 6 if bar3
wasn't declared on in 7.
5 & 6 contain memory leaks.
Syntax like new Bar ( Foo::Foo() );
is not usual. It's usually new Bar ( (Foo()) );
- extra parenthesis account for most-vexing parse. (corrected)
// Get the url from the Settings of the table: oSettings.sAjaxSource
function refreshTable(oTable) {
table = oTable.dataTable();
oSettings = table.fnSettings();
//Retrieve the new data with $.getJSON. You could use it ajax too
$.getJSON(oSettings.sAjaxSource, null, function( json ) {
table.fnClearTable(this);
for (var i=0; i<json.aaData.length; i++) {
table.oApi._fnAddData(oSettings, json.aaData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
table.fnDraw();
});
}
The size of the pointer may be something different than that of int
. Also an implementation could produce better than simple hex value representation of the address when you use %p
.
All a [self.navigationController pushViewController:controller animated:YES];
does is animate a transition, and add it to the navigation controller stack, and some other cool navigation bar animation stuffs. If you don't care about the bar animation, then this code should work. The bar does appear on the new controller, and you get an interactive pop gesture!
//Make Controller
DetailViewController *controller = [[DetailViewController alloc] initWithNibName:nil
bundle:[NSBundle mainBundle]];
//Customize presentation
controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
controller.modalPresentationStyle = UIModalPresentationCurrentContext;
//Present controller
[self presentViewController:controller
animated:YES
completion:nil];
//Add to navigation Controller
[self navigationController].viewControllers = [[self navigationController].viewControllers arrayByAddingObject:controller];
//You can't just [[self navigationController].viewControllers addObject:controller] because viewControllers are for some reason not a mutable array.
Edit: Sorry, presentViewController will fill the full screen. You will need to make a custom transition, with CGAffineTransform.translation or something, animate the controller with the transition, then add it to the navigationController's viewControllers.
I haven't tested on other Laravel versions but on 5.3-5.8 you reference the query parameter as if it were a member of the Request
class
.
http://example.com/path?page=2
Route::get('/path', function(Request $request){
dd($request->page);
});
//or in your controller
public function foo(Request $request){
dd($request->page);
}
//NOTE: If you are wondering where the request instance is coming from, Laravel automatically injects the request instance from the IOC container
//output
"2"
We can also pass in a default value which is returned if a parameter doesn't exist. It's much cleaner than a ternary expression that you'd normally use with the request globals
//wrong way to do it in Laravel
$page = isset($_POST['page']) ? $_POST['page'] : 1;
//do this instead
$request->get('page', 1);
//returns page 1 if there is no page
//NOTE: This behaves like $_REQUEST array. It looks in both the
//request body and the query string
$request->input('page', 1);
$page = request('page', 1);
//returns page 1 if there is no page parameter in the query string
//it is the equivalent of
$page = 1;
if(!empty($_GET['page'])
$page = $_GET['page'];
The default parameter is optional therefore one can omit it
While the input method retrieves values from entire request payload (including the query string), the query method will only retrieve values from the query string
//this is the equivalent of retrieving the parameter
//from the $_GET global array
$page = $request->query('page');
//with a default
$page = $request->query('page', 1);
$page = Request::get('page');
//with a default value
$page = Request::get('page', 1);
You can read more in the official documentation https://laravel.com/docs/5.8/requests
It's basically 2 step process:
First, you need to stringify like this:
var JSON_VAR = JSON.stringify(OBJECT_NAME, null, 2);
After that, you need to convert the string
to Object
:
var obj = JSON.parse(JSON_VAR);
Basically there are three ways without iterating manually,
1 Using constructor
ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = new ArrayList<Dog>(dogs);
2 Using addAll(Collection<? extends E> c)
ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = new ArrayList<Dog>();
clonedList.addAll(dogs);
3 Using addAll(int index, Collection<? extends E> c)
method with int
parameter
ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = new ArrayList<Dog>();
clonedList.addAll(0, dogs);
NB : The behavior of these operations will be undefined if the specified collection is modified while the operation is in progress.
Jeffrey Richter recommends following:
public sealed class Singleton
{
private static readonly Object s_lock = new Object();
private static Singleton instance = null;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if(instance != null) return instance;
Monitor.Enter(s_lock);
Singleton temp = new Singleton();
Interlocked.Exchange(ref instance, temp);
Monitor.Exit(s_lock);
return instance;
}
}
}
I had tried all of the solutions on this page: refresh project, rebuild, all projects clean, restart Eclipse, re-import (even) the projects, rebuild maven and refresh. Nothing worked. What did work was copying the class to a new name which runs fine -- bizarre but true.
After putting up with this for some time, I just fixed it by:
Run
menuRun Configurations
Run Configuration
by pressing delete or clicking the red X.Something must have been screwed up with the cached run configuration.
You could use the Get
method and check for null
as the method will return null
if the NameValueCollection does not contain the specified key.
See MSDN.
I did this;
In controller:
public ActionResult Index()
{
var invoices = db.Invoices;
var categories = db.Categories.ToList();
ViewData["MyData"] = categories; // Send this list to the view
return View(invoices.ToList());
}
In view:
@model IEnumerable<abc.Models.Invoice>
@{
ViewBag.Title = "Invoices";
}
@{
var categories = (List<Category>) ViewData["MyData"]; // Cast the list
}
@foreach (var c in @categories) // Print the list
{
@Html.Label(c.Name);
}
<table>
...
@foreach (var item in Model)
{
...
}
</table>
Hope it helps
I thought this might be useful when using bootstrap and some glypicons:
<a class="btn btn-primary"
href="<%: Url.Action("Download File", "Download",
new { id = msg.Id, distributorId = msg.DistributorId }) %>">
Download
<span class="glyphicon glyphicon-paperclip"></span>
</a>
This will show an A tag, with a link to a controller, with a nice paperclip icon on it to represent a download link, and the html output is kept clean
First, as for your Athlete class, you can remove your Getter and Setter
methods since you have declared your instance variables with an access modifier of public
. You can access the variables via <ClassName>.<variableName>
.
However, if you really want to use that Getter and Setter
, change the public
modifier to private
instead.
Second, for the constructor, you're trying to do a simple technique called shadowing
. Shadowing
is when you have a method having a parameter with the same name as the declared variable. This is an example of shadowing
:
----------Shadowing sample----------
You have the following class:
public String name;
public Person(String name){
this.name = name; // This is Shadowing
}
In your main method for example, you instantiate the Person
class as follow:
Person person = new Person("theolc");
Variable name
will be equal to "theolc"
.
----------End of shadowing----------
Let's go back to your question, if you just want to print the first element with your current code, you may remove the Getter and Setter
. Remove your parameters on your constructor
.
public class Athlete {
public String[] name = {"Art", "Dan", "Jen"};
public String[] country = {"Canada", "Germany", "USA"};
public Athlete() {
}
In your main method, you could do this.
public static void main(String[] args) {
Athlete art = new Athlete();
System.out.println(art.name[0]);
System.out.println(art.country[0]);
}
}
//load css first, then print <link> to header, and execute callback
//just set var href above this..
$.ajax({
url: href,
dataType: 'css',
success: function(){
$('<link rel="stylesheet" type="text/css" href="'+href+'" />').appendTo("head");
//your callback
}
});
For Jquery 1.2.6 and above ( omitting the fancy attributes functions above ).
I am doing it this way because I think that this will ensure that your requested stylesheet is loaded by ajax before you try to stick it into the head. Therefore, the callback is executed after the stylesheet is ready.
Apart from price and features, the throughput also varies greatly (as mentioned by user1677120):
Taken from EBS docs:
| EBS volume | Throughput | Throughput |
| type | MiB/s | dependent on.. |
|------------|------------|-------------------------------|
| gp2 (SSD) | 128-160 | volume size |
| io1 (SSD) | 0.25-500 | IOPS (256Kib/s per IOPS) |
| st1 (HDD) | 20-500 | volume size (40Mib/s per TiB) |
| sc1 (HDD) | 6-250 | volume size (12Mib/s per TiB) |
Note, that for io1, st1 and sc1 you can burst throughput traffic to at least 125Mib/s, but to 500Mib/s, depending on volume size.
You can further increase throughput by e.g. deploying EBS volumes as RAID0
Taken from EFS docs
| Filesystem | Base | Burst |
| Size | Throughput | Throughput |
| GiB | MiB/s | MiB/s |
|------------|------------|------------|
| 10 | 0.5 | 100 |
| 256 | 12.5 | 100 |
| 512 | 25.0 | 100 |
| 1024 | 50.0 | 100 |
| 1536 | 75.0 | 150 |
| 2048 | 100.0 | 200 |
| 3072 | 150.0 | 300 |
| 4096 | 200.0 | 400 |
The base throughput is guaranteed, burst throughput uses up credits you gathered while being below the base throughput (so you'll only have this for a limited time, see here for more details.
S3 is a total different thing, so it cannot really be compared to EBS and EFS. Plus: There are no published throughput metrics for S3. You can improve throughput by downloading in parallel (I somewhere read AWS states you would have basically unlimited throughput this way), or adding CloudFront to the mix
In your case(simple object):
useEffect(()=>{
// your logic
}, [rate, sendAmount, receiveAmount])
In other case(complex object)
const {cityInfo} = props;
useEffect(()=>{
// some logic
}, [cityInfo.cityId])
If you are using Eclipse Neon, try this:
1) Add the maven plugin in the properties section of the POM:
<properties>
<java.version>1.8</java.version>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
2) Force update of project snapshot by right clicking on Project
Maven -> Update Project -> Select your Project -> Tick on the 'Force Update of Snapshots/Releases' option -> OK
For raw files, you should consider creating a raw folder inside res directory and then call getResources().openRawResource(resourceName)
from your activity.
There is only workaround for the issue you are facing.
Check whether file id in process before starting the process of copy. You can call the following function until you get the False value.
1st Method, copied directly from this answer:
private bool IsFileLocked(FileInfo file)
{
FileStream stream = null;
try
{
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
return true;
}
finally
{
if (stream != null)
stream.Close();
}
//file is not locked
return false;
}
2nd Method:
const int ERROR_SHARING_VIOLATION = 32;
const int ERROR_LOCK_VIOLATION = 33;
private bool IsFileLocked(string file)
{
//check that problem is not in destination file
if (File.Exists(file) == true)
{
FileStream stream = null;
try
{
stream = File.Open(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (Exception ex2)
{
//_log.WriteLog(ex2, "Error in checking whether file is locked " + file);
int errorCode = Marshal.GetHRForException(ex2) & ((1 << 16) - 1);
if ((ex2 is IOException) && (errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION))
{
return true;
}
}
finally
{
if (stream != null)
stream.Close();
}
}
return false;
}
You have two options:
Extend your .paging
class definition:
.paging:hover {
border:1px solid #999;
color:#000;
}
Use the DOM hierarchy to apply the CSS style:
div.paginate input:hover {
border:1px solid #999;
color:#000;
}
Regarding the “summary” line (the 50 in your formula), the Linux kernel documentation has this to say:
For these reasons, the "summary" must be no more than 70-75
characters, and it must describe both what the patch changes, as well
as why the patch might be necessary. It is challenging to be both
succinct and descriptive, but that is what a well-written summary
should do.
That said, it seems like kernel maintainers do indeed try to keep things around 50. Here’s a histogram of the lengths of the summary lines in the git log for the kernel:
There is a smattering of commits that have summary lines that are longer (some much longer) than this plot can hold without making the interesting part look like one single line. (There’s probably some fancy statistical technique for incorporating that data here but oh well… :-)
If you want to see the raw lengths:
cd /path/to/repo
git shortlog | grep -e '^ ' | sed 's/[[:space:]]\+\(.*\)$/\1/' | awk '{print length($0)}'
or a text-based histogram:
cd /path/to/repo
git shortlog | grep -e '^ ' | sed 's/[[:space:]]\+\(.*\)$/\1/' | awk '{lens[length($0)]++;} END {for (len in lens) print len, lens[len] }' | sort -n
Don't serialize FormData
with POST
ing to server. Do this:
this.uploadFileToUrl = function(file, title, text, uploadUrl){
var payload = new FormData();
payload.append("title", title);
payload.append('text', text);
payload.append('file', file);
return $http({
url: uploadUrl,
method: 'POST',
data: payload,
//assign content-type as undefined, the browser
//will assign the correct boundary for us
headers: { 'Content-Type': undefined},
//prevents serializing payload. don't do it.
transformRequest: angular.identity
});
}
Then use it:
MyService.uploadFileToUrl(file, title, text, uploadUrl).then(successCallback).catch(errorCallback);
Here's a way to lazily evaluate the reverse using a generator:
def reverse(seq):
for x in range(len(seq), -1, -1): #Iterate through a sequence starting from -1 and increasing by -1.
yield seq[x] #Yield a value to the generator
Now iterate through like this:
for x in reverse([1, 2, 3]):
print(x)
If you need a list:
l = list(reverse([1, 2, 3]))
Eclipse is erroring because if you try and create a project on a directory that exists, Eclipse doesn't know if it's an actual project or not - so it errors, saving you from losing work!
So you have two solutions:
Move the folder counter_src
somewhere else, then create the project (which will create the directory), then import the source files back into the newly created counter_src
.
Right-click on the project explorer and import an existing project, select C:\Users\Martin\Java\Counter\
as your root directory. If Eclipse sees a project, you will be able to import it.
Absolutely the easiest way to see your indexed data is to view it in your browser. No downloads or installation needed.
I'm going to assume your elasticsearch host is http://127.0.0.1:9200
.
Step 1
Navigate to http://127.0.0.1:9200/_cat/indices?v
to list your indices. You'll see something like this:
Step 2
Try accessing the desired index:
http://127.0.0.1:9200/products_development_20160517164519304
The output will look something like this:
Notice the aliases
, meaning we can as well access the index at:
http://127.0.0.1:9200/products_development
Step 3
Navigate to http://127.0.0.1:9200/products_development/_search?pretty
to see your data:
'So from this discussion i am thinking this should be the code then.
Sub Button1_Click()
Dim excel As excel.Application
Dim wb As excel.Workbook
Dim sht As excel.Worksheet
Dim f As Object
Set f = Application.FileDialog(3)
f.AllowMultiSelect = False
f.Show
Set excel = CreateObject("excel.Application")
Set wb = excel.Workbooks.Open(f.SelectedItems(1))
Set sht = wb.Worksheets("Data")
sht.Activate
sht.Columns("A:G").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues
wb.Close
End Sub
'Let me know if this is correct or a step was missed. Thx.
Also, if you have Toad for Oracle, you can highlight the statement and press CTRL + F9 and you'll get a nice view of column and their datatypes.
You just add following lines of code in style.xml file
<style name="AppTheme.NoTitleBar" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
change apptheme in AndroidManifest.xml file
android:theme="@style/AppTheme.NoTitleBar"
The answer is CTRL + P (NOT CTRL + Q)
Someone else posted this answer on JetBrains forum: The idea is a different IDE. Try to discover its features and try to make the best of it, rather than trying to emulate whatever you used before. For the most part, Idea has very high usability (much better than Eclipse IMHO) and is streamlined for supporting code editing as best as possible (rather than relying on wizards too much for example).
... plus many more shortcuts to navigate in code and different idea views.
I think it rather nice that you can see just the specific bit of information you are interested in with a simple keystroke. Have a look at the menus which will also show the possibly modified shortcuts for your keymap.
0 Avatar Jens Voß Created June 12, 2008, 09:26 And, elsandros, in addition to what Stephen writes: Since you seem to be interested in IDEA's keyboard shortcuts, I highly recommend the "Key Promoter" plugin which helps you memorize the relevant shortcuts quickly.
Also very useful is the "Goto Action" feature, invoked by Ctrl-Shift-A. In the popup, you can enter a keyword (e.g. "Javadoc"), and the IDE tells you the available actions matching your search, along with keyboard shortcuts and the containing action groups (which often also give you a clue about how to navigate to the action using the menu).
Go to Tools >> Preferences >> IPython console >> Graphics >> Backend:Inline, change "Inline" to "Automatic", click "OK"
Reset the kernel at the console, and the plot will appear in a separate window
You will need to use strip()
because of the extra bits in the strings.
A2 = [float(x.strip('"')) for x in A1]
UPDATE: From .NET Version 4.6 use the FromUnixTimeMilliseconds method of the DateTimeOffset structure instead:
DateTimeOffset.FromUnixTimeMilliseconds(1310522400000).DateTime
This is the fastest way I have found, inspired by @divingTobi's answer. All The answers based on xlrd, openpyxl or pandas are slow for me, as they all load the whole file first.
from zipfile import ZipFile
from bs4 import BeautifulSoup # you also need to install "lxml" for the XML parser
with ZipFile(file) as zipped_file:
summary = zipped_file.open(r'xl/workbook.xml').read()
soup = BeautifulSoup(summary, "xml")
sheets = [sheet.get("name") for sheet in soup.find_all("sheet")]
ld
is trying to find libcrypto.so
which is not present as seen in your locate
output.
You can make a copy of the libcrypto.so.0.9.8
and name it as libcrypto.so
. Put this is your ld path. ( If you do not have root access then you can put it in a local path and specify the path manually )
My workaround since none of the above appear to work in Chrome 63 and beyond
I fixed this on my site by replacing the offending input element with
<p class="input" contenteditable="true"> </p>
and using jQuery to populate a hidden field prior to submission.
But this is a truly awful hack made necessary by a bad decision at Chromium.
For multiple interval types use a nested construction as in:
UPDATE table SET date = DATE_ADD(DATE_ADD(date, INTERVAL 1 YEAR), INTERVAL 1 DAY)
For updating a given date in the column date
to 1 year + 1 day
With recent versions of Matlab, you can use the Table data structure to your advantage. There's even a 'rowfun' operation but I found it easier just to do this:
a = magic(6);
incrementRow = cell2mat(cellfun(@(x) x+1,table2cell(table(a)),'UniformOutput',0))
or here's an older one I had that doesn't require tables, for older Matlab versions.
dataBinner = cell2mat(arrayfun(@(x) Binner(a(x,:),2)',1:size(a,1),'UniformOutput',0)')
index.html
<input id="suby" type="submit" value="Remove DUMMY"/>
myscripts.js
document.addEventListener("DOMContentLoaded", {
//Do this AFTER elements are loaded
document.getElementById("suby").addEventListener("click", e => {
document.getElementById("dummy").remove()
})
})
Import Reachable.h
class in your ViewController
, and use the following code to check connectivity:
#define hasInternetConnection [[Reachability reachabilityForInternetConnection] isReachable]
if (hasInternetConnection){
// To-do block
}
First, you can switch on an enum
in Java. I'm guessing you intended to say you can’t, but you can. char
s have a set range of values, so it's easy to compare. Strings can be anything.
A switch
statement is usually implemented as a jump table (branch table) in the underlying compilation, which is only possible with a finite set of values. C# can switch on strings, but it causes a performance decrease because a jump table cannot be used.
Java 7 and later supports String
switches with the same characteristics.
i am using v3.1.3 and i had to use data('DateTimePicker')
like this
var fromE = $( "#" + fromInput );
var toE = $( "#" + toInput );
$('.form-datepicker').datetimepicker(dtOpts);
$('.form-datepicker').on('change', function(e){
var isTo = $(this).attr('name') === 'to';
$( "#" + ( isTo ? fromInput : toInput ) )
.data('DateTimePicker')[ isTo ? 'setMaxDate' : 'setMinDate' ](moment($(this).val(), 'DD/MM/YYYY'))
});
You just need to put -y
with the install command.
For example: yum install <package_to_install> -y
Using filter
, you'd just need one line
line = filter(lambda char: char not in " ?.!/;:", line)
This treats the string as an iterable and checks every character if the lambda
returns True
:
>>> help(filter) Help on built-in function filter in module __builtin__: filter(...) filter(function or None, sequence) -> list, tuple, or string Return those items of sequence for which function(item) is true. If function is None, return the items that are true. If sequence is a tuple or string, return the same type, else return a list.
I like the Apache Commons IO library. Take a look at its version of ByteArrayOutputStream, which has a toString(String enc)
method as well as toByteArray()
. Using existing and trusted components like the Commons project lets your code be smaller and easier to extend and repurpose.
This works for me after a long hours of search , This solution is for Bootstrap datetimepicker version 4. when you have to set the default date in input field.
HTML
"input type='text' class="form-control" id='datetimepicker5' placeholder="Select to date" value='<?php echo $myDate?>'// $myDate is having value '2016-02-23' "
Note- If You are coding in php then you can set the value of the input datefield using php, but datetimepicker sets it back to current date when you apply datetimepicker() function to it. So in order to prevent it, use the given JS code
JAVASCRIPT
<script>
$('#datetimepicker5').datetimepicker({
useCurrent: false //this is important as the functions sets the default date value to the current value
,format: 'YYYY-MM-DD'
});
</script>
The exponential function is e^x
where e
is a mathematical constant called Euler's number, approximately 2.718281
. This value has a close mathematical relationship with pi
and the slope of the curve e^x
is equal to its value at every point. np.exp()
calculates e^x
for each value of x
in your input array.
You can use this:
'<input id="test" type="button" value="' + result.name + '" />'
$(document)..on('click', "#test", function () {
alert($(this).val());
});
It worked for me.
The problem is that the second part of your substring argument is including the first index. You need to subtract the first index from your second index to make this work.
SELECT SUBSTRING(@Text, CHARINDEX('the dog', @Text)
, CHARINDEX('immediately',@text) - CHARINDEX('the dog', @Text) + Len('immediately'))
You can pass boolean
by coercing it, put !!
before the variable.
let isRequired = '' || null || undefined
<input :required="!!isRequired"> // it will coerce value to respective boolean
But I would like to pull your attention for the following case where the receiving component has defined type
for props. In that case, if isRequired
has defined type to be string
then passing boolean
make it type check fails and you will get Vue warning. To fix that you may want to avoid passing that prop, so just put undefined
fallback and the prop will not sent to component
let isValue = false
<any-component
:my-prop="isValue ? 'Hey I am when the value exist' : undefined"
/>
Explanation
I have been through the same problem, and tried above solutions !!
Yes, I don't see the prop
but that actually does not fulfils what required here.
My problem -
let isValid = false
<any-component
:my-prop="isValue ? 'Hey I am when the value exist': false"
/>
In the above case, what I expected is not having my-prop
get passed to the child component - <any-conponent/>
I don't see the prop
in DOM
but In my <any-component/>
component, an error pops out of prop type check failure. As in the child component, I am expecting my-prop
to be a String
but it is boolean
.
myProp : {
type: String,
required: false,
default: ''
}
Which means that child component did receive the prop even if it is false
. Tweak here is to let the child component to take the default-value
and also skip the check. Passed undefined
works though!
<any-component
:my-prop="isValue ? 'Hey I am when the value exist' : undefined"
/>
This works and my child prop is having the default value.
I saw this problem before, when the (sub)folder I was trying to add had its name begin with "_Something_"
I removed the underscores and it worked. Check to see if your folder has characters which may be causing problems.
There are a couple of online, offline tools how to do this:
But the one that I liked the most, is a browser extension (tried it in chrome, hopefully it works in other browsers). After installation, it appears in your apps as HAR viewer. Then you can upload you HAR file and see something like this:
write this code up:
android:background="@color/colorAccent"
Sorry for ugly formatting. Just put a question character after declaration and everything will be ok. A question tells the compiler that the value is optional.
class Square: Shape {
var sideLength: Double? // <=== like this ..
init(sideLength:Double, name:String) {
super.init(name:name) // Error here
self.sideLength = sideLength
numberOfSides = 4
}
func area () -> Double {
return sideLength * sideLength
}
}
Edit1:
There is a better way to skip this error. According to jmaschad's comment there is no reason to use optional in your case cause optionals are not comfortable in use and You always have to check if optional is not nil before accessing it. So all you have to do is to initialize member after declaration:
class Square: Shape {
var sideLength: Double=Double()
init(sideLength:Double, name:String) {
super.init(name:name)
self.sideLength = sideLength
numberOfSides = 4
}
func area () -> Double {
return sideLength * sideLength
}
}
Edit2:
After two minuses got on this answer I found even better way. If you want class member to be initialized in your constructor you must assign initial value to it inside contructor and before super.init() call. Like this:
class Square: Shape {
var sideLength: Double
init(sideLength:Double, name:String) {
self.sideLength = sideLength // <= before super.init call..
super.init(name:name)
numberOfSides = 4
}
func area () -> Double {
return sideLength * sideLength
}
}
Good luck in learning Swift.
Give them a class and add your style to the class.
<style>
p {
color: red;
}
.paragraph1 {
font-size: 18px;
}
.paragraph2 {
font-size: 13px;
}
</style>
<p class="paragraph1">Paragraph 1</p>
<p class="paragraph2">Paragraph 2</p>
Check this EXAMPLE
return RedirectToAction("ProductImageManager","Index", new { id=id });
Here is an invalid parameters order, should be an action first
AND
ensure your routing table is correct
input:not([value=""])
This works because we are selecting the input only when there isn't an empty string.
Why don't you try the fadeIn() instead of using a show() with delay(). I think what you are trying to do can be done with this. Here is the jQuery code for fadeIn and FadeOut() which also has inbuilt method for delaying the process.
$(document).ready(function(){
$('element').click(function(){
//effects take place in 3000ms
$('element_to_hide').fadeOut(3000);
$('element_to_show').fadeIn(3000);
});
}
This looks to be the fastest way by far...
var el;
while (el = arr.shift()) {
el *= 2;
}
Take into account that this will consume the array, eating it, and leaving nothing left...
You can get it at PuTTY: Extreme Makeover Using PuTTY Connection Manager.
You can make use of cut
, sort
and uniq
commands as follows:
cat input_file | cut -f 1 | sort | uniq
gets unique values in field 1, replacing 1 by 2 will give you unique values in field 2.
Avoiding UUOC :)
cut -f 1 input_file | sort | uniq
EDIT:
To count the number of unique occurences you can make use of wc
command in the chain as:
cut -f 1 input_file | sort | uniq | wc -l
Here's another way to plot the data, involves turning the date_time into an index, this might help you for future slicing
#convert column to datetime
trip_data['lpep_pickup_datetime'] = pd.to_datetime(trip_data['lpep_pickup_datetime'])
#turn the datetime to an index
trip_data.index = trip_data['lpep_pickup_datetime']
#Plot
trip_data['Trip_distance'].plot(kind='hist')
plt.show()
I'd like to add that usually you'll want the program to wait only if it's connected to a console. Otherwise (like if it's a part of a pipeline) there is no point printing a message or waiting. For that you could use Java's Console
like this:
import java.io.Console;
// ...
public static void waitForEnter(String message, Object... args) {
Console c = System.console();
if (c != null) {
// printf-like arguments
if (message != null)
c.format(message, args);
c.format("\nPress ENTER to proceed.\n");
c.readLine();
}
}
if its numerically indexed:
foreach ($foo as $key=>$var){
if($var==$foo[$key+1]){
echo 'current and next var are the same';
}
}
This is a dirty hack, but may work.
s2 = ""
for i in s:
if ord(i) < 128:
s2 += i
An ORM (Object Relational Mapper) is a piece/layer of software that helps map your code Objects to your database.
Some handle more aspects than others...but the purpose is to take some of the weight of the Data Layer off of the developer's shoulders.
Here's a brief clip from Martin Fowler (Data Mapper):
Patterns of Enterprise Application Architecture Data Mappers
If you are using Sql Server Management Studio 2008 there are certain data fields you can view in the object explorer details window. Simply browse to and select the tables folder. In the details view you are able to right-click the column titles and add fields to the "report". Your mileage may vary if you are on SSMS 2008 express.
If you do an export with PhpMyAdmin, you can switch sql compatibility mode to 'MSSQL'. That way you just run the exported script against your MS SQL database and you're done.
If you cannot or don't want to use PhpMyAdmin, there's also a compatibility option in mysqldump, but personally I'd rather have PhpMyAdmin do it for me.
This should answer that question, and then some.
The second line, if (obj.GetType() == typeof(ClassA)) {}
, is faster, for those that don't want to read the article.
(Be aware that they don't do the same thing)
Syntax of waitpid()
:
pid_t waitpid(pid_t pid, int *status, int options);
The value of pid
can be:
pid
.pid
.The value of options is an OR of zero or more of the following constants:
WNOHANG
: Return immediately if no child has exited.WUNTRACED
: Also return if a child has stopped. Status for traced children which have stopped is provided even if this option is not specified.WCONTINUED
: Also return if a stopped child has been resumed by delivery of SIGCONT
.For more help, use man waitpid
.
Running git add
sometimes helps.
Git status is showing changed files and git diff is showing nothing...
> git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: package.json
no changes added to commit (use "git add" and/or "git commit -a")
> git diff
>
...running git add resolves the inconsistency.
> git add
> git status
On branch master
nothing to commit, working directory clean
>
Data can be pulled into an excel from another excel through Workbook method or External reference or through Data Import facility.
If you want to read or even if you want to update another excel workbook, these methods can be used. We may not depend only on VBA for this.
For more info on these techniques, please click here to refer the article
This worked for me
getActionBar().setDisplayShowHomeEnabled(false);
I currently have a workaround functional (it passes my unit tests). It is a good solution to my opinion when you only want to add a limited number of fields from other models.
Am I missing something here ?
class UserProfileForm(ModelForm):
def __init__(self, instance=None, *args, **kwargs):
# Add these fields from the user object
_fields = ('first_name', 'last_name', 'email',)
# Retrieve initial (current) data from the user object
_initial = model_to_dict(instance.user, _fields) if instance is not None else {}
# Pass the initial data to the base
super(UserProfileForm, self).__init__(initial=_initial, instance=instance, *args, **kwargs)
# Retrieve the fields from the user model and update the fields with it
self.fields.update(fields_for_model(User, _fields))
class Meta:
model = UserProfile
exclude = ('user',)
def save(self, *args, **kwargs):
u = self.instance.user
u.first_name = self.cleaned_data['first_name']
u.last_name = self.cleaned_data['last_name']
u.email = self.cleaned_data['email']
u.save()
profile = super(UserProfileForm, self).save(*args,**kwargs)
return profile
here is the solution for similar problem which i was facing while extracting name from user profile facebook json object
$uname=json_encode($userprof);
$uname=json_decode($uname);
echo "Welcome " . $uname -> name ;
You could use sp_executesql
instead of exec
. That allows you to specify an output parameter.
declare @out_var varchar(max);
execute sp_executesql
N'select @out_var = ''hello world''',
N'@out_var varchar(max) OUTPUT',
@out_var = @out_var output;
select @out_var;
This prints "hello world".
Single liner works
df['Name'] = 'abc'
Creates a Name
column and sets all rows to abc
value
My answer comes quite late because I'm a pretty new developer. This is what you can do:
Location.select(:name, :website, :city).find(row.id)
Btw, this is Rails 4
Look at how the current Object Results are created. Here is the BadRequestObjectResult. Just an extension of the ObjectResult with a value and StatusCode.
I created a TimeoutExceptionObjectResult just the same way for 408.
/// <summary>
/// An <see cref="ObjectResult"/> that when executed will produce a Request Timeout (408) response.
/// </summary>
[DefaultStatusCode(DefaultStatusCode)]
public class TimeoutExceptionObjectResult : ObjectResult
{
private const int DefaultStatusCode = StatusCodes.Status408RequestTimeout;
/// <summary>
/// Creates a new <see cref="TimeoutExceptionObjectResult"/> instance.
/// </summary>
/// <param name="error">Contains the errors to be returned to the client.</param>
public TimeoutExceptionObjectResult(object error)
: base(error)
{
StatusCode = DefaultStatusCode;
}
}
Client:
if (ex is TimeoutException)
{
return new TimeoutExceptionObjectResult("The request timed out.");
}
Set-ExecutionPolicy RemoteSigned
Executing this command in administrator mode in powershell will solve the problem.
Configure IIS7 for windows authentication in Windows Server 2008
See this link:
http://www.iis.net/ConfigReference/system.webServer/security/authentication/windowsAuthentication
Enjoy this post :-)
LIMIT 1
is what you want. Just keep in mind this returns the first record in the result set regardless of order (unless you specify an order
clause in an outer query).
Most easiest way to do it as follow:
var elementPosition = $('#navigation').offset();
$(window).scroll(function(){
if($(window).scrollTop() > elementPosition.top){
$('#navigation').css('position','fixed').css('top','0');
} else {
$('#navigation').css('position','static');
}
});
Depending on how much you know about the input, you may have to take into account that not all Unicode characters are valid XML characters.
Both Server.HtmlEncode and System.Security.SecurityElement.Escape seem to ignore illegal XML characters, while System.XML.XmlWriter.WriteString throws an ArgumentException when it encounters illegal characters (unless you disable that check in which case it ignores them). An overview of library functions is available here.
Edit 2011/8/14: seeing that at least a few people have consulted this answer in the last couple years, I decided to completely rewrite the original code, which had numerous issues, including horribly mishandling UTF-16.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
/// <summary>
/// Encodes data so that it can be safely embedded as text in XML documents.
/// </summary>
public class XmlTextEncoder : TextReader {
public static string Encode(string s) {
using (var stream = new StringReader(s))
using (var encoder = new XmlTextEncoder(stream)) {
return encoder.ReadToEnd();
}
}
/// <param name="source">The data to be encoded in UTF-16 format.</param>
/// <param name="filterIllegalChars">It is illegal to encode certain
/// characters in XML. If true, silently omit these characters from the
/// output; if false, throw an error when encountered.</param>
public XmlTextEncoder(TextReader source, bool filterIllegalChars=true) {
_source = source;
_filterIllegalChars = filterIllegalChars;
}
readonly Queue<char> _buf = new Queue<char>();
readonly bool _filterIllegalChars;
readonly TextReader _source;
public override int Peek() {
PopulateBuffer();
if (_buf.Count == 0) return -1;
return _buf.Peek();
}
public override int Read() {
PopulateBuffer();
if (_buf.Count == 0) return -1;
return _buf.Dequeue();
}
void PopulateBuffer() {
const int endSentinel = -1;
while (_buf.Count == 0 && _source.Peek() != endSentinel) {
// Strings in .NET are assumed to be UTF-16 encoded [1].
var c = (char) _source.Read();
if (Entities.ContainsKey(c)) {
// Encode all entities defined in the XML spec [2].
foreach (var i in Entities[c]) _buf.Enqueue(i);
} else if (!(0x0 <= c && c <= 0x8) &&
!new[] { 0xB, 0xC }.Contains(c) &&
!(0xE <= c && c <= 0x1F) &&
!(0x7F <= c && c <= 0x84) &&
!(0x86 <= c && c <= 0x9F) &&
!(0xD800 <= c && c <= 0xDFFF) &&
!new[] { 0xFFFE, 0xFFFF }.Contains(c)) {
// Allow if the Unicode codepoint is legal in XML [3].
_buf.Enqueue(c);
} else if (char.IsHighSurrogate(c) &&
_source.Peek() != endSentinel &&
char.IsLowSurrogate((char) _source.Peek())) {
// Allow well-formed surrogate pairs [1].
_buf.Enqueue(c);
_buf.Enqueue((char) _source.Read());
} else if (!_filterIllegalChars) {
// Note that we cannot encode illegal characters as entity
// references due to the "Legal Character" constraint of
// XML [4]. Nor are they allowed in CDATA sections [5].
throw new ArgumentException(
String.Format("Illegal character: '{0:X}'", (int) c));
}
}
}
static readonly Dictionary<char,string> Entities =
new Dictionary<char,string> {
{ '"', """ }, { '&', "&"}, { '\'', "'" },
{ '<', "<" }, { '>', ">" },
};
// References:
// [1] http://en.wikipedia.org/wiki/UTF-16/UCS-2
// [2] http://www.w3.org/TR/xml11/#sec-predefined-ent
// [3] http://www.w3.org/TR/xml11/#charsets
// [4] http://www.w3.org/TR/xml11/#sec-references
// [5] http://www.w3.org/TR/xml11/#sec-cdata-sect
}
Unit tests and full code can be found here.
Through this code, you can get click count on a button.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Button</title>
<link rel="stylesheet" type="text/css" href="css/button.css">
</head>
<body>
<script src="js/button.js" type="text/javascript"></script>
<button id="btn" class="btnst" onclick="myFunction()">0</button>
</body>
</html>
----------JAVASCRIPT----------
let count = 0;
function myFunction() {
count+=1;
document.getElementById("btn").innerHTML = count;
}
The following rather compact solution uses the PCRE positive lookahead assertion to match the last occurrence of the substring of interest, that is, an occurrence of the substring which is not followed by any other occurrences of the same substring. Thus the example replaces the last 'fox'
with 'dog'
.
$string = 'The quick brown fox, fox, fox jumps over the lazy fox!!!';
echo preg_replace('/(fox(?!.*fox))/', 'dog', $string);
OUTPUT:
The quick brown fox, fox, fox jumps over the lazy dog!!!
Some good answers already make use of calendar but the effect of setting the locale hasn't been mentioned yet.
Calendar set month names according to the current locale, for exemple in French:
import locale
import calendar
locale.setlocale(locale.LC_ALL, 'fr_FR')
assert calendar.month_name[1] == 'janvier'
assert calendar.month_abbr[1] == 'jan'
If you plan on using setlocale
in your code, make sure to read the tips and caveats and extension writer sections from the documentation. The example shown here is not representative of how it should be used. In particular, from these two sections:
It is generally a bad idea to call setlocale() in some library routine, since as a side effect it affects the entire program […]
Extension modules should never call setlocale() […]
For my Android projects I've used the Base64 library from here:
It's a very extensive library and so far I've had no problems with it.
render() {
var myloop = [];
for (let i = 0; i < 10; i++) {
myloop.push(
<View key={i}>
<Text>{i}</Text>
</View>
);
}
return (
<View >
<Text >Welcome to React Native!</Text>
{myloop}
</View>
);
}
}
You have two options:
Configure Workspace Settings (disable the validation for the current workspace): Go to Window > Preferences > Validation and uncheck the manual and build for: XML Schema Validator, XML Validator
Check enable project specific settings (disable the validation for this project): Right-click on the project, select Properties > Validation and uncheck the manual and build for: XML Schema Validator, XML Validator
Right-click on the project and select Validate to make the errors disappear.
Here's another variation that worked for me.
IF NOT EXISTS (SELECT 1
FROM INFORMATION_SCHEMA.COLUMNS
WHERE upper(TABLE_NAME) = 'TABLENAME'
AND upper(COLUMN_NAME) = 'COLUMNNAME')
BEGIN
ALTER TABLE [dbo].[Person] ADD Column
END
GO
EDIT: Note that
INFORMATION_SCHEMA
views may not always be updated, useSYS.COLUMNS
instead:
IF NOT EXISTS (SELECT 1
FROM SYS.COLUMNS....
I found a solution to my problem (thanks to the help of ImportanceOfBeingErnest).
All I had to do was to install tkinter
through the Linux bash terminal using the following command:
sudo apt-get install python3-tk
instead of installing it with pip
or directly in the virtual environment in Pycharm.
Try this:
@echo off
copy "C:\Remoting.config-Training" "C:\Remoting.config"
start C:\ThirdParty.exe
exit
Select both the column you are sorting, and the column that the picture is in (I am assuming the picture is small compared to the cell, i.e. it is "in" the cell). Make sure that the object positioning property is set as "move but don't size with cells". Now if you do a sort, the pictures will move with the list being sorted.
Note - you must include the column with the picture in your range when you sort, and the picture must fit inside the cell.
The following VBA snippet will make sure all pictures in your spreadsheet have their "move and size" property set:
Sub moveAndSize()
Dim s As Shape
For Each s In ActiveSheet.Shapes
If s.Type = msoPicture Or s.Type = msoLinkedPicture Or s.Type = msoPlaceholder Then
s.Placement = xlMove
End If
Next
End Sub
If you want to make sure the picture continues to fit after you move it, you can use xlMoveAndSize
instead of xlMove
.
Update : React Router v6 with hooks
import {useNavigate} from 'react-router-dom';
let navigate = useNavigate();
navigate('home');
And to move across the browser history,
navigate(-1); ---> Go back
navigate(1); ---> Go forward
navigate(-2); ---> Move two steps backward.
You need to add the Host
parameter
$mail->Host = "ssl://smtp.gmail.com";
Also, check if you have open_ssl
enabled.
<?php
echo !extension_loaded('openssl')?"Not Available":"Available";
Sourcetree 3.x has an option to accept gitLab. See here. I now use Sourcetree 3.0.15. In Settings, put your remote gitLab host and url, etc. If your existing git client version is not supported any more, the easiest way is perhaps to use Sourcetree embedded Git by Tools->Options->Git, in Git Version near the bottom, choose Embedded. A download may happen.
Most of these answers edit the string in place, when you are just formatting for view output you may not want to be changing the underlying string so you can use tap
after a dup
to get an edited copy
'test'.dup.tap { |string| string[0] = string[0].upcase }