With reference to the answer given by @djangofan, it looks like the viable solution is to keep your code inside try catch
block where a possible Staleness occurs. When I use this below code I didn't get the problem any time.
public void inputName(String name)
{
try {
waitForVisibilityElement(name);//My own visibility function
findElement(By.name("customerName")).sendKeys(name);
}
catch (StaleElementReferenceException e)
{
e.getMessage();
}
}
I have tried using the ExpectedConditions.presenceOfElementLocated(By)
but the staleness exceptions still throws intermittently.
Hope this solution helps.
If you want to compare image for similarity,I suggest you to used OpenCV. In OpenCV, there are few feature matching and template matching. For feature matching, there are SURF, SIFT, FAST and so on detector. You can use this to detect, describe and then match the image. After that, you can use the specific index to find number of match between the two images.
I would vote for ServiceStack's JSON Serializer:
using ServiceStack;
string jsonString = new { FirstName = "James" }.ToJson();
It is also the fastest JSON serializer available for .NET: http://www.servicestack.net/benchmarks/
Another easier way to do it is to upload your file to google sheets, then add a pivot, for the columns and rows select the same as you would with Excel, however, for values select Calculated Field and then in the formula type in =
If you are doing code in STS you just need to add the devtools dependency in your maven file. After that it will run itself whenever you will do some change.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
Am using Mountain Lion. What I did was Look for /usr/local and Get Info. On it there is Sharing and Permissions. Make sure that its only the user and Admin are the only ones who have read and write permissions. Anyone else should have read access only. That sorted my problem.
Its normally helpful is your Run disk utilities and repair permissions too.
If you even did not get scroll after doing what is written above .....
Set the android:layout_height="250dp"
or you can say xdp
where x
can be any numerical value.
In a loop it's harmless, but in an assignment statement it can lead to unexpected results:
var x = 5;
var y = x++; // y is now 5 and x is 6
var z = ++x; // z is now 7 and x is 7
Whitespace between the variable and the operator can lead to unexpected results as well:
a = b = c = 1; a ++ ; b -- ; c; console.log('a:', a, 'b:', b, 'c:', c)
In a closure, unexpected results can be an issue as well:
var foobar = function(i){var count = count || i; return function(){return count++;}}
baz = foobar(1);
baz(); //1
baz(); //2
var alphabeta = function(i){var count = count || i; return function(){return ++count;}}
omega = alphabeta(1);
omega(); //2
omega(); //3
And it triggers automatic semicolon insertion after a newline:
var foo = 1, bar = 2, baz = 3, alpha = 4, beta = 5, delta = alpha
++beta; //delta is 4, alpha is 4, beta is 6
preincrement/postincrement confusion can produce off-by-one errors that are extremely difficult to diagnose. Fortunately, they are also complete unnecessary. There are better ways to add 1 to a variable.
References
My coworkers helped me with this:
select CONVERT(VARCHAR(10), <tms_column>, 112), count(*)
from table where <tms_column> > '2012-09-10'
group by CONVERT(VARCHAR(10), <tms_column>, 112);
or
select CONVERT(DATE, <tms_column>, 112), count(*)
from table where <tms_column> > '2012-09-10'
group by CONVERT(DATE, <tms_column>, 112);
I find this useful:
function Get-Version($filePath)
{
$name = @{Name="Name";Expression= {split-path -leaf $_.FileName}}
$path = @{Name="Path";Expression= {split-path $_.FileName}}
dir -recurse -path $filePath | % { if ($_.Name -match "(.*dll|.*exe)$") {$_.VersionInfo}} | select FileVersion, $name, $path
}
I have tried setting the heap size upto 2200M on 32bit Linux machine and JVM worked fine. The JVM didnt start when I set it to 2300M.
Kotlin version below (Updated version of @paul-burke response:
fun openPDFDocument(context: Context, filename: String) {
//Create PDF Intent
val pdfFile = File(Environment.getExternalStorageDirectory().absolutePath + "/" + filename)
val pdfIntent = Intent(Intent.ACTION_VIEW)
pdfIntent.setDataAndType(Uri.fromFile(pdfFile), "application/pdf")
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
//Create Viewer Intent
val viewerIntent = Intent.createChooser(pdfIntent, "Open PDF")
context.startActivity(viewerIntent)
}
Solution for linux and specifically Ubuntu 20:04. First ensure you have Java installed before proceeding:
1. java -version
2. sudo apt-get update
3. sudo apt-get install openjdk-8-jdk
Open .bashrc
vim $HOME/.bashrc
Set Java environment variables.
export JAVA_HOME="/usr/lib/jvm/java-1.8.0-openjdk-amd64"
export JRE_HOME="/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre"
Visit Gradle's website and identify the version you would like to install. Replace version 6.5.1 with the version number you would like to install.
1. sudo apt-get update
2. cd /tmp && curl -L -O https://services.gradle.org/distributions/gradle-6.5.1-bin.zip
3. sudo mkdir /opt/gradle
4. sudo unzip -d /opt/gradle /tmp/gradle-6.5.1-bin.zip
To setup Gradle's environment variables use nano or vim or gedit editors to create a new file:
sudo vim /etc/profile.d/gradle.sh
Add the following lines to gradle.sh
export GRADLE_HOME="/opt/gradle/gradle-6.5.1/"
export PATH=${GRADLE_HOME}/bin:${PATH}
Run the following commands to make gradle.sh executable and to update your bash terminal with the environment variables you set as well as check the installed version.
1. sudo chmod +x /etc/profile.d/gradle.sh
3. source /etc/profile.d/gradle.sh
4. gradle -v
The second one is a classic example of the Arrow Anti-pattern So I'd avoid it...
If your conditions are too long extract them into methods/properties.
I think what @korona meant was since it's just a C API, you can consume it from C# directly with a heck of a lot of typing like this:
[DllImport("opengl32")]
public static extern void glVertex3f(float x, float y, float z);
You unfortunately would need to do this for every single OpenGL function you call, and is basically what Tao has done for you.
Take a look at this site, it explains two methods for reading from console in java, using Scanner
or the classical InputStreamReader
from System.in.
Following code is taken from cited website:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ReadConsoleSystem {
public static void main(String[] args) {
System.out.println("Enter something here : ");
try{
BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
String s = bufferRead.readLine();
System.out.println(s);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
--
import java.util.Scanner;
public class ReadConsoleScanner {
public static void main(String[] args) {
System.out.println("Enter something here : ");
String sWhatever;
Scanner scanIn = new Scanner(System.in);
sWhatever = scanIn.nextLine();
scanIn.close();
System.out.println(sWhatever);
}
}
Regards.
There is a way to achieve this without type assertion, by using generics instead, which are generally a bit nicer and safer to use.
Unfortunately, getElementById
is not generic, but querySelector
is:
const inputValue = document.querySelector<HTMLInputElement>('#greet')!.value;
Similarly, you can use querySelectorAll
to select multiple elements and use generics so TS can understand that all selected elements are of a particular type:
const inputs = document.querySelectorAll<HTMLInputElement>('.my-input');
This will produce a NodeListOf<HTMLInputElement>
.
TCPView is a Windows program that will show you detailed listings of all TCP and UDP endpoints on your system, including the local and remote addresses and state of TCP connections. On Windows Server 2008, Vista, NT, 2000 and XP TCPView also reports the name of the process that owns the endpoint. TCPView provides a more informative and conveniently presented subset of the Netstat program that ships with Windows. The TCPView download includes Tcpvcon, a command-line version with the same functionality.
http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx
It seems to me that CROSS APPLY can fill a certain gap when working with calculated fields in complex/nested queries, and make them simpler and more readable.
Simple example: you have a DoB and you want to present multiple age-related fields that will also rely on other data sources (such as employment), like Age, AgeGroup, AgeAtHiring, MinimumRetirementDate, etc. for use in your end-user application (Excel PivotTables, for example).
Options are limited and rarely elegant:
JOIN subqueries cannot introduce new values in the dataset based on data in the parent query (it must stand on its own).
UDFs are neat, but slow as they tend to prevent parallel operations. And being a separate entity can be a good (less code) or a bad (where is the code) thing.
Junction tables. Sometimes they can work, but soon enough you're joining subqueries with tons of UNIONs. Big mess.
Create yet another single-purpose view, assuming your calculations don't require data obtained mid-way through your main query.
Intermediary tables. Yes... that usually works, and often a good option as they can be indexed and fast, but performance can also drop due to to UPDATE statements not being parallel and not allowing to cascade formulas (reuse results) to update several fields within the same statement. And sometimes you'd just prefer to do things in one pass.
Nesting queries. Yes at any point you can put parenthesis on your entire query and use it as a subquery upon which you can manipulate source data and calculated fields alike. But you can only do this so much before it gets ugly. Very ugly.
Repeating code. What is the greatest value of 3 long (CASE...ELSE...END) statements? That's gonna be readable!
Did I miss something? Probably, so feel free to comment. But hey, CROSS APPLY is like a godsend in such situations: you just add a simple CROSS APPLY (select tbl.value + 1 as someFormula) as crossTbl
and voilà! Your new field is now ready for use practically like it had always been there in your source data.
Values introduced through CROSS APPLY can...
CROSS APPLY (select crossTbl.someFormula + 1 as someMoreFormula) as crossTbl2
Dang, there's nothing they can't do!
Alternatively you could use SciPy
from scipy import stats
stats.uniform(0.5, 13.3).rvs(50)
and for the record to sample integers it's
stats.randint(10, 20).rvs(50)
A simple thing you can do is position your fixed DIV relative to the rest of your page with % values.
Check out this jsfiddle here where the fixed DIV is a sidebar.
div#wrapper {
margin: auto;
width: 80%;
}
div#main {
width: 60%;
}
div#sidebar {
position: fixed;
width: 30%;
left: 60%;
}
And a brief picture below describing the layout above:
If you're trying to do this from within Excel (rather than programmatically), follow these steps:
From the "Orb" menu on the ribbon, click the "Excel Options" button near the bottom of the menu.
In the list of choices at the left, select "Advanced".
Scroll down until you see the heading "Display options for this worksheet".
Select the checkbox labeled "Show guidelines".
In java there is a length
field that you can use on any array to find out it's size:
String[] s = new String[10];
System.out.println(s.length);
You can take timestamp snapshots before and after, then repeat the experiments several times to average to results. There are also profilers that can do this for you.
With System.currentTimeMillis()
class TimeTest1 {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
long total = 0;
for (int i = 0; i < 10000000; i++) {
total += i;
}
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println(elapsedTime);
}
}
With a StopWatch class
You can use this StopWatch
class, and call start()
and stop
before and after the method.
class TimeTest2 {
public static void main(String[] args) {
Stopwatch timer = new Stopwatch().start();
long total = 0;
for (int i = 0; i < 10000000; i++) {
total += i;
}
timer.stop();
System.out.println(timer.getElapsedTime());
}
}
See here (archived).
Application Performance Application
Performance profiles method-level CPU performance (execution time). You can choose to profile the entire application or a part of the application.
See here.
run the following command will fix this issue.
npm install @types/node --save-dev
Check it out
tar cvpzf zip_folder.tgz . --exclude=./public --exclude=./tmp --exclude=./log --exclude=fileName
What you have will find a space anywhere in the string, not just between words.
If you want to find any kind of whitespace, you can use this, which uses a regular expression:
if (/\s/.test(str)) {
// It has any kind of whitespace
}
\s
means "any whitespace character" (spaces, tabs, vertical tabs, formfeeds, line breaks, etc.), and will find that character anywhere in the string.
According to MDN, \s
is equivalent to: [ \f\n\r\t\v?\u00a0\u1680?\u180e\u2000?\u2001\u2002?\u2003\u2004?\u2005\u2006?\u2007\u2008?\u2009\u200a?\u2028\u2029??\u202f\u205f?\u3000]
.
For some reason, I originally read your question as "How do I see if a string contains only spaces?" and so I answered with the below. But as @CrazyTrain points out, that's not what the question says. I'll leave it, though, just in case...
If you mean literally spaces, a regex can do it:
if (/^ *$/.test(str)) {
// It has only spaces, or is empty
}
That says: Match the beginning of the string (^
) followed by zero or more space characters followed by the end of the string ($
). Change the *
to a +
if you don't want to match an empty string.
If you mean whitespace as a general concept:
if (/^\s*$/.test(str)) {
// It has only whitespace
}
That uses \s
(whitespace) rather than the space, but is otherwise the same. (And again, change *
to +
if you don't want to match an empty string.)
I am sure Adding this code on your css file will solve the problem
<style type="text/css" media="print">
@page
{
size: auto; /* auto is the initial value */
margin: 0mm; /* this affects the margin in the printer settings */
}
</style>
just to update this, bootstrap v2 no longer conflicts with jquery ui
https://github.com/twbs/bootstrap/issues/171
Edit: as @Freshblood there are a few things that still conflict. However, as originally posted Twitter suggests that they are working on this and it largely works, specially compared to v1.
All radio buttons have to have the same name:
<input type='radio' name='foo'>
Only 1 radio button of each group of buttons with the same name can be checked.
The only standard mandated implementation dependent way is to use the system()
function from stdlib.h
.
Also if you know how to make user become the super-user that would be nice also.
Do you want the script to run as super-user or do you want to elevate the privileges of the C executable? The former can be done with sudo
but there are a few things you need to know before you can go off using sudo
.
Use the following function
window.scrollTo(xpos, ypos)
Here xpos is Required. The coordinate to scroll to, along the x-axis (horizontal), in pixels
ypos is also Required. The coordinate to scroll to, along the y-axis (vertical), in pixels
OK - turns out it was a permissions problem on GitHub that happened during the fork of emi/bixo to bixo/bixo. Once Tekkub fixed these, it started working again.
From .NET 2.0 you shouldn't need to do this. If you do not explicitly set the Proxy property on a web request it uses the value of the static WebRequest.DefaultWebProxy. If you wanted to change the proxy being used by all subsequent WebRequests, you can set this static DefaultWebProxy property.
The default behaviour of WebRequest.DefaultWebProxy is to use the same underlying settings as used by Internet Explorer.
If you wanted to use different proxy settings to the current user then you would need to code
WebRequest webRequest = WebRequest.Create("http://stackoverflow.com/");
webRequest.Proxy = new WebProxy("http://proxyserver:80/",true);
or
WebRequest.DefaultWebProxy = new WebProxy("http://proxyserver:80/",true);
You should also remember the object model for proxies includes the concept that the proxy can be different depending on the destination hostname. This can make things a bit confusing when debugging and checking the property of webRequest.Proxy. Call
webRequest.Proxy.GetProxy(new Uri("http://google.com.au"))
to see the actual details of the proxy server that would be used.
There seems to be some debate about whether you can set webRequest.Proxy
or WebRequest.DefaultWebProxy = null
to prevent the use of any proxy. This seems to work OK for me but you could set it to new DefaultProxy()
with no parameters to get the required behaviour. Another thing to check is that if a proxy element exists in your applications config file, the .NET Framework will NOT use the proxy settings in Internet Explorer.
The MSDN Magazine article Take the Burden Off Users with Automatic Configuration in .NET gives further details of what is happening under the hood.
Unfortunately DEBUG
is overloaded heavily. For instance, it's recommended to always generate and save a pdb file for RELEASE builds. Which means one of the -Zx
flags, and -DEBUG
linker option. While _DEBUG
relates to special debug versions of runtime library such as calls to malloc
and free
. Then NDEBUG
will disable assertions.
You need to remove shares
as your PRIMARY KEY
OR UNIQUE_KEY
rpm -Uvh http://yum.chrislea.com/centos/5/i386/chl-release-5-3.noarch.rpm
rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-CHL
rpm -Uvh ftp://ftp.pbone.net/mirror/centos.karan.org/el5/extras/testing/i386/RPMS/libffi-3.0.5-1.el5.kb.i386.rpm
yum install python26
python26
for dos that just dont know :=)
You can use the opt(int)
method and use a classical for
loop.
To set a default value to a column, try this:
ALTER TABLE tb_TableName
ALTER COLUMN Record_Status SET DEFAULT 'default value'
An element with ‘display: block’ (as div is by default) has a width determined by the width of its container. You can't make a block's width dependent on the width of its contents (shrink-to-fit).
(Except for blocks that are ‘float: left/right’ in CSS 2.1, but that's no use for centering.)
You could set the ‘display’ property to ‘inline-block’ to turn a block into a shrink-to-fit object that can be controlled by its parent's text-align property, but browser support is spotty. You can mostly get away with it by using hacks (eg. see -moz-inline-stack) if you want to go that way.
The other way to go is tables. This can be necessary when you have columns whose width really can't be known in advance. I can't really tell what you're trying to do from the example code — there's nothing obvious in there that would need a shrink-to-fit block — but a list of products could possibly be considered tabular.
[PS. never use ‘pt’ for font sizes on the web. ‘px’ is more reliable if you really need fixed size text, otherwise relative units like ‘%’ are better. And “clear: ccc both” — a typo?]
.center{
text-align:center;
}
.center > div{ /* N.B. child combinators don't work in IE6 or less */
display:inline-block;
}
Another option is to create a file in the $_SERVER['DOCUMENT_ROOT']
directory with the definition of your absolute path.
For example, if your $_SERVER['DOCUMENT_ROOT']
directory is
C:\wamp\www\
create a file (i.e. my_paths.php
) containing this
<?php if(!defined('MY_ABS_PATH')) define('MY_ABS_PATH',$_SERVER['DOCUMENT_ROOT'].'MyProyect/')
Now you only need to include in every file inside your MyProyect folder this file (my_paths.php
), so you can user MY_ABS_PATH
as an absolute path for MyProject.
CA5386 : Vulnerability analysis tools will alert you to these codes.
Correct code :
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) =>
{
return (sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != SslPolicyErrors.RemoteCertificateNotAvailable;
};
Canvas would be a great way to do this, as @pst said above. Check out this answer for a good example:
Some code that would serve you specifically as well:
var imgd = context.getImageData(x, y, width, height);
var pix = imgd.data;
for (var i = 0, n = pix.length; i < n; i += 4) {
console.log pix[i+3]
}
This will go row by row, so you'd need to convert that into an x,y and either convert the for loop to a direct check or run a conditional inside.
Reading your question again, it looks like you want to be able to get the point that the person clicks on. This can be done pretty easily with jquery's click event. Just run the above code inside a click handler as such:
$('el').click(function(e){
console.log(e.clientX, e.clientY)
}
Those should grab your x and y values.
Extending from YaroslavGaponov's answer, the simplest implementation is just using Math.random()
.
Math.random()
Mathematically, the chances of fractions being the same in a real space [0, 1] is theoretically 0. Probability-wise it is approximately close to 0 for a default length of 16 decimals in node.js. And this implementation should also reduce arithmetic overflows as no operations are performed. Also, it is more memory efficient compared to a string as Decimals occupy less memory than strings.
I call this the "Fractional-Unique-ID".
Wrote code to generate 1,000,000 Math.random()
numbers and could not find any duplicates (at least for default decimal points of 16). See code below (please provide feedback if any):
random_numbers = []
for (i = 0; i < 1000000; i++) {
random_numbers.push(Math.random());
//random_numbers.push(Math.random().toFixed(13)) //depends decimals default 16
}
if (i === 1000000) {
console.log("Before checking duplicate");
console.log(random_numbers.length);
console.log("After checking duplicate");
random_set = new Set(random_numbers); // Set removes duplicates
console.log([...random_set].length); // length is still the same after removing
}
In Sequel Pro, access the User Accounts window. Note that any MySQL administration program could be substituted in place of Sequel Pro.
Add the following accounts and privileges:
GRANT SUPER ON *.* TO 'user'@'%' IDENTIFIED BY PASSWORD
If you have PowerShell 5.0 or higher (pre-installed with Windows 10 and Windows Server 2016):
powershell Expand-Archive your.zip -DestinationPath your_destination
I created a new AutomapperProfile class. It extends Profile. We have over 100 projects in our solution. Many projects have an AutomapperProfile class, but this one was new to this existing project. However, I did find what I had to do to fix this issue for us. There is a Binding project. Within the Initialization there is this code:
var mappingConfig = new List<Action<IConfiguration>>();
// Initialize the Automapper Configuration for all Known Assemblies
mappingConfig.AddRange( new List<Action<IConfiguration>>
{
ConfigureProfilesInAssemblyOfType<Application.Administration.AutomapperProfile>,
//...
I had to add ConfigureProfilesInAssemblyOfType<MyNewNamespace.AutomapperProfile>
Note that ConfigureProfilesInAssemblyOfType looks like this:
private static void ConfigureProfilesInAssemblyOfType<T>( IConfiguration configuration )
{
var log = LogProvider.Get( typeof (AutomapperConfiguration) );
// The Automapper Profile Type
var automapperProfileType = typeof (Profile);
// The Assembly containing the type
var assembly = typeof (T).Assembly;
log.Debug( "Scanning " + assembly.FullName );
// Configure any Profile classes found in the assembly containing the type.
assembly.GetTypes()
.Where( automapperProfileType.IsAssignableFrom ).ToList()
.ForEach( x =>
{
log.Debug( "Adding Profile '" + x.FullName + "'" );
configuration.AddProfile( Activator.CreateInstance( x ) as Profile );
} );
}
Best regards, -Jeff
As discussed, there are several ways to search:
/pattern
?pattern
* (and g*, which I sometimes use in macros)
# (and g#)
plus, navigating prev/next with N and n.
You can also edit/recall your search history by pulling up the search prompt with /
and then cycle with C-p
/C-n
. Even more useful is q/
, which takes you to a window where you can navigate the search history.
Also for consideration is the all-important 'hlsearch'
(type :hls
to enable). This makes it much easier to find multiple instances of your pattern. You might even want make your matches extra bright with something like:
hi Search ctermfg=yellow ctermbg=red guifg=...
But then you might go crazy with constant yellow matches all over your screen. So you’ll often find yourself using :noh
. This is so common that a mapping is in order:
nmap <leader>z :noh<CR>
I easily remember this one as z
since I used to constantly type /zz<CR>
(which is a fast-to-type uncommon occurrence) to clear my highlighting. But the :noh
mapping is way better.
A hidden attribute is a boolean attribute (True/False). When this attribute is used on an element, it removes all relevance to that element. When a user views the html page, elements with the hidden attribute should not be visible.
Example:
<p hidden>You can't see this</p>
Aria-hidden attributes indicate that the element and ALL of its descendants are still visible in the browser, but will be invisible to accessibility tools, such as screen readers.
Example:
<p aria-hidden="true">You can't see this</p>
Take a look at this. It should answer all your questions.
Note: ARIA stands for Accessible Rich Internet Applications
Sources: Paciello Group
Text:
This is my first android application and
I am trying to make a funny game,
It seems android is really very easy to play.
Suppose above is your text and if you are using ellipsize
's start
attribute it will seen like this
This is my first android application and
...t seems android is really very easy to play.
with end
attribute
This is my first android application and
I am trying to make a funny game,...
To clear the whole thing use the reset_session method in a controller.
reset_session
Here's the documentation on this method: http://api.rubyonrails.org/classes/ActionController/Base.html#M000668
Resets the session by clearing out all the objects stored within and initializing a new session object.
Good luck!
You are wrong about LocalDateTime
: it does not store any time-zone information and it has nanosecond precision. Quoting the Javadoc (emphasis mine):
A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.
LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision. For example, the value "2nd October 2007 at 13:45.30.123456789" can be stored in a LocalDateTime.
The difference between the two is that Instant
represents an offset from the Epoch (01-01-1970) and, as such, represents a particular instant on the time-line. Two Instant
objects created at the same moment in two different places of the Earth will have exactly the same value.
SELECT [TABLE_NAME] ,
[INFORMATION_SCHEMA].COLUMNS.COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME LIKE '%NAME%' ;
HC-way :)
DECLARE
rt_mytable mytable%ROWTYPE;
CURSOR update_mytable_cursor(p_rt_mytable IN mytable%ROWTYPE) IS
SELECT *
FROM mytable
WHERE ID = p_rt_mytable.ID
FOR UPDATE;
BEGIN
rt_mytable.ID := 1;
rt_mytable.NAME := 'x';
INSERT INTO mytable VALUES (rt_mytable);
EXCEPTION WHEN DUP_VAL_ON_INDEX THEN
<<update_mytable>>
FOR i IN update_mytable_cursor(rt_mytable) LOOP
UPDATE mytable SET
NAME = p_rt_mytable.NAME
WHERE CURRENT OF update_mytable_cursor;
END LOOP update_mytable;
END;
Really depends on your requirement, although lately I have seen a trend for classes with at least one bare constructor defined.
The upside of posting your parameters in via constructor is that you know those values can be relied on after instantiation. The downside is that you'll need to put more work in with any library that expects to be able to create objects with a bare constructor.
My personal preference is to go with a bare constructor and set any properties as part of the declaration.
Person p=new Person()
{
Name = "Han Solo",
Age = 39
};
This gets around the "class lacks bare constructor" problem, plus reduces maintenance ( I can set more things without changing the constructor ).
You should put a padding in each object. For example, you want a space between images, you can use the following:
img{
padding: 5px;
}
That means 5px paddin for ALL sides. Read more at http://www.w3schools.com/css/css_padding.asp. By the way, studying a lot before attempting to program will make things easier for you (and for us).
You can reference the image using relative path:
<img src="../images/logo.png">
__ ______ ________
| | |
| | |___ 3. Get the file named "logo.png"
| |
| |___ 2. Go inside "images/" subdirectory
|
|
|____ 1. Go one level up
Or you can use absolute path: /
means that this is an absolute path on the server, So if your server is at https://example.org/, referencing /images/logo.png
from any page would point to https://example.org/images/logo.png
<img src="/images/logo.png">
|______ ________
| | |
| | |___ 3. Get the file named "logo.png"
| |
| |___ 2. Go inside "images/" subdirectory
|
|
|____ 1. Go to the root folder
Yes, you can do this in PHP e.g. in
Silex or Symfony3
using subrequest
$postParams = array(
'email' => $request->get('email'),
'agree_terms' => $request->get('agree_terms'),
);
$subRequest = Request::create('/register', 'POST', $postParams);
return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);
I had a need to add a guid primary key column in an existing table and populate it with unique GUID's and this update query with inner select worked for me:
UPDATE sri_issued_quiz SET quiz_id=(SELECT uuid());
So simple :-)
server.session.timeout=1200
server.servlet.session.timeout=10m
22 bytes, if you do it like this:
System.Guid guid = System.Guid.NewGuid();
byte[] guidbytes = guid.ToByteArray();
string uuid = Convert.ToBase64String(guidbytes).Trim('=');
If you want to target a device then just write min-device-width
. For example:
@media only screen and (min-device-width: 480px){}
@media only screen and (min-device-width: 768px){}
Here are some good articles:
If you have Perl 5.14 or greater, you can use the /r
option with the substitution operator to perform non-destructive substitution:
print "bla: ", $myvar =~ s/a/b/r, "\n";
In earlier versions you can achieve the same using a do()
block with a temporary lexical variable, e.g.:
print "bla: ", do { (my $tmp = $myvar) =~ s/a/b/; $tmp }, "\n";
You can use the Axes.set_yscale
method. That allows you to change the scale after the Axes
object is created. That would also allow you to build a control to let the user pick the scale if you needed to.
The relevant line to add is:
ax.set_yscale('log')
You can use 'linear'
to switch back to a linear scale. Here's what your code would look like:
import pylab
import matplotlib.pyplot as plt
a = [pow(10, i) for i in range(10)]
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)
line, = ax.plot(a, color='blue', lw=2)
ax.set_yscale('log')
pylab.show()
Here is my Library That I have created for simple Webservice Calling,
You can use this by adding a one line gradle dependency -
compile 'com.scantity.ScHttpLibrary:ScHttpLibrary:1.0.0'
Here is the demonstration of using.
static block is used for any technology to initialize static data member in dynamic way,or we can say for the dynamic initialization of static data member static block is being used..Because for non static data member initialization we have constructor but we do not have any place where we can dynamically initialize static data member
Eg:-class Solution{
// static int x=10;
static int x;
static{
try{
x=System.out.println();
}
catch(Exception e){}
}
}
class Solution1{
public static void main(String a[]){
System.out.println(Solution.x);
}
}
Now my static int x will initialize dynamically ..Bcoz when compiler will go to Solution.x it will load Solution Class and static block load at class loading time..So we can able to dynamically initialize that static data member..
}
To redirect your logs output to a file, you need to use the FileAppender and need to define other file details in your log4j.properties/xml file. Here is a sample properties file for the same:
# Root logger option
log4j.rootLogger=INFO, file
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\loging.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
Follow this tutorial to learn more about log4j usage:
http://www.mkyong.com/logging/log4j-log4j-properties-examples/
In case anyone is using the delegated approach for their listener, use e.target
(it will refer to the select element).
$('#myform').on('change', 'select', function (e) {
var val = $(e.target).val();
var text = $(e.target).find("option:selected").text(); //only time the find is required
var name = $(e.target).attr('name');
}
I have used in Google Sheets
={sheetname!columnnamefrom:columnnameto}
Example:
={sheet1!A:A}
={sheet2!A4:A20}
You can also use
cd %localhost%
to set the directory to the folder the batch file was opened from. Your script would look like this:
@echo off
cd %localhost%
echo .> dblank.txt
Make sure you set the directory before you use the command to create the text file.
If you also need to match the content of the link itself, use text():
//a[contains(@href,"/some_link")][text()="Click here"]
If it is not necessary turn off 'Enable 32-bit Applications' from your respective application pool of your website.
This worked for me on my local machine
Came across this old thread searching for a similar solution myself and found the accepted answer to be using .complete()
method of jquery ajax
. I quote the notice on jquery website here:
The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
To know the status code
of a ajax response, one can use the following code:
$.ajax( url [, settings ] )
.always(function (jqXHR) {
console.log(jqXHR.status);
});
Works similarily for .done()
and .fail()
From definition of IGrouping :
IGrouping<out TKey, out TElement> : IEnumerable<TElement>, IEnumerable
you can just iterate through elements like this:
IEnumerable<IGrouping<int, smth>> groups = list.GroupBy(x => x.ID)
foreach(IEnumerable<smth> element in groups)
{
//do something
}
The 'Go Offline' extension adds a button to the Source Control menu.
https://visualstudiogallery.msdn.microsoft.com/6e54271c-2c4e-4911-a1b4-a65a588ae138
In my case, migrating a Spring 3.1 app up to 3.2.7, my solution was similar to Matthias's but a bit different -- thus why I'm documenting it here:
In my POM I found this dependency and changed it from 6.0 to 7.0:
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
Then later in the POM I upgraded this plugin from 6.0 to 7.0:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
...
<configuration>
...
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>7.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
A somewhat different flavour of the Accepted Answer.
Swift 4
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1 + .milliseconds(500) +
.microseconds(500) + .nanoseconds(1000)) {
print("Delayed by 0.1 second + 500 milliseconds + 500 microseconds +
1000 nanoseconds)")
}
It is txtName.BackColor = System.Drawing.Color.Red;
one can also use txtName.BackColor = Color.Aqua;
which is the same as txtName.BackColor = System.Color.Aqua;
Only Problem with System.color is that it does not contain a definition for some basic colors especially white, which is important cause usually textboxes are white;
I was experiencing this problem on Samsung devices (fine on others). like zyamys suggested in his/her comment, I added the manifest.permission line but in addition to rather than instead of the original line, so:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.Manifest.permission.READ_PHONE_STATE" />
I'm targeting API 22, so don't need to explicitly ask for permissions.
Everything is possible only if there is enough time to research :)
What I got to do is like having people that I iterate into a ui:repeat and display names and other fields in inputs. But one of fields was singleSelect - A and depending on it value update another input - B. even ui:repeat do not have id I put and it appeared in the DOM tree
<ui:repeat id="peopleRepeat"
value="#{myBean.people}"
var="person" varStatus="status">
Than the ids in the html were something like:
myForm:peopleRepeat:0:personType
myForm:peopleRepeat:1:personType
Than in the view I got one method like:
<p:ajax event="change"
listener="#{myBean.onPersonTypeChange(person, status.index)}"/>
And its implementation was in the bean like:
String componentId = "myForm:peopleRepeat" + idx + "personType";
PrimeFaces.current().ajax().update(componentId);
So this way I updated the element from the bean with no issues. PF version 6.2
Good luck and happy coding :)
add this to you CSS:
html, body
{
height: 100%;
}
when you say to wrap
to be 100%
, 100% of what? of its parent (body), so his parent has to have some height.
and the same goes for body
, his parent his html
. html
parent his the viewport..
so, by setting them both to 100%, wrap
can also have a percentage height.
also: the elements have some default padding/margin, that causes them to span a little more then the height you applied to them. (causing a scroll bar) you can use
*
{
padding: 0;
margin: 0;
}
to disable that.
Look at That Fiddle
Try this:
jsonResponse = json.loads(response.decode('utf-8'))
To be able to use the jobParameters I think you need to define your reader as scope 'step', but I am not sure if you can do it using annotations.
Using xml-config it would go like this:
<bean id="foo-readers" scope="step"
class="...MyReader">
<property name="fileName" value="#{jobExecutionContext['fileName']}" />
</bean>
See further at the Spring Batch documentation.
Perhaps it works by using @Scope
and defining the step scope in your xml-config:
<bean class="org.springframework.batch.core.scope.StepScope" />
You actually have to use pow(number, power);. Unfortunately, carats don't work as a power sign in C. Many times, if you find yourself not being able to do something from another language, its because there is a diffetent function that does it for you.
Expanding on the excellent answer by @bluish and @Yishai, here is how you make the NodeLists and node attributes support iterators, i.e. the for(Node n: nodelist)
interface.
Use it like:
NodeList nl = ...
for(Node n : XmlUtil.asList(nl))
{...}
and
Node n = ...
for(Node attr : XmlUtil.asList(n.getAttributes())
{...}
The code:
/**
* Converts NodeList to an iterable construct.
* From: https://stackoverflow.com/a/19591302/779521
*/
public final class XmlUtil {
private XmlUtil() {}
public static List<Node> asList(NodeList n) {
return n.getLength() == 0 ? Collections.<Node>emptyList() : new NodeListWrapper(n);
}
static final class NodeListWrapper extends AbstractList<Node> implements RandomAccess {
private final NodeList list;
NodeListWrapper(NodeList l) {
this.list = l;
}
public Node get(int index) {
return this.list.item(index);
}
public int size() {
return this.list.getLength();
}
}
public static List<Node> asList(NamedNodeMap n) {
return n.getLength() == 0 ? Collections.<Node>emptyList() : new NodeMapWrapper(n);
}
static final class NodeMapWrapper extends AbstractList<Node> implements RandomAccess {
private final NamedNodeMap list;
NodeMapWrapper(NamedNodeMap l) {
this.list = l;
}
public Node get(int index) {
return this.list.item(index);
}
public int size() {
return this.list.getLength();
}
}
}
Or you can use like this. This may be faster.
int iFindNo = 14;
int j = dataGridView1.Rows.Count-1;
int iRowIndex = -1;
for (int i = 0; i < Convert.ToInt32(dataGridView1.Rows.Count/2) +1; i++)
{
if (Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value) == iFindNo)
{
iRowIndex = i;
break;
}
if (Convert.ToInt32(dataGridView1.Rows[j].Cells[0].Value) == iFindNo)
{
iRowIndex = j;
break;
}
j--;
}
if (iRowIndex != -1)
MessageBox.Show("Index is " + iRowIndex.ToString());
else
MessageBox.Show("Index not found." );
Efran Cobisi's suggestion of using an Auto Mapper is a good one. I have used Auto Mapper for a while and it worked well, until I found the much faster alternative, Mapster.
Given a large list or IEnumerable, Mapster outperforms Auto Mapper. I found a benchmark somewhere that showed Mapster being 6 times as fast, but I could not find it again. You could look it up and then, if it is suits you, use Mapster.
I tried all of these solutions before I realized that I had enabled opcache in PHP on my live environment. Wordpress was not reading a cached version of wp-config.
Do not forget to verify if your text editor encodes properly your code in UTF-8.
Otherwise, you may have invisible characters that are not interpreted as UTF-8.
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"imageName.png"]];
more info with example project
To expand upon the accepted answer, you can create custom MarkerImages
of any color using the API at http://chart.googleapis.com
In addition to changing color, this also changes marker shape, which may be unwanted.
const marker = new window.google.maps.Marker(
position: markerPosition,
title: markerTitle,
map: map)
marker.addListener('click', () => marker.setIcon(changeIcon('00ff00'));)
const changeIcon = (newIconColor) => {
const newIcon = new window.google.maps.MarkerImage(
`http://chart.googleapis.com/chart?
chst=d_map_spin&chld=1.0|0|${newIconColor}|60|_|%E2%80%A2`,
new window.google.maps.Size(21, 34),
new window.google.maps.Point(0, 0),
new window.google.maps.Point(10, 34),
new window.google.maps.Size(21,34)
);
return newIcon
}
There are many ways you can take back of table.
To get the fragment instance in a class that extends FragmentActivity:
MyclassFragment instanceFragment=
(MyclassFragment)getSupportFragmentManager().findFragmentById(R.id.idFragment);
To get the fragment instance in a class that extends Fragment:
MyclassFragment instanceFragment =
(MyclassFragment)getFragmentManager().findFragmentById(R.id.idFragment);
EXISTS
(or NOT EXISTS
) is specially designed for checking if something exists and therefore should be (and is) the best option. It will halt on the first row that matches so it does not require a TOP
clause and it does not actually select any data so there is no overhead in size of columns. You can safely use SELECT *
here - no different than SELECT 1
, SELECT NULL
or SELECT AnyColumn
... (you can even use an invalid expression like SELECT 1/0
and it will not break).
IF EXISTS (SELECT * FROM Products WHERE id = ?)
BEGIN
--do what you need if exists
END
ELSE
BEGIN
--do what needs to be done if not
END
Dim formattedDate As String = Date.Today.ToString("dd/MM/yyyy")
Use a margin to space around an element.
.box {
margin: top right bottom left;
}
.box {
margin: 10px 5px 10px 5px;
}
This adds space outside of the element. So background colours, borders etc will not be included.
If you want to add spacing within an element use padding instead. It can be called in the same way as above.
.has()
seems to be designed for this purpose. Since it returns a jQuery object, you have to test for .length
as well:
if ($('div#hello').has(target).length) {
alert('Target is a child of #hello');
}
This is because, even though Var1
exists, you're also using an assignment statement on the name Var1
inside of the function (Var1 -= 1
at the bottom line). Naturally, this creates a variable inside the function's scope called Var1
(truthfully, a -=
or +=
will only update (reassign) an existing variable, but for reasons unknown (likely consistency in this context), Python treats it as an assignment). The Python interpreter sees this at module load time and decides (correctly so) that the global scope's Var1
should not be used inside the local scope, which leads to a problem when you try to reference the variable before it is locally assigned.
Using global variables, outside of necessity, is usually frowned upon by Python developers, because it leads to confusing and problematic code. However, if you'd like to use them to accomplish what your code is implying, you can simply add:
global Var1, Var2
inside the top of your function. This will tell Python that you don't intend to define a Var1
or Var2
variable inside the function's local scope. The Python interpreter sees this at module load time and decides (correctly so) to look up any references to the aforementioned variables in the global scope.
nonlocal
statement - check that out as well.I will quickly complement for cases where the header contains emojis, in that case it is simpler to just remove the emoji in the link of the reference. For example
# ? Title 2
....
[Take me to title 2](#-title-2)
There are some cases where this does not work for a weird reason, for example here in setup. The solution in that case is to include the whole code for the emoji as well.
Solution for me was to set the "form" attribute of button
<form id="form_id_name"><button name="btnSubmit" form="form_id_name" /></form>
or is js:
YOURFORMOBJ.getElementsByTagName("button")[0].setAttribute("form", "form_id_name");
YOURFORMOBJ.submit();
You could use Spring Security Crypto (has only 2 optional compile dependencies), which supports PBKDF2, BCrypt, SCrypt and Argon2 password encryption.
Argon2PasswordEncoder argon2PasswordEncoder = new Argon2PasswordEncoder();
String aCryptedPassword = argon2PasswordEncoder.encode("password");
boolean passwordIsValid = argon2PasswordEncoder.matches("password", aCryptedPassword);
SCryptPasswordEncoder sCryptPasswordEncoder = new SCryptPasswordEncoder();
String sCryptedPassword = sCryptPasswordEncoder.encode("password");
boolean passwordIsValid = sCryptPasswordEncoder.matches("password", sCryptedPassword);
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
String bCryptedPassword = bCryptPasswordEncoder.encode("password");
boolean passwordIsValid = bCryptPasswordEncoder.matches("password", bCryptedPassword);
Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder();
String pbkdf2CryptedPassword = pbkdf2PasswordEncoder.encode("password");
boolean passwordIsValid = pbkdf2PasswordEncoder.matches("password", pbkdf2CryptedPassword);
HttpClient.get()
applies res.json()
automatically and returns Observable<HttpResponse<string>>
. You no longer need to call this function yourself.
Ok guys, I found a solution, . It's not great but does the trick with no side effects.
The HTML:
<span id="chromeFix"></span>
(put this below the body tags)
The CSS:
#chromeFix { display: block; position: absolute; width: 1px; height: 100%; top: 0px; left: 0px; }
What this does to solve the issue:
It forces Chrome to think the page's content is 100% when it's not - this stops the body 'appearing' the size of the content and resolves the missing background bug. This is basically doing what height: 100%
does when applied to the body or html but you don't get the side effect of having your backgrounds cut off when scrolling (past 100% page height) like you do with a 100% height on those elements.
I can sleep now =]
A simple solution:
<a href="#" onmouseover="this.style.color='orange';" onmouseout="this.style.color='';">My Link</a>
Or
<script>
/** Change the style **/
function overStyle(object){
object.style.color = 'orange';
// Change some other properties ...
}
/** Restores the style **/
function outStyle(object){
object.style.color = 'orange';
// Restore the rest ...
}
</script>
<a href="#" onmouseover="overStyle(this)" onmouseout="outStyle(this)">My Link</a>
Why don't you try something like:
lastBusDay = datetime.datetime.today()
if datetime.date.weekday(lastBusDay) not in range(0,5):
lastBusDay = 5
var keyCode = evt.keyCode;
if (keyCode==8)
alert('you pressed backspace');
if(keyCode==116)
alert('you pressed f5 to reload page')
Object AccountObject = _dbContext.Accounts
.Join(_dbContext.Users, acc => acc.AccountId, usr => usr.AccountId, (acc, usr) => new { acc, usr })
.Where(x => x.usr.EmailAddress == key1)
.Where(x => x.usr.Hash == key2)
.Select(x => new { AccountId = x.acc.AccountId, Name = x.acc.Name })
.SingleOrDefault();
this error basically comes when you use the object before using it.
Use xpath and text()
driver.findElement(By.Xpath("//strong[contains(text(),'" + service +"')]"));
In the scikit-learn 'metrics' library there is a confusion_matrix method which gives you the desired output.
You can use any classifier that you want. Here I used the KNeighbors as example.
from sklearn import metrics, neighbors
clf = neighbors.KNeighborsClassifier()
X_test = ...
y_test = ...
expected = y_test
predicted = clf.predict(X_test)
conf_matrix = metrics.confusion_matrix(expected, predicted)
>>> print conf_matrix
>>> [[1403 87]
[ 56 3159]]
"simple solution is here"
1 .Create a folder named libs under the app directory for that matter any directory within the project..
2 .Copy Paste your Library to libs folder
3.You simply copy the JAR to your libs/ directory and then from inside Android Studio, right click the Jar that shows up under libs/ > Add As Library..
Peace!
Try this:
cc=is.na(DF$y)
m=which(cc==c("TRUE"))
DF=DF[-m,]
Although I was expecting an automatic solution (fitting to the screen automatically), resizing solves the problem as well.
import cv2
cv2.namedWindow("output", cv2.WINDOW_NORMAL) # Create window with freedom of dimensions
im = cv2.imread("earth.jpg") # Read image
imS = cv2.resize(im, (960, 540)) # Resize image
cv2.imshow("output", imS) # Show image
cv2.waitKey(0) # Display the image infinitely until any keypress
element
on the block
:.border {_x000D_
border: 2px blue dashed;_x000D_
}_x000D_
_x000D_
.mr-0 {_x000D_
margin-right: 0;_x000D_
}_x000D_
.ml-auto {_x000D_
margin-left:auto;_x000D_
}_x000D_
.d-block {_x000D_
display:block;_x000D_
}
_x000D_
<p class="border">_x000D_
<input type="button" class="d-block mr-0 ml-auto" value="The Button">_x000D_
</p>
_x000D_
elements
on the block
:.border {_x000D_
border: 2px indigo dashed;_x000D_
}_x000D_
_x000D_
.d-table {_x000D_
display:table;_x000D_
}_x000D_
_x000D_
.d-table-cell {_x000D_
display:table-cell;_x000D_
}_x000D_
_x000D_
.w-100 {_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.tar {_x000D_
text-align: right;_x000D_
}
_x000D_
<div class="border d-table w-100">_x000D_
<p class="d-table-cell">The paragraph.....lorem ipsum...etc.</p>_x000D_
<div class="d-table-cell tar">_x000D_
<button >The Button</button>_x000D_
</div>_x000D_
</div>
_x000D_
flex-box
:.flex-box {_x000D_
display:flex;_x000D_
justify-content:space-between;_x000D_
outline: 2px dashed blue;_x000D_
}_x000D_
_x000D_
.flex-box-2 {_x000D_
display:flex;_x000D_
justify-content: flex-end;_x000D_
outline: 2px deeppink dashed;_x000D_
}
_x000D_
<h1>Button with Text</h1>_x000D_
<div class="flex-box">_x000D_
<p>Once upon a time in a ...</p>_x000D_
<button>Read More...</button>_x000D_
</div>_x000D_
_x000D_
<h1>Only Button</h1>_x000D_
<div class="flex-box-2">_x000D_
<button>The Button</button>_x000D_
</div>_x000D_
_x000D_
<h1>Multiple Buttons</h1>_x000D_
<div class="flex-box-2">_x000D_
<button>Button 1</button>_x000D_
<button>Button 2</button>_x000D_
</div>
_x000D_
Good Luck...
Going Relative:
Going Absolute:
All scripting languages are programming languages.
Languages are not classed as script or not - it entirely depends on the execution environment.
If the environment is one that is interpreted, this is commonly referred to as a scripting environment.
Python has several things that fulfill similar purposes:
list(your_string)
. You could also use a UserString.MutableString
for this.(c)StringIO.StringIO
is useful for things that would otherwise take a file, but less so for general string building.use move
then move <file or folder> <destination directory>
I had the same problem and I found this solution working with bindParam :
bindParam(':param', $myvar = NULL, PDO::PARAM_INT);
Please follow below steps :
1.Open Your project.
2.Go to the Left side of the Gradle button.
3.Look at below image.
4.Click button above image show.
5.if this type of view you are not in offline mode.
6.Go to Build and rebuild the project.
All above point is work for me.
'''
w write mode
r read mode
a append mode
w+ create file if it doesn't exist and open it in write mode
r+ open for reading and writing. Does not create file.
a+ create file if it doesn't exist and open it in append mode
'''
example:
file_name = 'my_file.txt'
f = open(file_name, 'w+') # open file in write mode
f.write('python rules')
f.close()
I hope this helps. [FYI am using python version 3.6.2]
use global scope on your $con and put it inside your getPosts() function like so.
function getPosts() {
global $con;
$query = mysqli_query($con,"SELECT * FROM Blog");
while($row = mysqli_fetch_array($query))
{
echo "<div class=\"blogsnippet\">";
echo "<h4>" . $row['Title'] . "</h4>" . $row['SubHeading'];
echo "</div>";
}
}
I have the same problem....
I change my project name and i have this problem...my solution was the checking project refences and use /
in my web.xml (instead of /*
)
In addition to standard net/http package, you can consider using my GoRequest which wraps around net/http and make your life easier without thinking too much about json or struct. But you can also mix and match both of them in one request! (you can see more details about it in gorequest github page)
So, in the end your code will become like follow:
func main() {
url := "http://restapi3.apiary.io/notes"
fmt.Println("URL:>", url)
request := gorequest.New()
titleList := []string{"title1", "title2", "title3"}
for _, title := range titleList {
resp, body, errs := request.Post(url).
Set("X-Custom-Header", "myvalue").
Send(`{"title":"` + title + `"}`).
End()
if errs != nil {
fmt.Println(errs)
os.Exit(1)
}
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
fmt.Println("response Body:", body)
}
}
This depends on how you want to achieve. I made this library because I have the same problem with you and I want code that is shorter, easy to use with json, and more maintainable in my codebase and production system.
Historically, there may have been a subtle difference with a "method" being something which does not return a value, and a "function" one which does.Each language has its own lexicon of terms with special meaning.
In "C", the word "function" means a program routine.
In Java, the term "function" does not have any special meaning. Whereas "method" means one of the routines that forms the implementation of a class.
In C# that would translate as:
public void DoSomething() {} // method
public int DoSomethingAndReturnMeANumber(){} // function
But really, I re-iterate that there is really no difference in the 2 concepts. If you use the term "function" in informal discussions about Java, people will assume you meant "method" and carry on. Don't use it in proper documents or presentations about Java, or you will look silly.
I would put the code in the viewWillAppear delegate on each view being shown:
Like this where you need to hide it:
- (void)viewWillAppear:(BOOL)animated
{
[yourObject hideBar];
}
Like this where you need to show it:
- (void)viewWillAppear:(BOOL)animated
{
[yourObject showBar];
}
You can use MATCH
for instance.
Select the column from the first cell, for example cell A2 to cell A100 and insert a conditional formatting, using 'New Rule...' and the option to conditional format based on a formula.
In the entry box, put:
=MATCH(A2, 'Sheet2'!A:A, 0)
Pick the desired formatting (change the font to red or fill the cell background, etc) and click OK.
MATCH
takes the value A2
from your data table, looks into 'Sheet2'!A:A
and if there's an exact match (that's why there's a 0
at the end), then it'll return the row number.
Note: Conditional formatting based on conditions from other sheets is available only on Excel 2010 onwards. If you're working on an earlier version, you might want to get the list of 'Don't check' in the same sheet.
EDIT: As per new information, you will have to use some reverse matching. Instead of the above formula, try:
=SUM(IFERROR(SEARCH('Sheet2'!$A$1:$A$44, A2),0))
You can simply use this code,
TelephonyManager tm = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
String countryCodeValue = tm.getNetworkCountryIso();
This will return 'US' if your current connected network is in the United States. This works without a SIM card even.
This is an old question but encountered it myself.
I have semi-solutions that work situational for the former question("Children visible in overflow:hidden parent")
If the parent div does not need to be position:relative, simply set the children styles to visibility:visible.
If the parent div does need to be position:relative, the only way possible I found to show the children was position:fixed. This worked for me in my situation luckily enough but I would imagine it wouldn't work in others.
Here is a crappy example just post into a html file to view.
<div style="background: #ff00ff; overflow: hidden; width: 500px; height: 500px; position: relative;">
<div style="background: #ff0000;position: fixed; top: 10px; left: 10px;">asd
<div style="background: #00ffff; width: 200px; overflow: visible; position: absolute; visibility: visible; clear:both; height: 1000px; top: 100px; left: 10px;"> a</div>
</div>
</div>
I was thinking about this exact issue for a case with long polling where I didn't want the php script to have to continually poll the db. Polling would need to be done somewhere, memory would probably be best. So if somehow the trigger could put the info into something like memcache, then php could poll that would would be much less intensive overall. Just need a method for mysql to use memcache. Perhaps into a predefined variable with a specific user id. Once the data is retrieved php could reset the var until the db sets it again. Not sure about timing issues though. Perhaps a second variable to store the previous key selected.
I find it can be annoying and error prone to do a lot of these .stat.exists
type checks. For example they require extra care to get check mode (--check
) working.
Many answers here suggest
However, sometimes this is a code smell so always look for better ways to use Ansible, specifically there are many advantages to using the correct module. e.g.
- name: install ntpdate
package:
name: ntpdate
or
- file:
path: /etc/file.txt
owner: root
group: root
mode: 0644
But when it is not possible use one module, also investigate if you can register and check the result of a previous task. e.g.
# jmeter_version: 4.0
- name: Download Jmeter archive
get_url:
url: "http://archive.apache.org/dist/jmeter/binaries/apache-jmeter-{{ jmeter_version }}.tgz"
dest: "/opt/jmeter/apache-jmeter-{{ jmeter_version }}.tgz"
checksum: sha512:eee7d68bd1f7e7b269fabaf8f09821697165518b112a979a25c5f128c4de8ca6ad12d3b20cd9380a2b53ca52762b4c4979e564a8c2ff37196692fbd217f1e343
register: download_result
- name: Extract apache-jmeter
unarchive:
src: "/opt/jmeter/apache-jmeter-{{ jmeter_version }}.tgz"
dest: "/opt/jmeter/"
remote_src: yes
creates: "/opt/jmeter/apache-jmeter-{{ jmeter_version }}"
when: download_result.state == 'file'
Note the when:
but also the creates:
so --check
doesn't error out
I mention this because often these less-than-ideal practices come in pairs i.e. no apt/yum package so we have to 1) download and 2) unzip
Hope this helps
You need to use the alias
directive for location /static
:
server {
index index.html;
server_name test.example.com;
root /web/test.example.com/www;
location /static/ {
alias /web/test.example.com/static/;
}
}
The nginx wiki explains the difference between root and alias better than I can:
Note that it may look similar to the root directive at first sight, but the document root doesn't change, just the file system path used for the request. The location part of the request is dropped in the request Nginx issues.
Note that root
and alias
handle trailing slashes differently.
Extending Piotr's answer, if you also need a way to figure what to put in requirements.in
, you can first use pip-chill
to find the minimal set of required packages you have. By combining these tools, you can show the dependency reason why each package is installed. The full cycle looks like this:
$ python3 -m venv venv
$ . venv/bin/activate
(venv)$ pip install --upgrade pip
(venv)$ pip install pip-tools pip-chill
(venv)$ pip-chill --no-version > requirements.in
(venv)$ pip-compile requirements.in
(venv)$ pip-sync
I think this is easy way to drop the index.
set FOREIGN_KEY_CHECKS=0; //disable checks
ALTER TABLE mytable DROP INDEX AID;
set FOREIGN_KEY_CHECKS=1; //enable checks
Actually, if you do not want to delete your local .m2/repository/... and you are have a downloaded copy of Maven from Apache, you can have Eclipse /STS use that external Maven and you can edit the {maven}\conf\settings.xml to point your localRepository to a new empty location.
<localRepository>C:\java\repository</localRepository>
Of course, you will have a new repository with all of the maven source downloads in addition to your previous .m2 location.
Just put the commands you want to run into a file, then pass it to the shell along with the database name and redirect the output to a file. So, if your find command is in find.js
and your database is foo
, it would look like this:
./mongo foo find.js >> out.json
This was very simple now that I realize how to do it, thanks to all the answers for leading me to the solution. I had to abandon $.getScript() in order to specify the source of the script...sometimes doing things manually is best.
Solution
//great suggestion @Jasper
var len = $('script[src*="Javascript/MyScript.js"]').length;
if (len === 0) {
alert('script not loaded');
loadScript('Javascript/MyScript.js');
if ($('script[src*="Javascript/MyScript.js"]').length === 0) {
alert('still not loaded');
}
else {
alert('loaded now');
}
}
else {
alert('script loaded');
}
function loadScript(scriptLocationAndName) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = scriptLocationAndName;
head.appendChild(script);
}
It's a list of public objects of that module, as interpreted by import *
. It overrides the default of hiding everything that begins with an underscore.
There's a module for that: https://www.npmjs.com/package/string-to-stream
var str = require('string-to-stream')
str('hi there').pipe(process.stdout) // => 'hi there'
See Semantic Designs' CloneDR, a "clone detection" tool that finds copy/paste/edited code.
It will find exact and near miss code fragments, in spite of white space, comments and even variable renamings. A sample detection report for PHP can be found at the website. (I'm the author.)
Languages like Delphi, C and C++ Compile to processor-native machine code, and the output executables have little or no metadata in them. This is in contrast with Java or .Net, which compile to object-oriented platform-independent bytecode, which retains the names of methods, method parameters, classes and namespaces, and other metadata.
So there is a lot less useful decompiling that can be done on Delphi or C code. However, Delphi typically has embedded form data for any form in the project (generated by the $R *.dfm line), and it also has metadata on all published properties, so a Delphi-specific tool would be able to extract this information.
I found this solution.I download JDK 8.Then I add downloading jdk file path name of JAVA_HOME into user variables in environment variable.
I have found that if the view model contains many div bindings the best way to clear the ko.applyBindings(new someModelView);
is to use: ko.cleanNode($("body")[0]);
This allows you to call a new ko.applyBindings(new someModelView2);
dynamically without the worry of the previous view model still being binded.
As already stated, it's a warning not an error, but (if like me) you want things to run without warnings, you can disable that warning, then re-enable it again when you're done.
SET sql_notes = 0; -- Temporarily disable the "Table already exists" warning
CREATE TABLE IF NOT EXISTS ...
SET sql_notes = 1; -- And then re-enable the warning again
@Mircea: It is very much easy to set the multiple styles for an element in a single statement. It doesn't effect the existing properties and avoids the complexity of going for loops or plugins.
document.getElementById("demo").setAttribute(
"style", "font-size: 100px; font-style: italic; color:#ff0000;");
BE CAREFUL: If, later on, you use this method to add or alter style properties, the previous properties set using 'setAttribute' will be erased.
You are experiencing this issue for two reasons.
When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)
User.java
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="iduser")
private Long idUser;
@Column(name="user_name")
private String userName;
@OneToOne()
@JoinColumn(name="idarea")
private Area area;
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
}
Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:
@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")
While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.
Area.java
@Entity
@Table(name = "area")
public class Area {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="idarea")
private Long idArea;
@Column(name="area_name")
private String areaName;
@OneToOne(fetch=FetchType.LAZY, mappedBy="area")
private User user;
public Long getIdArea() {
return idArea;
}
public void setIdArea(Long idArea) {
this.idArea = idArea;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:
1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)
2: Run your formula
3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank
4: Replace All
Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.
A (MySQLdb/PyMySQL-specific) difference worth noting when using a DictCursor
is that list(cursor)
will always give you a list, while cursor.fetchall()
gives you a list unless the result set is empty, in which case it gives you an empty tuple. This was the case in MySQLdb and remains the case in the newer PyMySQL, where it will not be fixed for backwards-compatibility reasons. While this isn't a violation of Python Database API Specification, it's still surprising and can easily lead to a type error caused by wrongly assuming that the result is a list, rather than just a sequence.
Given the above, I suggest always favouring list(cursor)
over cursor.fetchall()
, to avoid ever getting caught out by a mysterious type error in the edge case where your result set is empty.
In addition to the other great answers, here is the typical schema people use to show the difference between NP, NP-Complete, and NP-Hard:
my solution, hope help
custom ObjectMapper and config to spring xml(register message conveters)
public class PyResponseConfigObjectMapper extends ObjectMapper {
public PyResponseConfigObjectMapper() {
disable(SerializationFeature.WRITE_NULL_MAP_VALUES); //map no_null
setSerializationInclusion(JsonInclude.Include.NON_NULL); // bean no_null
}
}
I came across this solution from @jbabey while trying to solve a similar problem. With a little modification, I got it right. In my case, the object keys are numbers (489) and strings ("489"). Hence to solve this, each key is parse. The following code works:
var array = {"nR": 22, "nH": 7, "totB": "2761", "nSR": 16, "htRb": "91981"}
var parskey = 0;
for (var key in array) {
parskey = parseInt(array[key]);
sum += parskey;
};
return(sum);
deleted the c#... here is the vb.net
<%=Html.ActionLink("Home", "Index", "Home", New With {.class = "tab"}, Nothing)%>
If you are using Linux and you got the permission error, you will need to raise the allowed limit in the /etc/limits.conf
or /etc/security/limits.conf
file (where the file is located depends on your specific Linux distribution).
For example to allow anyone on the machine to raise their number of open files up to 10000 add the line to the limits.conf
file.
* hard nofile 10000
Then logout and relogin to your system and you should be able to do:
ulimit -n 10000
without a permission error.
Refer Below code which give the date in String form.
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test{
public static void main(String[] args) {
long val = 1346524199000l;
Date date=new Date(val);
SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
String dateText = df2.format(date);
System.out.println(dateText);
}
}
I needed my ASP.NET drop down list to take up all available space, and this is all I put in the CSS and it is working in Firefox and IE11:
width: 100%
I had to add the CSS class into the asp:DropDownList element
delete this line:
jsonp: 'jsonp_callback',
Or replace this line:
url: 'http://url.of.my.server/submit?callback=json_callback',
because currently you are asking jQuery to create a random callback function name with callback=?
and then telling jQuery that you want to use jsonp_callback
instead.
{{app.session}}
refers to the Session
object and not the $_SESSION
array. I don't think the $_SESSION
array is accessible unless you explicitly pass it to every Twig template or if you do an extension that makes it available.
Symfony2 is object-oriented, so you should use the Session
object to set session attributes and not rely on the array. The Session
object will abstract this stuff away from you so it is easier to, say, store the session in a database because storing the session variable is hidden from you.
So, set your attribute in the session and retrieve the value in your twig template by using the Session
object.
// In a controller
$session = $this->get('session');
$session->set('filter', array(
'accounts' => 'value',
));
// In Twig
{% set filter = app.session.get('filter') %}
{% set account-filter = filter['accounts'] %}
Hope this helps.
Regards,
Matt
Modals in Modal:
$('.modal-child').on('show.bs.modal', function () {_x000D_
var modalParent = $(this).attr('data-modal-parent');_x000D_
$(modalParent).css('opacity', 0);_x000D_
});_x000D_
_x000D_
$('.modal-child').on('hidden.bs.modal', function () {_x000D_
var modalParent = $(this).attr('data-modal-parent');_x000D_
$(modalParent).css('opacity', 1);_x000D_
});
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
<a href="#myModal" role="button" class="btn btn-primary" data-toggle="modal">Modals in Modal</a>_x000D_
_x000D_
_x000D_
<div id="myModal" class="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">_x000D_
<div class="modal-dialog">_x000D_
<!-- Modal content-->_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
_x000D_
<button type="button" class="close" data-dismiss="modal">×</button>_x000D_
<h4 class="modal-title">Modal Header</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<a href="#myModal1" role="button" class="btn btn-primary" data-toggle="modal">Launch other modal 1</a>_x000D_
<a href="#myModal2" role="button" class="btn btn-primary" data-toggle="modal">Launch other modal 2</a>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div id="myModal1" class="modal modal-child" data-backdrop-limit="1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-modal-parent="#myModal">_x000D_
<div class="modal-dialog">_x000D_
<!-- Modal content-->_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal">×</button>_x000D_
<h4 class="modal-title">Modal Header 1</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>Two modal body…1</p>_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button class="btn btn-default" data-dismiss="modal" data-dismiss="modal" aria-hidden="true">Cancel</button>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div id="myModal2" class="modal modal-child" data-backdrop-limit="1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-modal-parent="#myModal">_x000D_
<div class="modal-dialog">_x000D_
<!-- Modal content-->_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
_x000D_
<button type="button" class="close" data-dismiss="modal">×</button>_x000D_
<h4 class="modal-title">Modal Header 2</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>Modal body…2</p>_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button class="btn btn-default" data-dismiss="modal" data-dismiss="modal" aria-hidden="true">Cancel</button>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
brbcoding have been able to help me with the appropriate coding i needed, here is it
HTML
<input type="checkbox" id="checkme"/>
<input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />
Javascript
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('sendNewSms');
// when unchecked or checked, run the function
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
DIV is a generic block level container that can contain any other block or inline elements, including other DIV elements, whereas P is to wrap paragraphs (text).
You can easily do that with a for loop,
public static void main(String[] args) {
String aToZ="ABCD.....1234"; // 36 letter.
String randomStr=generateRandom(aToZ);
}
private static String generateRandom(String aToZ) {
Random rand=new Random();
StringBuilder res=new StringBuilder();
for (int i = 0; i < 17; i++) {
int randIndex=rand.nextInt(aToZ.length());
res.append(aToZ.charAt(randIndex));
}
return res.toString();
}
@Michael Yagudaev 's answer works for me.
But the original answer did not chain the wrapped promise with .catch() to handle reject handling, here is my improvement on top of @Michael Yagudaev's answer:
const makeCancelablePromise = promise => {
let hasCanceled = false;
const wrappedPromise = new Promise((resolve, reject) => {
promise
.then(val => (hasCanceled ? reject({ isCanceled: true }) : resolve(val)))
.catch(
error => (hasCanceled ? reject({ isCanceled: true }) : reject(error))
);
});
return {
promise: wrappedPromise,
cancel() {
hasCanceled = true;
}
};
};
// Example Usage:
const cancelablePromise = makeCancelable(
new Promise((rs, rj) => {
/*do something*/
})
);
cancelablePromise.promise.then(() => console.log('resolved')).catch(err => {
if (err.isCanceled) {
console.log('Wrapped promise canceled');
return;
}
console.log('Promise was not canceled but rejected due to errors: ', err);
});
cancelablePromise.cancel();
Quick fix to add icon in front of text:
< asp:CheckBox... Text="< img src='/link/to/img.png' />My Text" />
Just add to a variable encode('utf-8')
agent_contact.encode('utf-8')
Try this:
int num= 4321
int first = num % 10;
int second = ( num - first ) % 100 / 10;
int third = ( num - first - second ) % 1000 / 100;
int fourth = ( num - first - second - third ) % 10000 / 1000;
You will get first = 1, second = 2, third = 3 and fourth = 4 ....
Define the class before you use it:
class Something:
def out(self):
print("it works")
s = Something()
s.out()
You need to pass self
as the first argument to all instance methods.
As nice as "return by value" might be, it's the kind of code that can lead one into error. Consider the following program:
#include <string>
#include <vector>
#include <iostream>
using namespace std;
static std::vector<std::string> strings;
std::vector<std::string> vecFunc(void) { return strings; };
int main(int argc, char * argv[]){
// set up the vector of strings to hold however
// many strings the user provides on the command line
for(int idx=1; (idx<argc); ++idx){
strings.push_back(argv[idx]);
}
// now, iterate the strings and print them using the vector function
// as accessor
for(std::vector<std::string>::interator idx=vecFunc().begin(); (idx!=vecFunc().end()); ++idx){
cout << "Addr: " << idx->c_str() << std::endl;
cout << "Val: " << *idx << std::endl;
}
return 0;
};
The above erroneous program will indicate no errors even if one uses the GNU g++ reporting options -Wall -Wextra -Weffc++
If you must produce a value, then the following would work in place of calling vecFunc() twice:
std::vector<std::string> lclvec(vecFunc());
for(std::vector<std::string>::iterator idx=lclvec.begin(); (idx!=lclvec.end()); ++idx)...
The above also produces no anonymous objects during iteration of the loop, but requires a possible copy operation (which, as some note, might be optimized away under some circumstances. But the reference method guarantees that no copy will be produced. Believing the compiler will perform RVO is no substitute for trying to build the most efficient code you can. If you can moot the need for the compiler to do RVO, you are ahead of the game.
After a lot of searching, the best explanation I've found is from Java Performance Tuning website in Question of the month: 1.4.1 Garbage collection algorithms, January 29th, 2003
Young generation garbage collection algorithms
The (original) copying collector (Enabled by default). When this collector kicks in, all application threads are stopped, and the copying collection proceeds using one thread (which means only one CPU even if on a multi-CPU machine). This is known as a stop-the-world collection, because basically the JVM pauses everything else until the collection is completed.
The parallel copying collector (Enabled using -XX:+UseParNewGC). Like the original copying collector, this is a stop-the-world collector. However this collector parallelizes the copying collection over multiple threads, which is more efficient than the original single-thread copying collector for multi-CPU machines (though not for single-CPU machines). This algorithm potentially speeds up young generation collection by a factor equal to the number of CPUs available, when compared to the original singly-threaded copying collector.
The parallel scavenge collector (Enabled using -XX:UseParallelGC). This is like the previous parallel copying collector, but the algorithm is tuned for gigabyte heaps (over 10GB) on multi-CPU machines. This collection algorithm is designed to maximize throughput while minimizing pauses. It has an optional adaptive tuning policy which will automatically resize heap spaces. If you use this collector, you can only use the the original mark-sweep collector in the old generation (i.e. the newer old generation concurrent collector cannot work with this young generation collector).
From this information, it seems the main difference (apart from CMS cooperation) is that UseParallelGC supports ergonomics while UseParNewGC doesn't.
The relationship Room
to Class
is considered weak (non-identifying) because the primary key components CID
and DATE
of entity Class
doesn't contain the primary key RID
of entity Room
(in this case primary key of Room entity is a single component, but even if it was a composite key, one component of it also fulfills the condition).
However, for instance, in the case of the relationship Class
and Class_Ins
we see that is a strong (identifying) relationship because the primary key components EmpID
and CID
and DATE
of Class_Ins
contains a component of the primary key Class
(in this case it contains both components CID
and DATE
).
Do the following, download SQLLite Database Browser from here:
Locate your db. file in your phone.
Then, as soon you install the program go to: "Browse Data", you will see all the SMS there!!
You can actually export the data to an excel file or SQL.
Generally you don't kill, stop, or interrupt a thread (or check wheter it is interrupted()), but let it terminate naturally.
It is simple. You can use any loop together with (volatile) boolean variable inside run() method to control thread's activity. You can also return from active thread to the main thread to stop it.
This way you gracefully kill a thread :) .
Well, the JVM memory model works something like this: values are stored on one pile of memory stack and objects are stored on another pile of memory called the heap. The garbage collector looks for garbage by looking at a list of objects you've made and seeing which ones aren't pointed at by anything. This is where setting an object to null
comes in; all nonprimitive (think of classes) variables are really references that point to the object on the stack, so by setting the reference you have to null
the garbage collector can see that there's nothing else pointing at the object and it can decide to garbage collect it. All Java objects are stored on the heap so they can be seen and collected by the garbage collector.
Nonprimitive (int
s, char
s, double
s, those sort of things) values, however, aren't stored on the heap. They're created and stored temporarily as they're needed and there's not much you can do there, but thankfully the compilers nowadays are really efficient and will avoid needed to store them on the JVM stack unless they absolutely need to.
On a bytecode level, that's basically how it works. The JVM is based on a stack-based machine, with a couple instructions to create allocate objects on the heap as well, and a ton of instructions to manipulate, push and pop values, off the stack. Local variables are stored on the stack, allocated variables on the heap.* These are the heap and the stack I'm referring to above. Here's a pretty good starting point if you want to get into the nitty gritty details.
In the resulting compiled code, there's a bit of leeway in terms of implementing the heap and stack. Allocation's implemented as allocation, there's really not a way around doing so. Thus the virtual machine heap becomes an actual heap, and allocations in the bytecode are allocations in actual memory. But you can get around using a stack to some extent, since instead of storing the values on a stack (and accessing a ton of memory), you can stored them on registers on the CPU which can be up to a hundred times (maybe even a thousand) faster than storing it on memory. But there's cases where this isn't possible (look up register spilling for one example of when this may happen), and using a stack to implement a stack kind of makes a lot of sense.
And quite frankly in your case a few integers probably won't matter. The compiler will probably optimize them out by itself in this case anyways. Optimization should always happen after you get it running and notice it's a tad slower than you'd prefer it to be. Worry about making simple, elegant, working code first then later make it fast (and hopefully) simple, elegant, working code.
Java's actually very nicely made so that you shouldn't have to worry about null
ing variables very often. Whenever you stop needing to use something, it will usually incidentally be disappearing from the scope of your program (and thus becoming eligible for garbage collection). So I guess the real lesson here is to use local variables as often as you can.
*There's also a constant pool, a local variable pool, and a couple other things in memory but you have close to no control over the size of those things and I want to keep this fairly simple.
Be aware that this property isn't as useful as many people think it is. Just because your app is running on a Windows machine, for example, doesn't mean the file it's reading will be using Windows-style line separators. Many web pages contain a mixture of "\n" and "\r\n", having been cobbled together from disparate sources. When you're reading text as a series of logical lines, you should always look for all three of the major line-separator styles: Windows ("\r\n"), Unix/Linux/OSX ("\n") and pre-OSX Mac ("\r").
When you're writing text, you should be more concerned with how the file will be used than what platform you're running on. For example, if you expect people to read the file in Windows Notepad, you should use "\r\n" because it only recognizes the one kind of separator.
NodeJS (and newer browsers) have a nice shortcut to get the current time in milliseconds.
var timeInMss = Date.now()
Which has a performance boost compared with
var timeInMss = new Date().getTime()
Because you do not need to create a new object.
Change the machine address from localhost to IP address you want your client to connect with to call below mentioned service.
Client to call REST webservice:
package in.india.client.downloadfiledemo;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.multipart.BodyPart;
import com.sun.jersey.multipart.MultiPart;
public class DownloadFileClient {
private static final String BASE_URI = "http://localhost:8080/DownloadFileDemo/services/downloadfile";
public DownloadFileClient() {
try {
Client client = Client.create();
WebResource objWebResource = client.resource(BASE_URI);
ClientResponse response = objWebResource.path("/")
.type(MediaType.TEXT_HTML).get(ClientResponse.class);
System.out.println("response : " + response);
if (response.getStatus() == Status.OK.getStatusCode()
&& response.hasEntity()) {
MultiPart objMultiPart = response.getEntity(MultiPart.class);
java.util.List<BodyPart> listBodyPart = objMultiPart
.getBodyParts();
BodyPart filenameBodyPart = listBodyPart.get(0);
BodyPart fileLengthBodyPart = listBodyPart.get(1);
BodyPart fileBodyPart = listBodyPart.get(2);
String filename = filenameBodyPart.getEntityAs(String.class);
String fileLength = fileLengthBodyPart
.getEntityAs(String.class);
File streamedFile = fileBodyPart.getEntityAs(File.class);
BufferedInputStream objBufferedInputStream = new BufferedInputStream(
new FileInputStream(streamedFile));
byte[] bytes = new byte[objBufferedInputStream.available()];
objBufferedInputStream.read(bytes);
String outFileName = "D:/"
+ filename;
System.out.println("File name is : " + filename
+ " and length is : " + fileLength);
FileOutputStream objFileOutputStream = new FileOutputStream(
outFileName);
objFileOutputStream.write(bytes);
objFileOutputStream.close();
objBufferedInputStream.close();
File receivedFile = new File(outFileName);
System.out.print("Is the file size is same? :\t");
System.out.println(Long.parseLong(fileLength) == receivedFile
.length());
}
} catch (UniformInterfaceException e) {
e.printStackTrace();
} catch (ClientHandlerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String... args) {
new DownloadFileClient();
}
}
Service to response client:
package in.india.service.downloadfiledemo;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.sun.jersey.multipart.MultiPart;
@Path("downloadfile")
@Produces("multipart/mixed")
public class DownloadFileResource {
@GET
public Response getFile() {
java.io.File objFile = new java.io.File(
"D:/DanGilbert_2004-480p-en.mp4");
MultiPart objMultiPart = new MultiPart();
objMultiPart.type(new MediaType("multipart", "mixed"));
objMultiPart
.bodyPart(objFile.getName(), new MediaType("text", "plain"));
objMultiPart.bodyPart("" + objFile.length(), new MediaType("text",
"plain"));
objMultiPart.bodyPart(objFile, new MediaType("multipart", "mixed"));
return Response.ok(objMultiPart).build();
}
}
JAR needed:
jersey-bundle-1.14.jar
jersey-multipart-1.14.jar
mimepull.jar
WEB.XML:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>DownloadFileDemo</display-name>
<servlet>
<display-name>JAX-RS REST Servlet</display-name>
<servlet-name>JAX-RS REST Servlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>in.india.service.downloadfiledemo</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>JAX-RS REST Servlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
If you're using Django's built-in LoginView
, it takes next
as context, which is "The URL to redirect to after successful login
. This may contain a query string, too." (see docs)
Also from the docs:
"If login is successful, the view redirects to the URL specified in next
. If next isn’t provided, it redirects to settings.LOGIN_REDIRECT_URL
(which defaults to /accounts/profile/)."
Example code:
urls.py
from django.urls import path
from django.contrib.auth import views as auth_views
from account.forms import LoginForm # optional form to pass to view
urlpatterns = [
...
# --------------- login url/view -------------------
path('account/login/', auth_views.LoginView.as_view(
template_name='login.html',
authentication_form=LoginForm,
extra_context={
# option 1: provide full path
'next': '/account/my_custom_url/',
# option 2: just provide the name of the url
# 'next': 'custom_url_name',
},
), name='login'),
...
]
login.html
...
<form method="post" action="{% url 'login' %}">
...
{# option 1 #}
<input type="hidden" name="next" value="{{ next }}">
{# option 2 #}
{# <input type="hidden" name="next" value="{% url next %}"> #}
</form>
The simplest way is to simply use the following line of jquery
, using this you don't get the /fakepath
nonsense, you straight up get the file that was uploaded:
$('input[type=file]')[0].files[0]; // This gets the file
$('#idOfFileUpload')[0].files[0]; // This gets the file with the specified id
Some other useful commands are:
To get the name of the file:
$('input[type=file]')[0].files[0].name; // This gets the file name
To get the type of the file:
If I were to upload a PNG, it would return image/png
$("#imgUpload")[0].files[0].type
To get the size (in bytes) of the file:
$("#imgUpload")[0].files[0].size
Also you don't have to use these commands on('change'
, you can get the values at any time, for instance you may have a file upload and when the user clicks upload
, you simply use the commands I listed.
Consider this code,
int some_int = 100;
while(some_int == 100)
{
//your code
}
When this program gets compiled, the compiler may optimize this code, if it finds that the program never ever makes any attempt to change the value of some_int
, so it may be tempted to optimize the while
loop by changing it from while(some_int == 100)
to something which is equivalent to while(true)
so that the execution could be fast (since the condition in while
loop appears to be true
always). (if the compiler doesn't optimize it, then it has to fetch the value of some_int
and compare it with 100, in each iteration which obviously is a little bit slow.)
However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int
from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!
So, to ensure the desired result, you need to somehow stop the compiler from optimizing the while
loop. That is where the volatile
keyword plays its role. All you need to do is this,
volatile int some_int = 100; //note the 'volatile' qualifier now!
In other words, I would explain this as follows:
volatile
tells the compiler that,
"Hey compiler, I'm volatile and, you know, I can be changed by some XYZ that you're not even aware of. That XYZ could be anything. Maybe some alien outside this planet called program. Maybe some lightning, some form of interrupt, volcanoes, etc can mutate me. Maybe. You never know who is going to change me! So O you ignorant, stop playing an all-knowing god, and don't dare touch the code where I'm present. Okay?"
Well, that is how volatile
prevents the compiler from optimizing code. Now search the web to see some sample examples.
Quoting from the C++ Standard ($7.1.5.1/8)
[..] volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation.[...]
Related topic:
Does making a struct volatile make all its members volatile?
JAVA_HOME
is not necessary if you start java and javac from the command line. But JAVA_HOME
should point to the real jdk directory, C:\Program Files\Java\jdk1.7.0
in your case.
I'd never use the CLASSPATH
environment variable outside of build scripts, especially not global defined. The -cp
flag is better. But in your case, as you do not need additional libraries (rt.jar
doesn't count), you won't need a classpath declaration. A missing -cp
is equivalent to a -cp .
and that's what you need here)
The (I was pretty sure, that a source file needs one public class... or was it one public class at most ?)HelloWorld
class needs to be declared as public
. This actually may be the cause for your problems.
i tried to set default time for a picker and it worked:
$('#date2').datetimepicker({
format: 'DD-MM-YYYY 12:00:00'
});
this will save in database as : 2015-03-01 12:00:00
used for smalldatetime
type in sql server
There are several ways. I personally use the following ones:
extracting single value:
String user_Id =
given().
when().
then().
extract().
path("user_id");
work with the entire response when you need more than one:
Response response =
given().
when().
then().
extract().
response();
String userId = response.path("user_id");
extract one using the JsonPath to get the right type:
long userId =
given().
when().
then().
extract().
jsonPath().getLong("user_id");
Last one is really useful when you want to match against the value and the type i.e.
assertThat(
when().
then().
extract().
jsonPath().getLong("user_id"), equalTo(USER_ID)
);
The rest-assured documentation is quite descriptive and full. There are many ways to achieve what you are asking: https://github.com/jayway/rest-assured/wiki/Usage
if you want to operate with list of numbers it is better to use NumPy arrays:
import numpy
a = [1, 1, 1 ,1, 1]
ar = numpy.array(a)
print ar + 2
gives
[3, 3, 3, 3, 3]
I'm using Centos and the followings worked for me , I run this command
yum --enablerepo remi install php-xml
And restarted the Apache with this command
sudo service httpd restart
Please check whether the Default value for the column id in particular table.if not make it as default
I was using a custom downloader middleware, but wasn't very happy with it, as I didn't manage to make the cache work with it.
A better approach was to implement a custom download handler.
There is a working example here. It looks like this:
# encoding: utf-8
from __future__ import unicode_literals
from scrapy import signals
from scrapy.signalmanager import SignalManager
from scrapy.responsetypes import responsetypes
from scrapy.xlib.pydispatch import dispatcher
from selenium import webdriver
from six.moves import queue
from twisted.internet import defer, threads
from twisted.python.failure import Failure
class PhantomJSDownloadHandler(object):
def __init__(self, settings):
self.options = settings.get('PHANTOMJS_OPTIONS', {})
max_run = settings.get('PHANTOMJS_MAXRUN', 10)
self.sem = defer.DeferredSemaphore(max_run)
self.queue = queue.LifoQueue(max_run)
SignalManager(dispatcher.Any).connect(self._close, signal=signals.spider_closed)
def download_request(self, request, spider):
"""use semaphore to guard a phantomjs pool"""
return self.sem.run(self._wait_request, request, spider)
def _wait_request(self, request, spider):
try:
driver = self.queue.get_nowait()
except queue.Empty:
driver = webdriver.PhantomJS(**self.options)
driver.get(request.url)
# ghostdriver won't response when switch window until page is loaded
dfd = threads.deferToThread(lambda: driver.switch_to.window(driver.current_window_handle))
dfd.addCallback(self._response, driver, spider)
return dfd
def _response(self, _, driver, spider):
body = driver.execute_script("return document.documentElement.innerHTML")
if body.startswith("<head></head>"): # cannot access response header in Selenium
body = driver.execute_script("return document.documentElement.textContent")
url = driver.current_url
respcls = responsetypes.from_args(url=url, body=body[:100].encode('utf8'))
resp = respcls(url=url, body=body, encoding="utf-8")
response_failed = getattr(spider, "response_failed", None)
if response_failed and callable(response_failed) and response_failed(resp, driver):
driver.close()
return defer.fail(Failure())
else:
self.queue.put(driver)
return defer.succeed(resp)
def _close(self):
while not self.queue.empty():
driver = self.queue.get_nowait()
driver.close()
Suppose your scraper is called "scraper". If you put the mentioned code inside a file called handlers.py on the root of the "scraper" folder, then you could add to your settings.py:
DOWNLOAD_HANDLERS = {
'http': 'scraper.handlers.PhantomJSDownloadHandler',
'https': 'scraper.handlers.PhantomJSDownloadHandler',
}
And voilà, the JS parsed DOM, with scrapy cache, retries, etc.
I've connected to bank with two-way SSL (client and server certificate) with Spring Boot. So describe here all my steps, hope it helps someone (simplest working solution, I've found):
Generate sertificate request:
Generate private key:
openssl genrsa -des3 -passout pass:MY_PASSWORD -out user.key 2048
Generate certificate request:
openssl req -new -key user.key -out user.csr -passin pass:MY_PASSWORD
Keep user.key
(and password) and send certificate request user.csr
to bank for my sertificate
Receive 2 certificate: my client root certificate clientId.crt
and bank root certificate: bank.crt
Create Java keystore (enter key password and set keystore password):
openssl pkcs12 -export -in clientId.crt -inkey user.key -out keystore.p12 -name clientId -CAfile ca.crt -caname root
Don't pay attention on output: unable to write 'random state'
. Java PKCS12 keystore.p12
created.
Add into keystore bank.crt
(for simplicity I've used one keystore):
keytool -import -alias banktestca -file banktestca.crt -keystore keystore.p12 -storepass javaops
Check keystore certificates by:
keytool -list -keystore keystore.p12
Ready for Java code:) I've used Spring Boot RestTemplate
with add org.apache.httpcomponents.httpcore
dependency:
@Bean("sslRestTemplate")
public RestTemplate sslRestTemplate() throws Exception {
char[] storePassword = appProperties.getSslStorePassword().toCharArray();
URL keyStore = new URL(appProperties.getSslStore());
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(keyStore, storePassword)
// use storePassword twice (with key password do not work)!!
.loadKeyMaterial(keyStore, storePassword, storePassword)
.build();
// Solve "Certificate doesn't match any of the subject alternative names"
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
RestTemplate restTemplate = new RestTemplate(factory);
// restTemplate.setMessageConverters(List.of(new Jaxb2RootElementHttpMessageConverter()));
return restTemplate;
}
×
and font-family: Garamond, "Apple Garamond";
make it good enough. Garamond font is thin and web safe
This works in BS3, not tested in v2. It centers the modal vertically. Note that it will transition there - if you want it to just appear in position edit CSS transition
property for .modal-dialog
centerModal = function() {
var $dialog = $(this).find(".modal-dialog"),
offset = ($(window).height() - $dialog.height()) / 2;
// Center modal vertically in window
$dialog.css({
'transform': 'translateY(' + offset + 'px) !important',
});
};
$('.modal').on('shown.bs.modal', centerModal);
$(window).on("resize", function() {
$('.modal').each(centerModal);
});
What I did to make the Date (e.g December 01, 2016) as header. I used the StickyHeaderListView library
https://github.com/emilsjolander/StickyListHeaders
Convert the date to long in millis [do not include the time] and make it as the header Id.
@Override
public long getHeaderId(int position) {
return <date in millis>;
}
I would assume it's possible to place a proxy between the DB and your app then observe the communication. I'm not familiar with what software you would use to do this.
My trick is to put inside the div a table with 1 row and 1 column, set 100% of width and height, and the property vertical-align:middle.
<div>
<table style="width:100%; height:100%;">
<tr>
<td style="vertical-align:middle;">
BUTTON TEXT
</td>
</tr>
</table>
</div>
This is somewhat "native" .NET way of converting ViewState from string into StateBag Code is below:
public static StateBag LoadViewState(string viewState)
{
System.Web.UI.Page converterPage = new System.Web.UI.Page();
HiddenFieldPageStatePersister persister = new HiddenFieldPageStatePersister(new Page());
Type utilClass = typeof(System.Web.UI.BaseParser).Assembly.GetType("System.Web.UI.Util");
if (utilClass != null && persister != null)
{
MethodInfo method = utilClass.GetMethod("DeserializeWithAssert", BindingFlags.NonPublic | BindingFlags.Static);
if (method != null)
{
PropertyInfo formatterProperty = persister.GetType().GetProperty("StateFormatter", BindingFlags.NonPublic | BindingFlags.Instance);
if (formatterProperty != null)
{
IStateFormatter formatter = (IStateFormatter)formatterProperty.GetValue(persister, null);
if (formatter != null)
{
FieldInfo pageField = formatter.GetType().GetField("_page", BindingFlags.NonPublic | BindingFlags.Instance);
if (pageField != null)
{
pageField.SetValue(formatter, null);
try
{
Pair pair = (Pair)method.Invoke(null, new object[] { formatter, viewState });
if (pair != null)
{
MethodInfo loadViewState = converterPage.GetType().GetMethod("LoadViewStateRecursive", BindingFlags.Instance | BindingFlags.NonPublic);
if (loadViewState != null)
{
FieldInfo postback = converterPage.GetType().GetField("_isCrossPagePostBack", BindingFlags.NonPublic | BindingFlags.Instance);
if (postback != null)
{
postback.SetValue(converterPage, true);
}
FieldInfo namevalue = converterPage.GetType().GetField("_requestValueCollection", BindingFlags.NonPublic | BindingFlags.Instance);
if (namevalue != null)
{
namevalue.SetValue(converterPage, new NameValueCollection());
}
loadViewState.Invoke(converterPage, new object[] { ((Pair)((Pair)pair.First).Second) });
FieldInfo viewStateField = typeof(Control).GetField("_viewState", BindingFlags.NonPublic | BindingFlags.Instance);
if (viewStateField != null)
{
return (StateBag)viewStateField.GetValue(converterPage);
}
}
}
}
catch (Exception ex)
{
if (ex != null)
{
}
}
}
}
}
}
}
return null;
}
Note about tag of tag (tagging a tag), which is at the origin of your issue, as Charles Bailey correctly pointed out in the comment:
Make sure you study this thread, as overriding a signed tag is not as easy:
git tag
man page seriously advised against a simple git tag -f B
to replace a tag name "A
"don't try to recreate a signed tag with git tag -f
(see the thread extract below)
(it is about a corner case, but quite instructive about tags in general, and it comes from another SO contributor Jakub Narebski):
Please note that the name of tag (heavyweight tag, i.e. tag object) is stored in two places:
- in the tag object itself as a contents of 'tag' header (you can see it in output of "
git show <tag>
" and also in output of "git cat-file -p <tag>
", where<tag>
is heavyweight tag, e.g.v1.6.3
ingit.git
repository),- and also is default name of tag reference (reference in "
refs/tags/*
" namespace) pointing to a tag object.
Note that the tag reference (appropriate reference in the "refs/tags/*
" namespace) is purely local matter; what one repository has in 'refs/tags/v0.1.3
', other can have in 'refs/tags/sub/v0.1.3
' for example.So when you create signed tag '
A
', you have the following situation (assuming that it points at some commit)
35805ce <--- 5b7b4ead <=== refs/tags/A
(commit) tag A
(tag)
Please also note that "
git tag -f A A
" (notice the absence of options forcing it to be an annotated tag) is a noop - it doesn't change the situation.If you do "
git tag -f -s A A
": note that you force owerwriting a tag (so git assumes that you know what you are doing), and that one of-s
/-a
/-m
options is used to force annotated tag (creation of tag object), you will get the following situation
35805ce <--- 5b7b4ea <--- ada8ddc <=== refs/tags/A
(commit) tag A tag A
(tag) (tag)
Note also that "
git show A
" would show the whole chain down to the non-tag object...
if you already deployed the code or can't change any configuration, you could remove all temp files from wsdl:
rm /tmp/wsdl-*
if($_SERVER['REQUEST_METHOD']=='POST'){
$image_no="5";//or Anything You Need
$image = $_POST['image'];
$path = "uploads/".$image_no.".png";
$status = file_put_contents($path,base64_decode($image));
if($status){
echo "Successfully Uploaded";
}else{
echo "Upload failed";
}
}
I like to start with a class like this class settings { public int X {get;set;} public string Y { get; set; } // repeat as necessary
public settings()
{
this.X = defaultForX;
this.Y = defaultForY;
// repeat ...
}
public void Parse(Uri uri)
{
// parse values from query string.
// if you need to distinguish from default vs. specified, add an appropriate property
}
This has worked well on 100's of projects. You can use one of the many other parsing solutions to parse values.
Hows about this:
$json=Get-Content -Raw -Path 'my.json' | Out-String | ConvertFrom-Json
$foo="TheVariableYourUsingToSelectSomething"
$json.SomePathYouKnow.psobject.properties.Where({$_.name -eq $foo}).value
which would select from json structured
{"SomePathYouKnow":{"TheVariableYourUsingToSelectSomething": "Tada!"}
This is based on this accessing values in powershell SO question . Isn't powershell fabulous!
Here's a version without any position relative or absolute and without text-indent:
ul.dash {
list-style: none;
margin-left: 0;
padding-left: 1em;
}
ul.dash > li:before {
display: inline-block;
content: "-";
width: 1em;
margin-left: -1em;
}
Enjoy ;)
Dependency
dependencies {
implementation 'com.squareup.picasso:picasso:2.71828'
}
//Java Code for Image Loading into imageView
Picasso.get().load(werURL).into(imageView);