You could also use a dummy form arround it like:
<mat-card-footer>
<form (submit)="search(ref, id, forename, surname, postcode)" action="#">
<button mat-raised-button type="submit" class="successButton" id="invSearch" title="Click to perform search." >Search</button>
</form>
</mat-card-footer>
the search function has to return false
to make sure that the action doesn't get executed.
Just make sure the form is focused (should be when you have the input in the form) when you press enter.
Goto View -> Show Symbol -> Show All Characters. Uncheck it. There you go.!!
From comments:
But, this code never stops (because of integer overflow) !?! Yves Daoust
For many numbers it will not overflow.
If it will overflow - for one of those unlucky initial seeds, the overflown number will very likely converge toward 1 without another overflow.
Still this poses interesting question, is there some overflow-cyclic seed number?
Any simple final converging series starts with power of two value (obvious enough?).
2^64 will overflow to zero, which is undefined infinite loop according to algorithm (ends only with 1), but the most optimal solution in answer will finish due to shr rax
producing ZF=1.
Can we produce 2^64? If the starting number is 0x5555555555555555
, it's odd number, next number is then 3n+1, which is 0xFFFFFFFFFFFFFFFF + 1
= 0
. Theoretically in undefined state of algorithm, but the optimized answer of johnfound will recover by exiting on ZF=1. The cmp rax,1
of Peter Cordes will end in infinite loop (QED variant 1, "cheapo" through undefined 0
number).
How about some more complex number, which will create cycle without 0
?
Frankly, I'm not sure, my Math theory is too hazy to get any serious idea, how to deal with it in serious way. But intuitively I would say the series will converge to 1 for every number : 0 < number, as the 3n+1 formula will slowly turn every non-2 prime factor of original number (or intermediate) into some power of 2, sooner or later. So we don't need to worry about infinite loop for original series, only overflow can hamper us.
So I just put few numbers into sheet and took a look on 8 bit truncated numbers.
There are three values overflowing to 0
: 227
, 170
and 85
(85
going directly to 0
, other two progressing toward 85
).
But there's no value creating cyclic overflow seed.
Funnily enough I did a check, which is the first number to suffer from 8 bit truncation, and already 27
is affected! It does reach value 9232
in proper non-truncated series (first truncated value is 322
in 12th step), and the maximum value reached for any of the 2-255 input numbers in non-truncated way is 13120
(for the 255
itself), maximum number of steps to converge to 1
is about 128
(+-2, not sure if "1" is to count, etc...).
Interestingly enough (for me) the number 9232
is maximum for many other source numbers, what's so special about it? :-O 9232
= 0x2410
... hmmm.. no idea.
Unfortunately I can't get any deep grasp of this series, why does it converge and what are the implications of truncating them to k bits, but with cmp number,1
terminating condition it's certainly possible to put the algorithm into infinite loop with particular input value ending as 0
after truncation.
But the value 27
overflowing for 8 bit case is sort of alerting, this looks like if you count the number of steps to reach value 1
, you will get wrong result for majority of numbers from the total k-bit set of integers. For the 8 bit integers the 146 numbers out of 256 have affected series by truncation (some of them may still hit the correct number of steps by accident maybe, I'm too lazy to check).
virtualenv --python=/usr/local/bin/python3 <VIRTUAL ENV NAME>
this will add python3
path for your virtual enviroment.
I was facing the same issue; and the following worked well for me. Hope this helps someone landing here:
<div class="row">
<div class="col-md-6">
<div class="col-md-12">
Set room heater temperature
</div>
</div>
<div class="col-md-6">
<div class="col-md-12">
Set room heater temperature
</div>
</div>
</div>
This will automatically render some space between the 2 divs.
You can make virtualenvwrapper use a custom Python binary instead of the one virtualenvwrapper is run with. To do that you need to use VIRTUALENV_PYTHON variable which is utilized by virtualenv:
$ export VIRTUALENV_PYTHON=/usr/bin/python3
$ mkvirtualenv -a myproject myenv
Running virtualenv with interpreter /usr/bin/python3
New python executable in myenv/bin/python3
Also creating executable in myenv/bin/python
(myenv)$ python
Python 3.2.3 (default, Oct 19 2012, 19:53:16)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
I found a solution to this. It's bloody witchcraft, but it works.
When you install the client, open Control Panel > Network Connections.
You'll see a disabled network connection that was added by the TAP installer (Local Area Connection 3 or some such).
Right Click it, click Enable.
The device will not reset itself to enabled, but that's ok; try connecting w/ the client again. It'll work.
.so
files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.
.a
files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar
command -- a predecessor of tar
that's now just used for making libraries) of the original .o object files.
.la
files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?
Static and dynamic libraries each have pros and cons.
Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.
Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.
Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.
Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.
Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.
Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.
Dynamic libraries are especially useful for system libraries, like libc
. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.
I would suggest starting with the most straightforward solutions first - maybe simple HTTP Basic Authentication + HTTPS is enough in your scenario.
If not (for example you cannot use https, or need more complex key management), you may have a look at HMAC-based solutions as suggested by others. A good example of such API would be Amazon S3 (http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html)
I wrote a blog post about HMAC based authentication in ASP.NET Web API. It discusses both Web API service and Web API client and the code is available on bitbucket. http://www.piotrwalat.net/hmac-authentication-in-asp-net-web-api/
Here is a post about Basic Authentication in Web API: http://www.piotrwalat.net/basic-http-authentication-in-asp-net-web-api-using-message-handlers/
Remember that if you are going to provide an API to 3rd parties, you will also most likely be responsible for delivering client libraries. Basic authentication has a significant advantage here as it is supported on most programming platforms out of the box. HMAC, on the other hand, is not that standardized and will require custom implementation. These should be relatively straightforward but still require work.
PS. There is also an option to use HTTPS + certificates. http://www.piotrwalat.net/client-certificate-authentication-in-asp-net-web-api-and-windows-store-apps/
I am working on a MVC5/Web API project and needed to be able to get authorization for the Web Api methods. When my index view is first loaded I make a call to the 'token' Web API method which I believe is created automatically.
The client side code (CoffeeScript) to get the token is:
getAuthenticationToken = (username, password) ->
dataToSend = "username=" + username + "&password=" + password
dataToSend += "&grant_type=password"
$.post("/token", dataToSend).success saveAccessToken
If successful the following is called, which saves the authentication token locally:
saveAccessToken = (response) ->
window.authenticationToken = response.access_token
Then if I need to make an Ajax call to a Web API method that has the [Authorize] tag I simply add the following header to my Ajax call:
{ "Authorization": "Bearer " + window.authenticationToken }
Parameters to HttpURLConnection using POST using NameValuePair with OutPut
try {
URL url = new URL("https://yourUrl.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
JSONObject data = new JSONObject();
data.put("key1", "value1");
data.put("key2", "value2");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data.toString());
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Typically, arrays require constants to initialize their size. You could sweep over nvPairs once to get the length, then "dynamically" create an array using a variable for length like this.
InputProperty[] ip = (InputProperty[])Array.CreateInstance(typeof(InputProperty), length);
I wouldn't recommend it, though. Just stick with the
List<InputProperty> ip = ...
...
update.Items = ip.ToArray();
solution. It's not that much less performant, and way better looking.
Returning 0 should tell the programmer that the program has successfully finished the job.
This is completely possible with just CSS-- no JavaScript needed: Here's an example
Here is the source code behind that example:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=ISO-8859-1">
<title>Dead Centre</title>
<style type="text/css" media="screen"><!--
body
{
color: white;
background-color: #003;
margin: 0px
}
#horizon
{
color: white;
background-color: transparent;
text-align: center;
position: absolute;
top: 50%;
left: 0px;
width: 100%;
height: 1px;
overflow: visible;
visibility: visible;
display: block
}
#content
{
font-family: Verdana, Geneva, Arial, sans-serif;
background-color: transparent;
margin-left: -125px;
position: absolute;
top: -35px;
left: 50%;
width: 250px;
height: 70px;
visibility: visible
}
.bodytext
{
font-size: 14px
}
.headline
{
font-weight: bold;
font-size: 24px
}
#footer
{
font-size: 11px;
font-family: Verdana, Geneva, Arial, sans-serif;
text-align: center;
position: absolute;
bottom: 0px;
left: 0px;
width: 100%;
height: 20px;
visibility: visible;
display: block
}
a:link, a:visited
{
color: #06f;
text-decoration: none
}
a:hover
{
color: red;
text-decoration: none
}
--></style>
</head>
<body>
<div id="horizon">
<div id="content">
<div class="bodytext">
This text is<br>
<span class="headline">DEAD CENTRE</span><br>
and stays there!</div>
</div>
</div>
<div id="footer">
<a href="http://www.wpdfd.com/editorial/thebox/deadcentre4.html">view construction</a></div>
</body>
</html>
scp -r C:/site user@server_ip:path
path
is the place, where site
will be copied into the remote server
EDIT: As I said in my comment, try pscp
, as you want to use scp
using PuTTY
.
The other option is WinSCP
You forgot the .class
:
if (value.getClass() == Integer.class) {
System.out.println("This is an Integer");
}
else if (value.getClass() == String.class) {
System.out.println("This is a String");
}
else if (value.getClass() == Float.class) {
System.out.println("This is a Float");
}
Note that this kind of code is usually the sign of a poor OO design.
Also note that comparing the class of an object with a class and using instanceof is not the same thing. For example:
"foo".getClass() == Object.class
is false, whereas
"foo" instanceof Object
is true.
Whether one or the other must be used depends on your requirements.
To use base_url()
(shorthand), you have to load the URL Helper
first
$this->load->helper('url');
Or you can autoload it by changing application/config/autoload.php
Or just use
$this->config->base_url();
Same applies to site_url()
.
Also I can see you are missing echo
(though its not your current problem), use the code below to solve the problem
<link rel="stylesheet" href="<?php echo base_url(); ?>css/default.css" type="text/css" />
Just an another ussage example for Notepad++ (regular expression search mode)
Find: (g|c|u|d)(et|reate|pdate|elete)_(.)([^\s (]+)
Replace: \U\1\E$2\U\3\E$4
Example:
get_user -> GetUser
create_user -> CreateUser
update_user -> UpdateUser
delete_user -> DeleteUser
Found transport-attribute in binding-element which tells us that this is the WSDL 1.1 binding for the SOAP 1.1 HTTP binding.
ex.
<wsdlsoap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
Here you can create dynamically a UIButton:
//For button image
UIImage *closebtnimg = [UIImage imageNamed:@"close_btn.png"];
//Custom type button
btnclose = [[UIButton buttonWithType:UIButtonTypeCustom]retain];
//Set frame of button means position
btnclose.frame = CGRectMake(103, 257, 94, 32);
//Button with 0 border so it's shape like image shape
[btnclose.layer setBorderWidth:0];
//Set title of button
[btnclose setTitle:@"CLOSE" forState:UIControlStateNormal];
[btnclose addTarget:self action:@selector(methodname:) forControlEvents:UIControlEventTouchUpInside];
//Font size of title
btnclose.titleLabel.font = [UIFont boldSystemFontOfSize:14];
//Set image of button
[btnclose setBackgroundImage:closebtnimg forState:UIControlStateNormal];
Example an activity have 2 fragments and we use FragmentManager
to replace/add with addToBackstack
each fragment to a layout in activity
Use replace
Go Fragment1
Fragment1: onAttach
Fragment1: onCreate
Fragment1: onCreateView
Fragment1: onActivityCreated
Fragment1: onStart
Fragment1: onResume
Go Fragment2
Fragment2: onAttach
Fragment2: onCreate
Fragment1: onPause
Fragment1: onStop
Fragment1: onDestroyView
Fragment2: onCreateView
Fragment2: onActivityCreated
Fragment2: onStart
Fragment2: onResume
Pop Fragment2
Fragment2: onPause
Fragment2: onStop
Fragment2: onDestroyView
Fragment2: onDestroy
Fragment2: onDetach
Fragment1: onCreateView
Fragment1: onStart
Fragment1: onResume
Pop Fragment1
Fragment1: onPause
Fragment1: onStop
Fragment1: onDestroyView
Fragment1: onDestroy
Fragment1: onDetach
Use add
Go Fragment1
Fragment1: onAttach
Fragment1: onCreate
Fragment1: onCreateView
Fragment1: onActivityCreated
Fragment1: onStart
Fragment1: onResume
Go Fragment2
Fragment2: onAttach
Fragment2: onCreate
Fragment2: onCreateView
Fragment2: onActivityCreated
Fragment2: onStart
Fragment2: onResume
Pop Fragment2
Fragment2: onPause
Fragment2: onStop
Fragment2: onDestroyView
Fragment2: onDestroy
Fragment2: onDetach
Pop Fragment1
Fragment1: onPause
Fragment1: onStop
Fragment1: onDestroyView
Fragment1: onDestroy
Fragment1: onDetach
let str = "abc"
let substr = str.substringToIndex(str.endIndex.predecessor()) // "ab"
If you bind your service, you will get the Extra in onBind(Intent intent)
.
Activity:
Intent intent = new Intent(this, LocationService.class);
intent.putExtra("tour_name", mTourName);
bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
Service:
@Override
public IBinder onBind(Intent intent) {
mTourName = intent.getStringExtra("tour_name");
return mBinder;
}
My current solution solves most of the issues you mentioned yet its completely abstracted from platform specific things and can be reused. Also i used no code-behind only binding with DelegateCommands that implement ICommand. Dialog is basically a View - a separate control that has its own ViewModel and it is shown from the ViewModel of the main screen but triggered from the UI via DelagateCommand binding.
See full Silverlight 4 solution here Modal dialogs with MVVM and Silverlight 4
You need to return true inside onInterceptTouchEvent()
when you handle click event.
//change the value in the in-memory object
content.val1 = 42;
//Serialize as JSON and Write it to a file
fs.writeFileSync(filename, JSON.stringify(content));
If you are finding the following screen and facing the problem of code signing required, then one of the following solutions may help you.
Solution 1. As said before, sign in with an Apple ID. Then you will get options like this, if you enter correct bundle identifier. Then select the appropriate profile from the list.
Solution 2. If you don't want to sign in with your Apple ID, then change a small flag in project.pbxproj file. Find the following text in the project file.
/* Begin PBXProject section */
Change flag ProvisioningStyle = Automatic;
to ProvisioningStyle = Manual;
Refer to the following image. After changing the flag, you will see the options to select appropriate profile from the list.
The easiest way in recent browsers would be to use the appropriate GlobalEventHandlers, onDOMContentLoaded, onload, onloadeddata (...)
onDOMContentLoaded = (function(){ console.log("DOM ready!") })()_x000D_
_x000D_
onload = (function(){ console.log("Page fully loaded!") })()_x000D_
_x000D_
onloadeddata = (function(){ console.log("Data loaded!") })()
_x000D_
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event load should be used only to detect a fully-loaded page. It is an incredibly popular mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.
https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded
The function used is an IIFE, very useful on this case, as it trigger itself when ready:
https://en.wikipedia.org/wiki/Immediately-invoked_function_expression
It is obviously more appropriate to place it at the end of any scripts.
In ES6, we can also write it as an arrow function:
onload = (() => { console.log("ES6 page fully loaded!") })()
_x000D_
The best is to use the DOM elements, we can wait for any variable to be ready, that trigger an arrowed IIFE.
The behavior will be the same, but with less memory impact.
footer = (() => { console.log("Footer loaded!") })()
_x000D_
<div id="footer">
_x000D_
In many cases, the document object is also triggering when ready, at least in my browser. The syntax is then very nice, but it need further testings about compatibilities.
document=(()=>{ /*Ready*/ })()
Install PIL(Python Image Library) :
then:
from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();
Read the documentation:
with open('names.txt', 'r') as f:
myNames = f.readlines()
The others already provided answers how to get rid of the newline character.
Update:
Fred Larson provides a nice solution in his comment:
with open('names.txt', 'r') as f:
myNames = [line.strip() for line in f]
Julian's solution is tested working with some minor corrections. The following is an example that also used https://sourceforge.net/projects/bat-to-exe/ GenericConsole.cs and https://www.codeproject.com/Articles/19225/Bat-file-compiler program.txt for args part:
using System;
using System.Text; //StringBuilder
using System.Diagnostics;
using System.IO;
class Program
{
private static bool redirectStandardOutput = true;
private static string buildargument(string[] args)
{
StringBuilder arg = new StringBuilder();
for (int i = 0; i < args.Length; i++)
{
arg.Append("\"" + args[i] + "\" ");
}
return arg.ToString();
}
static void Main(string[] args)
{
Process prc = new Process();
prc.StartInfo = //new ProcessStartInfo("cmd.exe", String.Format("/c \"\"{0}\" {1}", Path.Combine(Environment.CurrentDirectory, "mapTargetIDToTargetNameA3.bat"), buildargument(args)));
//new ProcessStartInfo(Path.Combine(Environment.CurrentDirectory, "mapTargetIDToTargetNameA3.bat"), buildargument(args));
new ProcessStartInfo("mapTargetIDToTargetNameA3.bat");
prc.StartInfo.Arguments = buildargument(args);
prc.EnableRaisingEvents = true;
if (redirectStandardOutput == true)
{
prc.StartInfo.UseShellExecute = false;
}
else
{
prc.StartInfo.UseShellExecute = true;
}
prc.StartInfo.CreateNoWindow = true;
prc.OutputDataReceived += OnOutputDataRecived;
prc.ErrorDataReceived += OnErrorDataReceived;
//prc.Exited += OnExited;
prc.StartInfo.RedirectStandardOutput = redirectStandardOutput;
prc.StartInfo.RedirectStandardError = redirectStandardOutput;
try
{
prc.Start();
prc.BeginOutputReadLine();
prc.BeginErrorReadLine();
prc.WaitForExit();
}
catch (Exception e)
{
Console.WriteLine("OS error: " + e.Message);
}
prc.Close();
}
// Handle the dataevent
private static void OnOutputDataRecived(object sender, DataReceivedEventArgs e)
{
//do something with your data
Console.WriteLine(e.Data);
}
//Handle the error
private static void OnErrorDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
// Handle Exited event and display process information.
//private static void OnExited(object sender, System.EventArgs e)
//{
// var process = sender as Process;
// if (process != null)
// {
// Console.WriteLine("ExitCode: " + process.ExitCode);
// }
// else
// {
// Console.WriteLine("Process exited");
// }
//}
}
The code need to compile inside VS2007, using commandline csc.exe generated executable will not show console output correctly, or even crash with CLR20r3 error. Comment out the OnExited event process, the console output of the bat to exe will be more like the original bat console output.
ORDER BY column OFFSET 0 ROWS
Surprisingly makes it work, what a strange feature.
A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:
;WITH cte AS (
SELECT .....long select statement here....
)
SELECT * FROM
(
SELECT * FROM
( -- necessary to nest selects for union to work with where & order clauses
SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS
) first
UNION ALL
SELECT * FROM
(
SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS
) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example
So we get all results ordered by MainCol
But the results with MainCol = 1
get ordered by ColX
And the results with MainCol = 0
get ordered by ColY
I know nothing about Jenkins, but it looks like you are trying to access environment variables using some form of unix syntax - that won't work.
If the name of the variable is WORKSPACE, then the value is expanded in Windows batch using
%WORKSPACE%
. That form of expansion is performed at parse time. For example, this will print to screen the value of WORKSPACE
echo %WORKSPACE%
If you need the value at execution time, then you need to use delayed expansion !WORKSPACE!
. Delayed expansion is not normally enabled by default. Use SETLOCAL EnableDelayedExpansion
to enable it. Delayed expansion is often needed because blocks of code within parentheses and/or multiple commands concatenated by &
, &&
, or ||
are parsed all at once, so a value assigned within the block cannot be read later within the same block unless you use delayed expansion.
setlocal enableDelayedExpansion
set WORKSPACE=BEFORE
(
set WORKSPACE=AFTER
echo Normal Expansion = %WORKSPACE%
echo Delayed Expansion = !WORKSPACE!
)
The output of the above is
Normal Expansion = BEFORE
Delayed Expansion = AFTER
Use HELP SET
or SET /?
from the command line to get more information about Windows environment variables and the various expansion options. For example, it explains how to do search/replace and substring operations.
To expand on Ryand's answer, if you're using Bootstrap.ui, this on your modal-instance will do the trick:
modalInstance.rendered.then(function (result) {
$('.modal .modal-body').css('overflow-y', 'auto');
$('.modal .modal-body').css('max-height', $(window).height() * 0.7);
$('.modal .modal-body').css('height', $(window).height() * 0.7);
});
Why is this blocked by Java?
You'd have to ask the Java designers. There might be some subtle grammatical reason for the restriction. Note that some of the array creation / initialization constructs were not in Java 1.0, and (IIRC) were added in Java 1.1.
But "why" is immaterial ... the restriction is there, and you have to live with it.
I know how to work around it, but from time to time it would be simpler.
You can write this:
AClass[] array;
...
array = new AClass[]{object1, object2};
I had this problem while generating 1000+ graphs through VBA
. I generated the graphs and assigned a range to their series. However, when the sheet recalculated the graphs wouldn't update as the data ranges changed values.
Solution --> I turned WrapText off before the For...Next Loop that generates the graphs and then turned it on again after the loop.
Workbooks(x).Worksheets(x).Cells.WrapText=False
and after...
Workbooks(x).Worksheets(x).Cells.WrapText=True
This a great solution because it updates 1000+ graphs at once without looping through them all and changing something individually.
Also, I'm not really sure why this works; I suppose when WrapText changes one property of the data range it makes the graph update, although I have no documentation on this.
DATABASE_URL=postgres://{user}:{password}@{hostname}:{port}/{database-name}
INSERT INTO #Temp1
SELECT val1, val2
FROM TABLE1
UNION
SELECT val1, val2
FROM TABLE2
depends on the isolation level of the incomming transaction.
Use the Nlog http://nlog-project.org/. It is free and allows to write to file, database, event log and other 20+ targets. The other logging framework is log4net - http://logging.apache.org/log4net/ (ported from java Log4j project). Its also free.
Best practices are to use common logging - http://commons.apache.org/logging/ So you can later change NLog or log4net to other logging framework.
Beside rowid, you can define your own auto increment field but it is not recommended. It is always be better solution when we use rowid that is automatically increased.
The
AUTOINCREMENT
keyword imposes extra CPU, memory, disk space, and disk I/O overhead and should be avoided if not strictly needed. It is usually not needed.
Read here for detailed information.
It turns out that if-else if generally faster than switch
The two classes are functionally equivalent, except that System.Timers.Timer
has an option to invoke all its timer expiration callbacks through ISynchronizeInvoke by setting SynchronizingObject. Otherwise, both timers invoke expiration callbacks on thread pool threads.
When you drag a System.Timers.Timer
onto a Windows Forms design surface, Visual Studio sets SynchronizingObject to the form object, which causes all expiration callbacks to be called on the UI thread.
There is no need for an UDF here. Column
already provides cast
method with DataType
instance :
from pyspark.sql.types import DoubleType
changedTypedf = joindf.withColumn("label", joindf["show"].cast(DoubleType()))
or short string:
changedTypedf = joindf.withColumn("label", joindf["show"].cast("double"))
where canonical string names (other variations can be supported as well) correspond to simpleString
value. So for atomic types:
from pyspark.sql import types
for t in ['BinaryType', 'BooleanType', 'ByteType', 'DateType',
'DecimalType', 'DoubleType', 'FloatType', 'IntegerType',
'LongType', 'ShortType', 'StringType', 'TimestampType']:
print(f"{t}: {getattr(types, t)().simpleString()}")
BinaryType: binary
BooleanType: boolean
ByteType: tinyint
DateType: date
DecimalType: decimal(10,0)
DoubleType: double
FloatType: float
IntegerType: int
LongType: bigint
ShortType: smallint
StringType: string
TimestampType: timestamp
and for example complex types
types.ArrayType(types.IntegerType()).simpleString()
'array<int>'
types.MapType(types.StringType(), types.IntegerType()).simpleString()
'map<string,int>'
I had problem with encoding cyrillic letters to URF-8.
I modified one of the above scripts to match cyrillic char map. Implmented is the cyrrilic section of
https://en.wikipedia.org/wiki/UTF-8 and http://www.utf8-chartable.de/unicode-utf8-table.pl?start=1024
Other sections development is sample and need verification with real data and calculate the char map offsets
Here is the script:
Public Function UTF8Encode( _
StringToEncode As String, _
Optional UsePlusRatherThanHexForSpace As Boolean = False _
) As String
Dim TempAns As String
Dim TempChr As Long
Dim CurChr As Long
Dim Offset As Long
Dim TempHex As String
Dim CharToEncode As Long
Dim TempAnsShort As String
CurChr = 1
Do Until CurChr - 1 = Len(StringToEncode)
CharToEncode = Asc(Mid(StringToEncode, CurChr, 1))
' http://www.utf8-chartable.de/unicode-utf8-table.pl?start=1024
' as per https://en.wikipedia.org/wiki/UTF-8 specification the engoding is as follows
Select Case CharToEncode
' 7 U+0000 U+007F 1 0xxxxxxx
Case 48 To 57, 65 To 90, 97 To 122
TempAns = TempAns & Mid(StringToEncode, CurChr, 1)
Case 32
If UsePlusRatherThanHexForSpace = True Then
TempAns = TempAns & "+"
Else
TempAns = TempAns & "%" & Hex(32)
End If
Case 0 To &H7F
TempAns = TempAns + "%" + Hex(CharToEncode And &H7F)
Case &H80 To &H7FF
' 11 U+0080 U+07FF 2 110xxxxx 10xxxxxx
' The magic is in offset calculation... there are different offsets between UTF-8 and Windows character maps
' offset 192 = &HC0 = 1100 0000 b added to start of UTF-8 cyrillic char map at &H410
CharToEncode = CharToEncode - 192 + &H410
TempAnsShort = "%" & Right("0" & Hex((CharToEncode And &H3F) Or &H80), 2)
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40) And &H1F) Or &HC0), 2) & TempAnsShort
TempAns = TempAns + TempAnsShort
'' debug and development version
'' CharToEncode = CharToEncode - 192 + &H410
'' TempChr = (CharToEncode And &H3F) Or &H80
'' TempHex = Hex(TempChr)
'' TempAnsShort = "%" & Right("0" & TempHex, 2)
'' TempChr = ((CharToEncode And &H7C0) / &H40) Or &HC0
'' TempChr = ((CharToEncode \ &H40) And &H1F) Or &HC0
'' TempHex = Hex(TempChr)
'' TempAnsShort = "%" & Right("0" & TempHex, 2) & TempAnsShort
'' TempAns = TempAns + TempAnsShort
Case &H800 To &HFFFF
' 16 U+0800 U+FFFF 3 1110xxxx 10xxxxxx 10xxxxxx
' not tested . Doesnot match Case condition... very strange
MsgBox ("Char to encode matched U+0800 U+FFFF: " & CharToEncode & " = &H" & Hex(CharToEncode))
'' CharToEncode = CharToEncode - 192 + &H410
TempAnsShort = "%" & Right("0" & Hex((CharToEncode And &H3F) Or &H80), 2)
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40) And &H3F) Or &H80), 2) & TempAnsShort
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000) And &HF) Or &HE0), 2) & TempAnsShort
TempAns = TempAns + TempAnsShort
Case &H10000 To &H1FFFFF
' 21 U+10000 U+1FFFFF 4 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
'' MsgBox ("Char to encode matched &H10000 &H1FFFFF: " & CharToEncode & " = &H" & Hex(CharToEncode))
' sample offset. tobe verified
CharToEncode = CharToEncode - 192 + &H410
TempAnsShort = "%" & Right("0" & Hex((CharToEncode And &H3F) Or &H80), 2)
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40) And &H3F) Or &H80), 2) & TempAnsShort
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000) And &H3F) Or &H80), 2) & TempAnsShort
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40000) And &H7) Or &HF0), 2) & TempAnsShort
TempAns = TempAns + TempAnsShort
Case &H200000 To &H3FFFFFF
' 26 U+200000 U+3FFFFFF 5 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
'' MsgBox ("Char to encode matched U+200000 U+3FFFFFF: " & CharToEncode & " = &H" & Hex(CharToEncode))
' sample offset. tobe verified
CharToEncode = CharToEncode - 192 + &H410
TempAnsShort = "%" & Right("0" & Hex((CharToEncode And &H3F) Or &H80), 2)
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40) And &H3F) Or &H80), 2) & TempAnsShort
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000) And &H3F) Or &H80), 2) & TempAnsShort
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40000) And &H3F) Or &H80), 2) & TempAnsShort
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000000) And &H3) Or &HF8), 2) & TempAnsShort
TempAns = TempAns + TempAnsShort
Case &H4000000 To &H7FFFFFFF
' 31 U+4000000 U+7FFFFFFF 6 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
'' MsgBox ("Char to encode matched U+4000000 U+7FFFFFFF: " & CharToEncode & " = &H" & Hex(CharToEncode))
' sample offset. tobe verified
CharToEncode = CharToEncode - 192 + &H410
TempAnsShort = "%" & Right("0" & Hex((CharToEncode And &H3F) Or &H80), 2)
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40) And &H3F) Or &H80), 2) & TempAnsShort
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000) And &H3F) Or &H80), 2) & TempAnsShort
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40000) And &H3F) Or &H80), 2) & TempAnsShort
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H1000000) And &H3F) Or &H80), 2) & TempAnsShort
TempAnsShort = "%" & Right("0" & Hex(((CharToEncode \ &H40000000) And &H1) Or &HFC), 2) & TempAnsShort
TempAns = TempAns + TempAnsShort
Case Else
' somethig else
' to be developped
MsgBox ("Char to encode not matched: " & CharToEncode & " = &H" & Hex(CharToEncode))
End Select
CurChr = CurChr + 1
Loop
UTF8Encode = TempAns
End Function
Good luck!
Working off the best answer and addressing my comment, here is a function for the conversion
def bunch_to_dataframe(bunch):
fnames = bunch.feature_names
features = fnames.tolist() if isinstance(fnames, np.ndarray) else fnames
features += ['target']
return pd.DataFrame(data= np.c_[bunch['data'], bunch['target']],
columns=features)
This answer contains 2 generators for random-based and name-based UUIDs, compliant with RFC-4122. Feel free to use and share.
RANDOM-BASED (v4)
This utility class that generates random-based UUIDs:
package your.package.name;
import java.security.SecureRandom;
import java.util.Random;
import java.util.UUID;
/**
* Utility class that creates random-based UUIDs.
*
*/
public abstract class RandomUuidCreator {
private static final int RANDOM_VERSION = 4;
/**
* Returns a random-based UUID.
*
* It uses a thread local {@link SecureRandom}.
*
* @return a random-based UUID
*/
public static UUID getRandomUuid() {
return getRandomUuid(SecureRandomLazyHolder.THREAD_LOCAL_RANDOM.get());
}
/**
* Returns a random-based UUID.
*
* It uses any instance of {@link Random}.
*
* @return a random-based UUID
*/
public static UUID getRandomUuid(Random random) {
long msb = 0;
long lsb = 0;
// (3) set all bit randomly
if (random instanceof SecureRandom) {
// Faster for instances of SecureRandom
final byte[] bytes = new byte[16];
random.nextBytes(bytes);
msb = toNumber(bytes, 0, 8); // first 8 bytes for MSB
lsb = toNumber(bytes, 8, 16); // last 8 bytes for LSB
} else {
msb = random.nextLong(); // first 8 bytes for MSB
lsb = random.nextLong(); // last 8 bytes for LSB
}
// Apply version and variant bits (required for RFC-4122 compliance)
msb = (msb & 0xffffffffffff0fffL) | (RANDOM_VERSION & 0x0f) << 12; // apply version bits
lsb = (lsb & 0x3fffffffffffffffL) | 0x8000000000000000L; // apply variant bits
// Return the UUID
return new UUID(msb, lsb);
}
private static long toNumber(final byte[] bytes, final int start, final int length) {
long result = 0;
for (int i = start; i < length; i++) {
result = (result << 8) | (bytes[i] & 0xff);
}
return result;
}
// Holds thread local secure random
private static class SecureRandomLazyHolder {
static final ThreadLocal<Random> THREAD_LOCAL_RANDOM = ThreadLocal.withInitial(SecureRandom::new);
}
/**
* For tests!
*/
public static void main(String[] args) {
System.out.println("// Using thread local `java.security.SecureRandom` (DEFAULT)");
System.out.println("RandomUuidCreator.getRandomUuid()");
System.out.println();
for (int i = 0; i < 5; i++) {
System.out.println(RandomUuidCreator.getRandomUuid());
}
System.out.println();
System.out.println("// Using `java.util.Random` (FASTER)");
System.out.println("RandomUuidCreator.getRandomUuid(new Random())");
System.out.println();
Random random = new Random();
for (int i = 0; i < 5; i++) {
System.out.println(RandomUuidCreator.getRandomUuid(random));
}
}
}
This is the output:
// Using thread local `java.security.SecureRandom` (DEFAULT)
RandomUuidCreator.getRandomUuid()
'ef4f5ad2-8147-46cb-8389-c2b8c3ef6b10'
'adc0305a-df29-4f08-9d73-800fde2048f0'
'4b794b59-bff8-4013-b656-5d34c33f4ce3'
'22517093-ee24-4120-96a5-ecee943992d1'
'899fb1fb-3e3d-4026-85a8-8a2d274a10cb'
// Using `java.util.Random` (FASTER)
RandomUuidCreator.getRandomUuid(new Random())
'4dabbbc2-fcb2-4074-a91c-5e2977a5bbf8'
'078ec231-88bc-4d74-9774-96c0b820ceda'
'726638fa-69a6-4a18-b09f-5fd2a708059b'
'15616ebe-1dfd-4f5c-b2ed-cea0ac1ad823'
'affa31ad-5e55-4cde-8232-cddd4931923a'
NAME-BASED (v3 and v5)
This utility class that generates name-based UUIDs (MD5 and SHA1):
package your.package.name;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
/**
* Utility class that creates UUIDv3 (MD5) and UUIDv5 (SHA1).
*
*/
public class HashUuidCreator {
// Domain Name System
public static final UUID NAMESPACE_DNS = new UUID(0x6ba7b8109dad11d1L, 0x80b400c04fd430c8L);
// Uniform Resource Locator
public static final UUID NAMESPACE_URL = new UUID(0x6ba7b8119dad11d1L, 0x80b400c04fd430c8L);
// ISO Object ID
public static final UUID NAMESPACE_ISO_OID = new UUID(0x6ba7b8129dad11d1L, 0x80b400c04fd430c8L);
// X.500 Distinguished Name
public static final UUID NAMESPACE_X500_DN = new UUID(0x6ba7b8149dad11d1L, 0x80b400c04fd430c8L);
private static final int VERSION_3 = 3; // UUIDv3 MD5
private static final int VERSION_5 = 5; // UUIDv5 SHA1
private static final String MESSAGE_DIGEST_MD5 = "MD5"; // UUIDv3
private static final String MESSAGE_DIGEST_SHA1 = "SHA-1"; // UUIDv5
private static UUID getHashUuid(UUID namespace, String name, String algorithm, int version) {
final byte[] hash;
final MessageDigest hasher;
try {
// Instantiate a message digest for the chosen algorithm
hasher = MessageDigest.getInstance(algorithm);
// Insert name space if NOT NULL
if (namespace != null) {
hasher.update(toBytes(namespace.getMostSignificantBits()));
hasher.update(toBytes(namespace.getLeastSignificantBits()));
}
// Generate the hash
hash = hasher.digest(name.getBytes(StandardCharsets.UTF_8));
// Split the hash into two parts: MSB and LSB
long msb = toNumber(hash, 0, 8); // first 8 bytes for MSB
long lsb = toNumber(hash, 8, 16); // last 8 bytes for LSB
// Apply version and variant bits (required for RFC-4122 compliance)
msb = (msb & 0xffffffffffff0fffL) | (version & 0x0f) << 12; // apply version bits
lsb = (lsb & 0x3fffffffffffffffL) | 0x8000000000000000L; // apply variant bits
// Return the UUID
return new UUID(msb, lsb);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Message digest algorithm not supported.");
}
}
public static UUID getMd5Uuid(String string) {
return getHashUuid(null, string, MESSAGE_DIGEST_MD5, VERSION_3);
}
public static UUID getSha1Uuid(String string) {
return getHashUuid(null, string, MESSAGE_DIGEST_SHA1, VERSION_5);
}
public static UUID getMd5Uuid(UUID namespace, String string) {
return getHashUuid(namespace, string, MESSAGE_DIGEST_MD5, VERSION_3);
}
public static UUID getSha1Uuid(UUID namespace, String string) {
return getHashUuid(namespace, string, MESSAGE_DIGEST_SHA1, VERSION_5);
}
private static byte[] toBytes(final long number) {
return new byte[] { (byte) (number >>> 56), (byte) (number >>> 48), (byte) (number >>> 40),
(byte) (number >>> 32), (byte) (number >>> 24), (byte) (number >>> 16), (byte) (number >>> 8),
(byte) (number) };
}
private static long toNumber(final byte[] bytes, final int start, final int length) {
long result = 0;
for (int i = start; i < length; i++) {
result = (result << 8) | (bytes[i] & 0xff);
}
return result;
}
/**
* For tests!
*/
public static void main(String[] args) {
String string = "JUST_A_TEST_STRING";
UUID namespace = UUID.randomUUID(); // A custom name space
System.out.println("Java's generator");
System.out.println("UUID.nameUUIDFromBytes(): '" + UUID.nameUUIDFromBytes(string.getBytes()) + "'");
System.out.println();
System.out.println("This generator");
System.out.println("HashUuidCreator.getMd5Uuid(): '" + HashUuidCreator.getMd5Uuid(string) + "'");
System.out.println("HashUuidCreator.getSha1Uuid(): '" + HashUuidCreator.getSha1Uuid(string) + "'");
System.out.println();
System.out.println("This generator WITH name space");
System.out.println("HashUuidCreator.getMd5Uuid(): '" + HashUuidCreator.getMd5Uuid(namespace, string) + "'");
System.out.println("HashUuidCreator.getSha1Uuid(): '" + HashUuidCreator.getSha1Uuid(namespace, string) + "'");
}
}
This is the output:
// Java's generator
UUID.nameUUIDFromBytes(): '9e120341-627f-32be-8393-58b5d655b751'
// This generator
HashUuidCreator.getMd5Uuid(): '9e120341-627f-32be-8393-58b5d655b751'
HashUuidCreator.getSha1Uuid(): 'e4586bed-032a-5ae6-9883-331cd94c4ffa'
// This generator WITH name space
HashUuidCreator.getMd5Uuid(): '2b098683-03c9-3ed8-9426-cf5c81ab1f9f'
HashUuidCreator.getSha1Uuid(): '1ef568c7-726b-58cc-a72a-7df173463bbb'
ALTERNATE GENERATOR
You can also use the uuid-creator
library. See these examples:
// Create a random-based UUID
UUID uuid = UuidCreator.getRandomBased();
// Create a name based UUID (SHA1)
String name = "JUST_A_TEST_STRING";
UUID uuid = UuidCreator.getNameBasedSha1(name);
Project page: https://github.com/f4b6a3/uuid-creator
Change data type of DataFrame column:
To int:
df.column_name = df.column_name.astype(np.int64)
To str:
df.column_name = df.column_name.astype(str)
If you want to uncheck the checkbox that you have selected first under the condition of 3 checkboxes allowed. With vanilla javascript; you need to assign onclick = "checking(this)" in your html input checkbox
var queue = [];
function checking(id){
queue.push(id)
if (queue.length===3){
queue[0].checked = false
queue.shift()
}
}
The blog article is mostly right, but not complete. To have a full understanding of what an odex file does, you have to understand a little about how application files (APK) work.
Applications are basically glorified ZIP archives. The java code is stored in a file called classes.dex and this file is parsed by the Dalvik JVM and a cache of the processed classes.dex file is stored in the phone's Dalvik cache.
An odex is basically a pre-processed version of an application's classes.dex that is execution-ready for Dalvik. When an application is odexed, the classes.dex is removed from the APK archive and it does not write anything to the Dalvik cache. An application that is not odexed ends up with 2 copies of the classes.dex file--the packaged one in the APK, and the processed one in the Dalvik cache. It also takes a little longer to launch the first time since Dalvik has to extract and process the classes.dex file.
If you are building a custom ROM, it's a really good idea to odex both your framework JAR files and the stock apps in order to maximize the internal storage space for user-installed apps. If you want to theme, then simply deodex -> apply your theme -> reodex -> release.
To actually deodex, use small and baksmali:
For Bootstrap 3, there is
placement: 'auto right'
which is easier. By default, it will be right, but if the element is located in the right side of the screen, the popover will be left. So it should be:
$('.infopoint').popover({
trigger:'hover',
animation: false,
placement: 'auto right'
});
From a face value they look same
In very simple terms, Factory Pattern, a Creational Pattern helps to create us an object - "Define an interface for creating an object". If we have a key value sort of object pool (e.g. Dictionary), passing the key to the Factory (I am referring to the Simple Factory Pattern) you can resolve the Type. Job done! Dependency Injection Framework (such as Structure Map, Ninject, Unity ...etc) on the other hand seems to be doing the same thing.
But... "Don't reinvent the wheel"
From a architectural perspective its a binding layer and "Don't reinvent the wheel".
For an enterprise grade application, concept of DI is more of a architectural layer which defines dependencies. To simplify this further you can think of this as a separate classlibrary project, which does dependency resolving. The main application depends on this project where Dependency resolver refers to other concrete implementations and to the dependency resolving.
Inaddition to "GetType/Create" from a Factory, most often than not we need more features (ability to use XML to define dependencies, mocking and unit testing etc.). Since you referred to Structure Map, look at the Structure Map feature list. It's clearly more than simply resolving simple object Mapping. Don't reinvent the wheel!
If all you have is a hammer, everything looks like a nail
Depending on your requirements and what type of application you build you need to make a choice. If it has just few projects (may be one or two..) and involves few dependencies, you can pick a simpler approach. It's like using ADO .Net data access over using Entity Framework for a simple 1 or 2 database calls, where introducing EF is an overkill in that scenario.
But for a larger project or if your project gets bigger, I would highly recommend to have a DI layer with a framework and make room to change the DI framework you use (Use a Facade in the Main App (Web App, Web Api, Desktop..etc.).
Import
import android.net.Uri;
Intent openURL = new Intent(android.content.Intent.ACTION_VIEW);
openURL.setData(Uri.parse("http://www.example.com"));
startActivity(openURL);
or it can be done using,
TextView textView = (TextView)findViewById(R.id.yourID);
textView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://www.typeyourURL.com"));
startActivity(intent);
} });
Here is one more alternative that uses XSL transformations for more complex email templates: Sending HTML-based email from .NET applications.
This is a better way to center UL's inside of any DIV container.
This CSS solution does not use Width and Float properties. Float:Left and Width: 70%, will cause you headaches when you need to duplicate your menu on different pages with different menu items.
Instead of using width, we use padding and margin to determine the space around the text/menu item. Also, instead of using Float:Left in the LI element, use display:inline-block.
By floating your LI left, you literally float your content to the left and then you must use one of the Hacks mentioned above to center your UL. Display:inline-block creates your Float property for you (sort of). It takes your LI element and turns it into a block element that lays side by side each other (not floating).
With Responsive design and using frameworks like Bootstrap or Foundation, there will be issues when trying to float and center content. They have some built-in classes, but it's always better to do it from scratch. This solution is much better for dynamic menus (Such as Adobe Business Catalyst menu system).
Reference for this tutorial can be found at: http://html-tuts.com/center-div-image-table-ul-inside-div/
HTML
<div class="container">
<ul>
<li><a href="#">Button</a></li>
<li><a href="#">Button</a></li>
<li><a href="#">Button</a></li>
<li><a href="#">Button</a></li>
<li><a href="#">Button</a></li>
</ul>
</div>
CSS
.container {
text-align: center;
border: 1px solid green;
}
.container ul {
border: 2px solid red;
display: inline-block;
margin: 10px 0;
padding: 2px;
}
.container li {
display: inline-block;
}
.container li a {
display: inline-block;
background: #444;
color: #FFF;
padding: 5px;
text-decoration: none;
}
SELECT *, (
6371 * acos(cos(radians(search_lat)) * cos(radians(lat) ) *
cos(radians(lng) - radians(search_lng)) + sin(radians(search_lat)) * sin(radians(lat)))
) AS distance
FROM table
WHERE lat != search_lat AND lng != search_lng AND distance < 25
ORDER BY distance
FETCH 10 ONLY
for distance of 25 km
I really haven't had good success with convert
[update May 2020: actually: it pretty much never works for me], but I've had EXCELLENT success with pdftoppm
. Here's a couple examples of producing high-quality images from a PDF:
[Produces ~25 MB-sized files per pg] Output uncompressed .tif file format at 300 DPI into a folder called "images", with files being named pg-1.tif, pg-2.tif, pg-3.tif, etc:
mkdir -p images && pdftoppm -tiff -r 300 mypdf.pdf images/pg
[Produces ~1MB-sized files per pg] Output in .jpg format at 300 DPI:
mkdir -p images && pdftoppm -jpeg -r 300 mypdf.pdf images/pg
[Produces ~2MB-sized files per pg] Output in .jpg format at highest quality (least compression) and still at 300 DPI:
mkdir -p images && pdftoppm -jpeg -jpegopt quality=100 -r 300 mypdf.pdf images/pg
https://askubuntu.com/questions/150100/extracting-embedded-images-from-a-pdf/1187844#1187844.
pdf2searchablepdf
] https://askubuntu.com/questions/473843/how-to-turn-a-pdf-into-a-text-searchable-pdf/1187881#1187881Other than ERRORLEVEL, batch files have no error handling. You'd want to look at a more powerful scripting language. I've been moving code to PowerShell.
The ability to easily use .Net assemblies and methods was one of the major reasons I started with PowerShell. The improved error handling was another. The fact that Microsoft is now requiring all of its server programs (Exchange, SQL Server etc) to be PowerShell drivable was pure icing on the cake.
Right now, it looks like any time invested in learning and using PowerShell will be time well spent.
I have facing this issue many time. Please add following code for resolve this issue :
@Override
public void onDestroyView() {
super.onDestroyView();
if (view != null) {
ViewGroup parentViewGroup = (ViewGroup) view.getParent();
if (parentViewGroup != null) {
parentViewGroup.removeAllViews();
}
}
}
Thanks
Since I have to store various types of content in my blob field/column, I am suppose to update my code like this:
echo "data: $mime" $result['$data']";
where:
mime
can be an image of any kind, text, word document, text document, PDF document, etc... content datatype is blob
in database.
Do not use WP_Query()
or get_posts()
. From the WooCommerce doc:
wc_get_products and WC_Product_Query provide a standard way of retrieving products that is safe to use and will not break due to database changes in future WooCommerce versions. Building custom WP_Queries or database queries is likely to break your code in future versions of WooCommerce as data moves towards custom tables for better performance.
You can retrieve the products you want like this:
$args = array(
'category' => array( 'hoodies' ),
'orderby' => 'name',
);
$products = wc_get_products( $args );
Note: the category argument takes an array of slugs, not IDs.
Lets say above one is your original dataframe and you want to add a new column 'old'
If age greater than 50 then we consider as older=yes otherwise False
step 1: Get the indexes of rows whose age greater than 50
row_indexes=df[df['age']>=50].index
step 2:
Using .loc we can assign a new value to column
df.loc[row_indexes,'elderly']="yes"
same for age below less than 50
row_indexes=df[df['age']<50].index
df[row_indexes,'elderly']="no"
The accepted answer only works with direct children of the scrollable element, while the other answers didn't centered the child in the scrollable element.
Example HTML:
<div class="scrollable-box">
<div class="row">
<div class="scrollable-item">
Child 1
</div>
<div class="scrollable-item">
Child 2
</div>
<div class="scrollable-item">
Child 3
</div>
<div class="scrollable-item">
Child 4
</div>
<div class="scrollable-item">
Child 5
</div>
<div class="scrollable-item">
Child 6
</div>
<div class="scrollable-item">
Child 7
</div>
<div class="scrollable-item">
Child 8
</div>
<div class="scrollable-item">
Child 9
</div>
<div class="scrollable-item">
Child 10
</div>
<div class="scrollable-item">
Child 11
</div>
<div class="scrollable-item">
Child 12
</div>
<div class="scrollable-item">
Child 13
</div>
<div class="scrollable-item">
Child 14
</div>
<div class="scrollable-item">
Child 15
</div>
<div class="scrollable-item">
Child 16
</div>
</div>
</div>
<style>
.scrollable-box {
width: 800px;
height: 150px;
overflow-x: hidden;
overflow-y: scroll;
border: 1px solid #444;
}
.scrollable-item {
font-size: 20px;
padding: 10px;
text-align: center;
}
</style>
Build a small jQuery plugin:
$.fn.scrollDivToElement = function(childSel) {
if (! this.length) return this;
return this.each(function() {
let parentEl = $(this);
let childEl = parentEl.find(childSel);
if (childEl.length > 0) {
parentEl.scrollTop(
parentEl.scrollTop() - parentEl.offset().top + childEl.offset().top - (parentEl.outerHeight() / 2) + (childEl.outerHeight() / 2)
);
}
});
};
Usage:
$('.scrollable-box').scrollDivToElement('.scrollable-item:eq(12)');
Explanation:
parentEl.scrollTop(...)
sets current vertical position of the scroll bar.
parentEl.scrollTop()
gets the current vertical position of the scroll bar.
parentEl.offset().top
gets the current coordinates of the parentEl relative to the document.
childEl.offset().top
gets the current coordinates of the childEl relative to the document.
parentEl.outerHeight() / 2
gets the outer height divided in half (because we want it centered) of the child element.
when used:
$(parent).scrollDivToElement(child);
The parent is the scrollable div and it can be a string or a jQuery object of the DOM element.
The child is any child that you want to scroll to and it can be a string or a jQuery object of the DOM element.
It is very simple.
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
/**
* Created by Belal on 9/14/2017.
*/
//we need to extend the ArrayAdapter class as we are building an adapter
public class MyListAdapter extends ArrayAdapter<Hero> {
//the list values in the List of type hero
List<Hero> heroList;
//activity context
Context context;
//the layout resource file for the list items
int resource;
//constructor initializing the values
public MyListAdapter(Context context, int resource, List<Hero> heroList) {
super(context, resource, heroList);
this.context = context;
this.resource = resource;
this.heroList = heroList;
}
//this will return the ListView Item as a View
@NonNull
@Override
public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
//we need to get the view of the xml for our list item
//And for this we need a layoutinflater
LayoutInflater layoutInflater = LayoutInflater.from(context);
//getting the view
View view = layoutInflater.inflate(resource, null, false);
//getting the view elements of the list from the view
ImageView imageView = view.findViewById(R.id.imageView);
TextView textViewName = view.findViewById(R.id.textViewName);
TextView textViewTeam = view.findViewById(R.id.textViewTeam);
Button buttonDelete = view.findViewById(R.id.buttonDelete);
//getting the hero of the specified position
Hero hero = heroList.get(position);
//adding values to the list item
imageView.setImageDrawable(context.getResources().getDrawable(hero.getImage()));
textViewName.setText(hero.getName());
textViewTeam.setText(hero.getTeam());
//adding a click listener to the button to remove item from the list
buttonDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//we will call this method to remove the selected value from the list
//we are passing the position which is to be removed in the method
removeHero(position);
}
});
//finally returning the view
return view;
}
//this method will remove the item from the list
private void removeHero(final int position) {
//Creating an alert dialog to confirm the deletion
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Are you sure you want to delete this?");
//if the response is positive in the alert
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//removing the item
heroList.remove(position);
//reloading the list
notifyDataSetChanged();
}
});
//if response is negative nothing is being done
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
//creating and displaying the alert dialog
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
Source: Custom ListView Android Tutorial
you can use - addAll method
http://download.oracle.com/javase/6/docs/api/java/util/HashMap.html
But there is always this issue that - if your two hash maps have any key same - then it will override the value of the key from first hash map with the value of the key from second hash map.
For being on safer side - change the key values - you can use prefix or suffix on the keys - ( different prefix/suffix for first hash map and different prefix/suffix for second hash map )
I just had this issue as well and my normal branches start with pb-3.1-12345/namebranch
but I accidental capitalized the first 2 letters PB-3.1/12345/namebranch
. After renaming the branch to use lower case letters I could create the branch.
DiffUtil can the best choice for updating the data in the RecyclerView Adapter which you can find in the android framework. DiffUtil is a utility class that can calculate the difference between two lists and output a list of update operations that converts the first list into the second one.
Most of the time our list changes completely and we set new list to RecyclerView Adapter. And we call notifyDataSetChanged to update adapter. NotifyDataSetChanged is costly. DiffUtil class solves that problem now. It does its job perfectly!
Use this to get the Project directory (worked for me):
string projectPath =
Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
SELECT name
FROM orders,company
WHERE orderID = 1
AND companyID IN (attachedCompanyIDs)
attachedCompanyIDs
is a scalar value which is cast into INT
(type of companyID
).
The cast only returns numbers up to the first non-digit (a comma in your case).
Thus,
companyID IN ('1,2,3') = companyID IN (CAST('1,2,3' AS INT)) = companyID IN (1)
In PostgreSQL
, you could cast the string into array (or store it as an array in the first place):
SELECT name
FROM orders
JOIN company
ON companyID = ANY (('{' | attachedCompanyIDs | '}')::INT[])
WHERE orderID = 1
and this would even use an index on companyID
.
Unfortunately, this does not work in MySQL
since the latter does not support arrays.
You may find this article interesting (see #2
):
Update:
If there is some reasonable limit on the number of values in the comma separated lists (say, no more than 5
), so you can try to use this query:
SELECT name
FROM orders
CROSS JOIN
(
SELECT 1 AS pos
UNION ALL
SELECT 2 AS pos
UNION ALL
SELECT 3 AS pos
UNION ALL
SELECT 4 AS pos
UNION ALL
SELECT 5 AS pos
) q
JOIN company
ON companyID = CAST(NULLIF(SUBSTRING_INDEX(attachedCompanyIDs, ',', -pos), SUBSTRING_INDEX(attachedCompanyIDs, ',', 1 - pos)) AS UNSIGNED)
If Subversion is already installed ,there's no need to reinstall it with the command line client tools.
Simply Goto
Start(Rightclick) ->App and Feature ->TortoiseSvn->Modify->Install command line client tools.
You can use like this too:
SELECT * FROM fiberbox WHERE fiber IN('140 ', '1938 ', '1940 ')
You need to print the result of the getText()
. You're currently printing the object TxtBoxContent
.
getText()
will only get the inner text of an element. To get the value, you need to use getAttribute()
.
WebElement TxtBoxContent = driver.findElement(By.id(WebelementID));
System.out.println("Printing " + TxtBoxContent.getAttribute("value"));
From the docs:
str.split([sep[, maxsplit]])
Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most
maxsplit+1
elements).
s.split('mango', 1)[1]
It seems to me, that for current javascript implementations,
var [result='default']=[possiblyUndefinedValue]
is a nice way to do this (using object deconstruction).
<html>
<body onload = "load()">
<script>
function load(){
try {
var ax = new ActiveXObject("WScript.Network");
alert('User: ' + ax.UserName );
alert('Computer: ' + ax.ComputerName);
}
catch (e) {
document.write('Permission to access computer name is denied' + '<br />');
}
}
</script>
</body>
</html>
@ChrisPratt's answer about the use of Display Template is wrong. The correct code to make it work is:
@model DateTime?
@if (Model.HasValue)
{
@Convert.ToDateTime(Model).ToString("MM/dd/yyyy")
}
That's because .ToString()
for Nullable<DateTime>
doesn't accept Format
parameter.
echo date('d-m-Y', strtotime('+7 days'));
Here are some functions I created for working with fullscreen in the browser.
They provide both enter/exit fullscreen across most major browsers.
function isFullScreen()
{
return (document.fullScreenElement && document.fullScreenElement !== null)
|| document.mozFullScreen
|| document.webkitIsFullScreen;
}
function requestFullScreen(element)
{
if (element.requestFullscreen)
element.requestFullscreen();
else if (element.msRequestFullscreen)
element.msRequestFullscreen();
else if (element.mozRequestFullScreen)
element.mozRequestFullScreen();
else if (element.webkitRequestFullscreen)
element.webkitRequestFullscreen();
}
function exitFullScreen()
{
if (document.exitFullscreen)
document.exitFullscreen();
else if (document.msExitFullscreen)
document.msExitFullscreen();
else if (document.mozCancelFullScreen)
document.mozCancelFullScreen();
else if (document.webkitExitFullscreen)
document.webkitExitFullscreen();
}
function toggleFullScreen(element)
{
if (isFullScreen())
exitFullScreen();
else
requestFullScreen(element || document.documentElement);
}
This will list only modified files:
svn status -u | grep M
I was facing the same problem. After a lot of alternatives what I did was just reset the embed src="" with the same URL.
Code snippet:
$("#videocontainer").fadeOut(200);<br/>
$("#videoplayer").attr("src",videoURL);
I was able to at least stop the video from playing when I hide it.:-)
String myFormat= "yyyy-MM-dd";
String finalString = "";
try {
DateFormat formatter = new SimpleDateFormat("yyyy MMM dd");
Date date = (Date) formatter .parse("2015 Oct 09");
SimpleDateFormat newFormat = new SimpleDateFormat(myFormat);
finalString= newFormat .format(date );
newDate.setText(finalString);
} catch (Exception e) {
}
The answer given here works for some MVC versions but not for others.
The simple solution worked for MVC1 but on upgrading to MVC2 the views were no longer being compliled. This was due to a bug in the website project files. See this Haacked article.
See this: http://haacked.com/archive/2011/05/09/compiling-mvc-views-in-a-build-environment.aspx
A workaround for CONTAINS
: If you don't want to create a full text Index on the column, and performance is not one of your priorities you could use the LIKE
statement which doesn't need any prior configuration:
Example: find all Products that contains the letter Q:
SELECT ID, ProductName
FROM [ProductsDB].[dbo].[Products]
WHERE [ProductsDB].[dbo].[Products].ProductName LIKE '%Q%'
this.setState({ abc.xyz: 'new value' });
syntax is not allowed.
You have to pass the whole object.
this.setState({abc: {xyz: 'new value'}});
If you have other variables in abc
var abc = this.state.abc;
abc.xyz = 'new value';
this.setState({abc: abc});
You can have ordinary variables, if they don't rely on this.props and this.state
.
Query for just a single known column:
session.query(MyTable.col1).count()
I know its been a long time but I share my solution anyway. This is a jQuery trick.
--- HTML
<div class="custom-column">
<div class="column-left">
asd
asd<br/>
asd<br/>
</div>
<div class="column-right">
asd
</div>
</div>
<div class="custom-column">
<div class="column-left">
asd
</div>
<div class="column-right">
asd
asd<br/>
asd<br/>
</div>
</div>
---- CSS
<style>
.custom-column { margin-bottom:10px; }
.custom-column:after { clear:both; content:""; display:block; width:100%; }
.column-left { float:left; width:25%; background:#CCC; }
.column-right { float:right; width:75%; background:#EEE; }
</style>
--- JQUERY
<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
$balancer = function() {
$('.custom-column').each(function(){
if($('.column-left',this).height()>$('.column-right',this).height()){
$('.column-right',this).height($('.column-left',this).height())
} else {
$('.column-left',this).height($('.column-right',this).height())
}
});
}
$balancer();
$(window).load($balancer());
$(window).resize($balancer());
});
</script>
When I see things like this - it is usually because there are backslashes in the path which get converted.
For example - the following will fail - because \t in the string is converted to TAB character.
>>> import ctypes
>>> ctypes.windll.LoadLibrary("c:\tools\depends\depends.dll")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\tools\python271\lib\ctypes\__init__.py", line 431, in LoadLibrary
return self._dlltype(name)
File "c:\tools\python271\lib\ctypes\__init__.py", line 353, in __init__
self._handle = _dlopen(self._name, mode)
WindowsError: [Error 126] The specified module could not be found
There are 3 solutions (if that is the problem)
a) Use double slashes...
>>> import ctypes
>>> ctypes.windll.LoadLibrary("c:\\tools\\depends\\depends.dll")
b) use forward slashes
>>> import ctypes
>>> ctypes.windll.LoadLibrary("c:/tools/depends/depends.dll")
c) use RAW strings (prefacing the string with r
>>> import ctypes
>>> ctypes.windll.LoadLibrary(r"c:\tools\depends\depends.dll")
While this third one works - I have gotten the impression from time to time that it is not considered 'correct' because RAW strings were meant for regular expressions. I have been using it for paths on Windows in Python for years without problem :) )
You're not looping over the items. Try this instead:
$.getJSON(url, function(data){
$.each(data.response.venue.tips.groups.items, function (index, value) {
console.log(this.text);
});
});
For me shutil.copy is the best:
import shutil
#make a copy of the invoice to work with
src="invoice.pdf"
dst="copied_invoice.pdf"
shutil.copy(src,dst)
You can change the path of the files as you want.
As an alternative you may want to check out BridgeIt at bridgeit.mobi. Open source, it has resolved the browser performance / consistency issue discussed above in that it leverages the standard browser on the device vs. the web-view browser. It also allows you to access the native features without having to worry about app store deployments and/or native containers.
I've used if for simple camera based access and scanner access and it works well for simple apps. Documentation is a bit light. Not sure how it would do on more complex apps.
After making no changes to a production server we began receiving this error. After trying several different things and thinking that perhaps there were DNS issues, restarting IIS fixed the issue (restarting only the site did not fix the issue). It likely won't work for everyone but if we tried that first it would have saved a lot of time.
Though an old question, I would like to add that currently mock
library (backport of unittest.mock) supports assert_not_called
method.
Just upgrade yours;
pip install mock --upgrade
git show <revhash>
Documentation here. Or if that doesn't work, try Google Code's GIT Documentation
PHP has a built in function called bool chmod(string $filename, int $mode )
private function writeFileContent($file, $content){
$fp = fopen($file, 'w');
fwrite($fp, $content);
fclose($fp);
chmod($file, 0777); //changed to add the zero
return true;
}
pd.set_option('display.max_columns', None)
id
(second argument) can fully show the columns.
You'll have to create a Console window manually before you actually call any Console.Write methods. That will init the Console to work properly without changing the project type (which for WPF application won't work).
Here's a complete source code example, of how a ConsoleManager class might look like, and how it can be used to enable/disable the Console, independently of the project type.
With the following class, you just need to write ConsoleManager.Show()
somewhere before any call to Console.Write
...
[SuppressUnmanagedCodeSecurity]
public static class ConsoleManager
{
private const string Kernel32_DllName = "kernel32.dll";
[DllImport(Kernel32_DllName)]
private static extern bool AllocConsole();
[DllImport(Kernel32_DllName)]
private static extern bool FreeConsole();
[DllImport(Kernel32_DllName)]
private static extern IntPtr GetConsoleWindow();
[DllImport(Kernel32_DllName)]
private static extern int GetConsoleOutputCP();
public static bool HasConsole
{
get { return GetConsoleWindow() != IntPtr.Zero; }
}
/// <summary>
/// Creates a new console instance if the process is not attached to a console already.
/// </summary>
public static void Show()
{
//#if DEBUG
if (!HasConsole)
{
AllocConsole();
InvalidateOutAndError();
}
//#endif
}
/// <summary>
/// If the process has a console attached to it, it will be detached and no longer visible. Writing to the System.Console is still possible, but no output will be shown.
/// </summary>
public static void Hide()
{
//#if DEBUG
if (HasConsole)
{
SetOutAndErrorNull();
FreeConsole();
}
//#endif
}
public static void Toggle()
{
if (HasConsole)
{
Hide();
}
else
{
Show();
}
}
static void InvalidateOutAndError()
{
Type type = typeof(System.Console);
System.Reflection.FieldInfo _out = type.GetField("_out",
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
System.Reflection.FieldInfo _error = type.GetField("_error",
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
System.Reflection.MethodInfo _InitializeStdOutError = type.GetMethod("InitializeStdOutError",
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
Debug.Assert(_out != null);
Debug.Assert(_error != null);
Debug.Assert(_InitializeStdOutError != null);
_out.SetValue(null, null);
_error.SetValue(null, null);
_InitializeStdOutError.Invoke(null, new object[] { true });
}
static void SetOutAndErrorNull()
{
Console.SetOut(TextWriter.Null);
Console.SetError(TextWriter.Null);
}
}
This is what I normally use, albeit a bit manual:
/* Add a 'temporary' UDDT with the new definition */
exec sp_addtype t_myudt_tmp, 'numeric(18,5)', NULL
/* Build a command to alter all the existing columns - cut and
** paste the output, then run it */
select 'alter table dbo.' + TABLE_NAME +
' alter column ' + COLUMN_NAME + ' t_myudt_tmp'
from INFORMATION_SCHEMA.COLUMNS
where DOMAIN_NAME = 't_myudt'
/* Remove the old UDDT */
exec sp_droptype t_mydut
/* Rename the 'temporary' UDDT to the correct name */
exec sp_rename 't_myudt_tmp', 't_myudt', 'USERDATATYPE'
Instead of src
you need ng-src
.
AngularJS views support binary operators
condition && true || false
So your img
tag would look like this
<img ng-src="{{interface == 'UP' && 'green-checkmark.png' || 'big-black-X.png'}}"/>
Note : the quotes (ie 'green-checkmark.png') are important here. It won't work without quotes.
plunker here (open dev tools to see the produced HTML)
This seems nice
https://bytes.com/topic/sql-server/answers/881862-joining-different-tables-based-condition
FROM YourMainTable
LEFT JOIN AirportCity DepCity ON @TravelType = 'A' and DepFrom = DepCity.Code
LEFT JOIN AirportCity DepCity ON @TravelType = 'B' and SomeOtherColumn = SomeOtherColumnFromSomeOtherTable
Assign the window.onerror
event to an event handler like:
<script type="text/javascript">
window.onerror = function(msg, url, line, col, error) {
// Note that col & error are new to the HTML 5 spec and may not be
// supported in every browser. It worked for me in Chrome.
var extra = !col ? '' : '\ncolumn: ' + col;
extra += !error ? '' : '\nerror: ' + error;
// You can view the information in an alert to see things working like this:
alert("Error: " + msg + "\nurl: " + url + "\nline: " + line + extra);
// TODO: Report this error via ajax so you can keep track
// of what pages have JS issues
var suppressErrorAlert = true;
// If you return true, then error alerts (like in older versions of
// Internet Explorer) will be suppressed.
return suppressErrorAlert;
};
</script>
As commented in the code, if the return value of window.onerror
is true
then the browser should suppress showing an alert dialog.
In a nutshell, the event is raised when either 1.) there is an uncaught exception or 2.) a compile time error occurs.
uncaught exceptions
- throw "some messages"
- call_something_undefined();
- cross_origin_iframe.contentWindow.document;, a security exception
compile error
<script>{</script>
<script>for(;)</script>
<script>"oops</script>
setTimeout("{", 10);
, it will attempt to compile the first argument as a script
Example of the onerror code above in action after adding this to a test page:
<script type="text/javascript">
call_something_undefined();
</script>
var error_data = {
url: document.location.href,
};
if(error != null) {
error_data['name'] = error.name; // e.g. ReferenceError
error_data['message'] = error.line;
error_data['stack'] = error.stack;
} else {
error_data['msg'] = msg;
error_data['filename'] = filename;
error_data['line'] = line;
error_data['col'] = col;
}
var xhr = new XMLHttpRequest();
xhr.open('POST', '/ajax/log_javascript_error');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
console.log('JS error logged');
} else if (xhr.status !== 200) {
console.error('Failed to log JS error.');
console.error(xhr);
console.error(xhr.status);
console.error(xhr.responseText);
}
};
xhr.send(JSON.stringify(error_data));
https://jsfiddle.net/nzfvm44d/
You could try running the "mvn site" command and see what transitive dependencies you have, and then resolve potential conflicts (by ommitting an implicit dependency somewhere). Just a guess (it's a bit difficult to know what the problem could be without seeing your pom info)...
Add an app to run automatically at startup in Windows 10
Step 1: Select the Windows Start button and scroll to find the app you want to run at startup.
Step 2: Right-click the app, select More, and then select Open file location. This opens the location where the shortcut to the app is saved. If there isn't an option for Open file location, it means the app can't run at startup.
Step 3: With the file location open, press the Windows logo key + R, type shell:startup, then select OK. This opens the Startup folder.
Step 4: Copy and paste the shortcut to the app from the file location to the Startup folder.
I actually had a simple way to check if the sheet exists and then execute some instruction:
In my case I wanted to delete the sheet and then recreated the same sheet with the same name but the code was interrupted if the program was not able to delete the sheet as it was already deleted
Sub Foo ()
Application.DisplayAlerts = False
On Error GoTo instructions
Sheets("NAME OF THE SHEET").Delete
instructions:
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = "NAME OF THE SHEET"
End Sub
Here is a successful example of an implementation of the same thing, on a device which supported lower screen brightness values (I tested on an Allwinner Chinese 7" tablet running API15).
WindowManager.LayoutParams params = this.getWindow().getAttributes();
/** Turn off: */
params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
//TODO Store original brightness value
params.screenBrightness = 0.1f;
this.getWindow().setAttributes(params);
/** Turn on: */
params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
//TODO restoring from original value
params.screenBrightness = 0.9f;
this.getWindow().setAttributes(params);
If someone else tries this out, pls comment below if it worked/didn't work and the device, Android API.
This solution is even simpler than the one provided by Leigh
. It is actually based on it.
Here you can notice that the middle element (in our case, with "content__middle"
class) does not have any dimensional property specified - no width, nor padding, nor margin related property at all - but only an overflow: auto;
(see note 1).
The great advantage is that now you can specify a max-width
and a min-width
to your left & right elements. Which is fantastic for fluid layouts.. hence responsive layout :-)
note 1: versus Leigh's answer where you need to add the margin-left
& margin-right
properties to the "content__middle"
class.
Here the left & right elements (with classes "content__left"
and "content__right"
) have a fixed width (in pixels): hence called non-fluid layout.
Live Demo on http://jsbin.com/qukocefudusu/1/edit?html,css,output
<style>
/*
* [1] & [3] "floats" makes the 2 divs align themselves respectively right & left
* [2] "overflow: auto;" makes this div take the remaining width
*/
.content {
width: 100%;
}
.content__left {
width: 100px;
float: left; /* [1] */
background-color: #fcc;
}
.content__middle {
background-color: #cfc;
overflow: auto; /* [2] */
}
.content__right {
width: 100px;
float: right; /* [3] */
background-color: #ccf;
}
</style>
<div class="content">
<div class="content__left">
left div<br/>left div<br/>left div<br/>left div<br/>left div<br/>left div<br/>
</div>
<div class="content__right">
right div<br/>right div<br/>right div<br/>right div<br/>
</div>
<div class="content__middle">
middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br />bit taller
</div>
</div>
Here the left & right elements (with classes "content__left"
and "content__right"
) have a variable width (in percentages) but also a minimum and maximum width: hence called fluid layout.
Live Demo in a fluid layout with the max-width
properties http://jsbin.com/runahoremuwu/1/edit?html,css,output
<style>
/*
* [1] & [3] "floats" makes the 2 divs align themselves respectively right & left
* [2] "overflow: auto;" makes this div take the remaining width
*/
.content {
width: 100%;
}
.content__left {
width: 20%;
max-width: 170px;
min-width: 40px;
float: left; /* [1] */
background-color: #fcc;
}
.content__middle {
background-color: #cfc;
overflow: auto; /* [2] */
}
.content__right {
width: 20%;
max-width: 250px;
min-width: 80px;
float: right; /* [3] */
background-color: #ccf;
}
</style>
<div class="content">
<div class="content__left">
max-width of 170px & min-width of 40px<br />left div<br/>left div<br/>left div<br/>left div<br/>left div<br/>left div<br/>
</div>
<div class="content__right">
max-width of 250px & min-width of 80px<br />right div<br/>right div<br/>right div<br/>right div<br/>
</div>
<div class="content__middle">
middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br/>middle div<br />bit taller
</div>
</div>
Tested on BrowserStack.com on the following web browsers:
@Eddie has given a perfect answer of the question asked. But I would like to draw attention to using an more efficient approach of Pub/Sub.
As this answer suggests,
The $broadcast/$on approach is not terribly efficient as it broadcasts to all the scopes(Either in one direction or both direction of Scope hierarchy). While the Pub/Sub approach is much more direct. Only subscribers get the events, so it isn't going to every scope in the system to make it work.
you can use angular-PubSub
angular module. once you add PubSub
module to your app dependency, you can use PubSub
service to subscribe and unsubscribe events/topics.
Easy to subscribe:
// Subscribe to event
var sub = PubSub.subscribe('event-name', function(topic, data){
});
Easy to publish
PubSub.publish('event-name', {
prop1: value1,
prop2: value2
});
To unsubscribe, use PubSub.unsubscribe(sub);
OR PubSub.unsubscribe('event-name');
.
NOTE Don't forget to unsubscribe to avoid memory leaks.
I had the same problem when i have trying to read xml that was extracted from archive to memory stream.
MemoryStream SubSetupStream = new MemoryStream();
using (ZipFile archive = ZipFile.Read(zipPath))
{
archive.Password = "SomePass";
foreach (ZipEntry file in archive)
{
file.Extract(SubSetupStream);
}
}
Problem was in these lines:
XmlDocument doc = new XmlDocument();
doc.Load(SubSetupStream);
And solution is (Thanks to @Phil):
if (SubSetupStream.Position>0)
{
SubSetupStream.Position = 0;
}
Since you are on Windows, instead of \n use \r\n (carriage return + line feed).
I was ultimately able to resolve the solution by setting the column type in the flat file connection to be of type "database date [DT_DBDATE]"
Apparently the differences between these date formats are as follow:
DT_DATE A date structure that consists of year, month, day, and hour.
DT_DBDATE A date structure that consists of year, month, and day.
DT_DBTIMESTAMP A timestamp structure that consists of year, month, hour, minute, second, and fraction
By changing the column type to DT_DBDATE the issue was resolved - I attached a Data Viewer and the CYCLE_DATE value was now simply "12/20/2010" without a time component, which apparently resolved the issue.
There is a dedicated npm
package for it. css-scrollbar-side
I guess you missed to put semi-colon ;
at the closing curly brace }
of window.fbAsyncInit = function() { ... };
I use this method:
{% if quote.myfile %}
<div class="">
<a role="button"
href="{{ quote.myfile.url }}"
download="{{ quote.myfile.url }}"
class="btn btn-light text-dark ml-0">
Download attachment
</a>
</div>
{% endif %}
If you are using PostgreSQL, then it looks in ~/.pgpass
for passwords automatically. See the manual for more information.
I finally found my maven repo mirror is down. I changed to another one, problem solved.
I am describing a simple method which worked very smoothly in Python (Django Framework).
1. While sending the request, send the request like this
http://server/action?id=a,b
2. Now in my backend, I split the value received with a split function which always creates a list.
id_filter = id.split(',')
Example: So if I send two values in the request,
http://server/action?id=a,b
then the filter on the data is
id_filter = ['a', 'b']
If I send only one value in the request,
http://server/action?id=a
then the filter outcome is
id_filter = ['a']
3. To actually filter the data, I simply use the 'in' function
queryset = queryset.filter(model_id__in=id_filter)
which roughly speaking performs the SQL equivalent of
WHERE model_id IN ('a', 'b')
with the first request and,
WHERE model_id IN ('a')
with the second request.
This would work with more than 2 parameter values in the request as well !
You can also get value by name instead of id like this:
var message = $('textarea:input[name=message]').val();
Here is a one line Pythonic version:
import os
dir = 'given_directory_name'
filenames = [os.path.join(os.path.dirname(os.path.abspath(__file__)),dir,i) for i in os.listdir(dir)]
This code lists the full path of all files and directories in the given directory name.
typedef enum{
first = 2,
second = 6,
third = 17
}MyEnum;
static const int enumItems[] = {
first,
second,
third
}
static const int EnumLength = sizeof(enumItems) / sizeof(int);
for(int i = 0; i < EnumLength; i++){
//Do something with enumItems[i]
}
To see a list of current buffers, I use:
:ls
To open a new file, I use
:e ../myFile.pl
with enhanced tab completion (put set wildmenu
in your .vimrc
).
Note: you can also use :find
which will search a set of paths for you, but you need to customize those paths first.
To switch between all open files, I use
:b myfile
with enhanced tab completion (still set wildmenu
).
Note: :b#
chooses the last visited file, so you can use it to switch quickly between two files.
Ctrl-W s
and Ctrl-W v
to split the current window horizontally and vertically. You can also use :split
and :vertical split
(:sp
and :vs
)
Ctrl-W w
to switch between open windows, and Ctrl-W h
(or j
or k
or l
) to navigate through open windows.
Ctrl-W c
to close the current window, and Ctrl-W o
to close all windows except the current one.
Starting vim with a -o
or -O
flag opens each file in its own split.
With all these I don't need tabs in Vim, and my fingers find my buffers, not my eyes.
Note: if you want all files to go to the same instance of Vim, start Vim with the --remote-silent
option.
I was behind firewall|proxy
.
In my case with Studio, ERROR: Gradle sync failed
& Cannot find symbol
.
I have used
repositories {
jcenter(); // Points to HTTPS://jcenter.bintray.com
}
Replace it with http and maven
repositories {
maven { url "http://jcenter.bintray.com" }
}
In the lastest version of code with express-generator (4.13.1) app.js is an exported module and the server is started in /bin/www using app.set('port', process.env.PORT || 3001) in app.js will be overridden by a similar statement in bin/www. I just changed the statement in bin/www.
To support the Accessibility feature in UIButton
extension UILabel
{
func scaledFont(for font: UIFont) -> UIFont {
if #available(iOS 11.0, *) {
return UIFontMetrics.default.scaledFont(for: font)
} else {
return font.withSize(scaler * font.pointSize)
}
}
func customFontScaleFactor(font : UIFont) {
translatesAutoresizingMaskIntoConstraints = false
self.adjustsFontForContentSizeCategory = true
self.font = FontMetrics.scaledFont(for: font)
}
}
You can can button font now.
UIButton().titleLabel?.customFontScaleFactor(font: UIFont.systemFont(ofSize: 12))
This didn't exist when the question was asked, but ES2015 introduced array destructuring, allowing you to write it as follows:
let a = 1, b = 2;
// a: 1, b: 2
[a, b] = [b, a];
// a: 2, b: 1
Rather than rolling your own, the most reliable way to tell if an in-built type is numeric is probably to reference Microsoft.VisualBasic
and call Information.IsNumeric(object value)
. The implementation handles a number of subtle cases such as char[]
and HEX and OCT strings.
You need multiple LIKE clauses connected by OR.
SELECT * FROM table WHERE
column LIKE 'Text%' OR
column LIKE 'Link%' OR
column LIKE 'Hello%' OR
column LIKE '%World%' OR
You can use following addon to handle all subquery related function from laravel 5.5+
https://github.com/maksimru/eloquent-subquery-magic
User::selectRaw('user_id,comments_by_user.total_count')->leftJoinSubquery(
//subquery
Comment::selectRaw('user_id,count(*) total_count')
->groupBy('user_id'),
//alias
'comments_by_user',
//closure for "on" statement
function ($join) {
$join->on('users.id', '=', 'comments_by_user.user_id');
}
)->get();
The accepted answer didn't work for me as my page jumped slightly on click, messing up my scroll animation.
I decided to update the entire URL using window.history.replaceState
rather than using the window.location.hash
method. Thus circumventing the hashChange event fired by the browser.
// Only fire when URL has anchor
$('a[href*="#"]:not([href="#"])').on('click', function(event) {
// Prevent default anchor handling (which causes the page-jumping)
event.preventDefault();
if ( location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname ) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if ( target.length ) {
// Smooth scrolling to anchor
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
// Update URL
window.history.replaceState("", document.title, window.location.href.replace(location.hash, "") + this.hash);
}
}
});
Yes, use g++ to compile. It will automatically add all the references to libstdc++ which are necessary to link the program.
g++ source.cpp -o source
If you omit the -o
parameter, the resultant executable will be named a.out
. In any case, executable permissions have already been set, so no need to chmod
anything.
Also, the code will give you undefined behaviour (and probably a SIGSEGV) as you are dereferencing a NULL pointer and trying to call a member function on an object that doesn't exist, so it most certainly will not print anything. It will probably crash or do some funky dance.
It is the same as AppCompat versions of support but it has less mess of v4 and v7 versions so it is much help from Using the different components of android XML elements.
pip install --download
is deprecated. Starting from version 8.0.0 you should use pip download
command:
pip download <package-name>
DirBuster is such a hacking script that guesses a bunch of common names as nsanders had mentioned. It literally brute forces lists of common words and file endings (.html, .php) and over time figures out the directory structure of such sites, this could discover the page as you described but would also discover many others.
Generally there are several ways to serialize datetimes, like:
If you're okay with the last way, the json_tricks package handles dates, times and datetimes including timezones.
from datetime import datetime
from json_tricks import dumps
foo = {'title': 'String', 'datetime': datetime(2012, 8, 8, 21, 46, 24, 862000)}
dumps(foo)
which gives:
{"title": "String", "datetime": {"__datetime__": null, "year": 2012, "month": 8, "day": 8, "hour": 21, "minute": 46, "second": 24, "microsecond": 862000}}
So all you need to do is
`pip install json_tricks`
and then import from json_tricks
instead of json
.
The advantage of not storing it as a single string, int or float comes when decoding: if you encounter just a string or especially int or float, you need to know something about the data to know if it's a datetime. As a dict, you can store metadata so it can be decoded automatically, which is what json_tricks
does for you. It's also easily editable for humans.
Disclaimer: it's made by me. Because I had the same problem.
In JDK 8 source can be found in /src.zip. Now in some intermediate releases this zip was missing but again it is available.
make sure that you select source as well from installation wizard.
fname = 'filenotfound.txt'
try:
f = open(fname, 'rb')
except FileNotFoundError:
print("file {} does not exist".format(fname))
file filenotfound.txt does not exist
exception FileNotFoundError Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT.
https://docs.python.org/3/library/exceptions.html
This exception does not exist in Python 2.
Are they the home directories of users in /etc/passwd
? Services like postgres, sendmail, apache, etc., create system users that have home directories just like normal users.
I hope this can help someone who was faced with my same problem.
This answer uses the Bootstrap DatePicker Plugin, which is not native to bootstrap.
Make sure you install Bootstrap DatePicker through NuGet
Create a small piece of JavaScript and name it DatePickerReady.js save it in Scripts dir. This will make sure it works even in non HTML5 browsers although those are few nowadays.
if (!Modernizr.inputtypes.date) {
$(function () {
$(".datecontrol").datepicker();
});
}
Set the bundles
bundles.Add(New ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/bootstrap-datepicker.js",
"~/Scripts/DatePickerReady.js",
"~/Scripts/respond.js"))
bundles.Add(New StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/bootstrap-datepicker3.css",
"~/Content/site.css"))
Now set the Datatype so that when EditorFor is used MVC will identify what is to be used.
<Required>
<DataType(DataType.Date)>
Public Property DOB As DateTime? = Nothing
Your view code should be
@Html.EditorFor(Function(model) model.DOB, New With {.htmlAttributes = New With {.class = "form-control datecontrol", .PlaceHolder = "Enter Date of Birth"}})
and voila
Install Oracle's MySql.Data
NuGet package.
using MySql.Data;
using MySql.Data.MySqlClient;
namespace Data
{
public class DBConnection
{
private DBConnection()
{
}
public string Server { get; set; }
public string DatabaseName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
private MySqlConnection Connection { get; set;}
private static DBConnection _instance = null;
public static DBConnection Instance()
{
if (_instance == null)
_instance = new DBConnection();
return _instance;
}
public bool IsConnect()
{
if (Connection == null)
{
if (String.IsNullOrEmpty(databaseName))
return false;
string connstring = string.Format("Server={0}; database={1}; UID={2}; password={3}", Server, DatabaseName, UserName, Password);
Connection = new MySqlConnection(connstring);
Connection.Open();
}
return true;
}
public void Close()
{
Connection.Close();
}
}
}
Example:
var dbCon = DBConnection.Instance();
dbCon.Server = "YourServer";
dbCon.DatabaseName = "YourDatabase";
dbCon.UserName = "YourUsername";
dbCon.Password = "YourPassword";
if (dbCon.IsConnect())
{
//suppose col0 and col1 are defined as VARCHAR in the DB
string query = "SELECT col0,col1 FROM YourTable";
var cmd = new MySqlCommand(query, dbCon.Connection);
var reader = cmd.ExecuteReader();
while(reader.Read())
{
string someStringFromColumnZero = reader.GetString(0);
string someStringFromColumnOne = reader.GetString(1);
Console.WriteLine(someStringFromColumnZero + "," + someStringFromColumnOne);
}
dbCon.Close();
}
You should make x
and y
numpy arrays, not lists:
x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,
0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78])
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,
0.478,0.335,0.365,0.424,0.390,0.585,0.511])
With this change, it produces the expect plot. If they are lists, m * x
will not produce the result you expect, but an empty list. Note that m
is anumpy.float64
scalar, not a standard Python float
.
I actually consider this a bit dubious behavior of Numpy. In normal Python, multiplying a list with an integer just repeats the list:
In [42]: 2 * [1, 2, 3]
Out[42]: [1, 2, 3, 1, 2, 3]
while multiplying a list with a float gives an error (as I think it should):
In [43]: 1.5 * [1, 2, 3]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-43-d710bb467cdd> in <module>()
----> 1 1.5 * [1, 2, 3]
TypeError: can't multiply sequence by non-int of type 'float'
The weird thing is that multiplying a Python list with a Numpy scalar apparently works:
In [45]: np.float64(0.5) * [1, 2, 3]
Out[45]: []
In [46]: np.float64(1.5) * [1, 2, 3]
Out[46]: [1, 2, 3]
In [47]: np.float64(2.5) * [1, 2, 3]
Out[47]: [1, 2, 3, 1, 2, 3]
So it seems that the float gets truncated to an int, after which you get the standard Python behavior of repeating the list, which is quite unexpected behavior. The best thing would have been to raise an error (so that you would have spotted the problem yourself instead of having to ask your question on Stackoverflow) or to just show the expected element-wise multiplication (in which your code would have just worked). Interestingly, addition between a list and a Numpy scalar does work:
In [69]: np.float64(0.123) + [1, 2, 3]
Out[69]: array([ 1.123, 2.123, 3.123])
5. Something else - there must be other solutions out there?
You're right, there is! And it is called JWT (JSON Web Tokens).
JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA.
I highly recommend looking into JWTs. They're a much simpler solution to the problem when compared against alternative solutions.
My bad, in trying to simplify it, I went too far, actually stuffs
is a record of all kinds of info, I just want the id in it.
stuffs = [[123, first, last], [456, first, last]]
I want my_sting
to be
my_sting = '123, 456'
My original code should have looked like this:
{% set my_string = '' %}
{% for stuff in stuffs %}
{% set my_string = my_string + stuff.id + ', '%}
{% endfor%}
Thinking about it, stuffs
is probably a dictionary, but you get the gist.
Yes I found the join
filter, and was going to approach it like this:
{% set my_string = [] %}
{% for stuff in stuffs %}
{% do my_string.append(stuff.id) %}
{% endfor%}
{% my_string|join(', ') %}
But the append doesn't work without importing the extensions to do it, and reading that documentation gave me a headache. It doesn't explicitly say where to import it from or even where you would put the import statement, so I figured finding a way to concat would be the lesser of the two evils.
Here is another way to find out apps package name and launcher activity.
Step1: Start "adb logcat" in command prompt.
Step2: Open the app (either in emulator or real device)
Use a join with a temporary table. You don't need to pass temporary tables to functions, they are global.
create temporary table ids( id int ) ;
insert into ids values (1),(2),(3) ;
delimiter //
drop procedure if exists tsel //
create procedure tsel() -- uses temporary table named ids. no params
READS SQL DATA
BEGIN
-- use the temporary table `ids` in the SELECT statement or
-- whatever query you have
select * from Users INNER JOIN ids on userId=ids.id ;
END //
DELIMITER ;
CALL tsel() ; -- call the procedure
I had the same issue. In my case I found two issues causing the problem
Sometimes that problem occurs if you already have a branch with the base name.
I tried this:
git checkout -b features/aName origin/features/aName
Unfortunately, I already had a branch named features
, and I got the exception of the question asker.
Removing the branch features
resolved the problem, the above command worked.
Try this I think this is better.
var images = [];
function preload() {
for (var i = 0; i < arguments.length; i++) {
images[i] = new Image();
images[i].src = preload.arguments[i];
}
}
//-- usage --//
preload(
"http://domain.tld/gallery/image-001.jpg",
"http://domain.tld/gallery/image-002.jpg",
"http://domain.tld/gallery/image-003.jpg"
)
Source: http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/
^\d\d?[,.]\d\d?$
The ^ and $ means begin and end of input string (without this part 23.45 of string like 123.45 will be matched). The \d means digit, the \d? means optional digit, the [,.] means dot or comma. Working example (when you click on left menu> tools> code generator you can gen code for one of 9 popular languages like c#, js, php, java, ...) here.
// TEST
[
// valid
'11,11',
'11.11',
'1.1',
'1,1',
// nonvalid
'111,1',
'11.111',
'11-11',
',11',
'11.',
'a.11',
'11,a',
].forEach(n=> {
let result = /^\d\d?[,.]\d\d?$/.test(n);
console.log(`${n}`.padStart(6,' '), 'is valid:', result);
})
_x000D_
Work with jquery on load (cross browser):
<iframe src="your_url" marginwidth="0" marginheight="0" scrolling="No" frameborder="0" hspace="0" vspace="0" id="containiframe" onload="loaderIframe();" height="100%" width="100%"></iframe>
function loaderIframe(){
var heightIframe = $('#containiframe').contents().find('body').height();
$('#frame').css("height", heightFrame);
}
on resize in responsive page:
$(window).resize(function(){
if($('#containiframe').length !== 0) {
var heightIframe = $('#containiframe').contents().find('body').height();
$('#frame').css("height", heightFrame);
}
});
For a more detailed answer on creating your own colormaps, I highly suggest visiting this page
If that answer is too much work, you can quickly make your own list of colors and pass them to the color
parameter. All the colormaps are in the cm
matplotlib module. Let's get a list of 30 RGB (plus alpha) color values from the reversed inferno colormap. To do so, first get the colormap and then pass it a sequence of values between 0 and 1. Here, we use np.linspace
to create 30 equally-spaced values between .4 and .8 that represent that portion of the colormap.
from matplotlib import cm
color = cm.inferno_r(np.linspace(.4, .8, 30))
color
array([[ 0.865006, 0.316822, 0.226055, 1. ],
[ 0.851384, 0.30226 , 0.239636, 1. ],
[ 0.832299, 0.283913, 0.257383, 1. ],
[ 0.817341, 0.270954, 0.27039 , 1. ],
[ 0.796607, 0.254728, 0.287264, 1. ],
[ 0.775059, 0.239667, 0.303526, 1. ],
[ 0.758422, 0.229097, 0.315266, 1. ],
[ 0.735683, 0.215906, 0.330245, 1. ],
.....
Then we can use this to plot, using the data from the original post:
import random
x = [{i: random.randint(1, 5)} for i in range(30)]
df = pd.DataFrame(x)
df.plot(kind='bar', stacked=True, color=color, legend=False, figsize=(12, 4))
Adding for completeness of the answers: preloading with HTML
<link rel="preload" href="bg-image-wide.png" as="image">
Other preloading features exist, but none are quite as fit for purpose as <link rel="preload">
:
<link rel="prefetch">
has been supported in browsers for a long time,
but it is intended for prefetching resources that will be used in the
next navigation/page load (e.g. when you go to the next page). This
is fine, but isn't useful for the current page! In addition, browsers
will give prefetch resources a lower priority than preload ones — the
current page is more important than the next. See Link prefetching
FAQ for more details. <link rel="prerender">
renders a specified
webpage in the background, speeding up its load if the user navigates
to it. Because of the potential to waste users bandwidth, Chrome
treats prerender as a NoState prefetch instead. <link rel="subresource">
was supported in Chrome a while ago, and was
intended to tackle the same issue as preload, but it had a problem:
there was no way to work out a priority for the items (as didn't
exist back then), so they all got fetched with fairly low priority.There are a number of script-based resource loaders out there, but they don't have any power over the browser's fetch prioritization queue, and are subject to much the same performance problems.
Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content
exit function
. In the C Programming Language, the exit function calls all functions registered with at exit and terminates the program.
exit(1)
means program(process) terminate unsuccessfully.
File buffers are flushed, streams are closed, and temporary files are deleted
exit(0)
means Program(Process) terminate successfully.
One more reason, maybe your url include some hiden characters, such as '\n'.
If you define your url like below, this exception will raise:
url = '''
http://google.com
'''
because there are '\n' hide in the string. The url in fact become:
\nhttp://google.com\n
I have made a workaround to solve this problem. Visit the below link for more details http://code-outofbox.blogspot.com/2015/07/java-prepared-statement-print-values.html
Solution:
// Initialize connection
PreparedStatement prepStmt = connection.prepareStatement(sql);
PreparedStatementHelper prepHelper = new PreparedStatementHelper(prepStmt);
// User prepHelper.setXXX(indx++, value);
// .....
try {
Pattern pattern = Pattern.compile("\\?");
Matcher matcher = pattern.matcher(sql);
StringBuffer sb = new StringBuffer();
int indx = 1; // Parameter begin with index 1
while (matcher.find()) {
matcher.appendReplacement(sb, prepHelper.getParameter(indx++));
}
matcher.appendTail(sb);
LOGGER.debug("Executing Query [" + sb.toString() + "] with Database[" + /*db name*/ + "] ...");
} catch (Exception ex) {
LOGGER.debug("Executing Query [" + sql + "] with Database[" + /*db name*/+ "] ...");
}
/****************************************************/
package java.sql;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.Date;
import java.sql.NClob;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
public class PreparedStatementHelper implements PreparedStatement {
private PreparedStatement prepStmt;
private String[] values;
public PreparedStatementHelper(PreparedStatement prepStmt) throws SQLException {
this.prepStmt = prepStmt;
this.values = new String[this.prepStmt.getParameterMetaData().getParameterCount()];
}
public String getParameter(int index) {
String value = this.values[index-1];
return String.valueOf(value);
}
private void setParameter(int index, Object value) {
String valueStr = "";
if (value instanceof String) {
valueStr = "'" + String.valueOf(value).replaceAll("'", "''") + "'";
} else if (value instanceof Integer) {
valueStr = String.valueOf(value);
} else if (value instanceof Date || value instanceof Time || value instanceof Timestamp) {
valueStr = "'" + String.valueOf(value) + "'";
} else {
valueStr = String.valueOf(value);
}
this.values[index-1] = valueStr;
}
@Override
public ResultSet executeQuery(String sql) throws SQLException {
return this.prepStmt.executeQuery(sql);
}
@Override
public int executeUpdate(String sql) throws SQLException {
return this.prepStmt.executeUpdate(sql);
}
@Override
public void close() throws SQLException {
this.prepStmt.close();
}
@Override
public int getMaxFieldSize() throws SQLException {
return this.prepStmt.getMaxFieldSize();
}
@Override
public void setMaxFieldSize(int max) throws SQLException {
this.prepStmt.setMaxFieldSize(max);
}
@Override
public int getMaxRows() throws SQLException {
return this.prepStmt.getMaxRows();
}
@Override
public void setMaxRows(int max) throws SQLException {
this.prepStmt.setMaxRows(max);
}
@Override
public void setEscapeProcessing(boolean enable) throws SQLException {
this.prepStmt.setEscapeProcessing(enable);
}
@Override
public int getQueryTimeout() throws SQLException {
return this.prepStmt.getQueryTimeout();
}
@Override
public void setQueryTimeout(int seconds) throws SQLException {
this.prepStmt.setQueryTimeout(seconds);
}
@Override
public void cancel() throws SQLException {
this.prepStmt.cancel();
}
@Override
public SQLWarning getWarnings() throws SQLException {
return this.prepStmt.getWarnings();
}
@Override
public void clearWarnings() throws SQLException {
this.prepStmt.clearWarnings();
}
@Override
public void setCursorName(String name) throws SQLException {
this.prepStmt.setCursorName(name);
}
@Override
public boolean execute(String sql) throws SQLException {
return this.prepStmt.execute(sql);
}
@Override
public ResultSet getResultSet() throws SQLException {
return this.prepStmt.getResultSet();
}
@Override
public int getUpdateCount() throws SQLException {
return this.prepStmt.getUpdateCount();
}
@Override
public boolean getMoreResults() throws SQLException {
return this.prepStmt.getMoreResults();
}
@Override
public void setFetchDirection(int direction) throws SQLException {
this.prepStmt.setFetchDirection(direction);
}
@Override
public int getFetchDirection() throws SQLException {
return this.prepStmt.getFetchDirection();
}
@Override
public void setFetchSize(int rows) throws SQLException {
this.prepStmt.setFetchSize(rows);
}
@Override
public int getFetchSize() throws SQLException {
return this.prepStmt.getFetchSize();
}
@Override
public int getResultSetConcurrency() throws SQLException {
return this.prepStmt.getResultSetConcurrency();
}
@Override
public int getResultSetType() throws SQLException {
return this.prepStmt.getResultSetType();
}
@Override
public void addBatch(String sql) throws SQLException {
this.prepStmt.addBatch(sql);
}
@Override
public void clearBatch() throws SQLException {
this.prepStmt.clearBatch();
}
@Override
public int[] executeBatch() throws SQLException {
return this.prepStmt.executeBatch();
}
@Override
public Connection getConnection() throws SQLException {
return this.prepStmt.getConnection();
}
@Override
public boolean getMoreResults(int current) throws SQLException {
return this.prepStmt.getMoreResults(current);
}
@Override
public ResultSet getGeneratedKeys() throws SQLException {
return this.prepStmt.getGeneratedKeys();
}
@Override
public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
return this.prepStmt.executeUpdate(sql, autoGeneratedKeys);
}
@Override
public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
return this.prepStmt.executeUpdate(sql, columnIndexes);
}
@Override
public int executeUpdate(String sql, String[] columnNames) throws SQLException {
return this.prepStmt.executeUpdate(sql, columnNames);
}
@Override
public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
return this.prepStmt.execute(sql, autoGeneratedKeys);
}
@Override
public boolean execute(String sql, int[] columnIndexes) throws SQLException {
return this.prepStmt.execute(sql, columnIndexes);
}
@Override
public boolean execute(String sql, String[] columnNames) throws SQLException {
return this.prepStmt.execute(sql, columnNames);
}
@Override
public int getResultSetHoldability() throws SQLException {
return this.prepStmt.getResultSetHoldability();
}
@Override
public boolean isClosed() throws SQLException {
return this.prepStmt.isClosed();
}
@Override
public void setPoolable(boolean poolable) throws SQLException {
this.prepStmt.setPoolable(poolable);
}
@Override
public boolean isPoolable() throws SQLException {
return this.prepStmt.isPoolable();
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return this.prepStmt.unwrap(iface);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return this.prepStmt.isWrapperFor(iface);
}
@Override
public ResultSet executeQuery() throws SQLException {
return this.prepStmt.executeQuery();
}
@Override
public int executeUpdate() throws SQLException {
return this.prepStmt.executeUpdate();
}
@Override
public void setNull(int parameterIndex, int sqlType) throws SQLException {
this.prepStmt.setNull(parameterIndex, sqlType);
setParameter(parameterIndex, null);
}
@Override
public void setBoolean(int parameterIndex, boolean x) throws SQLException {
this.prepStmt.setBoolean(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setByte(int parameterIndex, byte x) throws SQLException {
this.prepStmt.setByte(parameterIndex, x);
// TODO Add to tree set
}
@Override
public void setShort(int parameterIndex, short x) throws SQLException {
this.prepStmt.setShort(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setInt(int parameterIndex, int x) throws SQLException {
this.prepStmt.setInt(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setLong(int parameterIndex, long x) throws SQLException {
this.prepStmt.setLong(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setFloat(int parameterIndex, float x) throws SQLException {
this.prepStmt.setFloat(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setDouble(int parameterIndex, double x) throws SQLException {
this.prepStmt.setDouble(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException {
this.prepStmt.setBigDecimal(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setString(int parameterIndex, String x) throws SQLException {
this.prepStmt.setString(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setBytes(int parameterIndex, byte[] x) throws SQLException {
this.prepStmt.setBytes(parameterIndex, x);
// TODO Add to tree set
}
@Override
public void setDate(int parameterIndex, Date x) throws SQLException {
this.prepStmt.setDate(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setTime(int parameterIndex, Time x) throws SQLException {
this.prepStmt.setTime(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException {
this.prepStmt.setTimestamp(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException {
this.prepStmt.setAsciiStream(parameterIndex, x, length);
}
@SuppressWarnings("deprecation")
@Override
public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException {
this.prepStmt.setUnicodeStream(parameterIndex, x, length);
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException {
this.prepStmt.setBinaryStream(parameterIndex, x, length);
}
@Override
public void clearParameters() throws SQLException {
this.prepStmt.clearParameters();
}
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException {
this.prepStmt.setObject(parameterIndex, x, targetSqlType);
setParameter(parameterIndex, x);
}
@Override
public void setObject(int parameterIndex, Object x) throws SQLException {
this.prepStmt.setObject(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public boolean execute() throws SQLException {
return this.prepStmt.execute();
}
@Override
public void addBatch() throws SQLException {
this.prepStmt.addBatch();
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException {
this.prepStmt.setCharacterStream(parameterIndex, reader, length);
}
@Override
public void setRef(int parameterIndex, Ref x) throws SQLException {
this.prepStmt.setRef(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setBlob(int parameterIndex, Blob x) throws SQLException {
this.prepStmt.setBlob(parameterIndex, x);
}
@Override
public void setClob(int parameterIndex, Clob x) throws SQLException {
this.prepStmt.setClob(parameterIndex, x);
}
@Override
public void setArray(int parameterIndex, Array x) throws SQLException {
this.prepStmt.setArray(parameterIndex, x);
// TODO Add to tree set
}
@Override
public ResultSetMetaData getMetaData() throws SQLException {
return this.prepStmt.getMetaData();
}
@Override
public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException {
this.prepStmt.setDate(parameterIndex, x, cal);
setParameter(parameterIndex, x);
}
@Override
public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException {
this.prepStmt.setTime(parameterIndex, x, cal);
setParameter(parameterIndex, x);
}
@Override
public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException {
this.prepStmt.setTimestamp(parameterIndex, x, cal);
setParameter(parameterIndex, x);
}
@Override
public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException {
this.prepStmt.setNull(parameterIndex, sqlType, typeName);
setParameter(parameterIndex, null);
}
@Override
public void setURL(int parameterIndex, URL x) throws SQLException {
this.prepStmt.setURL(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public ParameterMetaData getParameterMetaData() throws SQLException {
return this.prepStmt.getParameterMetaData();
}
@Override
public void setRowId(int parameterIndex, RowId x) throws SQLException {
this.prepStmt.setRowId(parameterIndex, x);
setParameter(parameterIndex, x);
}
@Override
public void setNString(int parameterIndex, String value) throws SQLException {
this.prepStmt.setNString(parameterIndex, value);
setParameter(parameterIndex, value);
}
@Override
public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException {
this.prepStmt.setNCharacterStream(parameterIndex, value, length);
}
@Override
public void setNClob(int parameterIndex, NClob value) throws SQLException {
this.prepStmt.setNClob(parameterIndex, value);
}
@Override
public void setClob(int parameterIndex, Reader reader, long length) throws SQLException {
this.prepStmt.setClob(parameterIndex, reader, length);
}
@Override
public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException {
this.prepStmt.setBlob(parameterIndex, inputStream, length);
}
@Override
public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException {
this.prepStmt.setNClob(parameterIndex, reader, length);
}
@Override
public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException {
this.prepStmt.setSQLXML(parameterIndex, xmlObject);
setParameter(parameterIndex, xmlObject);
}
@Override
public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException {
this.prepStmt.setObject(parameterIndex, x, targetSqlType, scaleOrLength);
setParameter(parameterIndex, x);
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException {
this.prepStmt.setAsciiStream(parameterIndex, x, length);
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException {
this.prepStmt.setBinaryStream(parameterIndex, x, length);
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException {
this.prepStmt.setCharacterStream(parameterIndex, reader, length);
}
@Override
public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException {
this.prepStmt.setAsciiStream(parameterIndex, x);
// TODO Add to tree set
}
@Override
public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException {
this.prepStmt.setBinaryStream(parameterIndex, x);
}
@Override
public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException {
this.prepStmt.setCharacterStream(parameterIndex, reader);
}
@Override
public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException {
this.prepStmt.setNCharacterStream(parameterIndex, value);
}
@Override
public void setClob(int parameterIndex, Reader reader) throws SQLException {
this.prepStmt.setClob(parameterIndex, reader);
// TODO Add to tree set
}
@Override
public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException {
this.prepStmt.setBlob(parameterIndex, inputStream);
}
@Override
public void setNClob(int parameterIndex, Reader reader) throws SQLException {
this.prepStmt.setNClob(parameterIndex, reader);
}
}
After reading this and troubleshooting the same issues, I agree that it is related to headings (h1 for sure, havent played with any others), also browser styles adding margins and paddings with clever rules that are hard to find and over-ride.
I have adapted a technique used to apply the box-sizing property properly to margins and paddings. the original article for box-sizing is located at CSS-Tricks :
html {
margin: 0;
padding: 0;
}
*, *:before, *:after {
margin: inherit;
padding: inherit;
}
So far it is exactly the trick for not using complex resets and makes applying a design much easier for myself anyways. Hope it helps.
This is fixed in version 1.6 of the plugin.
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>1.6</version>
Quick note though, I noticed that the first iteration output was being deleted. I fixed it by adding the following to each of the executions.
<removeOldOutput>false</removeOldOutput>
<clearOutputDir>false</clearOutputDir>
Here is my full working example with each iteration outputting correctly. BTW I had to do this due to a duplicate namespace problem with the xsd's I was given. This seems to resolve my problem.
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>1.6</version>
<executions>
<execution>
<id>submitOrderRequest</id>
<goals>
<goal>xjc</goal>
</goals>
<configuration>
<extension>true</extension>
<schemaDirectory>src/main/resources/xsd/</schemaDirectory>
<!-- <schemaFiles>getOrderStatusResponse.xsd,quoteShippingRequest.xsd,quoteShippingResponse.xsd,submitOrderRequest.xsd,submitOrderResponse.xsd</schemaFiles> -->
<schemaFiles>submitOrderRequest.xsd</schemaFiles>
<bindingDirectory>${project.basedir}/src/main/resources/xjb</bindingDirectory>
<bindingFiles>submitOrderRequest.xjb</bindingFiles>
<removeOldOutput>false</removeOldOutput>
<clearOutputDir>false</clearOutputDir>
</configuration>
</execution>
<execution>
<id>submitOrderResponse</id>
<goals>
<goal>xjc</goal>
</goals>
<configuration>
<extension>true</extension>
<schemaDirectory>src/main/resources/xsd/</schemaDirectory>
<!-- <schemaFiles>getOrderStatusResponse.xsd,quoteShippingRequest.xsd,quoteShippingResponse.xsd,submitOrderRequest.xsd,submitOrderResponse.xsd</schemaFiles> -->
<schemaFiles>submitOrderResponse.xsd</schemaFiles>
<bindingDirectory>${project.basedir}/src/main/resources/xjb</bindingDirectory>
<bindingFiles>submitOrderResponse.xjb</bindingFiles>
<removeOldOutput>false</removeOldOutput>
<clearOutputDir>false</clearOutputDir>
</configuration>
</execution>
</executions>
</plugin>
If you are floating the elements you can reverse the order
i.e. float: right;
instead of float: left;
And then use this method to select the first-child of a class.
/* 1: Apply style to ALL instances */
#header .some-class {
padding-right: 0;
}
/* 2: Remove style from ALL instances except FIRST instance */
#header .some-class~.some-class {
padding-right: 20px;
}
This is actually applying the class to the LAST instance only because it's now in reversed order.
Here is a working example for you:
<!doctype html>
<head><title>CSS Test</title>
<style type="text/css">
.some-class { margin: 0; padding: 0 20px; list-style-type: square; }
.lfloat { float: left; display: block; }
.rfloat { float: right; display: block; }
/* apply style to last instance only */
#header .some-class {
border: 1px solid red;
padding-right: 0;
}
#header .some-class~.some-class {
border: 0;
padding-right: 20px;
}
</style>
</head>
<body>
<div id="header">
<img src="some_image" title="Logo" class="lfloat no-border"/>
<ul class="some-class rfloat">
<li>List 1-1</li>
<li>List 1-2</li>
<li>List 1-3</li>
</ul>
<ul class="some-class rfloat">
<li>List 2-1</li>
<li>List 2-2</li>
<li>List 2-3</li>
</ul>
<ul class="some-class rfloat">
<li>List 3-1</li>
<li>List 3-2</li>
<li>List 3-3</li>
</ul>
<img src="some_other_img" title="Icon" class="rfloat no-border"/>
</div>
</body>
</html>
Try this:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val().toString().replace(/([0-9]+)\/([0-9]+)/,'$2/$1'));
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
The RegExp replace .replace(/([0-9]+)\/([0-9]+)/,'$2/$1')
change day/month position.
You can have an iframe inside the modal markup and give the src attribute of it as the link to your pdf. On click of the link you can show this modal markup.
You'll want to use JavaScript's built-in window.location
object.
I just wanted to add one more solution for those having issues installing setuptools from Windows 64-bit. The issue is discussed in this bug on python.org and is still unresolved as of the date of this comment. A simple workaround is mentioned and it works flawlessly. One registry change did the trick for me.
Link: http://bugs.python.org/issue6792#
Solution that worked for me...:
Add this registry setting for 2.6+ versions of Python:
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.6\InstallPath]
@="C:\\Python26\\"
This is most likely the registry setting you will already have for Python 2.6+:
[HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.6\InstallPath]
@="C:\\Python26\\"
Clearly, you will need to replace the 2.6 version with whatever version of Python you are running.
For those like me, only needing information on how to connect to a (DB2) WAS Data Source from Java using JNDI lookup (Used IBM Websphere 8.5.5 & DB2 Universal JDBC Driver Provider with implementation class: com.ibm.db2.jcc.DB2ConnectionPoolDataSource):
public DataSource getJndiDataSource() throws NamingException {
DataSource datasource = null;
InitialContext context = new InitialContext();
// Tomcat/Possibly others: java:comp/env/jdbc/myDatasourceJndiName
datasource = (DataSource) context.lookup("jdbc/myDatasourceJndiName");
return datasource;
}
Apart from all the answers given, I would like to add few points :-
1) __repr__()
is invoked when you simply write object's name on interactive python console and press enter.
2) __str__()
is invoked when you use object with print statement.
3) In case, if __str__
is missing, then print and any function using str()
invokes __repr__()
of object.
4) __str__()
of containers, when invoked will execute __repr__()
method of its contained elements.
5) str()
called within __str__()
could potentially recurse without a base case, and error on maximum recursion depth.
6) __repr__()
can call repr()
which will attempt to avoid infinite recursion automatically, replacing an already represented object with ...
.
you could connect all the data you need from the file to a single string, and in the excel sheet seperate it with text to column. here is an example i did for same issue, enjoy:
Sub CP()
Dim ToolFile As String
Cells(3, 2).Select
For i = 0 To 5
r = ActiveCell.Row
ToolFile = Cells(r, 7).Value
On Error Resume Next
ActiveCell.Value = CP_getdatta(ToolFile)
'seperate data by "-"
Selection.TextToColumns Destination:=Range("C3"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
:="-", FieldInfo:=Array(Array(1, 1), Array(2, 1)), TrailingMinusNumbers:=True
Cells(r + 1, 2).Select
Next
End Sub
Function CP_getdatta(ToolFile As String) As String
Workbooks.Open Filename:=ToolFile, UpdateLinks:=False, ReadOnly:=True
Range("A56000").Select
Selection.End(xlUp).Select
x = CStr(ActiveCell.Value)
ActiveCell.Offset(0, 20).Select
Selection.End(xlToLeft).Select
While IsNumeric(ActiveCell.Value) = False
ActiveCell.Offset(0, -1).Select
Wend
' combine data to 1 string
CP_getdatta = CStr(x & "-" & ActiveCell.Value)
ActiveWindow.Close False
End Function
It was just designed that way. Increment and decrement operators are just shortcuts for x = x + 1
. Python has typically adopted a design strategy which reduces the number of alternative means of performing an operation. Augmented assignment is the closest thing to increment/decrement operators in Python, and they weren't even added until Python 2.0.
Not on the freehackers list is gui2exe which can be used to build standalone Windows executables, Linux applications and Mac OS application bundles and plugins starting from Python scripts.
From my limited experience, I would say that the following two scenario could cause response status code: 0
, keep in mind; their could be more, but I know of those two:
the thing is, status: 0
is slightly generic, and their could be more use cases that trigger an empty response body.
You can assign int
to char
directly.
int a = 65;
char c = a;
printf("%c", c);
In fact this will also work.
printf("%c", a); // assuming a is in valid range
As a Mac user, I was unable to use the MS-DOS and Windows command line tools that were mentioned to fix the font embedding permission. However, I found out that you can fix this using FontLab to set the permission to 'Everything is allowed'. I hope this recipe on how to set the font permission to Installable on Mac OS X is useful for others as well.
In order to move a View anywhere on the screen, I would recommend placing it in a full screen layout. By doing so, you won't have to worry about clippings or relative coordinates.
You can try this sample code:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:id="@+id/rootLayout">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MOVE" android:layout_centerHorizontal="true"/>
<ImageView
android:id="@+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="10dip"/>
<ImageView
android:id="@+id/img2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_centerVertical="true" android:layout_alignParentRight="true"/>
<ImageView
android:id="@+id/img3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_alignParentBottom="true" android:layout_marginBottom="100dip"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:clipChildren="false" android:clipToPadding="false">
<ImageView
android:id="@+id/img4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_marginTop="150dip"/>
</LinearLayout>
</RelativeLayout>
Your activity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button) findViewById( R.id.btn1 )).setOnClickListener( new OnClickListener()
{
@Override
public void onClick(View v)
{
ImageView img = (ImageView) findViewById( R.id.img1 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img2 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img3 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img4 );
moveViewToScreenCenter( img );
}
});
}
private void moveViewToScreenCenter( View view )
{
RelativeLayout root = (RelativeLayout) findViewById( R.id.rootLayout );
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics( dm );
int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();
int originalPos[] = new int[2];
view.getLocationOnScreen( originalPos );
int xDest = dm.widthPixels/2;
xDest -= (view.getMeasuredWidth()/2);
int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;
TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
anim.setDuration(1000);
anim.setFillAfter( true );
view.startAnimation(anim);
}
The method moveViewToScreenCenter
gets the View's absolute coordinates and calculates how much distance has to move from its current position to reach the center of the screen. The statusBarOffset
variable measures the status bar height.
I hope you can keep going with this example. Remember that after the animation your view's position is still the initial one. If you tap the MOVE button again and again the same movement will repeat. If you want to change your view's position do it after the animation is finished.
Guava has a method Ints.asList()
for creating a List<Integer>
backed by an int[]
array. You can use this with Collections.sort to apply the Comparator to the underlying array.
List<Integer> integersList = Ints.asList(arr);
Collections.sort(integersList, Collections.reverseOrder());
Note that the latter is a live list backed by the actual array, so it should be pretty efficient.
In direct opposition to my other answer, this following function is probably safe, even with multi-byte characters.
// replace any non-ascii character with its hex code.
function escape($value) {
$return = '';
for($i = 0; $i < strlen($value); ++$i) {
$char = $value[$i];
$ord = ord($char);
if($char !== "'" && $char !== "\"" && $char !== '\\' && $ord >= 32 && $ord <= 126)
$return .= $char;
else
$return .= '\\x' . dechex($ord);
}
return $return;
}
I'm hoping someone more knowledgeable than myself can tell me why the code above won't work ...
You didn't specified what JAXB-IMPL version are you using, but once I had the same problem (with jaxb-impl 2.0.5) and solved it using the annotation at the getter level instead of using it at the member level.
In this case it would probably be better to just have an empty database that you use as a template and when you need to refresh, drop the existing database and create a new one from the template.
CodeIgniter way:
$this->load->helper('text');
$string = convert_accented_characters($string);
This function uses a companion config file application/config/foreign_chars.php
to define the to and from array for transliteration.
https://www.codeigniter.com/user_guide/helpers/text_helper.html#ascii_to_entities
I suppose this thread has a very good description of the problem with table refresh.
The following worked for me:
from pandas import read_excel
my_sheet = 'Sheet1' # change it to your sheet name, you can find your sheet name at the bottom left of your excel file
file_name = 'products_and_categories.xlsx' # change it to the name of your excel file
df = read_excel(file_name, sheet_name = my_sheet)
print(df.head()) # shows headers with top 5 rows
As suggested earlier too, you can look at launch4j to create the executable for your JAR file. Also, there is something called "JExePack" that can put an .exe wrapper around your jar file so that you can redistribute it (note: the client would anyways need a JRE to run the program on his pc) Exes created with GCJ will not have this dependency but the process is a little more involved.
Also, if you set your build target device, the problem will go away when you testing and debugging. The code signed is only need when you trying to deploy your app to an actually physical device
I changed mine from "myIphone" to simulator iPhone 6 Plus, and it solves the problem while I'm developing the app.
Summary
As mentioned by Ignacio, it updates your .config
for you after you update the kernel source, e.g. with git pull
.
It tries to keep your existing options.
Having a script for that is helpful because:
new options may have been added, or old ones removed
the kernel's Kconfig configuration format has options that:
select
depends
Those option relationships make manual config resolution even harder.
Let's modify .config manually to understand how it resolves configurations
First generate a default configuration with:
make defconfig
Now edit the generated .config
file manually to emulate a kernel update and run:
make oldconfig
to see what happens. Some conclusions:
Lines of type:
# CONFIG_XXX is not set
are not mere comments, but actually indicate that the parameter is not set.
For example, if we remove the line:
# CONFIG_DEBUG_INFO is not set
and run make oldconfig
, it will ask us:
Compile the kernel with debug info (DEBUG_INFO) [N/y/?] (NEW)
When it is over, the .config
file will be updated.
If you change any character of the line, e.g. to # CONFIG_DEBUG_INFO
, it does not count.
Lines of type:
# CONFIG_XXX is not set
are always used for the negation of a property, although:
CONFIG_XXX=n
is also understood as the negation.
For example, if you remove # CONFIG_DEBUG_INFO is not set
and answer:
Compile the kernel with debug info (DEBUG_INFO) [N/y/?] (NEW)
with N
, then the output file contains:
# CONFIG_DEBUG_INFO is not set
and not:
CONFIG_DEBUG_INFO=n
Also, if we manually modify the line to:
CONFIG_DEBUG_INFO=n
and run make oldconfig
, then the line gets modified to:
# CONFIG_DEBUG_INFO is not set
without oldconfig
asking us.
Configs whose dependencies are not met, do not appear on the .config
. All others do.
For example, set:
CONFIG_DEBUG_INFO=y
and run make oldconfig
. It will now ask us for: DEBUG_INFO_REDUCED
, DEBUG_INFO_SPLIT
, etc. configs.
Those properties did not appear on the defconfig
before.
If we look under lib/Kconfig.debug
where they are defined, we see that they depend on DEBUG_INFO
:
config DEBUG_INFO_REDUCED
bool "Reduce debugging information"
depends on DEBUG_INFO
So when DEBUG_INFO
was off, they did not show up at all.
Configs which are selected
by turned on configs are automatically set without asking the user.
For example, if CONFIG_X86=y
and we remove the line:
CONFIG_ARCH_MIGHT_HAVE_PC_PARPORT=y
and run make oldconfig
, the line gets recreated without asking us, unlike DEBUG_INFO
.
This happens because arch/x86/Kconfig
contains:
config X86
def_bool y
[...]
select ARCH_MIGHT_HAVE_PC_PARPORT
and select forces that option to be true. See also: https://unix.stackexchange.com/questions/117521/select-vs-depends-in-kernel-kconfig
Configs whose constraints are not met are asked for.
For example, defconfig
had set:
CONFIG_64BIT=y
CONFIG_RCU_FANOUT=64
If we edit:
CONFIG_64BIT=n
and run make oldconfig
, it will ask us:
Tree-based hierarchical RCU fanout value (RCU_FANOUT) [32] (NEW)
This is because RCU_FANOUT
is defined at init/Kconfig
as:
config RCU_FANOUT
int "Tree-based hierarchical RCU fanout value"
range 2 64 if 64BIT
range 2 32 if !64BIT
Therefore, without 64BIT
, the maximum value is 32
, but we had 64
set on the .config
, which would make it inconsistent.
Bonuses
make olddefconfig
sets every option to their default value without asking interactively. It gets run automatically on make
to ensure that the .config
is consistent in case you've modified it manually like we did. See also: https://serverfault.com/questions/116299/automatically-answer-defaults-when-doing-make-oldconfig-on-a-kernel-tree
make alldefconfig
is like make olddefconfig
, but it also accepts a config fragment to merge. This target is used by the merge_config.sh
script: https://stackoverflow.com/a/39440863/895245
And if you want to automate the .config
modification, that is not too simple: How do you non-interactively turn on features in a Linux kernel .config file?
Consider following code
<ul id="myTask">
<li>Coding</li>
<li>Answering</li>
<li>Getting Paid</li>
</ul>
Now, here goes the difference
// Remove the myTask item when clicked.
$('#myTask').children().click(function () {
$(this).remove()
});
Now, what if we add a myTask again?
$('#myTask').append('<li>Answer this question on SO</li>');
Clicking this myTask item will not remove it from the list, since it doesn't have any event handlers bound. If instead we'd used .on
, the new item would work without any extra effort on our part. Here's how the .on version would look:
$('#myTask').on('click', 'li', function (event) {
$(event.target).remove()
});
Summary:
The difference between .on()
and .click()
would be that .click()
may not work when the DOM elements associated with the .click()
event are added dynamically at a later point while .on()
can be used in situations where the DOM elements associated with the .on()
call may be generated dynamically at a later point.
just want to add another variant to update this wonderful "how to" list. Though, It may be really useful in more complicated cases:
try {
if (something)
{
//some code
if (something2)
{
throw new Exception("Weird-01.");
// now You will go to the catch statement
}
if (something3)
{
throw new Exception("Weird-02.");
// now You will go to the catch statement
}
//some code
return;
}
}
catch (Exception ex)
{
Console.WriteLine(ex); // you will get your Weird-01 or Weird-02 here
}
// The code i want to go if the second or third if is true
Depending on the script and its usage the best possible (in terms of page load and rendering time) may be to not use a conventional <script>-tag per se, but to dynamically trigger the loading of the script asynchronously.
There are some different techniques, but the most straight forward is to use document.createElement("script") when the window.onload event is triggered. Then the script is loaded first when the page itself has rendered, thus not impacting the time the user has to wait for the page to appear.
This naturally requires that the script itself is not needed for the rendering of the page.
For more information, see the post Coupling async scripts by Steve Souders (creator of YSlow but now at Google).
I've had the exact same experience as Eric at my last position. Now in my new job, I'm going through the same process I performed at my last job... rebuilding all their AMIs for EBS backed instances - and possibly as 32bit machines (cheaper - but can't use same AMI on 32 and 64 machines).
EBS backed instances launch quickly enough that you can begin to make use of the Amazon AutoScaling API which lets you use CloudWatch metrics to trigger the launch of additional instances and register them to the ELB (Elastic Load Balancer), and also to shut them down when no longer required.
This kind of dynamic autoscaling is what AWS is all about - where the real savings in IT infrastructure can come into play. It's pretty much impossible to do autoscaling right with the old s3 "InstanceStore"-backed instances.
You need to add a name
attribute to your dropdown list, then you need to add a required
attribute, and then you can reference the error using myForm.[input name].$error.required
:
HTML:
<form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
<input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
<select name="service_id" class="Sitedropdown" style="width: 220px;"
ng-model="ServiceID"
ng-options="service.ServiceID as service.ServiceName for service in services"
required>
<option value="">Select Service</option>
</select>
<span ng-show="myForm.service_id.$error.required">Select service</span>
</form>
Controller:
function Ctrl($scope) {
$scope.services = [
{ServiceID: 1, ServiceName: 'Service1'},
{ServiceID: 2, ServiceName: 'Service2'},
{ServiceID: 3, ServiceName: 'Service3'}
];
$scope.save = function(myForm) {
console.log('Selected Value: '+ myForm.service_id.$modelValue);
alert('Data Saved! without validate');
};
}
Here's a working plunker.
here is a simple one
here is my test.php for testing only
<?php
// this is just a test
//send back to the ajax request the request
echo json_encode($_POST);
here is my index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// click on button submit
$("#submit").on('click', function(){
// send ajax
$.ajax({
url: 'test.php', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#form").serialize(), // post data || get data
success : function(result) {
// you can see the result from the console
// tab of the developer tools
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
</script>
</body>
</html>
Both file are place in the same directory
Although, I had all proper babel loaders in my .babelrc config file. This build script with parcel-bundler was producing the unexpected token error < and mime type errors in the browser console for me on manual page refresh.
"scripts": {
"build": "parcel build ui/index.html --public-url ./",
"dev": "parcel watch ui/index.html"
}
Updating the build script fixed the issues for me.
"scripts": {
"build": "parcel build ui/index.html",
"ui": "parcel watch ui/index.html"
}
This work for me and always keeps two digits fractions
23.1 ==> 23.10
25.569 ==> 25.56
1 ==> 1.00
Cast(CONVERT(DECIMAL(10,2),Value1) as nvarchar) AS Value2
what you proposed with a change at the parenthesis at the Run command worked fine with VBA for me
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Dim errorCode As Integer
wsh.Run "C:\folder\runbat.bat", windowStyle, waitOnReturn
jQuery("#checker").click(function(){
jQuery("#mydiv :checkbox").each(function(){
this.checked = true;
});
});
jQuery("#dechecker").click(function(){
jQuery("#mydiv :checkbox").each(function(){
this.checked = false;
});
});
jQuery("#checktoggler").click(function(){
jQuery("#mydiv :checkbox").each(function(){
this.checked = !this.checked;
});
});
;)
It looks like you're not specifying a database name to connect to, should go something like
jdbc:hsqldb:hsql://serverName:port/DBname
You can get a Developer_Key from here Get your Google Developer Key
{select as answered, if it answered.}
if you check this code reference, it states
Set DEVELOPER_KEY to the "API key" value from the "Access" tab of the Google APIs Console http://code.google.com/apis/console#access`
Wiki on step by step to get API Key & secret
http://code.garyjones.co.uk/google-developer-api-key
OR
If say, for instance, you have a web app which would require a API key then check this:
The Service application that you have created can be used by your Web apps such as PHP, Python, ..., etc.
this is what i did
first execute create database x
. x is the name of your old database eg the name of the mdf.
Then open sql sever configration and stop the sql sever.
There after browse to the location of your new created database it should be under program file, in my case is
C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQL\MSSQL\DATA
and repleace the new created mdf and Idf with the old files/database.
then simply restart the sql server and walla :)
You should try using the Grid Template.
Here's what I've used for a two Column Layout of a <ul>
<ul class="list-group row">
<li class="list-group-item col-xs-6">Row1</li>
<li class="list-group-item col-xs-6">Row2</li>
<li class="list-group-item col-xs-6">Row3</li>
<li class="list-group-item col-xs-6">Row4</li>
<li class="list-group-item col-xs-6">Row5</li>
</ul>
This worked for me.
To set the value of the checkbox, you need to bind the v-model to a value. The checkbox will be checked if the value is truthy. In this case, you are iterating over modules
and each module
has a checked
property.
The following code will bind the checkbox with that property:
<input type="checkbox" v-model="module.checked" v-bind:id="module.id">
Notice that I removed v-bind:value="module.id"
. You shouldn't use v-model
and v-bind:value
on the same element. From the vue docs:
<input v-model="something">
is just syntactic sugar for:
<input v-bind:value="something" v-on:input="something = $event.target.value">
So, by using v-model
and v-bind:value
, you actually end up having v-bind:value
twice, which could lead to undefined behavior.
You mean altering the size of the bullet, I assume? I believe this is tied to the font-size of the li tag. Thus, you can blow up the font-size for the LI, then reduce it for an element contained inside. Kind of sucks to add the extra markup - but something like:
li {font-size:omgHuge;}
li span {font-size:mehNormal;}
Alternately, you can specify an image file for your list bullets, that could be as big as you want:
ul{
list-style: square url("38specialPlusP.gif");
}
When a variable is declared static inside a class then it becomes a shared variable for all objects of that class which means that the variable is longer specific to any object. For example: -
#include<iostream.h>
#include<conio.h>
class test
{
void fun()
{
static int a=0;
a++;
cout<<"Value of a = "<<a<<"\n";
}
};
void main()
{
clrscr();
test obj1;
test obj2;
test obj3;
obj1.fun();
obj2.fun();
obj3.fun();
getch();
}
This program will generate the following output: -
Value of a = 1
Value of a = 2
Value of a = 3
The same goes for globally declared static variable. The above code will generate the same output if we declare the variable a outside function void fun()
Whereas if u remove the keyword static and declare a as a non-static local/global variable then the output will be as follows: -
Value of a = 1
Value of a = 1
Value of a = 1
In addition to the above answers, there is always the scorched earth method.
rm -R <folder>
in Windows shell the command is:
rd /s <folder>
Then you can just checkout the project again:
git clone -v <repository URL>
This will definitely remove any local changes and pull the latest from the remote repository. Be careful with rm -R as it will delete your good data if you put the wrong path. For instance, definitely do not do:
rm -R /
edit: To fix spelling and add emphasis.
As said earlier, your code will work unless you have the same classes loaded on two different class loaders. This might happen in case you need multiple versions of the same class in memory at the same time, or you are doing some weird on the fly compilation stuff (as I am).
In this case, if you want to consider these as the same class (which might be reasonable depending on the case), you can match their names to compare them.
public static boolean areClassesQuiteTheSame(Class<?> c1, Class<?> c2) {
// TODO handle nulls maybe?
return c1.getCanonicalName().equals(c2.getCanonicalName());
}
Keep in mind that this comparison will do just what it does: compare class names; I don't think you will be able to cast from one version of a class to the other, and before looking into reflection, you might want to make sure there's a good reason for your classloader mess.
You need to cast the array - the returned array is actually of the requested type, i.e. myEnum[]
if you ask for typeof(myEnum)
:
myEnum[] values = (myEnum[]) Enum.GetValues(typeof(myEnum));
Then values[0]
etc
Its similar to select, But datalist has additional functionalities like auto suggest. You can even type and see suggestions as and when you type.
User will also be able to write items which is not there in list.
Instead of invoking the sp_helptext locally with a remote argument, invoke it remotely with a local argument:
EXEC [ServerName].[DatabaseName].dbo.sp_HelpText 'storedProcName'
start "systemLogCollector" /min cmd /k call systemLogCollector.bat
start "uiLogCollector" /min cmd /k call uiLogCollector.bat
start "appLogCollector" /min cmd /k call appLogCollector.bat
Here three batch files are run on separate command windows in a minimized state. If you don't want them minimized, then remove /min
. Also, if you don't need to control them later, then you can get rid of the titles. So, a bare-bone command will be- start cmd /k call systemLogCollector.bat
If you want to terminate them-
taskkill /FI "WindowTitle eq appLogCollector*" /T /F
taskkill /FI "WindowTitle eq uiLogCollector*" /T /F
taskkill /FI "WindowTitle eq systemLogCollector*" /T /F
curl -X PUT -d 'new_value' URL_PATH/key
where,
X - option to be used for request command
d - option to be used in order to put data on remote url
URL_PATH - remote url
new_value - value which we want to put to the server's key
One solution is:
div {
text-align:center;
width:100%;
}
iframe{
width: 200px;
}
_x000D_
<div>
<iframe></iframe>
</div>
_x000D_
JSFiddle: https://jsfiddle.net/h9gTm/
edit: vertical align added
div {
text-align: center;
width: 100%;
vertical-align: middle;
height: 100%;
display: table-cell;
}
.iframe{
width: 200px;
}
div,
body,
html {
height: 100%;
width: 100%;
}
body{
display: table;
}
JSFiddle: https://jsfiddle.net/h9gTm/1/
Edit: FLEX solution
Using display: flex
on the <div>
div {
display: flex;
align-items: center;
justify-content: center;
}
JSFiddle: https://jsfiddle.net/h9gTm/867/
For me this was the solution, after many hours of searching!!
For some reason, well into the development of a Swift 2.3 custom Framework, Xcode 8 had removed the DYLIB_INSTALL_NAME_BASE
setting from the project.pbxproj
file. A little walk into the Build Settings / Dynamic Library Install Name Base
setting back to @rpath
fixed it.
winutils.exe are required for hadoop to perform hadoop related commands. please download hadoop-common-2.2.0 zip file. winutils.exe can be found in bin folder. Extract the zip file and copy it in the local hadoop/bin folder.
It is better to use scanf(" %[^\n]",str) in c++ than cin.ignore() after cin>> statement.To do that first you have to include < cstdio > header.
Get All Parent Iframe functions and HTML
var parent = $(window.frameElement).parent();
//alert(parent+"TESTING");
var parentElement=window.frameElement.parentElement.parentElement.parentElement.parentElement;
var Ifram=parentElement.children;
var GetUframClass=Ifram[9].ownerDocument.activeElement.className;
var Decision_URLLl=parentElement.ownerDocument.activeElement.contentDocument.URL;
onCreate()
method gets called when activity gets created, and its called only once in whole Activity life cycle.
where as onStart()
is called when activity is stopped... I mean it has gone to background and its onStop()
method is called by the os. onStart()
may be called multiple times in Activity life cycle.More details here
They represent [
and ]
. The encoding is called "URL encoding".
From version 0.8.0, dplyr
offers a handy function called group_split()
:
# On sample data from @Aus_10
df %>%
group_split(g)
[[1]]
# A tibble: 25 x 3
ran_data1 ran_data2 g
<dbl> <dbl> <fct>
1 2.04 0.627 A
2 0.530 -0.703 A
3 -0.475 0.541 A
4 1.20 -0.565 A
5 -0.380 -0.126 A
6 1.25 -1.69 A
7 -0.153 -1.02 A
8 1.52 -0.520 A
9 0.905 -0.976 A
10 0.517 -0.535 A
# … with 15 more rows
[[2]]
# A tibble: 25 x 3
ran_data1 ran_data2 g
<dbl> <dbl> <fct>
1 1.61 0.858 B
2 1.05 -1.25 B
3 -0.440 -0.506 B
4 -1.17 1.81 B
5 1.47 -1.60 B
6 -0.682 -0.726 B
7 -2.21 0.282 B
8 -0.499 0.591 B
9 0.711 -1.21 B
10 0.705 0.960 B
# … with 15 more rows
To not include the grouping column:
df %>%
group_split(g, keep = FALSE)
@Rene Juuse - above in comments... Thanks for this link !
. the code to get the real path is a bit different from one SDK to another so below we have three methods that deals with different SDKs.
getRealPathFromURI_API19(): returns real path for API 19 (or above but not tested) getRealPathFromURI_API11to18(): returns real path for API 11 to API 18 getRealPathFromURI_below11(): returns real path for API below 11
public class RealPathUtil {
@SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri){
String filePath = "";
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{ id }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
@SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
CursorLoader cursorLoader = new CursorLoader(
context,
contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null){
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
return result;
}
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri){
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index
= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
font: http://hmkcode.com/android-display-selected-image-and-its-real-path/
UPDATE 2016 March
To fix all problems with path of images i try create a custom gallery as facebook and other apps. This is because you can use just local files ( real files, not virtual or temporary) , i solve all problems with this library.
https://github.com/nohana/Laevatein (this library is to take photo from camera or choose from galery , if you choose from gallery he have a drawer with albums and just show local files)
Here's a solution in pure PIL.
def blend_value(under, over, a):
return (over*a + under*(255-a)) / 255
def blend_rgba(under, over):
return tuple([blend_value(under[i], over[i], over[3]) for i in (0,1,2)] + [255])
white = (255, 255, 255, 255)
im = Image.open(object.logo.path)
p = im.load()
for y in range(im.size[1]):
for x in range(im.size[0]):
p[x,y] = blend_rgba(white, p[x,y])
im.save('/tmp/output.png')