Or you could do it like this.
var palindrome = word => word == word.split('').reverse().join('')
Here is an example that takes a user's input and checks if the input is a palindrome:
name = input("Write your word here: ")
input("Press <enter> to check if the word is a palindrome.")
if str(name) == str(name)[::-1]:
print("True")
else:
print("False")
However, there is no need to even set up the if
/else
statement. You can directly print the result of the logical comparison, as shown here:
name = input("Write your word here: ")
input("Press <enter> to check if the word is a palindrome.")
print(str(name) == str(name)[::-1])
Try the string - "HYTBCABADEFGHABCDEDCBAGHTFYW123456789987654321ZWETYGDE"; It should work for even and odd pals. Much Thanks to Mohit!
using namespace std;
string largestPal(string input_str)
{
string isPal = "";
string largest = "";
int j, k;
for(int i = 0; i < input_str.length() - 1; ++i)
{
k = i + 1;
j = i - 1;
// starting a new interation
// check to see if even pal
if(j >= 0 && k < input_str.length()) {
if(input_str[i] == input_str[j])
j--;
else if(input_str[i] == input_str[j]) {
k++;
}
}
while(j >= 0 && k < input_str.length())
{
if(input_str[j] != input_str[k])
break;
else
{
j--;
k++;
}
isPal = input_str.substr(j + 1, k - j - 1);
if(isPal.length() > largest.length()) {
largest = isPal;
}
}
}
return largest;
}
This is a short and efficient way of checking palindrome.
bool checkPalindrome(string inputString) {
int length = inputString.Length;
for(int i = 0; i < length/2; i++){
if(inputString[i] != inputString[length-1-i]){
return false;
}
}
return true;
}
Try this out :
import java.util.*;
public class str {
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.println("ENTER YOUR STRING: ");
String a=in.nextLine();
System.out.println("GIVEN STRING IS: "+a);
StringBuffer str=new StringBuffer(a);
StringBuffer str2=new StringBuffer(str.reverse());
String s2=new String(str2);
System.out.println("THE REVERSED STRING IS: "+str2);
if(a.equals(s2))
System.out.println("ITS A PALINDROME");
else
System.out.println("ITS NOT A PALINDROME");
}
}
Simple Solution 2 Scenario --(Odd or Even length String)
Base condition& Algo recursive(ch, i, j)
i==j //even len
if i< j recurve call (ch, i +1,j-1)
else return ch[i] ==ch[j]// Extra base condition for old length
public class HelloWorld { static boolean ispalindrome(char ch[], int i, int j) { if (i == j) return true; if (i < j) { if (ch[i] != ch[j]) return false; else return ispalindrome(ch, i + 1, j - 1); } if (ch[i] != ch[j]) return false; else return true; } public static void main(String[] args) { System.out.println(ispalindrome("jatin".toCharArray(), 0, 4)); System.out.println(ispalindrome("nitin".toCharArray(), 0, 4)); System.out.println(ispalindrome("jatinn".toCharArray(), 0, 5)); System.out.println(ispalindrome("nittin".toCharArray(), 0, 5)); } }
From PostreSQL 9.2 Range Types are supported. So you can write this like:
SELECT user_id
FROM user_logs
WHERE '[2014-02-01, 2014-03-01]'::daterange @> login_date
this should be more efficient than the string comparison
Try this.
EditText text = (EditText)findViewById(R.id.edittext1);
String str = text.getText().toString().trim();
As the other answers mentioned, dispatch_async from the main thread is fine.
However, depending on your use case, there is a side effect that you may consider a disadvantage: since the block is scheduled on a queue, it won't execute until control goes back to the run loop, which will have the effect of delaying your block's execution.
For example,
NSLog(@"before dispatch async");
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"inside dispatch async block main thread from main thread");
});
NSLog(@"after dispatch async");
Will print out:
before dispatch async
after dispatch async
inside dispatch async block main thread from main thread
For this reason, if you were expecting the block to execute in-between the outer NSLog's, dispatch_async would not help you.
I'll answer the more general question of how to have a canvas dynamically adapt in size upon window resize. The accepted answer appropriately handles the case where width and height are both supposed to be 100%, which is what was asked for, but which also will change the aspect ratio of the canvas. Many users will want the canvas to resize on window resize, but while keeping the aspect ratio untouched. It's not the exact question, but it "fits in", just putting the question into a slightly more general context.
The window will have some aspect ratio (width / height), and so will the canvas object. How you want these two aspect ratios to relate to each other is one thing you'll have to be clear about, there is no "one size fits all" answer to that question - I'll go through some common cases of what you might want.
Most important thing you have to be clear about: the html canvas object has a width attribute and a height attribute; and then, the css of the same object also has a width and a height attribute. Those two widths and heights are different, both are useful for different things.
Changing the width and height attributes is one method with which you can always change the size of your canvas, but then you'll have to repaint everything, which will take time and is not always necessary, because some amount of size change you can accomplish via the css attributes, in which case you do not redraw the canvas.
I see 4 cases of what you might want to happen on window resize (all starting with a full screen canvas)
1: you want the width to remain 100%, and you want the aspect ratio to stay as it was. In that case, you do not need to redraw the canvas; you don't even need a window resize handler. All you need is
$(ctx.canvas).css("width", "100%");
where ctx is your canvas context. fiddle: resizeByWidth
2: you want width and height to both stay 100%, and you want the resulting change in aspect ratio to have the effect of a stretched-out image. Now, you still don't need to redraw the canvas, but you need a window resize handler. In the handler, you do
$(ctx.canvas).css("height", window.innerHeight);
fiddle: messWithAspectratio
3: you want width and height to both stay 100%, but the answer to the change in aspect ratio is something different from stretching the image. Then you need to redraw, and do it the way that is outlined in the accepted answer.
fiddle: redraw
4: you want the width and height to be 100% on page load, but stay constant thereafter (no reaction to window resize.
fiddle: fixed
All fiddles have identical code, except for line 63 where the mode is set. You can also copy the fiddle code to run on your local machine, in which case you can select the mode via a querystring argument, as ?mode=redraw
The rule:
-webkit-backface-visibility: hidden;
will not work for sprites or image backgrounds.
body {-webkit-transform:translate3d(0,0,0);}
screws up backgrounds that are tiled.
I prefer to make a class called no-flick and do this:
.no-flick{-webkit-transform:translate3d(0,0,0);}
Your comparison function is not even wrong.
Its arguments should be the type stored in the range, i.e. std::pair<K,V>
, not const void*
.
It should return bool
not a positive or negative value. Both (bool)1
and (bool)-1
are true
so your function says every object is ordered before every other object, which is clearly impossible.
You need to model the less-than operator, not strcmp
or memcmp
style comparisons.
See StrictWeakOrdering which describes the properties the function must meet.
here is my solution:
List<String> list1 = new List<String>();
List<String> list2 = new List<String>();
List<String> exceptValue = new List<String>();
foreach(String L1 in List1)
{
if(!List2.Contains(L1)
{
exceptValue.Add(L1);
}
}
foreach(String L2 in List2)
{
if(!List1.Contains(L2)
{
exceptValue.Add(L2);
}
}
I have this code:
<html>_x000D_
<head>_x000D_
<SCRIPT type=text/javascript>_x000D_
function deshabilitarBoton() { _x000D_
document.getElementById("boton").style.display = 'none';_x000D_
document.getElementById("envio").innerHTML ="<br><img src='img/loading.gif' width='16' height='16' border='0'>Generando..."; _x000D_
return true;_x000D_
} _x000D_
</SCRIPT>_x000D_
<title>untitled</title>_x000D_
</head>_x000D_
<body>_x000D_
<form name="form" action="ok.do" method="post" >_x000D_
<table>_x000D_
<tr>_x000D_
<td>Fecha inicio:</td>_x000D_
<td><input type="TEXT" name="fecha_inicio" id="fecha_inicio" /></td>_x000D_
</tr>_x000D_
</table>_x000D_
<div id="boton">_x000D_
<input type="submit" name="event" value="Enviar" class="button" onclick="return deshabilitarBoton()" />_x000D_
</div>_x000D_
<div id="envio">_x000D_
</div>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
If you switch from Web to Express you will no longer be able to use the SQL Server Agent service so you need to set up a different scheduler for maintenance and backups.
Execute in a terminal:
mongo // To go to shell
show databases // To show all existing databases.
use <DATA_BASE> // To switch to the wanted database.
db.dropDatabase() // To remove the current database.
From: Matt Neuburg Book “iOS 13 Programming Fundamentals with Swift.” :
To combine (concatenate) two strings, the simplest approach is to use the + operator:
let s = "hello"
let s2 = " world"
let greeting = s + s2
This convenient notation is possible because the + operator is overloaded: it does one thing when the operands are numbers (numeric addition) and another when the operands are strings (concatenation). The + operator comes with a += assignment shortcut; naturally, the variable on the left side must have been declared with var:
var s = "hello"
let s2 = " world"
s += s2
As an alternative to +=, you can call the append(_:) instance method:
var s = "hello"
let s2 = " world"
s.append(s2)
Another way of concatenating strings is with the joined(separator:) method. You start with an array of strings to be concatenated, and hand it the string that is to be inserted between all of them:
let s = "hello"
let s2 = "world"
let space = " "
let greeting = [s,s2].joined(separator:space)
You can simply use substring
:
if(fieldName.endsWith(","))
{
fieldName = fieldName.substring(0,fieldName.length() - 1);
}
Make sure to reassign your field after performing substring
as Strings are immutable in java
Since .NET Core 2.0 or .NET Standard 2.1 respectively, this is baked into the .NET runtime [1]:
"hello world".Replace("World", "csharp", StringComparison.CurrentCultureIgnoreCase); // "hello csharp"
One simple way to do that is:
String url = "http://test.com/Services/rest/{id}/Identifier"
UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
uriComponents = uriComponents.expand(Collections.singletonMap("id", "1234"));
and then adds the query params.
All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if
to bind them all together in the way I believe you intend.
After validation and before INSERT check if username already exists, using mysqli(procedural). This works:
//check if username already exists
include 'phpscript/connect.php'; //connect to your database
$sql = "SELECT username FROM users WHERE username = '$username'";
$result = $conn->query($sql);
if($result->num_rows > 0) {
$usernameErr = "username already taken"; //takes'em back to form
} else { // go on to INSERT new record
I've changed my code like this and it works:
CREATE or REPLACE TRIGGER test001
AFTER INSERT OR UPDATE OR DELETE ON tabletest001
REFERENCING OLD AS old_buffer NEW AS new_buffer
FOR EACH ROW WHEN (new_buffer.field1 = 'HBP00' OR old_buffer.field1 = 'HBP00')
DECLARE
Operation NUMBER;
CustomerCode CHAR(10 BYTE);
BEGIN
IF DELETING THEN
Operation := 3;
CustomerCode := :old_buffer.field1;
END IF;
IF INSERTING THEN
Operation := 1;
CustomerCode := :new_buffer.field1;
END IF;
IF UPDATING THEN
Operation := 2;
CustomerCode := :new_buffer.field1;
END IF;
// DO SOMETHING ...
EXCEPTION
WHEN OTHERS THEN ErrorCode := SQLCODE;
END;
you can use siblings and removeClass method
$('.nav-link li').click(function() {
$(this).addClass('active').siblings().removeClass('active');
});
git checkout -f your_branch_name
if you have troubles reverting changes:
git checkout .
if you want to remove untracked directories and files:
git clean -fd
This has worked for me :
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public static void main(String[] args) throws Exception {
HttpClient client = new DefaultHttpClient();
//args[0] ="http://hostname:port/xyz/zbc";
HttpGet request1 = new HttpGet(args[0]);
HttpResponse response1 = client.execute(request1);
int code = response1.getStatusLine().getStatusCode();
try(BufferedReader br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));){
// Read in all of the post results into a String.
String output = "";
Boolean keepGoing = true;
while (keepGoing) {
String currentLine = br.readLine();
if (currentLine == null) {
keepGoing = false;
} else {
output += currentLine;
}
}
System.out.println("Response-->"+output);
}
catch(Exception e){
System.out.println("Exception"+e);
}
}
I was looking for answers. I found only one.
None of these work for me. I am not trying to write temporary files, unless this is defined as nonsystem files. Although I am designated the admin on my user profile, with full admin rights indicated in the UAC, I cannot write to program files or windows. This is very irritating.
I try to save an image found online directly to the windows/web/wallpaper folder and it won't let me. Instead, I must save it to my desktop (I REFUSE to navigate to "my documents/pictures/etc" as I refuse to USE such folders, I have my own directory tree thank you) then, from the desktop, cut and paste it to the windows/web/wallpaper folder. And you are telling me I should do that and smile? As an admin user, I SHOULD be able to save directly to its destination folder. My permissions in drive properties/security and in directory properties/security say I can write, but I can't. Not to program files, program files (86) and windows.
How about saving a file I just modified for a game in Program Files (86) (name of game) folder. It won't let me. I open the file to modify it, I can't save it without first either saving it to desktop etc as above, or opening the program which is used for modifying the file first as admin, which means first navigating all the way over to another part of the directory tree where I store those user mod programs, then within the program selecting to open file and navigate again to the file I could have just clicked on to modify in the first place from my projects folder, only to discover that this won't work either! It saves the file, but the file cannot be located. It is there, but invisible. The only solution is to save to desktop as above.
I shouldn't have to do all this as an admin user. However, if I use the true admin account all works fine. But I don't want to use the real admin account. I want to use a user account with admin rights. It says I have admin rights, but I don't.
And, finally, I refuse to store my portables in %appdata%. This is not how I wish to navigate through my directory tree. My personal installations which I use as portables are stored in the directory I create as a navigation preference.
So, here is the tried and true answer I have found:
From what I have seen so far.... unless one uses the real admin account, these permissions just aren't ever really available to any other user with admin privileges in the Windows Vista and Windows 7 OS's. While it was simple to set admin privileges in Windows XP, later versions have taken this away for all but those who can comfortably hack around.
You need to have superuser privileges,
sudo npm install -g <package name>
How about just $(this).is("[name]")
?
The [attr]
syntax is the CSS selector for an element with an attribute attr
, and .is()
checks if the element it is called on matches the given CSS selector.
while you are working in some whatever project and you want to make a minor change you can use git default editor, however you'd probably need a little script that parse the file generated by command below
git config -l
then the variable code.editor
holds the value /Applications/Sublime_Text.app -n -w
which you can open using os.system()
Maybe you can use matplotlib for this, you can also plot normal images with it. If you call show() the image pops up in a window. Take a look at this:
Check out momoflow: http://flow.momolog.info True coverflow effect, and performant on Webkit (Safari and Chrome) and Opera, ok on Firefox.
A quick-and-dirty approach:
function exec_sql_from_file($path, PDO $pdo) {
if (! preg_match_all("/('(\\\\.|.)*?'|[^;])+/s", file_get_contents($path), $m))
return;
foreach ($m[0] as $sql) {
if (strlen(trim($sql)))
$pdo->exec($sql);
}
}
Splits at reasonable SQL statement end points. There is no error checking, no injection protection. Understand your use before using it. Personally, I use it for seeding raw migration files for integration testing.
Add a prop 'key' to the rendering root component of the list.
<ScrollView>
<List>
{this.state.nationalities.map((prop, key) => {
return (
<ListItem key={key}>
<Text>{prop.name}</Text>
</ListItem>
);
})}
</List>
</ScrollView>
In static class, if you are getting information from xml or reg, class tries to initialize all properties. therefore, you should control if the config variable is there otherwise properties will not initialize so the class.
Check xml referance variable is there, Check reg referance variable is is there, Make sure you handle if they are not there.
I dug into this and all the answers above are partially right. It all depends on how the container is launched. It comes down to the following when the container was launched:
-t
)-i
)^P^Q
does work, BUT only when -t
and -i
is used to launch the container:[berto@g6]$ docker run -ti -d --name test python:3.6 /bin/bash -c 'while [ 1 ]; do sleep 30; done;'
b26e39632351192a9a1a00ea0c2f3e10729b6d3e22f8e0676d6519e15c08b518
[berto@g6]$ docker attach test
# here I typed ^P^Q
read escape sequence
# i'm back to my prompt
[berto@g6]$ docker kill test; docker rm -v test
test
test
ctrl+c
does work, BUT only when -t
(without -i
) is used to launch the container:[berto@g6]$ docker run -t -d --name test python:3.6 /bin/bash -c 'while [ 1 ]; do sleep 30; done;'
018a228c96d6bf2e73cccaefcf656b02753905b9a859f32e60bdf343bcbe834d
[berto@g6]$ docker attach test
^C
[berto@g6]$
There is a way to detach without killing the container though; you need another shell. In summary, running this in another shell detached and left the container running pkill -9 -f 'docker.*attach'
:
[berto@g6]$ docker run -d --name test python:3.6 /bin/bash -c 'while [ 1 ]; do sleep 30; done;'
b26e39632351192a9a1a00ea0c2f3e10729b6d3e22f8e0676d6519e15c08b518
[berto@g6]$ docker attach test
# here I typed ^P^Q and doesn't work
^P
# ctrl+c doesn't work either
^C
# can't background either
^Z
# go to another shell and run the `pkill` command above
# i'm back to my prompt
[berto@g6]$
Why? Because you're killing the process that connected you to the container, not the container itself.
Only when you can use ECMAScript 6 or transpilers.
Features:
Code:
function clone(target, source){
for(let key in source){
// Use getOwnPropertyDescriptor instead of source[key] to prevent from trigering setter/getter.
let descriptor = Object.getOwnPropertyDescriptor(source, key);
if(descriptor.value instanceof String){
target[key] = new String(descriptor.value);
}
else if(descriptor.value instanceof Array){
target[key] = clone([], descriptor.value);
}
else if(descriptor.value instanceof Object){
let prototype = Reflect.getPrototypeOf(descriptor.value);
let cloneObject = clone({}, descriptor.value);
Reflect.setPrototypeOf(cloneObject, prototype);
target[key] = cloneObject;
}
else {
Object.defineProperty(target, key, descriptor);
}
}
let prototype = Reflect.getPrototypeOf(source);
Reflect.setPrototypeOf(target, prototype);
return target;
}
The web server is prompting you for a SPNEGO (Simple and Protected GSSAPI Negotiation Mechanism) token.
This is a Microsoft invention for negotiating a type of authentication to use for Web SSO (single-sign-on):
See:
I ran into this problem when I moved to a new machine, carrying with me my AWS_DEFAULT_PROFILE environment variable, but not my ~/.aws directory. I couldn't get any awscli commands to work until I unset that variable or properly configured the named profile. But even the aws configure
command was broken, making things a bit tricky. Assuming you have a Unix-like shell handy:
env | grep AWS_
unset AWS_DEFAULT_PROFILE
aws --profile foo configure
exec $SHELL
aws iam get-user
The tutorial you saw was telling you how to exit nano editor. By typing Ctrl+X nano exits and if your file needs change you will be prompted to save the changes in which case to save you should press Y and then enter to save changes in the same file you open.
If you are not using any gui and you just want to leave the shell the command is Ctrl+D.
Regarding tutorial, The Linux Documentation Project would be a good place to start. If you like books I would recommend by far any book you want from O'Reilly. They have nice cd bookshelfs with good compilation for any linux sysadmin, and without much effort you can find many places where those html bookshelfs are available to read online.
Other 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.
This may not be a popular solution for everyone, but I like the Application Framework in Visual Basic, even when using C#.
Add a reference to Microsoft.VisualBasic
Create a class called WindowsFormsApplication
public class WindowsFormsApplication : WindowsFormsApplicationBase
{
/// <summary>
/// Runs the specified mainForm in this application context.
/// </summary>
/// <param name="mainForm">Form that is run.</param>
public virtual void Run(Form mainForm)
{
// set up the main form.
this.MainForm = mainForm;
// Example code
((Form1)mainForm).FileName = this.CommandLineArgs[0];
// then, run the the main form.
this.Run(this.CommandLineArgs);
}
/// <summary>
/// Runs this.MainForm in this application context. Converts the command
/// line arguments correctly for the base this.Run method.
/// </summary>
/// <param name="commandLineArgs">Command line collection.</param>
private void Run(ReadOnlyCollection<string> commandLineArgs)
{
// convert the Collection<string> to string[], so that it can be used
// in the Run method.
ArrayList list = new ArrayList(commandLineArgs);
string[] commandLine = (string[])list.ToArray(typeof(string));
this.Run(commandLine);
}
}
Modify your Main() routine to look like this
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var application = new WindowsFormsApplication();
application.Run(new Form1());
}
}
This method offers some additional usefull features (like SplashScreen support and some usefull events)
public event NetworkAvailableEventHandler NetworkAvailabilityChanged;d.
public event ShutdownEventHandler Shutdown;
public event StartupEventHandler Startup;
public event StartupNextInstanceEventHandler StartupNextInstance;
public event UnhandledExceptionEventHandler UnhandledException;
Add this single line in your activity, after setContentView()
call
getWindow().getDecorView().setBackgroundColor(Color.WHITE);
Didn't find the answer I wanted, so I solved it myself:
modify a container div!
<div class="rotation"> <!-- Set the container div's css -->
<div class="content" id='content-1'>This div gets scaled on hover</div>
</div>
<!-- Since there is no parent here the transform doesnt have specificity! -->
<div class="rotation content" id='content-2'>This div does not</div>
css you want to persist after executing $target.css()
.content:hover {
transform: scale(1.5);
}
modify content's containing div with css()
$(".rotation").css("transform", "rotate(" + degrees + "deg)");
it works for me. if you want to enable future time for choose, you have to delete maximum date. You need to to do like followings.
btnDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
});
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
dialog.getDatePicker().setMaxDate(c.getTimeInMillis());
return dialog;
}
public void onDateSet(DatePicker view, int year, int month, int day) {
btnDate.setText(ConverterDate.ConvertDate(year, month + 1, day));
}
}
Try running following:
show create table Parent //and check if type for both tables are the same, like myISAM or innoDB, etc //Other aspects to check with this error message: the columns used as foreign keys must be indexed, they must be of the same type (if i.e one is of type smallint(5) and the other of type smallint(6), it won't work), and, if they are integers, they should be unsigned. //or check for charsets show variables like "character_set_database"; show variables like "collation_database"; //edited: try something like this ALTER TABLE table2 ADD CONSTRAINT fk_IdTable2 FOREIGN KEY (Table1_Id) REFERENCES Table1(Table1_Id) ON UPDATE CASCADE ON DELETE CASCADE;
size: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number
]),
Learn more: Typechecking With PropTypes
Sorry this is and old thread but some people would still need this I guess,
Note: I achieved this using Animate.css library for animating the fade.
I used your code and just added .hidden class (using bootstrap's hidden class) but you can still just define
.hidden { opacity: 0; }
$(document).ready(function() {
/* Every time the window is scrolled ... */
$(window).scroll( function(){
/* Check the location of each desired element */
$('.hideme').each( function(i){
var bottom_of_object = $(this).position().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
/* If the object is completely visible in the window, fade it it */
if( bottom_of_window > bottom_of_object ){
$(this).removeClass('hidden');
$(this).addClass('animated fadeInUp');
} else {
$(this).addClass('hidden');
}
});
});
});
Another Note: Applying this to containers might cause it to be glitchy.
rate
is NOT the way to check whether a video is playing (it could stalled). From documentation of rate
:
Indicates the desired rate of playback; 0.0 means "paused", 1.0 indicates a desire to play at the natural rate of the current item.
Key words "desire to play" - a rate of 1.0
does not mean the video is playing.
The solution since iOS 10.0 is to use AVPlayerTimeControlStatus
which can be observed on AVPlayer
timeControlStatus
property.
The solution prior to iOS 10.0 (9.0, 8.0 etc.) is to roll your own solution. A rate of 0.0
means that the video is paused. When rate != 0.0
it means that the video is either playing or is stalled.
You can find out the difference by observing player time via: func addPeriodicTimeObserver(forInterval interval: CMTime, queue: DispatchQueue?, using block: @escaping (CMTime) -> Void) -> Any
The block returns the current player time in CMTime
, so a comparison of lastTime
(the time that was last received from the block) and currentTime
(the time that the block just reported) will tell whether the player is playing or is stalled. For example, if lastTime == currentTime
and rate != 0.0
, then the player has stalled.
As noted by others, figuring out whether playback has finished is indicated by AVPlayerItemDidPlayToEndTimeNotification
.
For Googlers, another way to get a list of users is to use:
Get-WmiObject -Class Win32_UserAccount
That line should be sufficient:
BooleanUtils.and(boolean... array)
but to calm the link-only purists:
Performs an and on a set of booleans.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
<title>Context menu - LabLogic.net</title>
</head>
<body>
<script language="javascript" type="text/javascript">
document.oncontextmenu=RightMouseDown;
document.onmousedown = mouseDown;
function mouseDown(e) {
if (e.which==3) {//righClick
alert("Right-click menu goes here");
}
}
function RightMouseDown() { return false; }
</script>
</body>
</html>
Tested and works in Opera 11.6, firefox 9.01, Internet Explorer 9 and chrome 17 You can check out a working sample at javascript right click menu
You can't, but you can print 0 or 1
_Bool b = 1;
printf("%d\n", b);
Just want to add some description over @Jackpap answer:
automaticallyImplyLeading:
This checks whether we want to apply the back widget(leading widget) over the app bar or not. If the automaticallyImplyLeading is false then automatically space is given to the title and if If the leading widget is true, then this parameter has no effect.
void main() {
runApp(
new MaterialApp(
home: new Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false, // Used for removing back buttoon.
title: new Center(
child: new Text("Demo App"),
),
),
body: new Container(
child: new Center(
child: Text("Hello world!"),
),
),
),
),
);
}
A string phrase normaly has words separated by space. Well you can split the phrase using the spaces as separating characters and count them as follows.
import java.util.HashMap;
import java.util.Map;
public class WordCountMethod {
public static void main (String [] args){
Map<String, Integer>m = new HashMap<String, Integer>();
String phrase = "hello my name is John I repeat John";
String [] array = phrase.split(" ");
for(int i =0; i < array.length; i++){
String word_i = array[i];
Integer ci = m.get(word_i);
if(ci == null){
m.put(word_i, 1);
}
else m.put(word_i, ci+1);
}
for(String s : m.keySet()){
System.out.println(s+" repeats "+m.get(s));
}
}
}
You need to write a document.write object:
document.write('<script type="text/javascript" src="file.js" ></script>');
and place it in your main javascript file
I know this is an old thread, but I wanted to post my 2 cents...
Using Javascript you can achieve this without using $_POST, and thus avoid reloading the page..
<script>
function ButtonPressed()
{
window.location='index.php?view=next'; //this will set $_GET['view']='next'
}
</script>
<button type='button' onClick='ButtonPressed()'>Click me!</button>
<?PHP
if(isset($_GET['next']))
{
echo "This will display after pressing the 'Click Me' button!";
}
?>
In a link, if you put rel=license it: Indicates that the main content of the current document is covered by the copyright license described by the referenced document. Source: http://www.w3.org/wiki/HTML/Elements/link
So, for example, <a rel="license" href="https://creativecommons.org/licenses/by/4.0/">Copyrighted but you can use what's here as long as you credit me</a>
gives a human something to read and lets computers know that the rest of the page is licensed under the CC BY 4.0 license.
There is no "better" but the more common one is ||
. They have different precedence and ||
would work like one would expect normally.
See also: Logical operators (the following example is taken from there):
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;
// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;
It is so much late but this can be helpful for someone. We can use RegEx as bellow.
Regex CSVParser = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
String[] Fields = CSVParser.Split(Test);
An answer with an important explanation:
There are two parameters of "TestNG" who are supposed to determine the order of execution the tests:
@Test(dependsOnGroups= "someGroup")
And:
@Test(dependsOnMethods= "someMethod")
In both cases these functions will depend on the method or group,
But the differences:
In this case:
@Test(dependsOnGroups= "someGroup")
The method will be dependent on the whole group, so it is not necessarily that immediately after the execution of the dependent function, this method will also be executed, but it may occur later in the run and even after other tests run.
It is important to note that in case and there is more than one use within the same set of tests in this parameter, this is a safe recipe for problems, because the dependent methods of the entire set of tests will run first and only then the methods that depend on them.
However, in this case:
@Test(dependsOnMethods= "someMethod")
Even if this parameter is used more than once within the same set of tests, the dependent method will still be executed after the dependent method is executed immediately.
Hope it's clearly and help.
This isn't an answer to your question, but rather a script you can use to avoid this in the future. It utilizes global hooks available since Git version 2.9 to check your email configuration based on the directory your in:
#!/bin/sh
PWD=`pwd`
if [[ $PWD == *"Ippon"* ]] # 1)
then
EMAIL=$(git config user.email)
if [[ $EMAIL == *"Work"* ]] # 2)
then
echo "";
else
echo "Email not configured to your Work email in the Work directory.";
git config user.email "[email protected]"
echo "Git email configuration has now been changed to \"$(git config user$
echo "\nPlease run your command again..."
echo ''
exit 1
fi;
elif [[ $PWD == *"Personal"* ]]
then
EMAIL=$(git config user.email)
if [[ $EMAIL == "[email protected]" ]]
then
echo "";
else
echo "Email is not configured to your personal account in the Personal di$
git config user.email "[email protected]"
echo "Git email configuration has now been changed to \"$(git config user$
echo "\nPlease run your command again..."
echo ''
exit 1;
fi;
fi;
It checks your current working directory, then verifies your git is configured to the correct email. If not, it changes it automatically. See the full details here.
Consider:
Sub SheetKiller()
Dim s As Worksheet, t As String
Dim i As Long, K As Long
K = Sheets.Count
For i = K To 1 Step -1
t = Sheets(i).Name
If t = "ID Sheet" Or t = "Summary" Then
Application.DisplayAlerts = False
Sheets(i).Delete
Application.DisplayAlerts = True
End If
Next i
End Sub
NOTE:
Because we are deleting, we run the loop backwards.
Hopefully this helps others in an enterprise setting looking for a solution. My solution after much tinkering was the following:
Follow the steps in the following link to install legacy browser extension and gpo settings: https://support.google.com/chrome/a/answer/3019558?hl=en&ref_topic=3062034
Enabled legacy browser redirect for "file://" through chrome gpo configuration Google Chrome -> Legacy Browser Support -> "Websites to open in alternative browser"
Configure gpo to also install extension: https://chrome.google.com/webstore/detail/enable-local-file-links/nikfmfgobenbhmocjaaboihbeocackld that redirects file:// links to bypass chrome file:// link block.
The extension opens the links which then triggers google chrome to open the link in internet explorer. The result is IE opens a window, then opens the file/folder for the user, then IE closes itself.
Q. When is the "with grant option" required ?
A. when you have a view executed from a third schema.
Example: schema DSDSW has a view called view_name
a) that view selects from a table in another schema (FDR.balance)
b) a third shema X_WORK tries to select from that view
Typical grants: grant select on dsdw.view_name to dsdw_select_role; grant dsdw_select_role to fdr;
But: fdr gets select count(*) from dsdw.view_name; ERROR at line 1: ORA-01031: insufficient privileges
issue the grant:
grant select on fdr.balance to dsdw with grant option;
now fdr: select count(*) from dsdw.view_name; 5 rows
You can write your own function:
void printVec(vector<char> vec){
for(int i = 0; i < vec.size(); i++){
cout << vec[i] << " ";
}
cout << endl;
}
you can get it with using this url : you will get the picture HD (max size)
https://graph.facebook.com/{userID}?fields=picture.width(720).height(720)&redirect=false
don't forget redirect=false or it will return an error
Everything in JavaScript is pass by reference, so if you want a true deep copy of the objects in the array, the best method I can think of is to serialize the entire array to JSON and then de-serialize it back.
Ya session storage and local storage are same in behaviour except one that is local storage will store the data until and unless the user delete the cache and cookies and session storage data will retain in the system until we close the session i,e until we close the session storage created window.
Okay so you are trying to get a bitmap from a file? Title says URL. Anyways, when you are getting files from external storage in Android you should never use a direct path. Instead call getExternalStorageDirectory() like so:
File bitmapFile = new File(Environment.getExternalStorageDirectory() + "/" + PATH_TO_IMAGE);
Bitmap bitmap = BitmapFactory.decodeFile(bitmapFile);
getExternalStorageDirectory() gives you the path to the SD card. Also you need to declare the WRITE_EXTERNAL_STORAGE permission in the Manifest.
I was asking myself the same question, and I found no clear answers, so I created a simple test.
I tried to add 100 rows with duplicate primary keys and measured the time needed to process it. I am using SQL Server 2014 Developer and Entity Framework 6.1.3 with a custom repository.
Dim newE As New Employee With {.Name = "e"}
For index = 1 To 100
Dim e = employees.Select(Function(item) item.Name = "e").FirstOrDefault()
If e Is Nothing Then
employees.Insert(newE)
End If
Next
2.1 seconds
Dim newE As New Employee With {.Name = "e"}
For index = 1 To 100
Try
employees.Insert(newE)
Catch ex As Exception
End Try
Next
3.1 seconds
This really all depends on what version of Xcode you are using as different versions use different methods to deploy to your iPhone without a provisioning profile.
Xcode 3.2.1 is a good version and is easy to sort out, but we need to know what version you are using.
ActiveSheet.Range("A10000").End(xlup).offset(1,0).Select
This uses javascript, not jquery directly. It might help get you started.
function updateTextInput(val) {_x000D_
document.getElementById('textInput').value=val; _x000D_
}
_x000D_
<input type="range" name="rangeInput" min="0" max="100" onchange="updateTextInput(this.value);">_x000D_
<input type="text" id="textInput" value="">
_x000D_
See the documentation on ?merge
, which states:
By default the data frames are merged on the columns with names they both have,
but separate specifications of the columns can be given by by.x and by.y.
This clearly implies that merge
will merge data frames based on more than one column. From the final example given in the documentation:
x <- data.frame(k1=c(NA,NA,3,4,5), k2=c(1,NA,NA,4,5), data=1:5)
y <- data.frame(k1=c(NA,2,NA,4,5), k2=c(NA,NA,3,4,5), data=1:5)
merge(x, y, by=c("k1","k2")) # NA's match
This example was meant to demonstrate the use of incomparables
, but it illustrates merging using multiple columns as well. You can also specify separate columns in each of x
and y
using by.x
and by.y
.
How about
DROP USER <username>
This is actually an alias for DROP ROLE
.
You have to explicity drop any privileges associated with that user, also to move its ownership to other roles (or drop the object).
This is best achieved by
REASSIGN OWNED BY <olduser> TO <newuser>
and
DROP OWNED BY <olduser>
The latter will remove any privileges granted to the user.
See the postgres docs for DROP ROLE and the more detailed description of this.
Addition:
Apparently, trying to drop a user by using the commands mentioned here will only work if you are executing them while being connected to the same database that the original GRANTS were made from, as discussed here:
Send XML requests with the raw
data type, then set the Content-Type to text/xml
.
After creating a request, use the dropdown to change the request type to POST.
Open the Body tab and check the data type for raw.
Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)
Enter your raw XML data into the input field below
Click Send to submit your XML Request to the specified server.
Several answers show dangerous examples. OP's example [ $a == $b ]
specifically used unquoted variable substitution (as of Oct '17 edit). For [...]
that is safe for string equality.
But if you're going to enumerate alternatives like [[...]]
, you must inform also that the right-hand-side must be quoted. If not quoted, it is a pattern match! (From bash man page: "Any part of the pattern may be quoted to force it to be matched as a string.").
Here in bash, the two statements yielding "yes" are pattern matching, other three are string equality:
$ rht="A*"
$ lft="AB"
$ [ $lft = $rht ] && echo yes
$ [ $lft == $rht ] && echo yes
$ [[ $lft = $rht ]] && echo yes
yes
$ [[ $lft == $rht ]] && echo yes
yes
$ [[ $lft == "$rht" ]] && echo yes
$
You might also want to check your server configuration - sometimes the default for development type servers is to only accept connections from localhost.
The object-fit CSS property sets how the content of a replaced element, such as an img or video, should be resized to fit its container.
Magically, object fit also works on a canvas element. No JavaScript needed, and the canvas doesn't stretch, automatically fills to proportion.
canvas {
width: 100%;
object-fit: contain;
}
(I would assume that folks using containers know what they're doing, but here's my two cents)
Let's say you setup your project using cookiecutter-django and enabled the docker container support, be sure to update the pip requirements file with djangorestframework==<x.yy.z>
(or whichever python dependency you're trying to install) and re-build the docker images (local and production).
You can still use angular.isDefined()
You just need to set
$rootScope.angular = angular;
in the "run" phase.
See update plunkr: http://plnkr.co/edit/h4ET5dJt3e12MUAXy1mS?p=preview
Here is another way of doing it with :)
git log | grep -o '\w\{8,\}' | head -n 1
The choice should be based on the which idiom is best understood.
An array is iterated using:
for (var i = 0; i < a.length; i++)
//do stuff with a[i]
An object being used as an associative array is iterated using:
for (var key in o)
//do stuff with o[key]
Unless you have earth shattering reasons, stick to the established pattern of usage.
Can be caused by a miss configured SPF record on the senders end.
There is an serial I/O chip on your motherboard's CPU (16650 UART). This chip uses 8-bit port as control and data bus, and thus you can issue a command to it through writing to this chip through the control and data bus.
Usually, an application did the following steps on the serial port
In short, you can specify the baud rate only in the STTY command, and then all other options would be kept as default, and it should enough to connect to ohter devices.
SET SCAN OFF is obsolete http://download-uk.oracle.com/docs/cd/B10501_01/server.920/a90842/apc.htm
Here is a variant for dynamically adding a class
function setClassStyle(class_name, css) {
var style_sheet = document.createElement('style');
if (style_sheet) {
style_sheet.setAttribute('type', 'text/css');
var cstr = '.' + class_name + ' {' + css + '}';
var rules = document.createTextNode(cstr);
if(style_sheet.styleSheet){// IE
style_sheet.styleSheet.cssText = rules.nodeValue;
} else {
style_sheet.appendChild(rules);
}
var head = document.getElementsByTagName('head')[0];
if (head) {
head.appendChild(style_sheet);
}
}
}
Personally I tried the TextInfo.ToTitleCase
method, but, I don´t understand why it doesn´t work when all chars are upper-cased.
Though I like the util function provided by Winston Smith, let me provide the function I'm currently using:
public static String TitleCaseString(String s)
{
if (s == null) return s;
String[] words = s.Split(' ');
for (int i = 0; i < words.Length; i++)
{
if (words[i].Length == 0) continue;
Char firstChar = Char.ToUpper(words[i][0]);
String rest = "";
if (words[i].Length > 1)
{
rest = words[i].Substring(1).ToLower();
}
words[i] = firstChar + rest;
}
return String.Join(" ", words);
}
Playing with some tests strings:
String ts1 = "Converting string to title case in C#";
String ts2 = "C";
String ts3 = "";
String ts4 = " ";
String ts5 = null;
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts1)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts2)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts3)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts4)));
Console.Out.WriteLine(String.Format("|{0}|", TitleCaseString(ts5)));
Giving output:
|Converting String To Title Case In C#|
|C|
||
| |
||
Here's a clue why an onchange() call might not fire your bound function:
Powershell + Curl + Zimbra SOAP API
${my_xml} = @"
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">
<soapenv:Body>
<GetFolderRequest xmlns=\"urn:zimbraMail\">
<folder>
<path>Folder Name</path>
</folder>
</GetFolderRequest>
</soapenv:Body>
</soapenv:Envelope>
"@
${my_curl} = "c:\curl.exe"
${cookie} = "c:\cookie.txt"
${zimbra_soap_url} = "https://zimbra:7071/service/admin/soap"
${curl_getfolder_args} = "-b", "${cookie}",
"--header", "Content-Type: text/xml;charset=UTF-8",
"--silent",
"--data-raw", "${my_xml}",
"--url", "${zimbra_soap_url}"
[xml]${my_response} = & ${my_curl} ${curl_getfolder_args}
${my_response}.Envelope.Body.GetFolderResponse.folder.id
I'm going to answer this myself.
I've determined that there is a difference. "git fetch --tags" might bring in all the tags, but it doesn't bring in any new commits!
Turns out one has to do this to be totally "up to date", i.e. replicated a "git pull" without the merge:
$ git fetch --tags
$ git fetch
This is a shame, because it's twice as slow. If only "git fetch" had an option to do what it normally does and bring in all the tags.
Currently, the link dlptest is working fine.
The files will only be stored for 30 minutes before being deleted.
PHP is run on a server, Your browser is a client. Once the server sends all the info to the client, nothing can be done on the server until another request is made.
To make another request without refreshing the page you are going to have to look into ajax. Look into jQuery as it makes ajax requests easy
You can apply a theme to any activity by including android:theme
inside <activity>
inside manifest file.
For example:
<activity android:theme="@android:style/Theme.Dialog">
<activity android:theme="@style/CustomTheme">
And if you want to set theme programatically then use setTheme()
before calling setContentView()
and super.onCreate()
method inside onCreate()
method.
The issue here is that the version of spring-web
that you're using (3.1.1-RELEASE) is not compatible with the version of spring-beans
that you're using (3.0.2-RELEASE). At the top of the stack you can see the NoSuchMethodError
which in turn triggers the BeanFactory not initialized...
exception.
The NoSuchMethodError
is caused because the method invocation XmlWebApplicationContext.loadBeanDefinitions()
in spring-web
is trying to call XmlBeanDefinitionReader.setEnvironment()
in spring-beans
which doesn't exist in 3.0.2-RELEASE. It does however exist in 3.1.1-RELEASE - as setEnvironment
is inherited from the parent AbstractBeanDefinitionReader
.
To resolve, you'd probably be best to upgrade the spring-beans
jar to 3.1.1-RELEASE. The version for this jar appears to be parameterized in your pom.xml and is controlled by the property org.springframework.version
further down in the file.
The Go trough this link state that the first argument of Output()
is the file path, second is the saving mode - you need to set it to 'F'
.
$upload_dir = public_path();
$filename = $upload_dir.'/testing7.pdf';
$mpdf = new \Mpdf\Mpdf();
//$test = $mpdf->Image($pro_image, 0, 0, 50, 50);
$html ='<h1> Project Heading </h1>';
$mail = ' <p> Project Heading </p> ';
$mpdf->autoScriptToLang = true;
$mpdf->autoLangToFont = true;
$mpdf->WriteHTML($mail);
$mpdf->Output($filename,'F');
$mpdf->debug = true;
Example :
$mpdf->Output($filename,'F');
Example #2
$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML('Hello World');
// Saves file on the server as 'filename.pdf'
$mpdf->Output('filename.pdf', \Mpdf\Output\Destination::FILE);
Here is the codepen demo showing the solution:
Important highlights:
html
, body
, ... .container
, should have the height set to 100%flex
to ANY of the flex items will trigger calculation of the items sizes based on flex distribution:
flex
, for example: flex: 1
then this flex item will occupy the remaining of the spaceflex
property, the calculation will be more complicated. For example, if the item 1 is set to flex: 1
and the item 2 is se to flex: 2
then the item 2 will take twice more of the remaining space
flex-direction
propertyflex
property: https://www.w3.org/TR/css-flexbox-1/#propdef-flex
min-*
and max-*
will be respectedIf anyone else that finds this question and needs a dynamic solution for this where you have an undefined number of columns to transpose to and not exactly 3, you can find a nice solution here: https://github.com/jumpstarter-io/colpivot
If you want to set cookie and get it outside of request, Laravel is not your friend.
Laravel cookies are part of Request, so if you want to do this outside of Request object, use good 'ole PHP setcookie(..) and $_COOKIE to get it.
If you're looking to preserve the existing branches and commit history, here's one way that worked for me.
git clone --mirror https://github.com/account/repo.git cloned-repo
cd cloned-repo
git push --mirror {URL of new (empty) repo}
# at this point only remote cloned-repo is correct, local has auto-generated repo structure with folders such as "branches" or "refs"
cd ..
rm -rf cloned-repo
git clone {URL of new (empty) repo}
# only now will you see the expected user-generated contents in local cloned-repo folder
# note: all non-master branches are avaialable, but git branch will not show them until you git checkout each of them
# to automatically checkout all remote branches use this loop:
for b in `git branch -r | grep -v -- '->'`; do git branch --track ${b##origin/} $b; done
Now, suppose you want to keep the source and destination repos in sync for a period of time. For example, there's still activity within the current remote repo that you want to bring over to the new/replacement repo.
git clone -o old https://github.com/account/repo.git my-repo
cd my-repo
git remote add new {URL of new repo}
To pull down the latest updates (assuming you have no local changes):
git checkout {branch(es) of interest}
git pull old
git push --all new
NB: I have yet to use submodules, so I don't know what additional steps might be required if you have them.
Are you asking about this?
public class VariantDate {
public int day;
public int month;
public int year;
public VariantDate(int day) : this(day, 1) {}
public VariantDate(int day, int month) : this(day, month,1900){}
public VariantDate(int day, int month, int year){
this.day=day;
this.month=month;
this.year=year;
}
}
Here's a regex which will grab what's between cow and milk (without leading/trailing space):
srctext = "My cow always gives milk.";
var re = /(.*cow\s+)(.*)(\s+milk.*)/;
var newtext = srctext.replace(re, "$2");
An example: http://jsfiddle.net/entropo/tkP74/
This thread is quite old, but you could also think about a recursive solution passing the StringBuilder to fill. This allows to prevent any reverse processing etc. Just need to design your iteration with a recursion and carefully decide for an exit condition.
public class Test {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
doRecursive(sb, 100, 0);
System.out.println(sb.toString());
}
public static void doRecursive(StringBuilder sb, int limit, int index) {
if (index < limit) {
doRecursive(sb, limit, index + 1);
sb.append(Integer.toString(index));
}
}
}
I have fixed this issue by unchecking 'Connect Hardware Keyboard'. Please refer to the image below to fix this issue
Take a look at Blaze-Persistence Entity Views which works on top of JPA and provides first class DTO support. You can project anything to attributes within Entity Views and it will even reuse existing join nodes for associations if possible.
Here is an example mapping
@EntityView(Order.class)
interface OrderSummary {
Integer getId();
@Mapping("SUM(orderPositions.price * orderPositions.amount * orderPositions.tax)")
BigDecimal getOrderAmount();
@Mapping("COUNT(orderPositions)")
Long getItemCount();
}
Fetching this will generate a JPQL/HQL query similar to this
SELECT
o.id,
SUM(p.price * p.amount * p.tax),
COUNT(p.id)
FROM
Order o
LEFT JOIN
o.orderPositions p
GROUP BY
o.id
Here is a blog post about custom subquery providers which might be interesting to you as well: https://blazebit.com/blog/2017/entity-view-mapping-subqueries.html
This seems to work for me:
>>>a = ['x', 'y', 'z']
>>>type(a)
<class 'list'>
>>>isinstance(a, list)
True
The current C++ standard does not have hash maps, but the coming C++0x standard does, and these are already supported by g++ in the shape of "unordered maps":
#include <unordered_map>
#include <iostream>
#include <string>
using namespace std;
int main() {
unordered_map <string, int> m;
m["foo"] = 42;
cout << m["foo"] << endl;
}
In order to get this compile, you need to tell g++ that you are using C++0x:
g++ -std=c++0x main.cpp
These maps work pretty much as std::map does, except that instead of providing a custom operator<()
for your own types, you need to provide a custom hash function - suitable functions are provided for types like integers and strings.
The approach I took reads the header information from the first row to determine the indexes of the columns of interest.
You mentioned in the question that you also want the values output to a string. I dynamically build a format string for the output from the FORMAT column list. Rows are appended to the values string separated by a new line char.
The output column order is determined by the order of the column names in the FORMAT list.
In my code below the case of the column name in the FORMAT list is important. In the question above you've got 'Pincode' in your FORMAT list, but 'PinCode' in your excel. This wouldn't work below, it would need to be 'PinCode'.
from xlrd import open_workbook
wb = open_workbook('sample.xls')
FORMAT = ['Arm_id', 'DSPName', 'PinCode']
values = ""
for s in wb.sheets():
headerRow = s.row(0)
columnIndex = [x for y in FORMAT for x in range(len(headerRow)) if y == firstRow[x].value]
formatString = ("%s,"*len(columnIndex))[0:-1] + "\n"
for row in range(1,s.nrows):
currentRow = s.row(row)
currentRowValues = [currentRow[x].value for x in columnIndex]
values += formatString % tuple(currentRowValues)
print values
For the sample input you gave above this code outputs:
>>> 1.0,JaVAS,282001.0
2.0,JaVAS,282002.0
3.0,JaVAS,282003.0
And because I'm a python noob, props be to: this answer, this answer, this question, this question and this answer.
Well, I'm a bit late but still would like to share my way of schema creation.
I have schemas for everything that can be described by a word, like you would do it in the classical OOP.
E.G.
Every schema can be saved as a Document or Subdocument, so I declare this for each schema.
Document:
Subdocument:
You can do this in a try and catch block:
try:
if val is None:
print("null")
except NameError:
# throw an exception or do something else
I was looking for a solution to the opposite problem where I needed a fixed width div in the centre and a fluid width div on either side, so I came up with the following and thought I'd post it here in case anyone needs it.
#wrapper {_x000D_
clear: both;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
#wrapper div {_x000D_
display: inline-block;_x000D_
height: 500px;_x000D_
}_x000D_
_x000D_
#center {_x000D_
background-color: green;_x000D_
margin: 0 auto;_x000D_
overflow: auto;_x000D_
width: 500px;_x000D_
}_x000D_
_x000D_
#left {_x000D_
float: left;_x000D_
}_x000D_
_x000D_
#right {_x000D_
float: right;_x000D_
}_x000D_
_x000D_
.fluid {_x000D_
background-color: yellow;_x000D_
width: calc(50% - 250px);_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<div id="center">_x000D_
This is fixed width in the centre_x000D_
</div>_x000D_
<div id="left" class="fluid">_x000D_
This is fluid width on the left_x000D_
</div>_x000D_
<div id="right" class="fluid">_x000D_
This is fluid width on the right_x000D_
</div>_x000D_
</div>
_x000D_
If you change the width of the #center
element then you need to update the width property of .fluid
to:
width: calc(50% - [half of center width]px);
^(?!my)\w+$
should work.
It first ensures that it's not possible to match my
at the start of the string, and then matches alphanumeric characters until the end of the string. Whitespace anywhere in the string will cause the regex to fail. Depending on your input you might want to either strip whitespace in the front and back of the string before passing it to the regex, or use add optional whitespace matchers to the regex like ^\s*(?!my)(\w+)\s*$
. In this case, backreference 1 will contain the name of the variable.
And if you need to ensure that your variable name starts with a certain group of characters, say [A-Za-z_]
, use
^(?!my)[A-Za-z_]\w*$
Note the change from +
to *
.
you can append the file with >> sign. It insert the contents at the last of the file which we are using.e.g if file let its name is myfile contains xyz then cat >> myfile abc ctrl d
after the above process the myfile contains xyzabc.
BundleConfig
is nothing more than bundle configuration moved to separate file. It used to be part of app startup code (filters, bundles, routes used to be configured in one class)
To add this file, first you need to add the Microsoft.AspNet.Web.Optimization
nuget package to your web project:
Install-Package Microsoft.AspNet.Web.Optimization
Then under the App_Start folder create a new cs file called BundleConfig.cs
. Here is what I have in my mine (ASP.NET MVC 5, but it should work with MVC 4):
using System.Web;
using System.Web.Optimization;
namespace CodeRepository.Web
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
Then modify your Global.asax and add a call to RegisterBundles()
in Application_Start()
:
using System.Web.Optimization;
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
A closely related question: How to add reference to System.Web.Optimization for MVC-3-converted-to-4 app
Or you could use the object tag:
<!--[if IE]>
<object classid="clsid:25336920-03F9-11CF-8FD0-00AA00686F13" data="http://www.google.be">
<p>backup content</p>
</object>
<![endif]-->
<!--[if !IE]> <-->
<object type="text/html" data="http://www.flickr.com" style="width:100%; height:100%">
<p>backup content</p>
</object>
<!--> <![endif]-->
The following JavaScript will open a new browser window, 450px wide by 300px high with scrollbars:
window.open("http://myurl", "_blank", "scrollbars=1,resizable=1,height=300,width=450");
You can add this to a link like so:
<a href='#' onclick='javascript:window.open("http://myurl", "_blank", "scrollbars=1,resizable=1,height=300,width=450");' title='Pop Up'>Pop Up</a>
You can insert Kestrel section in asp.net core 2.1+ appsettings.json file.
"Kestrel": {
"EndPoints": {
"Http": {
"Url": "http://0.0.0.0:5002"
}
}
},
SQL Server 2012 and 2014 supports IIF(cont,true,false) function. Thus for minimal selection you can use it like
SELECT IIF(first>second, second, first) the_minimal FROM table
While IIF is just a shorthand for writing CASE...WHEN...ELSE
, it's easier to write.
Swift 3:
let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.default, handler: nil))
alert.addTextField(configurationHandler: {(textField: UITextField!) in
textField.placeholder = "Enter text:"
})
self.present(alert, animated: true, completion: nil)
you could use the last-child psuedo class
table tr td:last-child {
border: none;
}
This will style the last td only. It's not fully supported yet so it may be unsuitable
Not for entire application or particular class.
CurrentUICulture and CurrentCulture are settable per thread as discussed here Is there a way of setting culture for a whole application? All current threads and new threads?. You can't change InvariantCulture
at all.
Sample code to change cultures for current thread:
CultureInfo ci = new CultureInfo(theCultureString);
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
For class you can set/restore culture inside critical methods, but it would be significantly safe to use appropriate overrides for most formatting related methods that take culture as one of arguments:
(3.3).ToString(new CultureInfo("fr-FR"))
To stop apache process try this command
ps aux | grep tomcat | awk '{print $2}' | xargs kill -9
Just adding to the other excellent answers. Scala offers two often criticized symbolic operators, /:
(foldLeft
) and :\
(foldRight
) operators, the first being right-associative. So the following three statements are the equivalent:
( 1 to 100 ).foldLeft( 0, _+_ )
( 1 to 100 )./:( 0 )( _+_ )
( 0 /: ( 1 to 100 ) )( _+_ )
As are these three:
( 1 to 100 ).foldRight( 0, _+_ )
( 1 to 100 ).:\( 0 )( _+_ )
( ( 1 to 100 ) :\ 0 )( _+_ )
If you need the construct for a quick example to play with, use the : operator.
But if you are creating a vector/range of numbers dynamically, then use seq() instead.
Let's say you are creating the vector/range of numbers from a to b with a:b, and you expect it to be an increasing series. Then, if b is evaluated to be less than a, you will get a decreasing sequence but you will never be notified about it, and your program will continue to execute with the wrong kind of input.
In this case, if you use seq(), you can set the sign of the by argument to match the direction of your sequence, and an error will be raised if they do not match. For example,
seq(a, b, -1)
will raise an error for a=2, b=6, because the coder expected a decreasing sequence.
Here is how you would construct your query for this type of requirement.
select ID,Item_Name,max(Flavor) as Flavor,max(Extra_Cheese) as Extra_Cheese
from (select i.*,
case when o.Option_Number=43 then o.value else null end as Flavor,
case when o.Option_Number=44 then o.value else null end as Extra_Cheese
from Ordered_Item i,Ordered_Options o) a
group by ID,Item_Name;
You basically "case out" each column using case when
, then select the max()
for each of those columns using group by
for each intended item.
The best option is create a directive and wrap the slider features there. The secret is use $timeout, the jquery code will be called only when DOM is ready.
angular.module('app')
.directive('my-slider',
['$timeout', function($timeout) {
return {
restrict:'E',
scope: true,
template: '<div id="{{ id }}"></div>',
link: function($scope) {
$scope.id = String(Math.random()).substr(2, 8);
$timeout(function() {
angular.element('#'+$scope.id).slider();
});
}
};
}]
);
Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "]
with array("title" => "Welcome ")
use this code below as progress.xml:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<shape>
<corners android:radius="5dip" />
<gradient
android:startColor="#ff9d9e9d"
android:centerColor="#ff5a5d5a"
android:centerY="0.75"
android:endColor="#ff747674"
android:angle="270"
/>
</shape>
</item>
<item android:id="@android:id/secondaryProgress">
<clip>
<shape>
<solid android:color="#00000000" />
</shape>
</clip>
</item>
<item android:id="@android:id/progress">
<clip>
<shape>
<solid android:color="#00000000" />
</shape>
</clip>
</item>
</layer-list>
where:
after that use it in the layout containing the xml:
<SeekBar
android:id="@+id/myseekbar"
...
android:progressDrawable="@drawable/progress"
/>
you can also customize the thumb by using a custom icon seek_thumb.png:
android:thumb="@drawable/seek_thumb"
Hello There is an example:
import numpy as np
import matplotlib.pyplot as ptl
def grafica_seno_coseno():
x = np.arange(-4,2*np.pi, 0.3)
y = 2*np.sin(x)
y2 = 3*np.cos(x)
ptl.plot(x, y, '-gD')
ptl.plot(x, y2, '-rD')
for xitem,yitem in np.nditer([x,y]):
etiqueta = "{:.1f}".format(xitem)
ptl.annotate(etiqueta, (xitem,yitem), textcoords="offset points",xytext=(0,10),ha="center")
for xitem,y2item in np.nditer([x,y2]):
etiqueta2 = "{:.1f}".format(xitem)
ptl.annotate(etiqueta2, (xitem,y2item), textcoords="offset points",xytext=(0,10),ha="center")
ptl.grid(True)
return ptl.show()
I had some luck with this open-source Python project, seemingly inactive: https://github.com/JRBANCEL/Chromagnon
I ran:
python2 Chromagnon/chromagnonCache.py path/to/Chrome/Cache -o browsable_cache/
And I got a locally-browsable extract of all my open tabs cache.
Since AngularJS 1.3.4 you can use $setDirty()
on fields (source). For example, for each field with error and marked required you can do the following:
angular.forEach($scope.form.$error.required, function(field) {
field.$setDirty();
});
One of the way you can achieve this is:
Now your java program can be opened in a fancy way just like any other MSWindows apps.! :)
Need to add lazy for TapGestureRecognizer to register
since the 'self' in UITapGestureRecognizer(target: self ...) will be nil if it's not a lazy var. Even if you set isUserInteractionEnable = true, it won't register without lazy var.
lazy var imageSelector : UIImageView = {
let image = UIImageView(image: "imageName.png")
//now add tap gesture
image.isUserInteractionEnabled = true
image.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleImageSelector)))
return image
}()
@objc private func handleImageSelector() {
print("Pressed image selector")
}
Broken pipe means you wrote to a connection that is already closed by the other end.
isConnected()
does not detect this condition. Only a write does.
is it wise to always call SocketChannel.isConnected() before attempting a SocketChannel.write()
It is pointless. The socket itself is connected. You connected it. What may not be connected is the connection itself, and you can only determine that by trying it.
This code should do the trick:
var array = ["ab", "abcdefgh", "abcd"];
array.sort(function(a, b){return b.length - a.length});
console.log(JSON.stringify(array, null, '\t'));
I had the same issue and the point is that the element was not adapting its width to the container.
Instead of using width:100%
, be consistent (don't mix the floating model and the flex model) and use flex by adding this:
.child { align-self: stretch; }
Or:
.parent { align-items: stretch; }
This worked for me.
Support for TLS 1.0 and 1.1 was dropped for PyPI. If your system does not use a more recent version, it could explain your error.
Could you try reinstalling pip system-wide, to update your system dependencies to a newer version of TLS?
This seems to be related to Unable to install Python libraries
See Dominique Barton's answer:
Apparently pip is trying to access PyPI via HTTPS (which is encrypted and fine), but with an old (insecure) SSL version. Your system seems to be out of date. It might help if you update your packages.
On Debian-based systems I'd try:
apt-get update && apt-get upgrade python-pip
On Red Hat Linux-based systems:
yum update python-pip # (or python2-pip, at least on Red Hat Linux 7)
On Mac:
sudo easy_install -U pip
You can also try to update
openssl
separately.
A simple function that sort an array of object by a property
function sortArray(array, property, direction) {
direction = direction || 1;
array.sort(function compare(a, b) {
let comparison = 0;
if (a[property] > b[property]) {
comparison = 1 * direction;
} else if (a[property] < b[property]) {
comparison = -1 * direction;
}
return comparison;
});
return array; // Chainable
}
Usage:
var objs = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
sortArray(objs, "last_nom"); // Asc
sortArray(objs, "last_nom", -1); // Desc
Mock data:
df = pd.DataFrame({'Group':['A','A','A','B','C','B','B','C','A','C'],\
'Apple':np.random.rand(10),'Orange':np.random.rand(10)})
df = df[['Group','Apple','Orange']]
Group Apple Orange
0 A 0.465636 0.537723
1 A 0.560537 0.727238
2 A 0.268154 0.648927
3 B 0.722644 0.115550
4 C 0.586346 0.042896
5 B 0.562881 0.369686
6 B 0.395236 0.672477
7 C 0.577949 0.358801
8 A 0.764069 0.642724
9 C 0.731076 0.302369
You can use the Seaborn library for these plots. First melt
the dataframe to format data and then create the boxplot of your choice.
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
dd=pd.melt(df,id_vars=['Group'],value_vars=['Apple','Orange'],var_name='fruits')
sns.boxplot(x='Group',y='value',data=dd,hue='fruits')
Baron Schwartz blogs that due to race conditions, this 'check before write' is a bad practice. He advocates a try/catch pattern with a reconnect
in the catch. Here is the pseudo code he recommends:
function query_database(connection, sql, retries=1)
while true
try
result=connection.execute(sql)
return result
catch InactiveConnectionException e
if retries > 0 then
retries = retries - 1
connection.reconnect()
else
throw e
end
end
end
end
Here is his full blog: https://www.percona.com/blog/2010/05/05/checking-for-a-live-database-connection-considered-harmful/
For formatting jsonfile gives spaces
option which you can pass as a parameter:
jsonfile.writeFile(file, obj, {spaces: 2}, function (err) {
console.error(err);
})
Or use jsonfile.spaces = 4
. Read details here.
I would not suggest writing to file each time in the loop, instead construct the JSON object in the loop and write to file outside the loop.
var jsonfile = require('jsonfile');
var obj={
'table':[]
};
for (i=0; i <11 ; i++){
obj.table.push({"id":i,"square":i*i});
}
jsonfile.writeFile('loop.json', obj, {spaces:2}, function(err){
console.log(err);
});
Found a solution with pop
and map
d = {'a': 'valueA', 'b': 'valueB', 'c': 'valueC', 'd': 'valueD'}
keys = ['a', 'b', 'c']
list(map(d.pop, keys))
print(d)
The output of this:
{'d': 'valueD'}
I have answered this question so late just because I think it will help in the future if anyone searches the same. And this might help.
Update
The above code will throw an error if a key does not exist in the dict.
DICTIONARY = {'a': 'valueA', 'b': 'valueB', 'c': 'valueC', 'd': 'valueD'}
keys = ['a', 'l', 'c']
def remove_keys(key):
try:
DICTIONARY.pop(key, None)
except:
pass # or do any action
list(map(remove_key, keys))
print(DICTIONARY)
output:
DICTIONARY = {'b': 'valueB', 'd': 'valueD'}
@Peter: This could work out for you-
echo "Start!";for p in $(cat ./pep); do
echo $p
done
This would return the output-
Start!
RKEKNVQ
IPKKLLQK
QYFHQLEKMNVK
IPKKLLQK
GDLSTALEVAIDCYEK
QYFHQLEKMNVKIPENIYR
RKEKNVQ
VLAKHGKLQDAIN
ILGFMK
LEDVALQILL
Another approach to count number of list elements:
var num = $("#mylist").find("li").length;_x000D_
console.log(num);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<ul id="mylist">_x000D_
<li>Element 1</li>_x000D_
<li>Element 2</li>_x000D_
<li>Element 3</li>_x000D_
<li>Element 4</li>_x000D_
<li>Element 5</li>_x000D_
</ul>
_x000D_
I had the same issue on MySQL. I took the procedure from symcbean and adapted her to my needs.
Mine is only replacing textual values (or any type you put in the SELECT FROM information_schema) so if you have date fields, you will not have an error in execution.
Mind the collate in SET @stmt, it must match you database collation.
I used a template request in a variable with multiple replaces but if you have motivation, you could have done it with one CONCAT().
Anyway, if you have serialized data in your database, don't use this. It will not work unless you replace your string with a string with the same lenght.
Hope it helps someone.
DELIMITER $$
DROP PROCEDURE IF EXISTS replace_all_occurences_in_database$$
CREATE PROCEDURE replace_all_occurences_in_database (find_string varchar(255), replace_string varchar(255))
BEGIN
DECLARE loop_done integer DEFAULT 0;
DECLARE current_table varchar(255);
DECLARE current_column varchar(255);
DECLARE all_columns CURSOR FOR
SELECT
t.table_name,
c.column_name
FROM information_schema.tables t,
information_schema.columns c
WHERE t.table_schema = DATABASE()
AND c.table_schema = DATABASE()
AND t.table_name = c.table_name
AND c.DATA_TYPE IN('varchar', 'text', 'longtext');
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET loop_done = 1;
OPEN all_columns;
table_loop:
LOOP
FETCH all_columns INTO current_table, current_column;
IF (loop_done > 0) THEN
LEAVE table_loop;
END IF;
SET @stmt = 'UPDATE `|table|` SET `|column|` = REPLACE(`|column|`, "|find|", "|replace|") WHERE `|column|` LIKE "%|find|%"' COLLATE `utf8mb4_unicode_ci`;
SET @stmt = REPLACE(@stmt, '|table|', current_table);
SET @stmt = REPLACE(@stmt, '|column|', current_column);
SET @stmt = REPLACE(@stmt, '|find|', find_string);
SET @stmt = REPLACE(@stmt, '|replace|', replace_string);
PREPARE s1 FROM @stmt;
EXECUTE s1;
DEALLOCATE PREPARE s1;
END LOOP;
END
$$
DELIMITER ;
You could also do it with PowerShell:
Get-WmiObject win32_service -filter "Name='My Service'" `
| Invoke-WmiMethod -Name Change `
-ArgumentList @($null,$null,$null,$null,$null, `
"C:\Program Files (x86)\My Service\NewName.EXE")
Or:
Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Services\My Service" `
-Name ImagePath -Value "C:\Program Files (x86)\My Service\NewName.EXE"
Solution using Guava libraries. Method getPlanet () is case insensitive, so getPlanet ("MerCUrY") will return Planet.MERCURY.
package com.universe.solarsystem.planets;
import org.apache.commons.lang3.StringUtils;
import com.google.common.base.Enums;
import com.google.common.base.Optional;
//Pluto and Eris are dwarf planets, who cares!
public enum Planet {
MERCURY,
VENUS,
EARTH,
MARS,
JUPITER,
SATURN,
URANUS,
NEPTUNE;
public static Planet getPlanet(String name) {
String val = StringUtils.trimToEmpty(name).toUpperCase();
Optional <Planet> possible = Enums.getIfPresent(Planet.class, val);
if (!possible.isPresent()) {
throw new IllegalArgumentException(val + "? There is no such planet!");
}
return possible.get();
}
}
Against all expectation, views are way slower in some circumstances.
I discovered this recently when I had problems with data which was pulled from Oracle which needed to be massaged into another format. Maybe 20k source rows. A small table. To do this we imported the oracle data as unchanged as I could into a table and then used views to extract data. We had secondary views based on those views. Maybe 3-4 levels of views.
One of the final queries, which extracted maybe 200 rows would take upwards of 45 minutes! That query was based on a cascade of views. Maybe 3-4 levels deep.
I could take each of the views in question, insert its sql into one nested query, and execute it in a couple of seconds.
We even found that we could even write each view into a temp table and query that in place of the view and it was still way faster than simply using nested views.
What was even odder was that performance was fine until we hit some limit of source rows being pulled into the database, performs just dropped off a cliff over the space of a couple of days - a few more source rows was all it took.
So, using queries which pull from views which pull from views is much slower than a nested query - which makes no sense for me.
I think you want to set
tableView.alwaysBounceVertical = NO;
Kevin Muchwat above has the BEST answer, despite only 10 upvotes and not selected answer.
setTimeout(function () {
this.basketAddSuccess = false
}.bind(this), 2000)
Let me explain WHY.
"Arrow Function" is ECMA6/ECMA2015. It's perfectly valid in compiled code or controlled client situations (cordova phone apps, Node.js), and it's nice and succinct. It will even probably pass your testing!
However, Microsoft in their infinite wisdom has decided that Internet Explorer WILL NOT EVER SUPPORT ECMA2015!
Their new Edge browser does, but that's not good enough for public facing websites.
Doing a standard function(){} and adding .bind(this) however is the ECMA5.1 (which IS fully supported) syntax for the exact same functionality.
This is also important in ajax/post .then/else calls. At the end of your .then(function){}) you need to bind(this) there as well so: .then(function(){this.flag = true}.bind(this))
I would have added this as a comment to Kevin's response, but for some silly reason it takes less points to post replies than to comment on replies
DO NOT MAKE THE SAME MISTAKE I MADE!
I code on a Mac, and used the 48 points upvoted comment which worked great! Until I got some calls on my scripts failing and I couldn't figure out why. I had to go back and update dozens of calls from arrow syntax to function(){}.bind(this) syntax.
Thankfully I found this thread again and got the right answer. Kevin, I am forever grateful.
As per the "Accepted answer", that has other potential issues dealing with additional libraries (had problems properly accessing/updating Vue properties/functions)
DNS server is obtained via
getprop net.dns1
UPDATE: as of Android Nougat 7.x, ifconfig is present, and netcfg is gone. So ifconfig can be used to find the IP and netmask.
The difference can be demonstrated by this example:
generate a matrix
>>> A = numpy.matrix(numpy.ones((3,3)))
>>> A
matrix([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
use numpy.array
to modify A
. Doesn't work because you are modifying a copy
>>> numpy.array(A)[2]=2
>>> A
matrix([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
use numpy.asarray
to modify A
. It worked because you are modifying A
itself
>>> numpy.asarray(A)[2]=2
>>> A
matrix([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 2., 2., 2.]])
Hope this helps!
Kindly find below one liner bash script command to find all broken symbolic links recursively in any linux based OS
a=$(find / -type l); for i in $(echo $a); do file $i ; done |grep -i broken 2> /dev/null
If you want to pass just the index.php ( no other php file will be passed to fastcgi ) to fastcgi in case you have routes like this in a framework like codeigniter
$route["/download.php"] = "controller/method";
location ~ index\.php$ {
fastcgi_pass 127.0.0.1:9000;
include fastcgi.conf;
}
Although its not a good idea to disable F5 key you can do it in JQuery as below.
<script type="text/javascript">
function disableF5(e) { if ((e.which || e.keyCode) == 116 || (e.which || e.keyCode) == 82) e.preventDefault(); };
$(document).ready(function(){
$(document).on("keydown", disableF5);
});
</script>
Hope this will help!
if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:
If x and/or y is 2-dimensional, then the corresponding columns will be plotted.
In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:
np.squeez doc: Remove single-dimensional entries from the shape of an array.
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()
But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:
The default value parameter expansion is often useful in build scripts like the example one below. If the user just calls the script as-is, perl will not be built in. The user has to explicitly set WITH_PERL
to a value other than "no" to have it built in.
$ cat defvar.sh
#!/bin/bash
WITH_PERL=${WITH_PERL:-no}
if [[ "$WITH_PERL" != no ]]; then
echo "building with perl"
# ./configure --enable=perl
else
echo "not building with perl"
# ./configure
fi
Build without Perl
$ ./defvar.sh
not building with perl
Build with Perl
$ WITH_PERL=yes ./defvar.sh
building with perl
I have the same issue and solved it by reading this post, while solving it, I hitted a problem: auth failed
.
And I finally solved it by using a ssh key
way to authorize myself. I found the EGit offical guide very useful and I configured the ssh
way successfully by refer to the Eclipse SSH Configuration
section in the link provided.
Hope it helps.
I know this was asked a long time ago but I found an answer while searching for this exact question.
There are two solutions.
You can either set an empty onlick attribute on the html element:
<div class="clickElement" onclick=""></div>
Or you can add it in css by setting the pointer cursor:
.clickElement { cursor:pointer }
The problem is that on ipad, the first click on a non-anchor element registers as a hover. This is not really a bug, because it helps with sites that have hover-menus that haven't been tablet/mobile optimised. Setting the cursor or adding an empty onclick attribute tells the browser that the element is indeed a clickable area.
(via http://www.mitch-solutions.com/blog/17-ipad-jquery-live-click-events-not-working)
Here's an easy way to do it:
x=[1,2,20,6,210]
print sorted(set(x))
Tried and always successful
When you have 2 formats in the same column: A - one can be sorted as oldest to newest (real date such as 17/4/2017) B - the other as A to Z ( not real date such as 15/3/2018 00.00.00 )
Select only B cells and replace " 00.00.00" with "blank", so it now appears as "15/3/2018"
Select only B cells and select -- data -- text to column --Delimited --Next -- unselect all -- Next -- Date DMY -- finish
Select the whole cells A and B and sort as you like oldest to newest
If you are using PHP, you can check previous url using php script rather than javascript. Here is the code:
echo $_SERVER['HTTP_REFERER'];
Hope it helps even out of relevance :)
Sure, use Enumerable.Distinct
.
Given a collection of obj
(e.g. foo
), you'd do something like this:
var distinctTypeIDs = foo.Select(x => x.typeID).Distinct();
You can get good Time Series graphs in Excel, the way you want, but you have to work with a few quirks.
Be sure to select "Scatter Graph" (with a line option). This is needed if you have non-uniform time stamps, and will scale the X-axis accordingly.
In your data, you need to add a column with the mid-point. Here's what I did with your sample data. (This trick ensures that the data gets plotted at the mid-point, like you desire.)
You can format the x-axis options with this menu. (Chart->Design->Layout)
Select "Axes" and go to Primary Horizontal Axis, and then select "More Primary Horizontal Axis Options"
Set up the options you wish. (Fix the starting and ending points.)
And you will get a graph such as the one below.
You can then tweak many of the options, label the axes better etc, but this should get you started.
Hope this helps you move forward.
You can do it like that
Expanded(
child: Text(
'Text',
overflow: TextOverflow.ellipsis,
maxLines: 1
)
)
Bind search
-event the search box as given below-
$('input[type=search]').on('search', function () {
// search logic here
// this function will be executed on click of X (clear button)
});
In addition to above answers suggesting (1) the modification of the configuration files pg_hba.conf and (2) postgresql.conf and (3) restarting the PostgreSQL service, some Windows computers might also require incoming TCP traffic to be allowed on the port (usually 5432
).
To do this, you would need to open Windows Firewall and add an inbound rule for the port (e.g. 5432).
Head to Control Panel\System and Security\Windows Defender Firewall > Advanced Settings > Actions (right tab) > Inbound Rules > New Rule… > Port > Specific local ports and type in the port your using, usually 5432 > (defaults settings for the rest and type any name you'd like)
Now, try connecting again from pgAdmin on the client computer. Restarting the service is not required.
Most of the above work, but for me, this was the easiest.
Install the plugin, log out, log in, system, advanced, front end links manager, check and uncheck the options you want to show. It also works on any of the front end navigation's on your site.
http://www.magentocommerce.com/magento-connect/frontend-links-manager.html
The default font for iOS is San Francisco . You can refer the link for further details
The >
is a child selector. So if your HTML looks like this:
<h1 class="hc-reform">
title
<p>stuff here</p>
</h1>
... then that's your ticket.
But if your HTML looks like this:
<h1 class="hc-reform">
title
</h1>
<p>stuff here</p>
Then you want the adjacent selector:
h1.hc-reform + p{
clear:both;
}
Maybe the anwswers here are obsolete... in any case, for me running Symfony 4, it is easy
Just type symfony -V
from the command line.
The issue seems to be that you are adding the deffered.promise
when deffered
is itself the promise you should be adding:
Try changing to promises.push(deffered);
so you don't add the unwrapped promise to the array.
UploadService.uploadQuestion = function(questions){
var promises = [];
for(var i = 0 ; i < questions.length ; i++){
var deffered = $q.defer();
var question = questions[i];
$http({
url : 'upload/question',
method: 'POST',
data : question
}).
success(function(data){
deffered.resolve(data);
}).
error(function(error){
deffered.reject();
});
promises.push(deffered);
}
return $q.all(promises);
}
the actual index is available as a property of the select element.
var sel = document.getElementById('CCards');
alert(sel.selectedIndex);
you can use the index to get to the selection option, where you can pull the text and value.
var opt = sel.options[sel.selectedIndex];
alert(opt.text);
alert(opt.value);
M.Ali's answer could be modified as
select Cast(Cast((37.0/38.0)*100 as decimal(18,2)) as varchar(5)) + ' %' as Percentage
nonatomic
property means @synthesize
d methods are not going to be generated threadsafe -- but this is much faster than the atomic
property since extra checks are eliminated.
strong
is used with ARC and it basically helps you , by not having to worry about the retain count of an object. ARC automatically releases it for you when you are done with it.Using the keyword strong
means that you own the object.
weak
ownership means that you don't own it and it just keeps track of the object till the object it was assigned to stays , as soon as the second object is released it loses is value. For eg. obj.a=objectB;
is used and a has weak property , than its value will only be valid till objectB remains in memory.
copy
property is very well explained here
strong,weak,retain,copy,assign
are mutually exclusive so you can't use them on one single object... read the "Declared Properties " section
hoping this helps you out a bit...
"use strict";
Basically it enables the strict mode.
Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.
As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.
So, there will be no major difference how "use strict";
is interpreted by the Chrome browser and Node.js.
Please read what is strict mode in JavaScript.
For more information:
ECMAScript 6 Code & strict mode. Following is brief from the specification:
10.2.1 Strict Mode Code
An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:
- Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
- Module code is always strict mode code.
- All parts of a ClassDeclaration or a ClassExpression are strict mode code.
- Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
- Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
- Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.
Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).
This is actually redundant except in cases where you want to override the defaults. All of these settings are implied defaults.
You can verify that by checking your effective POM using this command
mvn help:effective-pom
<finalName>name</finalName>
<directory>target</directory>
<outputDirectory>target/classes</outputDirectory>
<testOutputDirectory>target/test-classes</testOutputDirectory>
<sourceDirectory>src/main/java</sourceDirectory>
<testSourceDirectory>src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
</testResource>
</testResources>
For example, if i want to point to a different test resource path or resource path you should use this otherwise you don't.
<resources>
<resource>
<directory>/home/josh/desktop/app_resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>/home/josh/desktop/test_resources</directory>
</testResource>
</testResources>
inputString = input("Enter a String:")
countedArray = {}
for char in inputString:
if char in countedArray:
countedArray[char] += 1
else:
countedArray[char] = 1
print(countedArray)
Add this to the stylesheet:
table {
border-collapse: collapse;
}
The reason why it behaves this way is actually described pretty well in the specification:
There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.
... and later, for collapse
setting:
In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.
`List<String> unavailable = list1.stream()
.filter(e -> (list2.stream()
.filter(d -> d.getStr().equals(e))
.count())<1)
.collect(Collectors.toList());`
for this if i change to
`List<String> unavailable = list1.stream()
.filter(e -> (list2.stream()
.filter(d -> d.getStr().equals(e))
.count())>0)
.collect(Collectors.toList());`
will it give me list1 matched with list2 right?
type="button
"
should be
type="submit"
this is the source code about wraps:
WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')
WRAPPER_UPDATES = ('__dict__',)
def update_wrapper(wrapper,
wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Update a wrapper function to look like the wrapped function
wrapper is the function to be updated
wrapped is the original function
assigned is a tuple naming the attributes assigned directly
from the wrapped function to the wrapper function (defaults to
functools.WRAPPER_ASSIGNMENTS)
updated is a tuple naming the attributes of the wrapper that
are updated with the corresponding attribute from the wrapped
function (defaults to functools.WRAPPER_UPDATES)
"""
for attr in assigned:
setattr(wrapper, attr, getattr(wrapped, attr))
for attr in updated:
getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
# Return the wrapper so this can be used as a decorator via partial()
return wrapper
def wraps(wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
"""Decorator factory to apply update_wrapper() to a wrapper function
Returns a decorator that invokes update_wrapper() with the decorated
function as the wrapper argument and the arguments to wraps() as the
remaining arguments. Default arguments are as for update_wrapper().
This is a convenience function to simplify applying partial() to
update_wrapper().
"""
return partial(update_wrapper, wrapped=wrapped,
assigned=assigned, updated=updated)
When I started with $ nohup storm dev-zookeper
,
METHOD1 : using jobs
,
prayagupd@prayagupd:/home/vmfest# jobs -l
[1]+ 11129 Running nohup ~/bin/storm/bin/storm dev-zookeeper &
METHOD2 : using ps
command.
$ ps xw
PID TTY STAT TIME COMMAND
1031 tty1 Ss+ 0:00 /sbin/getty -8 38400 tty1
10582 ? S 0:01 [kworker/0:0]
10826 ? Sl 0:18 java -server -Dstorm.options= -Dstorm.home=/root/bin/storm -Djava.library.path=/usr/local/lib:/opt/local/lib:/usr/lib -Dsto
10853 ? Ss 0:00 sshd: vmfest [priv]
TTY column with ?
=> nohup
running programs.
Description
Reference
$ man ps
# then search /PROCESS STATE CODES
I have been looking at the answers all impressive. I think He should provide the code that is giving him a problem. Given the example below, If you have a script to link to jquery in page.php then you get that notice.
$().ready(function () {
$.ajax({url: "page.php",
type: 'GET',
success: function (result) {
$("#page").html(result);
}});
});
This is what worked for me when I had this error:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>example.com</key>
<dict>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
</dict>
</dict>
</dict>
Here, to get the text of the menu that triggered the event (does not seem to have any id):
$(document).ready(function()
{
$('ul.art-vmenu li').click(function(e)
{
alert($(this).find("span.t").text());
});
});
As of TypeScript 0.9 (currently an alpha release) you can use the enum definition like this:
enum TShirtSize {
Small,
Medium,
Large
}
var mySize = TShirtSize.Large;
By default, these enumerations will be assigned 0, 1 and 2 respectively. If you want to explicitly set these numbers, you can do so as part of the enum declaration.
Listing 6.2 Enumerations with explicit members
enum TShirtSize {
Small = 3,
Medium = 5,
Large = 8
}
var mySize = TShirtSize.Large;
Both of these examples lifted directly out of TypeScript for JavaScript Programmers.
Note that this is different to the 0.8 specification. The 0.8 specification looked like this - but it was marked as experimental and likely to change, so you'll have to update any old code:
Disclaimer - this 0.8 example would be broken in newer versions of the TypeScript compiler.
enum TShirtSize {
Small: 3,
Medium: 5,
Large: 8
}
var mySize = TShirtSize.Large;
In my case I had an issue around using Microsoft.ReportViewer.WebForms. I removed validate=true from add verb
line in web.config and it started working:
<system.web>
<httpHandlers>
<add verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
This error could actually be in the code preceding where the error is reported. See the For example, if you have a syntax error as below, you'll get the indentation error. The syntax error is actually next to the "except" because it should contain a ":" right after it.
try:
#do something
except
print 'error/exception'
def printError(e):
print e
If you change "except" above to "except:", the error will go away.
Good luck.
You can evaluate based on severity type. Note to use this you must be subscribed to OnInfoMessage
conn.InfoMessage += OnInfoMessage;
conn.FireInfoMessageEventOnUserErrors = true;
Then your OnInfoMessage would contain:
foreach(SqlError err in e.Errors) {
//Informational Errors
if (Between(Convert.ToInt16(err.Class), 0, 10, true)) {
logger.Info(err.Message);
//Errors users can correct.
} else if (Between(Convert.ToInt16(err.Class), 11, 16, true)) {
logger.Error(err.Message);
//Errors SysAdmin can correct.
} else if (Between(Convert.ToInt16(err.Class), 17, 19, true)) {
logger.Error(err.Message);
//Fatal Errors 20+
} else {
logger.Fatal(err.Message);
}}
This way you can evaluate on severity rather than on error number and be more effective. You can find more information on severity here.
private static bool Between( int num, int lower, int upper, bool inclusive = false )
{
return inclusive
? lower <= num && num <= upper
: lower < num && num < upper;
}
If your web server supports Serlvet 3.0 spec, like tomcat 7.0+, you can use below in web.xml
as:
<session-config>
<cookie-config>
<http-only>true</http-only>
<secure>true</secure>
</cookie-config>
</session-config>
As mentioned in docs:
HttpOnly: Specifies whether any session tracking cookies created by this web application will be marked as HttpOnly
Secure: Specifies whether any session tracking cookies created by this web application will be marked as secure even if the request that initiated the corresponding session is using plain HTTP instead of HTTPS
Please refer to how to set httponly and session cookie for java web application
on Wayland xcopy doesn't seem to work, use wl-clipboard instead. e.g. on fedora
sudo dnf install wl-clipboard
tree | wl-copy
wl-paste > file
You can use ClosedXML for this.
Store your table in a DataTable and you can export the table to excel by this simple snippet:
XLWorkbook workbook = new XLWorkbook();
DataTable table = GetYourTable();
workbook.Worksheets.Add(table );
You can read the documentation of ClosedXML to learn more. Hope this helps!
In your github account
Click on the image on the top corner of the page that contains your profile picture ->
Settings ->
In the side menu ->
Developer Settings ->
Personal access Tokens ->
Generate new token.
$ git push
Username: <your username>
Password: <the access token>
Now I do not have to type username and password every time I push changes.
I just type git push
and press Enter, And changes will be pushed.
group by fV.tier_id, f.form_template_id
You can do this with a custom action. You can add a refrence to your custom action under <InstallExecuteSequence>
:
<InstallExecuteSequence>
...
<Custom Action="FileCleaner" After='InstallFinalize'>
Installed AND NOT UPGRADINGPRODUCTCODE</Custom>
Then you will also have to define your Action under <Product>
:
<Product>
...
<CustomAction Id='FileCleaner' BinaryKey='FileCleanerEXE'
ExeCommand='' Return='asyncNoWait' />
Where FileCleanerEXE is a binary (in my case a little c++ program that does the custom action) which is also defined under <Product>
:
<Product>
...
<Binary Id="FileCleanerEXE" SourceFile="path\to\fileCleaner.exe" />
The real trick to this is the Installed AND NOT UPGRADINGPRODUCTCODE
condition on the Custom Action, with out that your action will get run on every upgrade (since an upgrade is really an uninstall then reinstall). Which if you are deleting files is probably not want you want during upgrading.
On a side note: I recommend going through the trouble of using something like C++ program to do the action, instead of a batch script because of the power and control it provides -- and you can prevent the "cmd prompt" window from flashing while your installer runs.
HTTP/2 supports queries multiplexing, headers compression, priority and more intelligent packet streaming management. This results in reduced latency and accelerates content download on modern web pages.
For windows, @shoaly parameters didn't completely work for me. I was getting this error:
NCAT DEBUG: Proxy returned status code 501.
Ncat: Proxy returned status code 501.
ssh_exchange_identification: Connection closed by remote host
I wanted to ssh to a REMOTESERVER and the SSH port had been closed in my network. I found two solutions but the second is better.
To solve the problem using Ncat:
ncat.exe
into the current directory.SSH using Ncat as ProxyCommand in Git Bash with addition --proxy-type socks4
parameter:
ssh -o "ProxyCommand=./ncat --proxy-type socks4 --proxy 127.0.0.1:9150 %h %p" USERNAME@REMOTESERVER
Note that this implementation of Ncat does not support socks5.
THE BETTER SOLUTION:
SSH using connect.c as ProxyCommand in Git Bash:
ssh -o "ProxyCommand=connect -a none -S 127.0.0.1:9150 %h %p"
Note that connect.c supports socks version 4/4a/5.
To use the proxy in git
commands using ssh (for example while using GitHub) -- assuming you installed Git Bash in C:\Program Files\Git\
-- open ~/.ssh/config
and add this entry:
host github.com
user git
hostname github.com
port 22
proxycommand "/c/Program Files/Git/mingw64/bin/connect.exe" -a none -S 127.0.0.1:9150 %h %p
WITH
Digits AS (SELECT 0 D UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9),
Dates AS (SELECT adddate('1970-01-01',t4.d*10000 + t3.d*1000 + t2.d*100 + t1.d*10 +t0.d) AS date FROM Digits AS t0, Digits AS t1, Digits AS t2, Digits AS t3, Digits AS t4)
SELECT * FROM Dates WHERE date BETWEEN '2017-01-01' AND '2017-12-31'
uint32_t
is standard, uint32
is not. That is, if you include <inttypes.h>
or <stdint.h>
, you will get a definition of uint32_t
. uint32
is a typedef in some local code base, but you should not expect it to exist unless you define it yourself. And defining it yourself is a bad idea.
To set a title for a button in Xcode using swift - 04: first create a method called setTitle with parameter title and UIController state like below ;
func setTitle(_ title : String?, for state : UIControl.State) {
}
and recall this method in your button action method like ;
yourButtonName.setTitle("String", for: .state)
public static void copyFolder(File source, File destination)
{
if (source.isDirectory())
{
if (!destination.exists())
{
destination.mkdirs();
}
String files[] = source.list();
for (String file : files)
{
File srcFile = new File(source, file);
File destFile = new File(destination, file);
copyFolder(srcFile, destFile);
}
}
else
{
InputStream in = null;
OutputStream out = null;
try
{
in = new FileInputStream(source);
out = new FileOutputStream(destination);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0)
{
out.write(buffer, 0, length);
}
}
catch (Exception e)
{
try
{
in.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
try
{
out.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
}