The Eclipse releases are named after the moons of Jupiter, and each denotes a successive release.
Helios is the current release you can download eclipse as your programming needs http://www.eclipse.org/downloads/
you may try this one, used CONCAT
WHERE LastName LIKE Concat('%',@LastName,'%')
Try the method rstrip()
(see doc Python 2 and Python 3)
>>> 'test string\n'.rstrip()
'test string'
Python's rstrip()
method strips all kinds of trailing whitespace by default, not just one newline as Perl does with chomp
.
>>> 'test string \n \r\n\n\r \n\n'.rstrip()
'test string'
To strip only newlines:
>>> 'test string \n \r\n\n\r \n\n'.rstrip('\n')
'test string \n \r\n\n\r '
There are also the methods strip()
, lstrip()
and strip()
:
>>> s = " \n\r\n \n abc def \n\r\n \n "
>>> s.strip()
'abc def'
>>> s.lstrip()
'abc def \n\r\n \n '
>>> s.rstrip()
' \n\r\n \n abc def'
Few more Practical Application of data structures
Red-Black Trees (Used when there is frequent Insertion/Deletion and few searches) - K-mean Clustering using red black tree, Databases, Simple-minded database, searching words inside dictionaries, searching on web
AVL Trees (More Search and less of Insertion/Deletion) - Data Analysis and Data Mining and the applications which involves more searches
Min Heap - Clustering Algorithms
I prefer not messing with HTML and use as much as native infrastructure as possible. You can use Output widget with Hbox or VBox:
import ipywidgets as widgets
from IPython import display
import pandas as pd
import numpy as np
# sample data
df1 = pd.DataFrame(np.random.randn(8, 3))
df2 = pd.DataFrame(np.random.randn(8, 3))
# create output widgets
widget1 = widgets.Output()
widget2 = widgets.Output()
# render in output widgets
with widget1:
display.display(df1)
with widget2:
display.display(df2)
# create HBox
hbox = widgets.HBox([widget1, widget2])
# render hbox
hbox
This outputs:
CSS 3
divContainer input[type="text"] {
width:150px;
}
CSS2 add a class "text" to the text inputs then in your css
.divContainer.text{
width:150px;
}
Perhaps your main
function has been commented out because of e.g. preprocessing.
To learn what preprocessing is doing, try gcc -C -E es3.c > es3.i
then look with an editor into the generated file es3.i (and search main
inside it).
First, you should always (since you are a newbie) compile with
gcc -Wall -g -c es3.c
gcc -Wall -g es3.o -o es3
The -Wall
flag is extremely important, and you should always use it. It tells the compiler to give you (almost) all warnings. And you should always listen to the warnings, i.e. correct your source code file es3.C
till you got no more warnings.
The -g
flag is important also, because it asks gcc
to put debugging information in the object file and the executable. Then you are able to use a debugger (like gdb
) to debug your program.
To get the list of symbols in an object file or an executable, you can use nm
.
Of course, I'm assuming you use a GNU/Linux system (and I invite you to use GNU/Linux if you don't use it already).
You cannot.
According to the XML Schema specification, a boolean is true
or false
. True
is not valid:
3.2.2.1 Lexical representation An instance of a datatype that is defined as ·boolean· can have the following legal literals {true, false, 1, 0}. 3.2.2.2 Canonical representation The canonical representation for boolean is the set of literals {true, false}.
If the tool you are using truly validates against the XML Schema standard, then you cannot convince it to accept True for a boolean.
Under VS2013 you can install the new compilers into the project as a nuget package. That way you don't need VS2015 or an updated build server.
https://www.nuget.org/packages/Microsoft.Net.Compilers/
Install-Package Microsoft.Net.Compilers
The package allows you to use/build C# 6.0 code/syntax. Because VS2013 doesn't natively recognize the new C# 6.0 syntax, it will show errors in the code editor window although it will build fine.
Using Resharper, you'll get squiggly lines on C# 6 features, but the bulb gives you the option to 'Enable C# 6.0 support for this project' (setting saved to .DotSettings).
As mentioned by @stimpy77: for support in MVC Razor views you'll need an extra package (for those that don't read the comments)
Install-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform
If you want full C# 6.0 support, you'll need to install VS2015.
Use the below code.
<div id="outer">
<div id="inner">Foo foo</div>
</div>
#outer {
text-align: center;
}
#inner{
display: inline-block;
}
Based in @TMS answer, I like it because there's no need for subqueries but I think ommiting the 'OR'
part will be sufficient and much simpler to understand and read.
SELECT t1.*
FROM lms_attendance AS t1
LEFT JOIN lms_attendance AS t2
ON t1.user = t2.user
AND t1.time < t2.time
WHERE t2.user IS NULL
if you are not interested in rows with null times you can filter them in the WHERE
clause:
SELECT t1.*
FROM lms_attendance AS t1
LEFT JOIN lms_attendance AS t2
ON t1.user = t2.user
AND t1.time < t2.time
WHERE t2.user IS NULL and t1.time IS NOT NULL
header.php has the title tag set to <title>%TITLE%</title>;
the "%" are important since hardly anyone types %TITLE% so u can use that for str_replace() later. then, you use output buffer like so
<?php
ob_start();
include("header.php");
$buffer=ob_get_contents();
ob_end_clean();
$buffer=str_replace("%TITLE%","NEW TITLE",$buffer);
echo $buffer;
?>
For more reference, click PHP - how to change title of the page AFTER including header.php?
Your LMSInitialize
function is declared inside Scorm_API_12
function. So it can be seen only in Scorm_API_12
function's scope.
If you want to use this function like API.LMSInitialize("")
, declare Scorm_API_12
function like this:
function Scorm_API_12() {
var Initialized = false;
this.LMSInitialize = function(param) {
errorCode = "0";
if (param == "") {
if (!Initialized) {
Initialized = true;
errorCode = "0";
return "true";
} else {
errorCode = "101";
}
} else {
errorCode = "201";
}
return "false";
}
// some more functions, omitted.
}
var API = new Scorm_API_12();
If react-scripts
is present in package.json
, then just type this command
npm install
If react-scripts
is not present in package.json
, then you probably haven't installed it. To do that, run:
npm install react-scripts --save
You can also load the context while defining the servlet itself (WebApplicationContext)
<servlet>
<servlet-name>admin</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/*.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>admin</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
rather than (ApplicationContext)
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
or can do both together.
Drawback of just using WebApplicationContext is that it will load context only for this particular Spring entry point (DispatcherServlet
) where as with above mentioned methods context will be loaded for multiple entry points (Eg. Webservice Servlet, REST servlet
etc)
Context loaded by ContextLoaderListener
will infact be a parent context to that loaded specifically for DisplacherServlet . So basically you can load all your business service, data access or repository beans in application context and separate out your controller, view resolver beans to WebApplicationContext.
For all those facing a similar issue, I came across this same issue when i was trying to run a particular code snippet, shown below.
<html>
<head>
<script>
var div, container = document.getElementById("container")
for(var i=0;i<5;i++){
div = document.createElement("div");
div.onclick = function() {
alert("This is a box #"+i);
};
container.appendChild(div);
}
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
https://codepen.io/pcwanderer/pen/MMEREr
Looking at the error in the console for the above code.
Since the document.getElementById is returning a null and as null does not have a attribute named appendChild, therefore a error is thrown. To solve the issue see the code below.
<html>
<head>
<style>
#container{
height: 200px;
width: 700px;
background-color: red;
margin: 10px;
}
div{
height: 100px;
width: 100px;
background-color: purple;
margin: 20px;
display: inline-block;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
var div, container = document.getElementById("container")
for(let i=0;i<5;i++){
div = document.createElement("div");
div.onclick = function() {
alert("This is a box #"+i);
};
container.appendChild(div);
}
</script>
</body>
</html>
https://codepen.io/pcwanderer/pen/pXWBQL
I hope this helps. :)
In straight-up computer programming, there is no such thing as "printing bold text". Let's back up a bit and understand that your text is a string of bytes and bytes are just bundles of bits. To the computer, here's your "hello" text, in binary.
0110100001100101011011000110110001101111
Each one or zero is a bit. Every eight bits is a byte. Every byte is, in a string like that in Python 2.x, one letter/number/punctuation item (called a character). So for example:
01101000 01100101 01101100 01101100 01101111
h e l l o
The computer translates those bits into letters, but in a traditional string (called an ASCII string), there is nothing to indicate bold text. In a Unicode string, which works a little differently, the computer can support international language characters, like Chinese ones, but again, there's nothing to say that some text is bold and some text is not. There's also no explicit font, text size, etc.
In the case of printing HTML, you're still outputting a string. But the computer program reading that string (a web browser) is programmed to interpret text like this is <b>bold</b>
as "this is bold" when it converts your string of letters into pixels on the screen. If all text were WYSIWYG, the need for HTML itself would be mitigated -- you would just select text in your editor and bold it instead of typing out the HTML.
Other programs use different systems -- a lot of answers explained a completely different system for printing bold text on terminals. I'm glad you found out how to do what you want to do, but at some point, you'll want to understand how strings and memory work.
Problem
git clone https://github.com/rojarfast1991/TestGit.git fatal: protocol 'https' is not supported
Solution:
Steps:
(1):- Open the new terminal and clone the git repository
git clone https://github.com/rojarfast1991/TestGit.git
(2) Automatic git login prompt will open and it will be asked you to enter a user credential.
UserName : - xxxxxxx
PassWord : - xxxxxxx
Finally, cloning will start...
git clone https://github.com/rojarfast1991/TestGit.git
Cloning into 'TestGit'...
remote: Enumerating objects: 4, done.
remote: Counting objects: 100% (4/4), done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 4 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (4/4), done.
( tl;dr
: goto option 3: INSERT with RETURNING )
Recall that in postgresql there is no "id" concept for tables, just sequences (which are typically but not necessarily used as default values for surrogate primary keys, with the SERIAL pseudo-type).
If you are interested in getting the id of a newly inserted row, there are several ways:
Option 1: CURRVAL(<sequence name>);
.
For example:
INSERT INTO persons (lastname,firstname) VALUES ('Smith', 'John');
SELECT currval('persons_id_seq');
The name of the sequence must be known, it's really arbitrary; in this example we assume that the table persons
has an id
column created with the SERIAL
pseudo-type. To avoid relying on this and to feel more clean, you can use instead pg_get_serial_sequence
:
INSERT INTO persons (lastname,firstname) VALUES ('Smith', 'John');
SELECT currval(pg_get_serial_sequence('persons','id'));
Caveat: currval()
only works after an INSERT
(which has executed nextval()
), in the same session.
Option 2: LASTVAL();
This is similar to the previous, only that you don't need to specify the sequence name: it looks for the most recent modified sequence (always inside your session, same caveat as above).
Both CURRVAL
and LASTVAL
are totally concurrent safe. The behaviour of sequence in PG is designed so that different session will not interfere, so there is no risk of race conditions (if another session inserts another row between my INSERT and my SELECT, I still get my correct value).
However they do have a subtle potential problem. If the database has some TRIGGER (or RULE) that, on insertion into persons
table, makes some extra insertions in other tables... then LASTVAL
will probably give us the wrong value. The problem can even happen with CURRVAL
, if the extra insertions are done intto the same persons
table (this is much less usual, but the risk still exists).
Option 3: INSERT
with RETURNING
INSERT INTO persons (lastname,firstname) VALUES ('Smith', 'John') RETURNING id;
This is the most clean, efficient and safe way to get the id. It doesn't have any of the risks of the previous.
Drawbacks? Almost none: you might need to modify the way you call your INSERT statement (in the worst case, perhaps your API or DB layer does not expect an INSERT to return a value); it's not standard SQL (who cares); it's available since Postgresql 8.2 (Dec 2006...)
Conclusion: If you can, go for option 3. Elsewhere, prefer 1.
Note: all these methods are useless if you intend to get the last inserted id globally (not necessarily by your session). For this, you must resort to SELECT max(id) FROM table
(of course, this will not read uncommitted inserts from other transactions).
Conversely, you should never use SELECT max(id) FROM table
instead one of the 3 options above, to get the id just generated by your INSERT
statement, because (apart from performance) this is not concurrent safe: between your INSERT
and your SELECT
another session might have inserted another record.
you can try this
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);
Add this code into the css file:
input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
This will help.
I can do like that (sorry it's c# not java but it's not a problem...) :
private int iValue = 1234567890;
function void MyTest()
{
Intent oIntent = new Intent (this, typeof(Camera2Activity));
Bundle oBundle = new Bundle();
oBundle.PutInt("MYVALUE", iValue); //=> 1234567890
oIntent.PutExtras (oBundle);
iRequestCode = 1111;
StartActivityForResult (oIntent, 1111);
}
AND IN YOUR ACTIVITY FOR RESULT
private int iValue = 0;
protected override void OnCreate(Bundle bundle)
{
Bundle oBundle = Intent.Extras;
if (oBundle != null)
{
iValue = oBundle.GetInt("MYVALUE", 0);
//=>1234567890
}
}
private void FinishActivity(bool bResult)
{
Intent oIntent = new Intent();
Bundle oBundle = new Bundle();
oBundle.PutInt("MYVALUE", iValue);//=>1234567890
oIntent.PutExtras(oBundle);
if (bResult)
{
SetResult (Result.Ok, oIntent);
}
else
SetResult(Result.Canceled, oIntent);
GC.Collect();
Finish();
}
FINALLY
protected override void OnActivityResult(int iRequestCode, Android.App.Result oResultCode, Intent oIntent)
{
base.OnActivityResult (iRequestCode, oResultCode, oIntent);
iValue = oIntent.Extras.GetInt("MYVALUE", -1); //=> 1234567890
}
The dataframe can be changed by just doing
df.columns = df.iloc[0]
df = df[1:]
Then
df.to_csv(path, index=False)
Should do the trick.
It's certainly possible to grab a screenshot using the .NET Framework. The simplest way is to create a new Bitmap
object and draw into that using the Graphics.CopyFromScreen
method.
Sample code:
using (Bitmap bmpScreenCapture = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height))
using (Graphics g = Graphics.FromImage(bmpScreenCapture))
{
g.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0, 0,
bmpScreenCapture.Size,
CopyPixelOperation.SourceCopy);
}
Caveat: This method doesn't work properly for layered windows. Hans Passant's answer here explains the more complicated method required to get those in your screen shots.
./script.sh | sort -u
This is the same as monoxide's answer, but a bit more concise.
Note: Adding a new answer as the publish/unpublish option is moved to different location.
As mentioned in other answers you cannot delete the app. With updated Google Play Console (Beta), the Unpublish option is moved to different location:
Setup -> Advanced Settings -> App Availability
Enable Published / Unpublished accordingly!
A PDB file contains information used by the debugger. It is not required to run your application and it does not need to be included in your released version.
You can disable pdb files from being created in Visual Studio. If you are building from the command line or a script then omit the /Debug
switch.
I had to decide between the parseFloat() and Number() conversions before I could make toFixed() call. Here's an example of a number formatting post-capturing user input.
HTML:
<input type="number" class="dec-number" min="0" step="0.01" />
Event handler:
$('.dec-number').on('change', function () {
const value = $(this).val();
$(this).val(value.toFixed(2));
});
The above code will result in TypeError exception. Note that although the html input type is "number", the user input is actually a "string" data type. However, toFixed() function may only be invoked on an object that is a Number.
My final code would look as follows:
$('.dec-number').on('change', function () {
const value = Number($(this).val());
$(this).val(value.toFixed(2));
});
The reason I favor to cast with Number() vs. parseFloat() is because I don't have to perform an extra validation neither for an empty input string, nor NaN value. The Number() function would automatically handle an empty string and covert it to zero.
I have a similar problem: I have to start manually this service once in a while. For those of you who have the same problem you can create a bat file and execute it when the service is not running (VMAuthdService service). This doesn't solve the problem, it's just a kind of workaround. The content of the file is the following:
:: BatchGotAdmin
:-------------------------------------
REM --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
echo Requesting administrative privileges...
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
exit /B
:gotAdmin
if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
pushd "%CD%"
CD /D "%~dp0"
:--------------------------------------
net start VMAuthdService
Name the file Start Auth VmWare.bat
As alternative, you can code something like this:
<Border
x:Name="borderBtnAdd"
BorderThickness="1"
BorderBrush="DarkGray"
CornerRadius="360"
Height="30"
Margin="0,10,10,0"
VerticalAlignment="Top" HorizontalAlignment="Right" Width="30">
<Image x:Name="btnAdd"
Source="Recursos/Images/ic_add_circle_outline_black_24dp_2x.png"
Width="{Binding borderBtnAdd.Width}" Height="{Binding borderBtnAdd.Height}"/>
</Border>
The "Button" will look something like this:
You could set any other content instead of the image.
The basic setup of decorators is like this:
InputStream fileStream = new FileInputStream(filename);
InputStream gzipStream = new GZIPInputStream(fileStream);
Reader decoder = new InputStreamReader(gzipStream, encoding);
BufferedReader buffered = new BufferedReader(decoder);
The key issue in this snippet is the value of encoding
. This is the character encoding of the text in the file. Is it "US-ASCII", "UTF-8", "SHIFT-JIS", "ISO-8859-9", …? there are hundreds of possibilities, and the correct choice usually cannot be determined from the file itself. It must be specified through some out-of-band channel.
For example, maybe it's the platform default. In a networked environment, however, this is extremely fragile. The machine that wrote the file might sit in the neighboring cubicle, but have a different default file encoding.
Most network protocols use a header or other metadata to explicitly note the character encoding.
In this case, it appears from the file extension that the content is XML. XML includes the "encoding" attribute in the XML declaration for this purpose. Furthermore, XML should really be processed with an XML parser, not as text. Reading XML line-by-line seems like a fragile, special case.
Failing to explicitly specify the encoding is against the second commandment. Use the default encoding at your peril!
File extensions do not have any bearing or impact on the content of the file. You can hold YAML content in files with any extension: .yml
, .yaml
or indeed anything else.
The (rather sparse) YAML FAQ recommends that you use .yaml
in preference to .yml
, but for historic reasons many Windows programmers are still scared of using extensions with more than three characters and so opt to use .yml
instead.
So, what really matters is what is inside the file, rather than what its extension is.
You need to use a back_inserter
:
std::copy(input.begin(), input.end(), std::back_inserter(output));
std::copy
doesn't add elements to the container into which you are inserting: it can't; it only has an iterator into the container. Because of this, if you pass an output iterator directly to std::copy
, you must make sure it points to a range that is at least large enough to hold the input range.
std::back_inserter
creates an output iterator that calls push_back
on a container for each element, so each element is inserted into the container. Alternatively, you could have created a sufficient number of elements in the std::vector
to hold the range being copied:
std::vector<double> output(input.size());
std::copy(input.begin(), input.end(), output.begin());
Or, you could use the std::vector
range constructor:
std::vector<double> output(input.begin(), input.end());
Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.
With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.
If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.
The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.
Locally I run visual studio with admin rights and the error was gone.
If you get this error in task scheduler you have to check the option run with high privileges.
I think if you add margin: auto; to the div below it should work.
div#iframe-wrapper iframe {
position: absolute;
top: 0;
bottom: 0;
left: 0;
margin: auto;
right: 100px;
height: 100%;
width: 100%;
}
It does not make sense to put your business layer in the Model for an MVC project.
Say that your boss decides to change the presentation layer to something else, you would be screwed! The business layer should be a separate assembly. A Model contains the data that comes from the business layer that passes to the view to display. Then on post for example, the model binds to a Person class that resides in the business layer and calls PersonBusiness.SavePerson(p); where p is the Person class. Here's what I do (BusinessError class is missing but would go in the BusinessLayer too):
For bootstrap date picker
$( ".classNmae" ).datepicker( "setDate", new Date());
* new Date is jquery default function in which you can pass custom date & if it not set, it will take current date by default
Don't use SELECT currval('MySequence') - the value gets incremented on inserts that fail.
XMLHttpRequest is a built-in object in web browsers.
It is not distributed with Node; you have to install it separately,
Install it with npm,
npm install xmlhttprequest
Now you can require
it in your code.
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
That said, the http module is the built-in tool for making HTTP requests from Node.
Axios is a library for making HTTP requests which is available for Node and browsers that is very popular these days.
No macros required. Data as below, two columns, dates don't need to be in order. Select range, convert to a Table (Ctrl+T). When data is added to the table, a chart based on the table will automatically include the added data.
Select table, insert a line chart. Right click chart, choose Select Data, click on Blank and Hidden Cells button, choose Interpolate option.
POJO: If the class can be executed with underlying JDK,without any other external third party libraries support then its called POJO
JavaBean: If class only contains attributes with accessors(setters and getters) those are called javabeans.Java beans generally will not contain any bussiness logic rather those are used for holding some data in it.
All Javabeans are POJOs but all POJO are not Javabeans
From c++20:
A non-member function introduced std::erase
, which takes the vector and value to be removed as inputs.
ex:
std::vector<int> v = {90,80,70,60,50};
std::erase(v,50);
Instead of wasting your time to design a JFrame
just to display a error message, you can use an JOptionPane
which is by default modal:
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Your message goes here!","Message", JOptionPane.ERROR_MESSAGE);
}
}
P.S. Stop using Windowbuilder if you want to learn Swing.
You can use various local storage mechanisms to store this data in the browser such as Web Storage, IndexedDB, WebSQL (deprecated) and File API (deprecated and only available in Chrome) (and UserData with IE).
The simplest and most widely supported is WebStorage where you have persistent storage (localStorage
) or session based (sessionStorage
) which is in memory until you close the browser. Both share the same API.
You can for example (simplified) do something like this when the page is about to reload:
window.onbeforeunload = function() {
localStorage.setItem("name", $('#inputName').val());
localStorage.setItem("email", $('#inputEmail').val());
localStorage.setItem("phone", $('#inputPhone').val());
localStorage.setItem("subject", $('#inputSubject').val());
localStorage.setItem("detail", $('#inputDetail').val());
// ...
}
Web Storage works synchronously so this may work here. Optionally you can store the data for each blur event on the elements where the data is entered.
At page load you can check:
window.onload = function() {
var name = localStorage.getItem("name");
if (name !== null) $('#inputName').val("name");
// ...
}
getItem
returns null
if the data does not exist.
Use sessionStorage
instead of localStorage
if you want to store only temporary.
Updating timestamp, only if the values changed
Based on E.J's link and add a if statement from this link (https://stackoverflow.com/a/3084254/1526023)
CREATE OR REPLACE FUNCTION update_modified_column()
RETURNS TRIGGER AS $$
BEGIN
IF row(NEW.*) IS DISTINCT FROM row(OLD.*) THEN
NEW.modified = now();
RETURN NEW;
ELSE
RETURN OLD;
END IF;
END;
$$ language 'plpgsql';
You can see the full table of percentages to hex values and run the code in this playground in https://play.golang.org/p/l1JaPYFzDkI .
More infos for the conversion decimal <=> hexadecimal
The problem can be solved generically by a cross multiplication.
We have a percentage (ranging from 0 to 100 ) and another number (ranging from 0 to 255) then converted to hexadecimal.
For 1%
For 2%
The table in the best answer gives the percentage by step of 5%.
How to calculate the numbers between in your head ? Due to the 2.5 increment, add 2 to the first and 3 to the next
I prefer to teach how to find the solution rather than showing an answer table you don't know where the results come from.
Give a man a fish and you feed him for a day; teach a man to fish and you feed him for a lifetime
Just use the official upgrade guide which will tell you what you need to do for your own particular needs:
Step 1: Remove the Existing Reference Step 2: Clean Solution Step 3: Add project Reference again.
and its done. :)
You can use LINQ to XML,
XDocument doc = XDocument.Load(file);
var result = (from ele in doc.Descendants("section")
select ele).ToList();
foreach (var t in result)
{
if (t.Attributes("split").Count() != 0)
{
// Exist
}
// Suggestion from @UrbanEsc
if(t.Attributes("split").Any())
{
}
}
OR
XDocument doc = XDocument.Load(file);
var result = (from ele in doc.Descendants("section").Attributes("split")
select ele).ToList();
foreach (var t in result)
{
// Response.Write("<br/>" + t.Value);
}
Following up on @srhegde suggestion of using setattr:
class ExampleClass(object):
__acceptable_keys_list = ['foo', 'bar']
def __init__(self, **kwargs):
[self.__setattr__(key, kwargs.get(key)) for key in self.__acceptable_keys_list]
This variant is useful when the class is expected to have all of the items in our acceptable
list.
If the variable ax.xaxis._autolabelpos = True, matplotlib sets the label position in function _update_label_position in axis.py according to (some excerpts):
bboxes, bboxes2 = self._get_tick_bboxes(ticks_to_draw, renderer)
bbox = mtransforms.Bbox.union(bboxes)
bottom = bbox.y0
x, y = self.label.get_position()
self.label.set_position((x, bottom - self.labelpad * self.figure.dpi / 72.0))
You can set the label position independently of the ticks by using:
ax.xaxis.set_label_coords(x0, y0)
that sets _autolabelpos to False or as mentioned above by changing the labelpad parameter.
An example, just to make this a 15 seconds answer -
Say you have "styles.xaml" in a WPF library named "common" and you want to use it from your main application project:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/Common;component/styles.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
I hade the same issue recently, and my case was something that's not mentioned here yet:
The problem was I was testing it on localhost
domain. I'm not sure why exactly was this an issue, but it started to work after I added a host name alias for localhost
into /etc/hosts
like this:
127.0.0.1 foobar
There's probably something wrong with the session while using Apache and localhost
as a domain. If anyone can elaborate in the comments I'd be happy to edit this answer to include more details.
Use a combination of Microsoft specific CSS rules to filter IE11:
<!doctype html>
<html>
<head>
<title>IE10/11 Media Query Test</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<style>
@media all and (-ms-high-contrast:none)
{
.foo { color: green } /* IE10 */
*::-ms-backdrop, .foo { color: red } /* IE11 */
}
</style>
</head>
<body>
<div class="foo">Hi There!!!</div>
</body>
</html>
Filters such as this work because of the following:
When a user agent cannot parse the selector (i.e., it is not valid CSS 2.1), it must ignore the selector and the following declaration block (if any) as well.
<!doctype html>_x000D_
<html>_x000D_
<head>_x000D_
<title>IE10/11 Media Query Test</title>_x000D_
<meta charset="utf-8">_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
<style>_x000D_
@media all and (-ms-high-contrast:none)_x000D_
{_x000D_
.foo { color: green } /* IE10 */_x000D_
*::-ms-backdrop, .foo { color: red } /* IE11 */_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div class="foo">Hi There!!!</div>_x000D_
</body>_x000D_
</html>
_x000D_
References
If I understand correctly you want to change the CSS style of an element by clicking an item in a ul
list. Am I right?
HTML:
<div class="results" style="background-color:Red;">
</div>
<ul class="colors-list">
<li>Red</li>
<li>Blue</li>
<li>#ffee99</li>
</ul>
jquery
$('.colors-list li').click(function(e){
var color = $(this).text();
$('.results').css('background-color',color);
});
Note that jquery can use addClass
, removeClass
and toggleClass
if you want to use classes rather than inline styling. This means that you can do something like that:
$('.results').addClass('selected');
And define the 'selected' styling in the CSS.
Working example: http://jsfiddle.net/uuJmP/
Jquery later allowed you to to find the parents with the .parents()
method.
Hence I recommend using:
var $div = $('#divid').parents('div[class^="div-a"]');
This gives all parent nodes matching the selector. To get the first parent matching the selector use:
var $div = $('#divid').parents('div[class^="div-a"]').eq(0);
For other such DOM traversal queries, check out the documentation on traversing the DOM.
Think about it as array of array.
If you do this str[x][y], then there is array of length x where each element in turn contains array of length y. In java its not necessary for second dimension to have same length. So for x=i you can have y=m and x=j you can have y=n
For this your declaration looks like
String[][] test = new String[4][]; test[0] = new String[3]; test[1] = new String[2];
etc..
Try this instead of your code:
var type=$("#the-span").attr("data-type");
alert(type);
To overcome the issue of Win7 32bit VB6, try copying from Windows Server 2003 C:\Windows\system32\
the files mscomctl.ocx
and mscomcctl.oba
.
If you have a list view you can do this:
Define a select list:
@{
var Acciones = new SelectList(new[]
{
new SelectListItem { Text = "Modificar", Value =
Url.Action("Edit", "Countries")},
new SelectListItem { Text = "Detallar", Value =
Url.Action("Details", "Countries") },
new SelectListItem { Text = "Eliminar", Value =
Url.Action("Delete", "Countries") },
}, "Value", "Text");
}
Use the defined SelectList, creating a diferent id for each record (remember that id of each element must be unique in a view), and finally call a javascript function for onchange event (include parameters in example url and record key):
@Html.DropDownList("ddAcciones", Acciones, "Acciones", new { id =
item.CountryID, @onchange = "RealizarAccion(this.value ,id)" })
onchange function can be something as:
@section Scripts {
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script type="text/javascript">
function RealizarAccion(accion, country)
{
var url = accion + '/' + country;
if (url != null && url != '') {
window.location.href = url ;
}
}
</script>
@Scripts.Render("~/bundles/jqueryval")
}
This is SUPER late and probably not relevant anymore, but if anyone stumbles upon this answer, I believe I know the cause.
So the JSON encoded string is perfectly valid with the degree symbol in it, as the other answer mentions. The problem is most likely in the character encoding that you are reading/writing with. Depending on how you are using Gson, you are probably passing it a java.io.Reader
instance. Any time you are creating a Reader
from an InputStream
, you need to specify the character encoding, or java.nio.charset.Charset
instance (it's usually best to use java.nio.charset.StandardCharsets.UTF_8
). If you don't specify a Charset
, Java will use your platform default encoding, which on Windows is usually CP-1252.
Change this line:
The 2 should be 0. Every count starts at 0.
//Aboutme.Text = String.Format("{2}", reader.GetString(0));//wrong
//Aboutme.Text = String.Format("{0}", reader.GetString(0));//correct
Use translate:
import string
def clean(instr):
return instr.translate(None, string.punctuation + ' ')
Caveat: Only works on ascii strings.
Check your node version node -v and your npm version npm -v Then To update your npm, type this into your terminal : sudo npm install npm@latest -g
N.B: Debian Based OS{ubuntu or Linux mint}
To my knowledge, Ejabberd (http://www.ejabberd.im/) is the parent, this is XMPP server which provide quite good features of open source, Whatsapp uses some modified version of this, facebook messaging also uses a modified version of this. Some more chat applications likes Samsung's ChatOn, Nimbuzz messenger all use ejabberd based ones and Erlang solutions also have modified version of this ejabberd which they claim to be highly scalable and well tested with more performance improvements and renamed as MongooseIM.
Ejabberd is the server which has most of the featured implemented when compared to other. Since it is build in Erlang it is highly scalable horizontally.
Perhaps you can use JavaScript to solve your cross-browser problem. It uses a different escape mechanism, one with which you're obviously already familiar:
(reference-to-the-tag).title = "Some \"text\"";
It doesn't strictly separate the functions of HTML, JavaScript, and CSS the way folks want you to nowadays, but whom do you need to make happy? Your users or techies you don't know?
You probably need to reference it from the Rows
rather than as a cell:
var cellValue = dt.Rows[i][j];
If you're going to be doing this search frequently, consider changing the format of your object so dinner actually is a key. This is kind of like assigning a primary clustered key in a database table. So, for example:
Obj = { 'pizza' : { 'name' : 'bob' }, 'sushi' : { 'name' : 'john' } }
You can now easily access it like this: Object['sushi']['name']
Or if the object really is this simple (just 'name' in the object), you could just change it to:
Obj = { 'pizza' : 'bob', 'sushi' : 'john' }
And then access it like: Object['sushi']
.
It's obviously not always possible or to your advantage to restructure your data object like this, but the point is, sometimes the best answer is to consider whether your data object is structured the best way. Creating a key like this can be faster and create cleaner code.
typedef enum {
false = 0,
true
} t_bool;
You set the DisplayMemberPath and the SelectedValuePath to "Name", so I assume that you have a class PhoneBookEntry with a public property Name.
Have you set the DataContext to your ConnectionViewModel object?
I copied you code and made some minor modifications, and it seems to work fine. I can set the viewmodels PhoneBookEnty property and the selected item in the combobox changes, and I can change the selected item in the combobox and the view models PhoneBookEntry property is set correctly.
Here is my XAML content:
<Window x:Class="WpfApplication6.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<StackPanel>
<Button Click="Button_Click">asdf</Button>
<ComboBox ItemsSource="{Binding Path=PhonebookEntries}"
DisplayMemberPath="Name"
SelectedValuePath="Name"
SelectedValue="{Binding Path=PhonebookEntry}" />
</StackPanel>
</Grid>
</Window>
And here is my code-behind:
namespace WpfApplication6
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
ConnectionViewModel vm = new ConnectionViewModel();
DataContext = vm;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
((ConnectionViewModel)DataContext).PhonebookEntry = "test";
}
}
public class PhoneBookEntry
{
public string Name { get; set; }
public PhoneBookEntry(string name)
{
Name = name;
}
public override string ToString()
{
return Name;
}
}
public class ConnectionViewModel : INotifyPropertyChanged
{
public ConnectionViewModel()
{
IList<PhoneBookEntry> list = new List<PhoneBookEntry>();
list.Add(new PhoneBookEntry("test"));
list.Add(new PhoneBookEntry("test2"));
_phonebookEntries = new CollectionView(list);
}
private readonly CollectionView _phonebookEntries;
private string _phonebookEntry;
public CollectionView PhonebookEntries
{
get { return _phonebookEntries; }
}
public string PhonebookEntry
{
get { return _phonebookEntry; }
set
{
if (_phonebookEntry == value) return;
_phonebookEntry = value;
OnPropertyChanged("PhonebookEntry");
}
}
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
Edit: Geoffs second example does not seem to work, which seems a bit odd to me. If I change the PhonebookEntries property on the ConnectionViewModel to be of type ReadOnlyCollection, the TwoWay binding of the SelectedValue property on the combobox works fine.
Maybe there is an issue with the CollectionView? I noticed a warning in the output console:
System.Windows.Data Warning: 50 : Using CollectionView directly is not fully supported. The basic features work, although with some inefficiencies, but advanced features may encounter known bugs. Consider using a derived class to avoid these problems.
Edit2 (.NET 4.5): The content of the DropDownList can be based on ToString() and not of DisplayMemberPath, while DisplayMemberPath specifies the member for the selected and displayed item only.
In my case it was the missing .pub
extension of a key. I pasted it from clipboard and saved as mykey
. The following command returned described error:
ssh-copy-id -i mykey localhost
After renaming it with mv mykey mykey.pub
, works correctly.
ssh-copy-id -i mykey.pub localhost
Check your git repo before committing
gitrepo/.git/hooks/commit-msg
if this file is not present in that location then you will get this error "missing Change-Id in commit message" .
To solve this just copy paste the commit hook in .git folder.
Don't delete it: for just one commit git cherry-pick
is enough.
But if you had several commits on the wrong branch, that is where git rebase --onto
shines:
Suppose you have this:
x--x--x--x <-- master
\
-y--y--m--m <- y branch, with commits which should have been on master
, then you can mark master
and move it where you would want to be:
git checkout master
git branch tmp
git checkout y
git branch -f master
x--x--x--x <-- tmp
\
-y--y--m--m <- y branch, master branch
, reset y branch where it should have been:
git checkout y
git reset --hard HEAD~2 # ~1 in your case,
# or ~n, n = number of commits to cancel
x--x--x--x <-- tmp
\
-y--y--m--m <- master branch
^
|
-- y branch
, and finally move your commits (reapply them, making actually new commits)
git rebase --onto tmp y master
git branch -D tmp
x--x--x--x--m'--m' <-- master
\
-y--y <- y branch
The sqlite3 .import command won't work for ordinary csv data because it treats any comma as a delimiter even in a quoted string.
This includes trying to re-import a csv file that was created by the shell:
Create table T (F1 integer, F2 varchar);
Insert into T values (1, 'Hey!');
Insert into T values (2, 'Hey, You!');
.mode csv
.output test.csv
select * from T;
Contents of test.csv:
1,Hey!
2,"Hey, You!"
delete from T;
.import test.csv T
Error: test.csv line 2: expected 2 columns of data but found 3
It seems we must transform the csv into a list of Insert statements, or perhaps a different delimiter will work.
Over at SuperUser I saw a suggestion to use LogParser to deal with csv files, I'm going to look into that.
Swift 5.1, Xcode 11:
public extension String {
/// Assuming the current string is base64 encoded, this property returns a String
/// initialized by converting the current string into Unicode characters, encoded to
/// utf8. If the current string is not base64 encoded, nil is returned instead.
var base64Decoded: String? {
guard let base64 = Data(base64Encoded: self) else { return nil }
let utf8 = String(data: base64, encoding: .utf8)
return utf8
}
/// Returns a base64 representation of the current string, or nil if the
/// operation fails.
var base64Encoded: String? {
let utf8 = self.data(using: .utf8)
let base64 = utf8?.base64EncodedString()
return base64
}
}
Having unsigned
in variable declaration is more useful for the programmers themselves - don't treat the variables as negative. As you've noticed, both -1
and 4294967295
have exact same bit representation for a 4 byte integer. It's all about how you want to treat or see them.
The statement unsigned int a = -1;
is converting -1
in two's complement and assigning the bit representation in a
. The printf()
specifier x
, d
and u
are showing how the bit representation stored in variable a
looks like in different format.
You are absolutely correct. We cannot instantiate an abstract class because abstract methods don't have any body i.e. implementation is not possible for abstract methods. But there may be some scenarios where you want to initialize some variables of base class. You can do that by using base keyword as suggested by @Rodrick. In such cases, we need to use constructors in our abstract class.
If you are experiencing errors during PKG installation following the accepted answer, I will give you another procedure that worked for me (please note the little changes to xar, cpio and mkbom commands):
mkdir Foo
cd Foo
xar -xf ../Foo.pkg
cd foo.pkg
cat Payload | gunzip -dc | cpio -i
# edit Foo.app/*
rm Payload
find ./Foo.app | cpio -o --format odc --owner 0:80 | gzip -c > Payload
mkbom -u 0 -g 80 Foo.app Bom # or edit Bom
# edit PackageInfo
rm -rf Foo.app
cd ..
xar --compression none -cf ../Foo-new.pkg
The resulted PKG will have no compression, cpio now uses odc format and specify the owner of the file as well as mkbom.
git checkout master
git pull
should do the job.
You will get the "Your branch is behind" message every time when you work on a branch different than master, someone does changes to master and you git pull.
(branch) $ //hack hack hack, while someone push the changes to origin/master
(branch) $ git pull
now the origin/master reference is pulled, but your master is not merged with it
(branch) $ git checkout master
(master) $
now master is behind origin/master and can be fast forwarded
this will pull and merge (so merge also newer commits to origin/master)
(master) $ git pull
this will just merge what you have already pulled
(master) $ git merge origin/master
now your master and origin/master are in sync
I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.
To answer the question in the header: To install make in ubuntu you have to install build-essentials
sudo apt-get install build-essential
Use git clean
Get help on this running
git clean -h
If you want to see what would happen first, make sure to pass the -n switch for a dry run:
git clean -xn
To remove gitingnored garbage
git clean -xdf
Careful: You may be ignoring local config files like database.yml which would also be removed. Use at your own risk.
Then
git add .
git commit -m ".gitignore is now working"
git push
In my case, the host was unkown and instead of typing yes
to the question are you sure you want to continue connecting(yes/no/[fingerprint])?
I was just hitting enter
.
You can switch to manual build so can control when this is done. Just make sure that Project > Build Automatically
from the main menu is unchecked.
I think this is the clearest way:
require 'open-uri'
File.write 'image.png', open('http://example.com/image.png').read
Those errors :
"CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage"
means you haven't installed mingw32-base.
Go to http://sourceforge.net/projects/mingw/files/latest/download?source=files
and then make sure you select "mingw32-base"
Make sure you set up environment variables correctly in PATH section. "C:\MinGW\bin"
After that open CMake and Select Installation --> Delete Cache.
And click configure button again. I solved the problem this way, hope you solve the problem.
How about adding a new script tag to <head> with the script to (re)load? Something like below:
<script>
function load_js()
{
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
script.src= 'source_file.js';
head.appendChild(script);
}
load_js();
</script>
The main point is inserting a new script tag -- you can remove the old one without consequence. You may need to add a timestamp to the query string if you have caching issues.
string replace() function perfectly solves this problem:
string.replace(s, old, new[, maxreplace])
Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.
>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)
u'longlong?stringTEST'
The args parameter stores all command line arguments which are given by the user when you run the program.
If you run your program from the console like this:
program.exe there are 4 parameters
Your args parameter will contain the four strings: "there", "are", "4", and "parameters"
Here is an example of how to access the command line arguments from the args parameter: example
Sounds like you're trying to execute the PHP code directly in your shell. Your shell doesn't speak PHP, so it interprets your PHP code as though it's in your shell's native language, as though you had literally run <?php
at the command line.
Shell scripts usually start with a "shebang" line that tells the shell what program to use to interpret the file. Begin your file like this:
#!/usr/bin/env php
<?php
//Connection
function connection () {
Besides that, the string you're passing to exec
doesn't make any sense. It starts with a slash all by itself, it uses too many periods in the path, and it has a stray right parenthesis.
Copy the contents of the command string and paste them at your command line. If it doesn't run there, then exec
probably won't be able to run it, either.
Another option is to change the command you execute. Instead of running the script directly, run php
and pass your script as an argument. Then you shouldn't need the shebang line.
exec('php name.php');
First of all, there are still browsers out there that don't support those pseudo-elements (ie. :first-child, :last-child), so you have to 'deal' with this issue.
There is a good example how to make that work without using pseudo-elements:
-- see the divider pipe example.
I hope that was useful.
Try using a format like %d.%02d
int iAmount = 10050;
printf("The number with fake decimal point is %d.%02d", iAmount/100, iAmount%100);
Another approach is to type cast it to double before printing it using %f like this:
printf("The number with fake decimal point is %0.2f", (double)(iAmount)/100);
My 2 cents :)
FormsModule
should be added at imports array
not declarations array
.
BrowserModule
, FormsModule
, HttpModule
Components
, Pipes
, Directives
refer below change:
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
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
You could set its width
:
<input type="text" id="text" name="text_name" style="width: 300px;" />
or even better define a class:
<input type="text" id="text" name="text_name" class="mytext" />
and in a separate CSS file apply the necessary styling:
.mytext {
width: 300px;
}
If you want to limit the number of characters that the user can type into this textbox you could use the maxlength
attribute:
<input type="text" id="text" name="text_name" class="mytext" maxlength="25" />
After gone throug the various post, this worked fine for me doing on IntelliJ Idea
:
java -cp "./lib/*;Path to your test.class" org.testng.TestNG testng.xml
Here is my directory structure:
/lib
-- all jar including testng.jar
/out
--/production/Example1/test.class
/src
-- test.java
testing.xml
So execute by this command:
java -cp "./lib/*;C:\Users\xyz\IdeaProjects\Example1\out\production\Example1" org.testng.TestNG testng.xml
My project directory Example1
is in the path:
C:\Users\xyz\IdeaProjects\
Here is another alternative. Download it directly here: http://androidsdkoffline.blogspot.com.ng/p/android-sdk-tools.html.
The present version as of this writing is Android SDK Tools 25.1.7. Unzip it when the download is done and place it in your sdk folder. You can then download other missing files directly from the SDK Manager.
Given the lack of information regarding the original image size, specifying percentages for the width and height would result in highly erratic results. If you are trying to ensure that an image will fit within a specific location on your page then you'll need to use some server side code to manage that rescaling.
bool exists = arr.Contains("One");
I have created siple code-only implementation which works fine for WPF and Silverlight as well:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
public class TextBoxWatermarked : TextBox
{
#region [ Dependency Properties ]
public static DependencyProperty WatermarkProperty = DependencyProperty.Register("Watermark",
typeof(string),
typeof(TextBoxWatermarked),
new PropertyMetadata(new PropertyChangedCallback(OnWatermarkChanged)));
#endregion
#region [ Fields ]
private bool _isWatermarked;
private Binding _textBinding;
#endregion
#region [ Properties ]
protected new Brush Foreground
{
get { return base.Foreground; }
set { base.Foreground = value; }
}
public string Watermark
{
get { return (string)GetValue(WatermarkProperty); }
set { SetValue(WatermarkProperty, value); }
}
#endregion
#region [ .ctor ]
public TextBoxWatermarked()
{
Loaded += (s, ea) => ShowWatermark();
}
#endregion
#region [ Event Handlers ]
protected override void OnGotFocus(RoutedEventArgs e)
{
base.OnGotFocus(e);
HideWatermark();
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
ShowWatermark();
}
private static void OnWatermarkChanged(DependencyObject sender, DependencyPropertyChangedEventArgs ea)
{
var tbw = sender as TextBoxWatermarked;
if (tbw == null) return;
tbw.ShowWatermark();
}
#endregion
#region [ Methods ]
private void ShowWatermark()
{
if (string.IsNullOrEmpty(base.Text))
{
_isWatermarked = true;
base.Foreground = new SolidColorBrush(Colors.Gray);
var bindingExpression = GetBindingExpression(TextProperty);
_textBinding = bindingExpression == null ? null : bindingExpression.ParentBinding;
if (bindingExpression != null)
bindingExpression.UpdateSource();
SetBinding(TextProperty, new Binding());
base.Text = Watermark;
}
}
private void HideWatermark()
{
if (_isWatermarked)
{
_isWatermarked = false;
ClearValue(ForegroundProperty);
base.Text = "";
SetBinding(TextProperty, _textBinding ?? new Binding());
}
}
#endregion
}
Usage:
<TextBoxWatermarked Watermark="Some text" />
VBA is not VB/VB.NET
The correct reference to use is Do..Loop Statement (VBA). Also see the article Excel VBA For, Do While, and Do Until. One way to write this is:
Do While counter < 20
counter = counter + 1
Loop
(But a For..Next might be more appropriate here.)
Happy coding.
osascript -e "tell application \"System Events\" to keystroke \"w\" using command down"
This simulates a CMD + w keypress.
If you want Terminal to quit completely you can use:
osascript -e "tell application \"System Events\" to keystroke \"q\" using command down"
This doesn't give any errors and makes the Terminal stop cleanly.
Actually, you only need to use the default
argument to add_argument
as in this test.py
script:
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--example', default=1)
args = parser.parse_args()
print(args.example)
test.py --example
% 1
test.py --example 2
% 2
Details are here.
If number
could be None
or a number, and you wanted to include 0
, filter on None
instead:
if number is not None:
If number
can be any number of types, test for the type; you can test for just int
or a combination of types with a tuple:
if isinstance(number, int): # it is an integer
if isinstance(number, (int, float)): # it is an integer or a float
or perhaps:
from numbers import Number
if isinstance(number, Number):
to allow for integers, floats, complex numbers, Decimal
and Fraction
objects.
I had this issue after migrating from spring-boot-starter-data-jpa
ver. 1.5.7 to 2.0.2 (from old hibernate to hibernate 5.2). In my @Configuration
class I injected entityManagerFactory
and transactionManager
.
//I've got my data source defined in application.yml config file,
//so there is no need to configure it from java.
@Autowired
DataSource dataSource;
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
//JpaVendorAdapteradapter can be autowired as well if it's configured in application properties.
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(false);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
//Add package to scan for entities.
factory.setPackagesToScan("com.company.domain");
factory.setDataSource(dataSource);
return factory;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory);
return txManager;
}
Also remember to add hibernate-entitymanager dependency to pom.xml otherwise EntityManagerFactory won't be found on classpath:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.0.12.Final</version>
</dependency>
In rare cases, it can be useful to change the line that is given by __LINE__
to something else. I've seen GNU configure does that for some tests to report appropriate line numbers after it inserted some voodoo between lines that do not appear in original source files. For example:
#line 100
Will make the following lines start with __LINE__
100. You can optionally add a new file-name
#line 100 "file.c"
It's only rarely useful. But if it is needed, there are no alternatives I know of. Actually, instead of the line, a macro can be used too which must result in any of the above two forms. Using the boost preprocessor library, you can increment the current line by 50:
#line BOOST_PP_ADD(__LINE__, 50)
I thought it's useful to mention it since you asked about the usage of __LINE__
and __FILE__
. One never gets enough surprises out of C++ :)
Edit: @Jonathan Leffler provides some more good use-cases in the comments:
Messing with #line is very useful for pre-processors that want to keep errors reported in the user's C code in line with the user's source file. Yacc, Lex, and (more at home to me) ESQL/C preprocessors do that.
seems that currently there is no difference between the 2 functions, as shown on the source code (credit to this post) :
public void setBackground(Drawable background) {
//noinspection deprecation
setBackgroundDrawable(background);
}
@Deprecated
public void setBackgroundDrawable(Drawable background) { ... }
so it's just a naming decision, similar to the one with fill-parent vs match-parent .
gem list --no-version | grep -v -e 'psych' -e 'rdoc' -e 'openssl' -e 'json' -e 'io-console' -e 'bigdecimal' | xargs sudo gem uninstall -ax
grep here is excluding default gems. All other gems will be uninstalled. You can also precede it with sudo
in case you get permission issues.
Previous examples have two main drawbacks:
Below is a solution which has not such drawbacks.
By the default, the 'popover' element is inserted immediately after the referenced-element in the DOM (then notice the referenced-element and the popover are immediate sibling elements). Thus, when the 'close' button is clicked, you can simply look for its closest 'div.popover' parent, and then look for the immediately preceding sibling element of such parent.
Just add the following code in the 'onclick' handler of the 'close button:
$(this).closest('div.popover').popover('hide');
Example:
var genericCloseBtnHtml = '<button onclick="$(this).closest(\'div.popover\').popover(\'hide\');" type="button" class="close" aria-hidden="true">×</button>';
$loginForm.popover({
placement: 'auto left',
trigger: 'manual',
html: true,
title: 'Alert' + genericCloseBtnHtml,
content: 'invalid email and/or password'
});
Instead of using
response.sendRedirect("/demo.jsp");
Which does a permanent redirect to an absolute URL path,
Rather use RequestDispatcher
. Example:
RequestDispatcher dispatcher = request.getRequestDispatcher("demo.jsp");
dispatcher.forward(request, response);
For Bootstrap 4, there are now spacing utilities so it's easier to change the height via padding on the nav links. This can be responsively applied only at specific breakpoints (ie: py-md-3
). For example, on larger (md) screens, this nav is 120px high, then shrinks to normal height for the mobile menu. No extra CSS is needed..
<nav class="navbar navbar-fixed-top navbar-inverse bg-primary navbar-toggleable-md py-md-3">
<button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
<div class="navbar-collapse collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item py-md-3"><a href="#" class="nav-link">Home</a></li>
<li class="nav-item py-md-3"><a href="#" class="nav-link">Link</a></li>
<li class="nav-item py-md-3"><a href="#" class="nav-link">Link</a></li>
<li class="nav-item py-md-3"><a href="#" class="nav-link">More</a></li>
<li class="nav-item py-md-3"><a href="#" class="nav-link">Options</a></li>
</ul>
</div>
</nav>
Its not exactly elegant, but if you use List.listIterator(int index) you can get a bi-directional ListIterator to the end of the list:
//Assume List<String> foo;
ListIterator li = foo.listIterator(foo.size());
while (li.hasPrevious()) {
String curr = li.previous()
}
This comes from the official site of Chome-devtools and it helps. Here i quote:
- Queuing If a request is queued it indicated that:
- The request was postponed by the rendering engine because it's considered lower priority than critical resources (such as scripts/styles). This often happens with images.
- The request was put on hold to wait for an unavailable TCP socket that's about to free up.
- The request was put on hold because the browser only allows six TCP connections per origin on HTTP 1. Time spent making disk cache entries (typically very quick.)
- Stalled/Blocking Time the request spent waiting before it could be sent. It can be waiting for any of the reasons described for Queueing. Additionally, this time is inclusive of any time spent in proxy negotiation.
As per comment from @Paul, If display: block is specified, span stops to be an inline element and an element after it appears on next line.
I came here to find solution to my span height problem and I got a solution of my own
Adding overflow:hidden;
and keeing it inline will solve the problem just tested in IE8 Quirks mode
This is a one-liner which avoids delayed expansion, which could disturb certain commands:
cmd /E /C "prompt $T$$ & echo.%TIME%$ & COMMAND_TO_MEASURE & for %Z in (.) do rem/ "
The output is something like:
14:30:27.58$ ... 14:32:43.17$ rem/
For long-term tests replace $T
by $D, $T
and %TIME%
by %DATE%, %TIME%
to include the date.
To use this inside of a batch file, replace %Z
by %%Z
.
Here is an improved one-liner (without delayed expansion too):
cmd /E /C "prompt $D, $T$$ & (for %# in (.) do rem/ ) & COMMAND_TO_MEASURE & for %# in (.) do prompt"
The output looks similar to this:
2015/09/01, 14:30:27.58$ rem/ ... 2015/09/01, 14:32:43.17$ prompt
This approach does not include the process of instancing a new cmd
in the result, nor does it include the prompt
command(s).
The tr
command could be replaced by //
bashism:
COMMAND=$'\nREBOOT\r \n'
echo "|${COMMAND}|"
|
OOT
|
echo "|${COMMAND//[$'\t\r\n']}|"
|REBOOT |
echo "|${COMMAND//[$'\t\r\n ']}|"
|REBOOT|
See Parameter Expansion and QUOTING in bash's man page:
man -Pless\ +/\/pattern bash
man -Pless\ +/\\\'string\\\' bash
man -Pless\ +/^\\\ *Parameter\\\ Exp bash
man -Pless\ +/^\\\ *QUOTING bash
As asked by @AlexJordan, this will suppress all specified characters. So what if $COMMAND
do contain spaces...
COMMAND=$' \n RE BOOT \r \n'
echo "|$COMMAND|"
|
BOOT
|
CLEANED=${COMMAND//[$'\t\r\n']}
echo "|$CLEANED|"
| RE BOOT |
shopt -q extglob || { echo "Set shell option 'extglob' on.";shopt -s extglob;}
CLEANED=${CLEANED%%*( )}
echo "|$CLEANED|"
| RE BOOT|
CLEANED=${CLEANED##*( )}
echo "|$CLEANED|"
|RE BOOT|
Shortly:
COMMAND=$' \n RE BOOT \r \n'
CLEANED=${COMMAND//[$'\t\r\n']} && CLEANED=${CLEANED%%*( )}
echo "|${CLEANED##*( )}|"
|RE BOOT|
Note: bash have extglob
option to be enabled (shopt -s extglob
) in order to use *(...)
syntax.
The below function would return '0' if there is no match and a 'positive integer' in case of matching:
Function IsInArray(stringToBeFound As String, arr As Variant) As Integer
IsInArray = InStr(Join(arr, ""), stringToBeFound)
End Function
______________________________________________________________________________
Note: the function first concatenates the entire array content to a string using 'Join' (not sure if the join method uses looping internally or not) and then checks for a macth within this string using InStr.
To complete Sunit's answer, you can use a selector, not to the text string but to the textColorHint. You must add this attribute on your editText:
android:textColorHint="@color/text_hint_selector"
And your text_hint_selector should be:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:color="@android:color/transparent" />
<item android:color="@color/hint_color" />
</selector>
export PATH=$PATH:/usr/local/git/bin:/usr/local/bin
One note: you don't need quotation marks here because it's on the right hand side of an assignment, but in general, and especially on Macs with their tradition of spacy pathnames, expansions like $PATH
should be double-quoted as "$PATH"
.
You can try this:
df['2nd'] = pd.to_numeric(df['2nd'].str.replace(',', ''))
df['CTR'] = pd.to_numeric(df['CTR'].str.replace('%', ''))
MySQL is the same:
select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'tablename'
As pointed out in comments, you cannot call cellForRowAtIndexPath
inside heightForRowAtIndexPath
.
What you can do is creating a template cell used to populate with your data and then compute its height. This cell doesn't participate to the table rendering, and it can be reused to calculate the height of each table cell.
Briefly, it consists of configuring the template cell with the data you want to display, make it resize accordingly to the content, and then read its height.
I have taken this code from a project I am working on - unfortunately it's in Objective C, I don't think you will have problems translating to swift
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
static PostCommentCell *sizingCell = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sizingCell = [self.tblComments dequeueReusableCellWithIdentifier:POST_COMMENT_CELL_IDENTIFIER];
});
sizingCell.comment = self.comments[indexPath.row];
[sizingCell setNeedsLayout];
[sizingCell layoutIfNeeded];
CGSize size = [sizingCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
return size.height;
}
What about having different names for your dev and prod servers? That should avoid any confusions and you'd not have to edit the hosts file every time.
<?php echo substr($string, 0, strlen($string) - 3); ?>
One classic root cause for this message is:
git init lis4368/assignments
),Ie, if you don't have added and committed at least once, there won't be a local master
branch to push to.
Try first to create a commit:
git add .
) then git commit -m "first commit"
git commit --allow-empty -m "Initial empty commit"
And then try git push -u origin master
again.
See "Why do I need to explicitly push a new branch?" for more.
As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().
Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static
for the example. Once it's done, add this line in your server code:
app.use("/static", express.static('./static/'));
This will effectively serve every file in your "static" folder via the /static route.
Querying your index.js file in the client thus becomes:
<script src="static/index.js"></script>
If you want to create and copy the content in a single shot, just use the SELECT
:
CREATE TABLE new_tbl SELECT * FROM orig_tbl;
If you are not wanting to use async
you can add .Result
to force the code to execute synchronously:
private string GetResponseString(string text)
{
var httpClient = new HttpClient();
var parameters = new Dictionary<string, string>();
parameters["text"] = text;
var response = httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters)).Result;
var contents = response.Content.ReadAsStringAsync().Result;
return contents;
}
Nick Vogt at H3XED posted this syntax: https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080
Take this link and replace the expression "VIDEOID" with the (shortened/shared) ID of the video.
Exapmple for ID: i3jNECZ3ybk looks like this: ... /v/i3jNECZ3ybk?version=3&vq=hd1080
What you get as a result is the standalone 1080p video but not in the Tube environment.
You are using wrong formatting sequence for double
, you should use %lf
instead of %ld
:
double a;
scanf("%lf",&a);
Depending on your application, you might want to implement regex matching for the countries where most of your visitors originate and no validation for the rest (accept anything).
The docs show you are now able to add:
"env": {
"jest/globals": true
}
To your .eslintrc
which will add all the jest related things to your environment, eliminating the linter errors/warnings.
.getJson is simply a wrapper around .ajax but it provides a simpler method signature as some of the settings are defaulted e.g dataType to json, type to get etc
N.B .load, .get and .post are also simple wrappers around the .ajax method.
In WPF there is a control named Popup.
Popup myPopup = new Popup();
//(...)
myPopup.IsOpen = true;
You can use AngularJS build-in service $rootScope
and inject this service in both of your controllers.
You can then listen for events that are fired on $rootScope object.
$rootScope provides two event dispatcher called $emit and $broadcast
which are responsible for dispatching events(may be custom events) and use $rootScope.$on
function to add event listener.
Trim just removes the trailing and leading whitespace. Use .replace(/ /g, "") if there are just spaces to be replaced.
this.maintabinfo = this.inner_view_data.replace(/ /g, "").toLowerCase();
My experiments show that it definitely helps to call Stream.ReadByte() fewer times, but using BitConverter to package bytes does not make much difference against comparing bytes in a byte array.
So it is possible to replace that "Math.Ceiling and iterations" loop in the comment above with the simplest one:
for (int i = 0; i < count1; i++)
{
if (buffer1[i] != buffer2[i])
return false;
}
I guess it has to do with the fact that BitConverter.ToInt64 needs to do a bit of work (check arguments and then perform the bit shifting) before you compare and that ends up being the same amount of work as compare 8 bytes in two arrays.
I ran into this error on a fresh build of Windows Server 2012 R2. IIS and .NET 4.5 had been installed, but the ASP.NET Server Role (version 4.5 in my case) had not been added. Make sure that the version of ASP.NET you need has been added/installed like ASP.NET 4.5 is in this screenshot.
This is what worked for me
curl --form file='@filename' URL
It seems when I gave this answer (4+ years ago), I didn't really understand the question, or how form fields worked. I was just answering based on what I had tried in a difference scenario, and it worked for me.
So firstly, the only mistake the OP made was in not using the @
symbol before the file name. Secondly, my answer which uses file=...
only worked for me because the form field I was trying to do the upload for was called file
. If your form field is called something else, use that name instead.
From the curl
manpages; under the description for the option --form
it says:
This enables uploading of binary files etc. To force the 'content' part to be a file, prefix the file name with an @ sign. To just get the content part from a file, prefix the file name with the symbol <. The difference between @ and < is then that @ makes a file get attached in the post as a file upload, while the < makes a text field and just get the contents for that text field from a file.
Chances are that if you are trying to do a form upload, you will most likely want to use the @
prefix to upload the file rather than <
which uploads the contents of the file.
Now I must also add that one must be careful with using the <
symbol because in most unix shells, <
is the input redirection symbol [which coincidentally will also supply the contents of the given file to the command standard input of the program before <
]. This means that if you do not properly escape that symbol or wrap it in quotes, you may find that your curl
command does not behave the way you expect.
On that same note, I will also recommend quoting the @
symbol.
You may also be interested in this other question titled: application/x-www-form-urlencoded or multipart/form-data?
I say this because curl
offers other ways of uploading a file, but they differ in the content-type set in the header. For example the --data
option offers a similar mechanism for uploading files as data, but uses a different content-type for the upload.
Anyways that's all I wanted to say about this answer since it started to get more upvotes. I hope this helps erase any confusions such as the difference between this answer and the accepted answer. There is really none, except for this explanation.
To put text, use .text('text')
If you want to use .html(SomeValue)
, SomeValue should have html tags that can be inside a div it must work too.
Just check your script location, as farzad said.
1) for example HTML code:
<ul>
<li>
<a href="#">firstlink</a>
<span><a href="#">second link</a>
</li>
</ul>
and css rules:
1) ul li a {color:red;}
2) ul > li > a {color:blue;}
">" - symbol mean that that will be searching only child selector (parentTag > childTag)
so first css rule will apply to all links (first and second) and second rule will apply anly to first link
2) As for efficiency - I think second will be more fast - as in case with JavaScript selectors. This rule read from right to left, this mean that when rule will parse by browser, it get all links on page: - in first case it will find all parent elements for each link on page and filter all links where exist parent tags "ul" and "li" - in second case it will check only parent node of link if it is "li" tag then -> check if parent tag of "li" is "ul"
some thing like this. Hope I describe all properly for you
You can sed's -i
option to edit in-place without using temporary file:
sed -i '/^$/d' file
I tried the accepted answer, it did not work.
However the simple way to do it is below:-
<option value="1" <c:if test="${item.quantity == 1}"> <c:out value= "selected=selected"/</c:if>>1</option>
<option value="2" <c:if test="${item.quantity == 2}"> <c:out value= "selected=selected"/</c:if>>2</option>
<option value="3" <c:if test="${item.quantity == 3}"> <c:out value= "selected=selected"/</c:if>>3</option>
Enjoy!!
People are confusing about what closure is. Closure is not the inner function. the meaning of closure is act of closing. So inner function is closing over a nonlocal variable which is called free variable.
def counter_in(initial_value=0):
# initial_value is the free variable
def inc(increment=1):
nonlocal initial_value
initial_value += increment
return print(initial_value)
return inc
when you call counter_in()
this will return inc
function which has a free variable initial_value
. So we created a CLOSURE. people call inc
as closure function and I think this is confusing people, people think "ok inner functions are closures". in reality inc
is not a closure, since it is part of the closure, to make life easy, they call it closure function.
myClosingOverFunc=counter_in(2)
this returns inc
function which is closing over the free variable initial_value
. when you invoke myClosingOverFunc
myClosingOverFunc()
it will print 2.
when python sees that a closure sytem exists, it creates a new obj called CELL. this will store only the name of the free variable which is initial_value
in this case. This Cell obj will point to another object which stores the value of the initial_value
.
in our example, initial_value
in outer function and inner function will point to this cell object, and this cell object will be point to the value of the initial_value
.
variable initial_value =====>> CELL ==========>> value of initial_value
So when you call counter_in
its scope is gone, but it does not matter. because variable initial_value
is directly referencing the CELL Obj. and it indirectly references the value of initial_value
. That is why even though scope of outer function is gone, inner function will still have access to the free variable
let's say I want to write a function, which takes in a function as an arg and returns how many times this function is called.
def counter(fn):
# since cnt is a free var, python will create a cell and this cell will point to the value of cnt
# every time cnt changes, cell will be pointing to the new value
cnt = 0
def inner(*args, **kwargs):
# we cannot modidy cnt with out nonlocal
nonlocal cnt
cnt += 1
print(f'{fn.__name__} has been called {cnt} times')
# we are calling fn indirectly via the closue inner
return fn(*args, **kwargs)
return inner
in this example cnt
is our free variable and inner
+ cnt
create CLOSURE. when python sees this it will create a CELL Obj and cnt
will always directly reference this cell obj and CELL will reference the another obj in the memory which stores the value of cnt
. initially cnt=0.
cnt ======>>>> CELL =============> 0
when you invoke the inner function wih passing a parameter counter(myFunc)()
this will increase the cnt by 1. so our referencing schema will change as follow:
cnt ======>>>> CELL =============> 1 #first counter(myFunc)()
cnt ======>>>> CELL =============> 2 #second counter(myFunc)()
cnt ======>>>> CELL =============> 3 #third counter(myFunc)()
this is only one instance of closure. You can create multiple instances of closure with passing another function
counter(differentFunc)()
this will create a different CELL obj from the above. We just have created another closure instance.
cnt ======>> difCELL ========> 1 #first counter(differentFunc)()
cnt ======>> difCELL ========> 2 #secon counter(differentFunc)()
cnt ======>> difCELL ========> 3 #third counter(differentFunc)()
See my code:
@IBAction func foundclicked(sender: AnyObject) {
if (amountTF.text.isEmpty)
{
let alert = UIAlertView(title: "Oops! Empty Field", message: "Please enter the amount", delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
else {
var alertController = UIAlertController(title: "Confirm Bid Amount", message: "Final Bid Amount : "+amountTF.text , preferredStyle: .Alert)
var okAction = UIAlertAction(title: "Confirm", style: UIAlertActionStyle.Default) {
UIAlertAction in
JHProgressHUD.sharedHUD.loaderColor = UIColor.redColor()
JHProgressHUD.sharedHUD.showInView(self.view, withHeader: "Amount registering" , andFooter: "Loading")
}
var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
UIAlertAction in
alertController .removeFromParentViewController()
}
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
For someone who hate OOP like me (This is based on Bryan Oakley's answer)
import tkinter as tk
def show_label():
label1.lift()
def hide_label():
label1.lower()
root = tk.Tk()
frame1 = tk.Frame(root)
frame1.pack()
label1 = tk.Label(root, text="Hello, world")
label1.pack(in_=frame1)
button1 = tk.Button(root, text="Click to hide label",command=hide_label)
button2 = tk.Button(root, text="Click to show label", command=show_label)
button1.pack(in_=frame1)
button2.pack(in_=frame1)
root.mainloop()
Codecs proper:
ffmpeg -codecs
Formats:
ffmpeg -formats
If you would to validate WSDL programatically then you use WSDL Validator out of eclipse. http://wiki.eclipse.org/Using_the_WSDL_Validator_Outside_of_Eclipse should help or try this tool Graphical WSDL 1.1/2.0 editor.
for refresh data gridview in any where you just need this code:
datagridview1.DataSource = "your DataSource";
datagridview1.Refresh();
The style that you give the "g" element will apply the child elements, not the "g" element itself.
Add a rectangle element and position around the group you wish to style.
See: https://developer.mozilla.org/en-US/docs/Web/SVG/Element/g
EDIT: updated wording and added fiddle in comments.
If you use normalize.css, that stylesheet will do something like input[type="search"] { -webkit-appearance: textfield; }
.
This has a higher specificity than a single class selector like .foo
, so be aware that you then can't do just .my-field { -webkit-appearance: none; }
. If you have no better way to achieve the right specificity, this will help:
.my-field { -webkit-appearance: none !important; }
If you are using C++, why don't you use std::string
instead of C-style strings?
std::string one="Hello";
std::string two="World";
std::string three= one+two;
If you need to pass this string to a C-function, simply pass three.c_str()
Some of the answers here are for infinite page. What Salman is asking is lazy loading of images.
EDIT: How do these plugins work?
This is a simplified explanation:
cd
has a parameter /d
, which will change drive and path with one command:
cd /d d:\temp
( see cd /?
)
What are the advantages of having a contiguous block of memory? Specifically, why would I need to have a contiguous physical block of memory in a system call? Is there any reason I couldn't just use vmalloc?
From Google's "I'm Feeling Lucky" on vmalloc
:
kmalloc is the preferred way, as long as you don't need very big areas. The trouble is, if you want to do DMA from/to some hardware device, you'll need to use kmalloc, and you'll probably need bigger chunk. The solution is to allocate memory as soon as possible, before memory gets fragmented.
git remote add
=> ADDS a new remote.
git remote set-url
=> UPDATES existing remote.
add
is a new remote name that did not exist prior to that command.set-url
should already exist as a remote name to your repository.git remote add myupstream someurl
=> myupstream remote name did not exist now creating it with this command.
git remote set-url upstream someurl
=> upstream remote name already exist i'm just changing it's url.
git remote add myupstream https://github.com/nodejs/node => **ADD** If you don't already have upstream
git remote set-url upstream https://github.com/nodejs/node # => **UPDATE** url for upstream
NSLog
below code somewhere in "AppDelegate", run your project and follow the path. This will be easy for you to get to the documents rather than searching randomly inside "~/Library/Developer/CoreSimulator/Devices/"
Objective-C
NSLog(@"%@",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);
Swift
If you are using Swift 1.2, use the code below which will only output in development when using the Simulator because of the #if
#endif
block:
#if arch(i386) || arch(x86_64)
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString
NSLog("Document Path: %@", documentsPath)
#endif
Copy your path from "/Users/ankur/Library/Developer/CoreSimulator/Devices/7BA821..." go to "Finder" and then "Go to Folder" or command + shift + g and paste your path, let the mac take you to your documents directory :)
In SSMS:
Right click on the database > Tasks > Generate Scripts
Next
Select "Select specific database objects" and check the table you want scripted, Next
Click Advanced >
in the list of options, scroll down to the bottom and look for the "Types of data to script" and change it to "Data Only" > OK
Select "Save to new query window" > Next > Next > Finish
All 180 rows now written as 180 insert statements!
Map
does not supports duplicate keys. you can use collection as value against same key.
Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value.
you can use any kind of List
or Set
implementation according to your requirement.
If your values might be also duplicate you can go with ArrayList
or LinkedList
, in case values are unique you can use HashSet
or TreeSet
etc.
Also In google guava collection library Multimap
is available, it is a collection that maps keys to values, similar to Map, but in which each key may be associated with multiple values. You can visualize the contents of a multimap either as a map from keys to nonempty collections of values:
a ? 1, 2
b ? 3
Example -
ListMultimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("a", "1");
multimap.put("a", "2");
multimap.put("c", "3");
Action Sheet in iOS10 with Swift3.0. Follow this link.
@IBAction func ShowActionSheet(_ sender: UIButton) {
// Create An UIAlertController with Action Sheet
let optionMenuController = UIAlertController(title: nil, message: "Choose Option from Action Sheet", preferredStyle: .actionSheet)
// Create UIAlertAction for UIAlertController
let addAction = UIAlertAction(title: "Add", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("File has been Add")
})
let saveAction = UIAlertAction(title: "Edit", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("File has been Edit")
})
let deleteAction = UIAlertAction(title: "Delete", style: .default, handler: {
(alert: UIAlertAction!) -> Void in
print("File has been Delete")
})
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: {
(alert: UIAlertAction!) -> Void in
print("Cancel")
})
// Add UIAlertAction in UIAlertController
optionMenuController.addAction(addAction)
optionMenuController.addAction(saveAction)
optionMenuController.addAction(deleteAction)
optionMenuController.addAction(cancelAction)
// Present UIAlertController with Action Sheet
self.present(optionMenuController, animated: true, completion: nil)
}
According to the specification, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf:
A string is a sequence of Unicode code points wrapped with quotation marks (
U+0022
). All characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark (U+0022
), reverse solidus (U+005C
), and the control charactersU+0000
toU+001F
. There are two-character escape sequence representations of some characters.
So you can't pass 0x0A
or 0x0C
codes directly. It is forbidden! The specification suggests to use escape sequences for some well-defined codes from U+0000
to U+001F
:
\f
represents the form feed character (U+000C
).\n
represents the line feed character (U+000A
).As most of programming languages uses \
for quoting, you should escape the escape syntax (double-escape - once for language/platform, once for JSON itself):
jsonStr = "{ \"name\": \"Multi\\nline.\" }";
What you need is called attribute selector. An example, using your html structure, is the following:
div[class^="tocolor-"], div[class*=" tocolor-"] {
color:red
}
In the place of div
you can add any element or remove it altogether, and in the place of class
you can add any attribute of the specified element.
[class^="tocolor-"]
— starts with "tocolor-".
[class*=" tocolor-"]
— contains the substring "tocolor-" occurring directly after a space character.
Demo: http://jsfiddle.net/K3693/1/
More information on CSS attribute selectors, you can find here and here. And from MDN Docs MDN Docs
For databases:
Just use these commands:
USE db_name;
SELECT @@character_set_database;
-- or:
-- SELECT @@collation_database;
Just delete the ".project" file in your project folder (it's hidden on Linux, use "ls -a" to show), then from Eclipse, choose Create Android Project from existing source
UseEnvironment.NewLine
instead of vbcrlf
You can use sprintf: http://php.net/manual/en/function.sprintf.php
<?php
$num = 4;
$num_padded = sprintf("%02d", $num);
echo $num_padded; // returns 04
?>
It will only add the zero if it's less than the required number of characters.
Edit: As pointed out by @FelipeAls:
When working with numbers, you should use %d
(rather than %s
), especially when there is the potential for negative numbers. If you're only using positive numbers, either option works fine.
For example:
sprintf("%04s", 10);
returns 0010
sprintf("%04s", -10);
returns 0-10
Where as:
sprintf("%04d", 10);
returns 0010
sprintf("%04d", -10);
returns -010
The old way:
xcopy [source] [destination] /E
xcopy is deprecated. Robocopy replaces Xcopy. It comes with Windows 8, 8.1 and 10.
robocopy [source] [destination] /E
robocopy has several advantages:
More details here.
public static class Utilities
{
public static T Deserialize<T>(string jsonString)
{
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
}
More information go to following link http://ishareidea.blogspot.in/2012/05/json-conversion.html
About DataContractJsonSerializer Class
you can read here.
It's only necessary to prepare the string variable first and then convert it to the RegEx.
for example:
You want to add minLength
and MaxLength
with the variable to RegEx:
function getRegEx() {
const minLength = "5"; // for exapmle: min is 5
const maxLength = "12"; // for exapmle: man is 12
var regEx = "^.{" + minLength + ","+ maxLength +"}$"; // first we make a String variable of our RegEx
regEx = new RegExp(regEx, "g"); // now we convert it to RegEx
return regEx; // In the end, we return the RegEx
}
now if you change value of MaxLength
or MinLength
, It will change in all RegExs.
Hope to be useful. Also sorry about my English.
On iOS there is the switch UI component instead of a checkbox, look into the UISwitch
class.
The property on
(boolean) can be used to determine the state of the slider and about the saving of its state: That depends on how you save your other stuff already, its just saving a boolean value.
<ul>
<li><strong>This text will be bold.</strong>This text will NOT be bold.
</li>
</ul>
Try:
InputStream inputStream= // Your InputStream from your database.
Reader reader = new InputStreamReader(inputStream,"UTF-8");
InputSource is = new InputSource(reader);
is.setEncoding("UTF-8");
saxParser.parse(is, handler);
If it's anything else than UTF-8, just change the encoding part for the good one.
If you can expect the browser's open/save interface to pop up for the user once the download is complete, then you can run this when you start the download:
$( document ).blur( function () {
// Your code here...
});
When the dialogue pops up on top of the page, the blur event will trigger.
Another interesing way is to use $redact, which is one of the new aggregation features of MongoDB 2.6. If you are using 2.6, you don't need an $unwind which might cause you performance problems if you have large arrays.
db.test.aggregate([
{ $match: {
shapes: { $elemMatch: {color: "red"} }
}},
{ $redact : {
$cond: {
if: { $or : [{ $eq: ["$color","red"] }, { $not : "$color" }]},
then: "$$DESCEND",
else: "$$PRUNE"
}
}}]);
$redact
"restricts the contents of the documents based on information stored in the documents themselves". So it will run only inside of the document. It basically scans your document top to the bottom, and checks if it matches with your if
condition which is in $cond
, if there is match it will either keep the content($$DESCEND
) or remove($$PRUNE
).
In the example above, first $match
returns the whole shapes
array, and $redact strips it down to the expected result.
Note that {$not:"$color"}
is necessary, because it will scan the top document as well, and if $redact
does not find a color
field on the top level this will return false
that might strip the whole document which we don't want.
I found this to work for me.
<script> document.write(unescape('%3Cscript src="' + window.location.protocol + "//" +
window.location.host + "/" + 'js/general.js?ver=2"%3E%3C/script%3E'))</script>
between script tags of course... (I'm not sure why the script tags didn't show up in this post)...
None of the above answers worked for me, here is my solution which updates a disabled input with the filename:
<script type="text/javascript">
document.getElementById('img_name').onchange = function () {
var filePath = this.value;
if (filePath) {
var fileName = filePath.replace(/^.*?([^\\\/]*)$/, '$1');
document.getElementById('img_name_input').value = fileName;
}
};
</script>
(Addendum to existing answers)
... And a deleted function shall be the first declaration of the function (except for deleting explicit specializations of function templates - deletion should be at the first declaration of the specialization), meaning you cannot declare a function and later delete it, say, at its definition local to a translation unit.
Citing [dcl.fct.def.delete]/4:
A deleted function is implicitly inline. ( Note: The one-definition rule ([basic.def.odr]) applies to deleted definitions. — end note ] A deleted definition of a function shall be the first declaration of the function or, for an explicit specialization of a function template, the first declaration of that specialization. [ Example:
struct sometype { sometype(); }; sometype::sometype() = delete; // ill-formed; not first declaration
— end example )
Albeit a general rule of thumb is to avoid specializing function templates as specializations do not participate in the first step of overload resolution, there are arguable some contexts where it can be useful. E.g. when using a non-overloaded primary function template with no definition to match all types which one would not like implicitly converted to an otherwise matching-by-conversion overload; i.e., to implicitly remove a number of implicit-conversion matches by only implementing exact type matches in the explicit specialization of the non-defined, non-overloaded primary function template.
Before the deleted function concept of C++11, one could do this by simply omitting the definition of the primary function template, but this gave obscure undefined reference errors that arguably gave no semantic intent whatsoever from the author of primary function template (intentionally omitted?). If we instead explicitly delete the primary function template, the error messages in case no suitable explicit specialization is found becomes much nicer, and also shows that the omission/deletion of the primary function template's definition was intentional.
#include <iostream>
#include <string>
template< typename T >
void use_only_explicit_specializations(T t);
template<>
void use_only_explicit_specializations<int>(int t) {
std::cout << "int: " << t;
}
int main()
{
const int num = 42;
const std::string str = "foo";
use_only_explicit_specializations(num); // int: 42
//use_only_explicit_specializations(str); // undefined reference to `void use_only_explicit_specializations< ...
}
However, instead of simply omitting a definition for the primary function template above, yielding an obscure undefined reference error when no explicit specialization matches, the primary template definition can be deleted:
#include <iostream>
#include <string>
template< typename T >
void use_only_explicit_specializations(T t) = delete;
template<>
void use_only_explicit_specializations<int>(int t) {
std::cout << "int: " << t;
}
int main()
{
const int num = 42;
const std::string str = "foo";
use_only_explicit_specializations(num); // int: 42
use_only_explicit_specializations(str);
/* error: call to deleted function 'use_only_explicit_specializations'
note: candidate function [with T = std::__1::basic_string<char>] has
been explicitly deleted
void use_only_explicit_specializations(T t) = delete; */
}
Yielding a more more readable error message, where the deletion intent is also clearly visible (where an undefined reference error could lead to the developer thinking this an unthoughtful mistake).
Returning to why would we ever want to use this technique? Again, explicit specializations could be useful to implicitly remove implicit conversions.
#include <cstdint>
#include <iostream>
void warning_at_best(int8_t num) {
std::cout << "I better use -Werror and -pedantic... " << +num << "\n";
}
template< typename T >
void only_for_signed(T t) = delete;
template<>
void only_for_signed<int8_t>(int8_t t) {
std::cout << "UB safe! 1 byte, " << +t << "\n";
}
template<>
void only_for_signed<int16_t>(int16_t t) {
std::cout << "UB safe! 2 bytes, " << +t << "\n";
}
int main()
{
const int8_t a = 42;
const uint8_t b = 255U;
const int16_t c = 255;
const float d = 200.F;
warning_at_best(a); // 42
warning_at_best(b); // implementation-defined behaviour, no diagnostic required
warning_at_best(c); // narrowing, -Wconstant-conversion warning
warning_at_best(d); // undefined behaviour!
only_for_signed(a);
only_for_signed(c);
//only_for_signed(b);
/* error: call to deleted function 'only_for_signed'
note: candidate function [with T = unsigned char]
has been explicitly deleted
void only_for_signed(T t) = delete; */
//only_for_signed(d);
/* error: call to deleted function 'only_for_signed'
note: candidate function [with T = float]
has been explicitly deleted
void only_for_signed(T t) = delete; */
}
In my experience all the files which i have downloaded from internet,gmail
are stored in
/sdcard/download
on ics
/sdcard/Download
You can access it using
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
One way of doing this is to do add junit.jar to your $CLASSPATH
as an external dependency.
So to do that, go to project structure, and then add JUnit as one of the libraries as shown in the gif.
In the 'Choose Modules' prompt choose only the modules that you'd need JUnit for.
New Excel versions
=IF(ISNA(VLOOKUP(A1,B,B,1,FALSE)),"",A1)
Older Excel versions
=IF(ISNA(VLOOKUP(A1;B:B;1;FALSE));"";A1)
That is: "If the value of A1 exists in the B column, display it here. If it doesn't exist, leave it empty."
Thanks for enlightening us Cypawer.
I also tried this app https://play.google.com/store/apps/details?id=com.oneguyinabasement.leapwifi
and it worked flawlessly.
I made a mix of the answers here, took the code of @Julian and ideas from the others, seems clearer to me, this is what's left:
//store the element
var $cache = $('.my-sticky-element');
//store the initial position of the element
var vTop = $cache.offset().top - parseFloat($cache.css('marginTop').replace(/auto/, 0));
$(window).scroll(function (event) {
// what the y position of the scroll is
var y = $(this).scrollTop();
// whether that's below the form
if (y >= vTop) {
// if so, ad the fixed class
$cache.addClass('stuck');
} else {
// otherwise remove it
$cache.removeClass('stuck');
}
});
.my-sticky-element.stuck {
position:fixed;
top:0;
box-shadow:0 2px 4px rgba(0, 0, 0, .3);
}
event.key
and modern JS!No number codes anymore. You can check key directly. For example "Enter"
, "LeftArrow"
, "r"
, or "R"
.
const input = document.getElementById("searchbox");
input.addEventListener("keypress", function onEvent(event) {
if (event.key === "Enter") {
// Submit
}
else if (event.key === "Q") {
// Play quacking duck sound, maybe...
}
});
sys.argv is a list containing the script path and command line arguments; i.e. sys.argv[0] is the path of the script you're running and all following members are arguments.
Xcode 8.x • Swift 3.x or later
do {
// get the documents folder url
if let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
// create the destination url for the text file to be saved
let fileURL = documentDirectory.appendingPathComponent("file.txt")
// define the string/text to be saved
let text = "Hello World !!!"
// writing to disk
// Note: if you set atomically to true it will overwrite the file if it exists without a warning
try text.write(to: fileURL, atomically: false, encoding: .utf8)
print("saving was successful")
// any posterior code goes here
// reading from disk
let savedText = try String(contentsOf: fileURL)
print("savedText:", savedText) // "Hello World !!!\n"
}
} catch {
print("error:", error)
}
Short story: The 0
tells the parser it's dealing with a constant (and not an identifier/reserved word). Something is still needed to specify the number base: the x
is an arbitrary choice.
Long story: In the 60's, the prevalent programming number systems were decimal and octal — mainframes had 12, 24 or 36 bits per byte, which is nicely divisible by 3 = log2(8).
The BCPL language used the syntax 8 1234
for octal numbers. When Ken Thompson created B from BCPL, he used the 0
prefix instead. This is great because
0
is the same in both bases),00005 == 05
), and#123
).When C was created from B, the need for hexadecimal numbers arose (the PDP-11 had 16-bit words) and all of the points above were still valid. Since octals were still needed for other machines, 0x
was arbitrarily chosen (00
was probably ruled out as awkward).
C# is a descendant of C, so it inherits the syntax.
Why not negate the padding added by container-fluid by marking left and right padding as 0?
<div class="container-fluid pl-0 pr-0">
even better way? no padding at all at the container level (cleaner)
<div class="container-fluid pl-0 pr-0">
There is HTML and URI encodings. &
is &
encoded in HTML while %26
is &
in URI encoding.
So before URI encoding your string you might want to HTML decode and then URI encode it :)
var div = document.createElement('div');
div.innerHTML = '&AndOtherHTMLEncodedStuff';
var htmlDecoded = div.firstChild.nodeValue;
var urlEncoded = encodeURIComponent(htmlDecoded);
result %26AndOtherHTMLEncodedStuff
Hope this saves you some time
I think it's important to mention little difference between 'self' and 'static' in PHP as 'best answer' uses 'static' which can give confusing result to some people.
<?php
class X {
function getStatic() {
// gets THIS class of instance of object
// that extends class in which is definied function
return static::class;
}
function getSelf() {
// gets THIS class of class in which function is declared
return self::class;
}
}
class Y extends X {
}
class Z extends Y {
}
$x = new X();
$y = new Y();
$z = new Z();
echo 'X:' . $x->getStatic() . ', ' . $x->getSelf() .
', Y: ' . $y->getStatic() . ', ' . $y->getSelf() .
', Z: ' . $z->getStatic() . ', ' . $z->getSelf();
Results:
X: X, X
Y: Y, X
Z: Z, X
For those looking a more modern approach, you can use the fetch API
. The following example shows how to download a PDF
file. It is easily done with the following code.
fetch(url, {
body: JSON.stringify(data),
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
})
.then(response => response.blob())
.then(response => {
const blob = new Blob([response], {type: 'application/pdf'});
const downloadUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = downloadUrl;
a.download = "file.pdf";
document.body.appendChild(a);
a.click();
})
I believe this approach to be much easier to understand than other XMLHttpRequest
solutions. Also, it has a similar syntax to the jQuery
approach, without the need to add any additional libraries.
Of course, I would advise checking to which browser you are developing, since this new approach won't work on IE. You can find the full browser compatibility list on the following [link][1].
Important: In this example I am sending a JSON request to a server listening on the given url
. This url
must be set, on my example I am assuming you know this part. Also, consider the headers needed for your request to work. Since I am sending a JSON, I must add the Content-Type
header and set it to application/json; charset=utf-8
, as to let the server know the type of request it will receive.
This flexbox principle also works horizontally
During calculations of flex bases and flexible lengths, auto margins
are treated as 0.
Prior to alignment via justify-content and
align-self, any positive free space is distributed to auto margins in
that dimension.
Setting an automatic left margin for the Last Item will do the work.
.last-item {
margin-left: auto;
}
Code Example:
.container {_x000D_
display: flex;_x000D_
width: 400px;_x000D_
outline: 1px solid black;_x000D_
}_x000D_
_x000D_
p {_x000D_
height: 50px;_x000D_
width: 50px;_x000D_
margin: 5px;_x000D_
background-color: blue;_x000D_
}_x000D_
_x000D_
.last-item {_x000D_
margin-left: auto;_x000D_
}
_x000D_
<div class="container">_x000D_
<p></p>_x000D_
<p></p>_x000D_
<p></p>_x000D_
<p class="last-item"></p>_x000D_
</div>
_x000D_
This can be very useful for Desktop Footers.
As Envato did here with the company logo.
Check Empty object
$scope.isValid = function(value) {
return !value
}
As of API 19, Bitmap setWidth(int width) and setHeight(int height) exist. http://developer.android.com/reference/android/graphics/Bitmap.html
japf has answer it correctly. Just in case if you are looking at multi-line actions, you can write as below.
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() => {
this.progressBar.Value = 50;
}));
Information for other users who want to know about performance:
If your code NEED to be written for high performance, you can first check if the invoke is required by using CheckAccess flag.
if(Application.Current.Dispatcher.CheckAccess())
{
this.progressBar.Value = 50;
}
else
{
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() => {
this.progressBar.Value = 50;
}));
}
Note that method CheckAccess() is hidden from Visual Studio 2015 so just write it without expecting intellisense to show it up. Note that CheckAccess has overhead on performance (overhead in few nanoseconds). It's only better when you want to save that microsecond required to perform the 'invoke' at any cost. Also, there is always option to create two methods (on with invoke, and other without) when calling method is sure if it's in UI Thread or not. It's only rarest of rare case when you should be looking at this aspect of dispatcher.
Another easy flexible approach to display block at center: using native text alignment with line-height
and text-align
.
Solution:
.parent {
line-height: 100vh;
text-align: center;
}
.child {
display: inline-block;
vertical-align: middle;
line-height: 100%;
}
And html sample:
<div class="parent">
<div class="child">My center block</div>
</div>
We make div.parent
fullscreen, and his single child div.child
align as text with display: inline-block
.
Advantages:
Simple example on JSFiddle: https://jsfiddle.net/k9u6ma8g
Ran into this exact problem.
What I ended up doing:
# starting with date string
sdt = "20190901"
std_format = '%Y%m%d'
# create naive datetime object
from datetime import datetime
dt = datetime.strptime(sdt, sdt_format)
# extract the relevant date time items
dt_formatters = ['%Y','%m','%d']
dt_vals = tuple(map(lambda formatter: int(datetime.strftime(dt,formatter)), dt_formatters))
# set timezone
import pendulum
tz = pendulum.timezone('utc')
dt_tz = datetime(*dt_vals,tzinfo=tz)
Format(Fields!CUL1.Value, "0.00")
would work better since @abe
suggests they want to show 0.00
, and if the value was 0, "#0.##"
would show "0"
.
By default Wampserver comes configured as securely as it can, so Apache is set to only allow access from the machine running wamp. Afterall it is supposed to be a development server and not a live server.
Also there was a little error released with WAMPServer 2.4 where it used the old Apache 2.2 syntax instead of the new Apache 2.4 syntax for access rights.
You need to change the security setting on Apache to allow access from anywhere else, so edit your httpd.conf
file.
Change this section from :
# onlineoffline tag - don't remove
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
To :
# onlineoffline tag - don't remove
Require local
Require ip 192.168.0
The Require local
allows access from these ip's 127.0.0.1 & localhost & ::1
.
The statement Require ip 192.168.0
will allow you to access the Apache server from any ip on your internal network. Also it will allow access using the server mechines actual ip address from the server machine, as you are trying to do.
In version 3 and > of WAMPServer there is a Virtual Hosts pre defined for localhost
so you have to make the access privilage amendements in the Virtual Host definition config file
First dont amend the httpd.conf
file at all, leave it as you found it.
Using the menus, edit the httpd-vhosts.conf
file.
It should look like this :
<VirtualHost *:80>
ServerName localhost
DocumentRoot D:/wamp/www
<Directory "D:/wamp/www/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
Amend it to
<VirtualHost *:80>
ServerName localhost
DocumentRoot D:/wamp/www
<Directory "D:/wamp/www/">
Options +Indexes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
Hopefully you will have created a Virtual Host for your project and not be using the wamp\www
folder for your site. In that case leave the localhost definition alone and make the change only to your Virtual Host.
Dont forget to restart Apache after making this change