$percentage = 50;
$totalWidth = 350;
$new_width = ($percentage / 100) * $totalWidth;
See PEP 308 for more info.
I am sharing my code. form1.cs:-
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BorderExp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
}
private void ExitClick(object sender, EventArgs e)
{
Application.Exit();
}
private void MaxClick(object sender, EventArgs e)
{
if (WindowState ==FormWindowState.Normal)
{
this.WindowState = FormWindowState.Maximized;
}
else
{
this.WindowState = FormWindowState.Normal;
}
}
private void MinClick(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
}
}
Now, the designer:-
namespace BorderExp
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button1.BackColor = System.Drawing.SystemColors.ButtonFace;
this.button1.BackgroundImage = global::BorderExp.Properties.Resources.blank_1_;
this.button1.FlatAppearance.BorderSize = 0;
this.button1.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button1.Location = new System.Drawing.Point(376, 1);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(27, 26);
this.button1.TabIndex = 0;
this.button1.Text = "X";
this.button1.UseVisualStyleBackColor = false;
this.button1.Click += new System.EventHandler(this.ExitClick);
//
// button2
//
this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button2.BackColor = System.Drawing.SystemColors.ButtonFace;
this.button2.BackgroundImage = global::BorderExp.Properties.Resources.blank_1_;
this.button2.FlatAppearance.BorderSize = 0;
this.button2.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button2.Location = new System.Drawing.Point(343, 1);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(27, 26);
this.button2.TabIndex = 1;
this.button2.Text = "[]";
this.button2.UseVisualStyleBackColor = false;
this.button2.Click += new System.EventHandler(this.MaxClick);
//
// button3
//
this.button3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.button3.BackColor = System.Drawing.SystemColors.ButtonFace;
this.button3.BackgroundImage = global::BorderExp.Properties.Resources.blank_1_;
this.button3.FlatAppearance.BorderSize = 0;
this.button3.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224)))));
this.button3.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button3.Location = new System.Drawing.Point(310, 1);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(27, 26);
this.button3.TabIndex = 2;
this.button3.Text = "___";
this.button3.UseVisualStyleBackColor = false;
this.button3.Click += new System.EventHandler(this.MinClick);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackgroundImage = global::BorderExp.Properties.Resources.blank_1_;
this.ClientSize = new System.Drawing.Size(403, 320);
this.ControlBox = false;
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
}
}
the screenshot:- NoBorderForm
Use,
yum list installedcommand to find the packages you installed.
This worked for me:
<script>
jQuery.noConflict();
// Use jQuery via jQuery() instead of via $()
jQuery(document).ready(function(){
jQuery("div").hide();
});
</script>
Reason: "Many JavaScript libraries use $ as a function or variable name, just as jQuery does. In jQuery's case, $ is just an alias for jQuery, so all functionality is available without using $".
Read full reason here: https://api.jquery.com/jquery.noconflict/
If this solves your issue, it's likely another library is also using $.
In your CSS file:
.TableHeader { width: 100px; }
This will set all of the td
tags below each header to 100px. You can also add a width definition (in the markup) to each individual th
tag, but the above solution would be easier.
Yes and you don't need to learn Objective-C and buying Apple software and hardware.
Adobe have created compilator from ActionScript 3 to program for iOS. And later Apple approved this method of application creation.
This is best way to create Apple applications under Windows or Linux/BSD (and another one for MacOS-X)
You can do this with the win32 class in the Microsoft namespace
using Microsoft.Win32;
using (RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true))
{
key.SetValue("aldwin", "\"" + Application.ExecutablePath + "\"");
}
Create composer.json file with requisite library for ex:
{
"require": {
"mpdf/mpdf": "^6.1"
}
}
Execute the below command where composer.json exists:
composer install
In case of Drupal :
Use the web root folder of drupal to include autoload for ex:
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/vendor/autoload.php';
In case of other systems: Use the root folder variable or location to include the autoload.php
Your code should be something like
require_once('class.twitter.php');
$t = new twitter;
$t->username = 'user';
$t->password = 'password';
$data = $t->publicTimeline();
Comparing Java 7 and C# 3
(Some features of Java 7 aren't mentioned here, but the using
statement advantage of all versions of C# over Java 1-6 has been removed.)
Not all of your summary is correct:
Beyond that (and what's in your summary already):
List<byte>
as a byte[]
backing it, rather than an array of boxed bytes.)ref
and out
for passing parameters by referenceThis is not exhaustive, but it covers everything I can think of off-hand.
The important thing is that you know what those terms mean to your colleagues. Different groups will have slightly varying definitions of what they mean when they say "full end-to-end" tests, for instance.
I came across Google's naming system for their tests recently, and I rather like it - they bypass the arguments by just using Small, Medium, and Large. For deciding which category a test fits into, they look at a few factors - how long does it take to run, does it access the network, database, filesystem, external systems and so on.
http://googletesting.blogspot.com/2010/12/test-sizes.html
I'd imagine the difference between Small, Medium, and Large for your current workplace might vary from Google's.
However, it's not just about scope, but about purpose. Mark's point about differing perspectives for tests, e.g. programmer vs customer/end user, is really important.
To set it programmatically in Activity.java:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.MyTheme); // (for Custom theme)
setTheme(android.R.style.Theme_Holo); // (for Android Built In Theme)
this.setContentView(R.layout.myactivity);
To set in Application scope in Manifest.xml (all activities):
<application
android:theme="@android:style/Theme.Holo"
android:theme="@style/MyTheme">
To set in Activity scope in Manifest.xml (single activity):
<activity
android:theme="@android:style/Theme.Holo"
android:theme="@style/MyTheme">
To build a custom theme, you will have to declare theme in themes.xml file, and set styles in styles.xml file.
This is what I did:
useEffect(() => ref.current.scrollTo(0, 0));
const ref = useRef()
return(
<div ref={ref}>
...
</div>
)
In this case, it appears that you've already included the file somewhere. But for class files, you should really "include" them using require_once
to avoid that sort of thing; it won't include the file if it already has been. (And you should usually use require[_once]
, not include[_once]
, the difference being that require
will cause a fatal error if the file doesn't exist, instead of just issuing a warning.)
to pick the values from property file, we can have a Config reader class something like ApplicationConfigReader.class Then define all the variables against properties. Refer below example,
application.properties
myapp.nationality: INDIAN
myapp.gender: Male
Below is corresponding reader class.
@Component
@EnableConfigurationProperties
@ConfigurationProperties(prefix = "myapp")
class AppConfigReader{
private String nationality;
private String gender
//getter & setter
}
Now we can auto-wire the reader class wherever we want to access property values. e.g.
@Service
class ServiceImpl{
@Autowired
private AppConfigReader appConfigReader;
//...
//fetching values from config reader
String nationality = appConfigReader.getNationality() ;
String gender = appConfigReader.getGender();
}
Your code can get messy fast when dealing with CSS3 transitions. I would recommend using a plugin such as jQuery Transit that handles the complexity of CSS3 animations/transitions.
Moreover, the plugin uses webkit-transform rather than webkit-transition, which allows for mobile devices to use hardware acceleration in order to give your web apps that native look and feel when the animations occur.
Javascript:
$("#startTransition").on("click", function()
{
if( $(".boxOne").is(":visible"))
{
$(".boxOne").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxOne").hide(); });
$(".boxTwo").css({ x: '100%' });
$(".boxTwo").show().transition({ x: '0%', opacity: 1.0 });
return;
}
$(".boxTwo").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxTwo").hide(); });
$(".boxOne").css({ x: '100%' });
$(".boxOne").show().transition({ x: '0%', opacity: 1.0 });
});
Most of the hard work of getting cross-browser compatibility is done for you as well and it works like a charm on mobile devices.
Use the constructor for appending material to the file:
FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.
So to append to a file say "abc.txt" use
FileOutputStream fos=new FileOutputStream(new File("abc.txt"),true);
As many know, there is no need for a gem.
Steps to take:
Copy
bootstrap/dist/css/bootstrap.css
bootstrap/dist/css/bootstrap.min.css
to: app/assets/stylesheets
Copy
bootstrap/dist/js/bootstrap.js
bootstrap/dist/js/bootstrap.min.js
to: app/assets/javascripts
Append to: app/assets/stylesheets/application.css
*= require bootstrap
Append to: app/assets/javascripts/application.js
//= require bootstrap
That is all. You are ready to add a new cool Bootstrap template.
Why app/
instead of vendor/
?
It is important to add the files to app/assets, so in the future you'll be able to overwrite Bootstrap styles.
If later you want to add a custom.css.scss
file with custom styles. You'll have something similar to this in application.css
:
*= require bootstrap
*= require custom
If you placed the bootstrap files in app/assets, everything works as expected. But, if you placed them in vendor/assets, the Bootstrap files will be loaded last. Like this:
<link href="/assets/custom.css?body=1" media="screen" rel="stylesheet">
<link href="/assets/bootstrap.css?body=1" media="screen" rel="stylesheet">
So, some of your customizations won't be used as the Bootstrap styles will override them.
Reason behind this
Rails will search for assets in many locations; to get a list of this locations you can do this:
$ rails console
> Rails.application.config.assets.paths
In the output you'll see that app/assets takes precedence, thus loading it first.
This is the right way:
double randd() {
return (double)rand() / ((double)RAND_MAX + 1);
}
or
double randd() {
return (double)rand() / (RAND_MAX + 1.0);
}
What are the situations where "yield from" is useful?
Every situation where you have a loop like this:
for x in subgenerator:
yield x
As the PEP describes, this is a rather naive attempt at using the subgenerator, it's missing several aspects, especially the proper handling of the .throw()
/.send()
/.close()
mechanisms introduced by PEP 342. To do this properly, rather complicated code is necessary.
What is the classic use case?
Consider that you want to extract information from a recursive data structure. Let's say we want to get all leaf nodes in a tree:
def traverse_tree(node):
if not node.children:
yield node
for child in node.children:
yield from traverse_tree(child)
Even more important is the fact that until the yield from
, there was no simple method of refactoring the generator code. Suppose you have a (senseless) generator like this:
def get_list_values(lst):
for item in lst:
yield int(item)
for item in lst:
yield str(item)
for item in lst:
yield float(item)
Now you decide to factor out these loops into separate generators. Without yield from
, this is ugly, up to the point where you will think twice whether you actually want to do it. With yield from
, it's actually nice to look at:
def get_list_values(lst):
for sub in [get_list_values_as_int,
get_list_values_as_str,
get_list_values_as_float]:
yield from sub(lst)
Why is it compared to micro-threads?
I think what this section in the PEP is talking about is that every generator does have its own isolated execution context. Together with the fact that execution is switched between the generator-iterator and the caller using yield
and __next__()
, respectively, this is similar to threads, where the operating system switches the executing thread from time to time, along with the execution context (stack, registers, ...).
The effect of this is also comparable: Both the generator-iterator and the caller progress in their execution state at the same time, their executions are interleaved. For example, if the generator does some kind of computation and the caller prints out the results, you'll see the results as soon as they're available. This is a form of concurrency.
That analogy isn't anything specific to yield from
, though - it's rather a general property of generators in Python.
Swift 5, Xcode 11.4
`UIApplication.shared.keyWindow`
It will give deprecation warning. ''keyWindow' was deprecated in iOS 13.0: Should not be used for applications that support multiple scenes as it returns a key window across all connected scenes' because of connected scenes. I use this way.
extension UIView {
var safeAreaBottom: CGFloat {
if #available(iOS 11, *) {
if let window = UIApplication.shared.keyWindowInConnectedScenes {
return window.safeAreaInsets.bottom
}
}
return 0
}
var safeAreaTop: CGFloat {
if #available(iOS 11, *) {
if let window = UIApplication.shared.keyWindowInConnectedScenes {
return window.safeAreaInsets.top
}
}
return 0
}
}
extension UIApplication {
var keyWindowInConnectedScenes: UIWindow? {
return windows.first(where: { $0.isKeyWindow })
}
}
We just need to use below query to dump one table data into other table.
Select * into SampleProductTracking_tableDump
from SampleProductTracking;
SampleProductTracking_tableDump
is a new table which will be created automatically
when using with above query.
It will copy the records from SampleProductTracking
to SampleProductTracking_tableDump
I use SourceTree git client, and I see that their initial commit/push command is:
git -c diff.mnemonicprefix=false -c core.quotepath=false push -v --tags --set-upstream origin master:master
Most of the above mentioned solution didn't worked for me. However, below given solution works just fine:
<div class="fixed-bottom">...</div>
A solution which works with Python 2 and Python 3:
try:
from urllib.request import urlretrieve # Python 3
except ImportError:
from urllib import urlretrieve # Python 2
url = "http://www.digimouth.com/news/media/2011/09/google-logo.jpg"
urlretrieve(url, "local-filename.jpg")
or, if the additional requirement of requests
is acceptable and if it is a http(s) URL:
def load_requests(source_url, sink_path):
"""
Load a file from an URL (e.g. http).
Parameters
----------
source_url : str
Where to load the file from.
sink_path : str
Where the loaded file is stored.
"""
import requests
r = requests.get(source_url, stream=True)
if r.status_code == 200:
with open(sink_path, 'wb') as f:
for chunk in r:
f.write(chunk)
Just weighing in here with a nice solution I have been using. This is similar to Lucky Soni's solution above in that it supports aggregation, but doesn't require hard coding of the field names.
cursor = db.<collection_name>.<my_query_with_aggregation>;
headerPrinted = false;
while (cursor.hasNext()) {
item = cursor.next();
if (!headerPrinted) {
print(Object.keys(item).join(','));
headerPrinted = true;
}
line = Object
.keys(item)
.map(function(prop) {
return '"' + item[prop] + '"';
})
.join(',');
print(line);
}
Save this as a .js
file, in this case we'll call it example.js
and run it with the mongo command line like so:
mongo <database_name> example.js --quiet > example.csv
There are several other ways, besides using the in
operator (easiest):
index()
>>> try:
... "xxxxABCDyyyy".index("test")
... except ValueError:
... print "not found"
... else:
... print "found"
...
not found
find()
>>> if "xxxxABCDyyyy".find("ABCD") != -1:
... print "found"
...
found
re
>>> import re
>>> if re.search("ABCD" , "xxxxABCDyyyy"):
... print "found"
...
found
Use Range("A1").Text
instead of .Value
post comment edit:
Why?
Because the .Text
property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92
then <- Text
will return exactly what it in the cell including any formatting.
The .Value
and .Value2
properties return what's stored in the cell under the hood excluding formatting. Specially .Value2
for date types, it will return the decimal representation.
If you want to dig deeper into the meaning and performance, I just found this article
which seems like a good guide
another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
now,
paste this code in a module
Sub main()
Dim ws As Worksheet, i&, j&
Set ws = Sheets(1)
For i = 3 To 7
For j = 1 To 4
Debug.Print _
"row " & i & vbTab & vbTab & _
Cells(i, j).Text & vbTab & _
Cells(i, j).Value & vbTab & _
Cells(i, j).Value2
Next j
Next i
End Sub
and Analyse
the output! Its really easy and there isn't much more i can do to help :)
.TEXT .VALUE .VALUE2
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 3 hello hello hello
row 4 1 1 1
row 4 1 1 1
row 4 01/01/1900 31/12/1899 1
row 4 1.00% 0.01 0.01
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 5 helo1$$ helo1$$ helo1$$
row 6 63 63 63
row 6 =7*9 =7*9 =7*9
row 6 03/03/1900 03/03/1900 63
row 6 6300.00% 63 63
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013 29/05/2013 29/05/2013
row 7 29/05/2013 29/05/2013 41423
row 7 29/05/2013% 29/05/2013% 29/05/2013%
We should avoid using traditional for loop while working with Collections. The simple reason what I will give is that the complexity of for loop is of the order O(sqr(n)) and complexity of Iterator or even the enhanced for loop is just O(n). So it gives a performence difference.. Just take a list of some 1000 items and print it using both ways. and also print the time difference for the execution. You can sees the difference.
This depends on the shell you prefer to use.
If you are using the cmd shell on Windows then the following should work:
FOR /F "tokens=*" %%G IN ('DIR /B /AD /S bin') DO RMDIR /S /Q "%%G"
FOR /F "tokens=*" %%G IN ('DIR /B /AD /S obj') DO RMDIR /S /Q "%%G"
If you are using a bash or zsh type shell (such as git bash or babun on Windows or most Linux / OS X shells) then this is a much nicer, more succinct way to do what you want:
find . -iname "bin" | xargs rm -rf
find . -iname "obj" | xargs rm -rf
and this can be reduced to one line with an OR:
find . -iname "bin" -o -iname "obj" | xargs rm -rf
Note that if your directories of filenames contain spaces or quotes, find will send those entries as-is, which xargs may split into multiple entries. If your shell supports them, -print0
and -0
will work around this short-coming, so the above examples become:
find . -iname "bin" -print0 | xargs -0 rm -rf
find . -iname "obj" -print0 | xargs -0 rm -rf
and:
find . -iname "bin" -o -iname "obj" -print0 | xargs -0 rm -rf
If you are using Powershell then you can use this:
Get-ChildItem .\ -include bin,obj -Recurse | foreach ($_) { remove-item $_.fullname -Force -Recurse }
as seen in Robert H's answer below - just make sure you give him credit for the powershell answer rather than me if you choose to up-vote anything :)
It would of course be wise to run whatever command you choose somewhere safe first to test it!
Remove the '#' and do
Color c = Color.FromArgb(int.Parse("#FFFFFF".Replace("#",""),
System.Globalization.NumberStyles.AllowHexSpecifier));
The default value of enum is the enummember equal to 0 or the first element(if value is not specified)
... But i have faced critical problems using enum in my projects and overcome by doing something below ... How ever my need was related to class level ...
class CDDtype
{
public int Id { get; set; }
public DDType DDType { get; set; }
public CDDtype()
{
DDType = DDType.None;
}
}
[DefaultValue(None)]
public enum DDType
{
None = -1,
ON = 0,
FC = 1,
NC = 2,
CC = 3
}
and get expected result
CDDtype d1= new CDDtype();
CDDtype d2 = new CDDtype { Id = 50 };
Console.Write(d1.DDType);//None
Console.Write(d2.DDType);//None
Now what if value is coming from DB .... Ok in this scenario... pass value in below function and it will convertthe value to enum ...below function handled various scenario and it's generic... and believe me it is very fast ..... :)
public static T ToEnum<T>(this object value)
{
//Checking value is null or DBNull
if (!value.IsNull())
{
return (T)Enum.Parse(typeof(T), value.ToStringX());
}
//Returanable object
object ValueToReturn = null;
//First checking whether any 'DefaultValueAttribute' is present or not
var DefaultAtt = (from a in typeof(T).CustomAttributes
where a.AttributeType == typeof(DefaultValueAttribute)
select a).FirstOrNull();
//If DefaultAttributeValue is present
if ((!DefaultAtt.IsNull()) && (DefaultAtt.ConstructorArguments.Count == 1))
{
ValueToReturn = DefaultAtt.ConstructorArguments[0].Value;
}
//If still no value found
if (ValueToReturn.IsNull())
{
//Trying to get the very first property of that enum
Array Values = Enum.GetValues(typeof(T));
//getting very first member of this enum
if (Values.Length > 0)
{
ValueToReturn = Values.GetValue(0);
}
}
//If any result found
if (!ValueToReturn.IsNull())
{
return (T)Enum.Parse(typeof(T), ValueToReturn.ToStringX());
}
return default(T);
}
parser.add_argument
also has a switch required. You can use required=False
.
Here is a sample snippet with Python 2.7:
parser = argparse.ArgumentParser(description='get dir')
parser.add_argument('--dir', type=str, help='dir', default=os.getcwd(), required=False)
args = parser.parse_args()
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
This help me a lot
It's not really a question of what's more efficient.
The commands 'rsync', and 'cp' are not equivalent and achieve different goals.
1- rsync can preserve the time of creation of existing files. (using -a option)
2- rsync will run multiprocess and transfer using either local sockets or network sockets. (i.e. fork itself into multiple processes)
3- The multiprocessing, and threading will increase your throughput when copying large number of small files, and even with multiple larger files.
So bottom line is rsync is for large data, and cp is for smaller local copying. (MB to small GB range). When you start getting into multiple GB or in the TB range, go with rsync. And of course network copies, rsync all the way.
_x000D_
_x000D_
/* add javascript*/_x000D_
{_x000D_
document.getElementById('abc 1').style.display='none';_x000D_
}_x000D_
/* after that add html*/_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<title>...</title>_x000D_
</head>_x000D_
<body>_x000D_
<table border = 2>_x000D_
<tr id = "abc 1">_x000D_
<td>abcd</td>_x000D_
</tr>_x000D_
<tr id ="abc 2">_x000D_
<td>efgh</td>_x000D_
</tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
Console Application is an application (.exe), not a Library (.dll). To make a library, create a new project, select "Class Library" in type of project, then copy the logic of your first code into this new project.
Or you can edit the Project Properties and select Class Library instead of Console Application in Output type.
As some code can be "console" dependant, I think first solution is better if you check your logic when you copy it.
Thanks Darin, For me, to be able to post to the create method, It only worked after I modified the BindModel code to :
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (!string.IsNullOrEmpty(displayFormat) && value != null)
{
DateTime date;
displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
// use the format specified in the DisplayFormat attribute to parse the date
if (DateTime.TryParse(value.AttemptedValue, CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out date))
{
return date;
}
else
{
bindingContext.ModelState.AddModelError(
bindingContext.ModelName,
string.Format("{0} is an invalid date format", value.AttemptedValue)
);
}
}
return base.BindModel(controllerContext, bindingContext);
}
Hope this could help someone else...
I like google gson library.
When you don't know structure of json. You can use
JsonElement root = new JsonParser().parse(jsonString);
and then you can work with json. e.g. how to get "value1" from your gson:
String value1 = root.getAsJsonObject().get("data").getAsJsonObject().get("field1").getAsString();
There are two ways to doing the same:
You may set the value of android:divider="#FFCCFF" in layout xml file. With this you also have to specify height of divider like this android:dividerHeight="5px".
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/lvMyList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#FFCCFF"
android:dividerHeight="5px"/>
</LinearLayout>
You may also do this by programmatically...
ListView listView = getListView();
ColorDrawable myColor = new ColorDrawable(
this.getResources().getColor(R.color.myColor)
);
listView.setDivider(myColor);
listView.setDividerHeight();
I came across this question and thought I would clarify that the lists() method of a eloquent builder object was depreciated in Laravel 5.2 and replaced with pluck().
// <= Laravel 5.1
Word_relation::where('word_one', $word_id)->lists('word_one')->toArray();
// >= Laravel 5.2
Word_relation::where('word_one', $word_id)->pluck('word_one')->toArray();
These methods can also be called on a Collection for example
// <= Laravel 5.1
$collection = Word_relation::where('word_one', $word_id)->get();
$array = $collection->lists('word_one');
// >= Laravel 5.2
$collection = Word_relation::where('word_one', $word_id)->get();
$array = $collection->pluck('word_one');
For Windows Forms applications an optional disabling of a UI-Control can be very useful. So my suggestion looks like this:
public class AppWaitCursor : IDisposable
{
private readonly Control _eventControl;
public AppWaitCursor(object eventSender = null)
{
_eventControl = eventSender as Control;
if (_eventControl != null)
_eventControl.Enabled = false;
Application.UseWaitCursor = true;
Application.DoEvents();
}
public void Dispose()
{
if (_eventControl != null)
_eventControl.Enabled = true;
Cursor.Current = Cursors.Default;
Application.UseWaitCursor = false;
}
}
Usage:
private void UiControl_Click(object sender, EventArgs e)
{
using (new AppWaitCursor(sender))
{
LongRunningCall();
}
}
import datetime
datetime.datetime.now().strftime ("%Y%m%d")
20151015
For the time
from time import gmtime, strftime
showtime = strftime("%Y-%m-%d %H:%M:%S", gmtime())
print showtime
2015-10-15 07:49:18
You probably want to add one day rather than 24 hours. Not all days have 24 hours due to (among other circumstances) daylight saving time:
strtotime('+1 day', $timestamp);
The way to keep SELECT dbo.fCalculateEstimateDate(647)
call working is:
ALTER function [dbo].[fCalculateEstimateDate] (@vWorkOrderID numeric)
Returns varchar(100) AS
Declare @Result varchar(100)
SELECT @Result = [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID,DEFAULT)
Return @Result
Begin
End
CREATE function [dbo].[fCalculateEstimateDate_v2] (@vWorkOrderID numeric,@ToDate DateTime=null)
Returns varchar(100) AS
Begin
<Function Body>
End
[EDIT: this was a stupid suggestion from a time I did not know Vim well enough. Please don't use tabs instead of buffers; tabs are Vim's "window layouts"]
Maybe switch to using tabs?
vim -p a/*.php
opens the same files in tabs
gt
and gT
switch tabs back and forth
:q
closes only the current tab
:qa
closes everything and exits
:tabo
closes everything but the current tab
Changing the index variable i
from within the loop is unlikely to do what you expect. You may need to use a while
loop instead, and control the incrementing of the loop variable yourself. Each time around the for
loop, i
is reassigned with the next value from range()
. So something like:
i = 2
while i < n:
if(something):
do something
else:
do something else
i = 2 # restart the loop
continue
i += 1
In my example, the continue
statement jumps back up to the top of the loop, skipping the i += 1
statement for that iteration. Otherwise, i
is incremented as you would expect (same as the for
loop).
std::vector<CustomClass *> whatever(20000);
or:
std::vector<CustomClass *> whatever;
whatever.reserve(20000);
The former sets the actual size of the array -- i.e., makes it a vector of 20000 pointers. The latter leaves the vector empty, but reserves space for 20000 pointers, so you can insert (up to) that many without it having to reallocate.
At least in my experience, it's fairly unusual for either of these to make a huge difference in performance--but either can affect correctness under some circumstances. In particular, as long as no reallocation takes place, iterators into the vector are guaranteed to remain valid, and once you've set the size/reserved space, you're guaranteed there won't be any reallocations as long as you don't increase the size beyond that.
It can be done.
From the designer: Select your DataGridView Open the Properties Navigate to ColumnHeaderDefaultCellStype Hit the button to edit the style.
You can also do it programmatically:
dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Purple;
Hope that helps!
For some non-activity classes, like Worker, you're already given a Context object in the public constructor.
Worker(Context context, WorkerParameters workerParams)
You can just use that, e.g., save it to a private Context variable in the class (say, mContext
), and then, for example
mContext.getSystenService(Context.ACTIVITY_SERVICE)
Recently, AWS added a feature called Sessions Manager to the Systems Manager service that allows one to SSH into an instance without needing to setup a private key or opening up port 22. I believe authentication is done with IAM and optionally MFA.
You can find out more about it here:
I had a similar error today and the issue was the content-type header of the post request. Make sure the content type is what you expect. In my case a multipart/form-data
content-type header was being sent to the API instead of application/json
.
No code? For shame!
Here is a simple JavaScript address parser. It's pretty awful for every single reason that Matt gives in his dissertation above (which I almost 100% agree with: addresses are complex types, and humans make mistakes; better to outsource and automate this - when you can afford to).
But rather than cry, I decided to try:
This code works OK for parsing most Esri results for findAddressCandidate
and also with some other (reverse)geocoders that return single-line address where street/city/state are delimited by commas. You can extend if you want or write country-specific parsers. Or just use this as case study of how challenging this exercise can be or at how lousy I am at JavaScript. I admit I only spent about thirty mins on this (future iterations could add caches, zip validation, and state lookups as well as user location context), but it worked for my use case: End user sees form that parses geocode search response into 4 textboxes. If address parsing comes out wrong (which is rare unless source data was poor) it's no big deal - the user gets to verify and fix it! (But for automated solutions could either discard/ignore or flag as error so dev can either support the new format or fix source data.)
/* _x000D_
address assumptions:_x000D_
- US addresses only (probably want separate parser for different countries)_x000D_
- No country code expected._x000D_
- if last token is a number it is probably a postal code_x000D_
-- 5 digit number means more likely_x000D_
- if last token is a hyphenated string it might be a postal code_x000D_
-- if both sides are numeric, and in form #####-#### it is more likely_x000D_
- if city is supplied, state will also be supplied (city names not unique)_x000D_
- zip/postal code may be omitted even if has city & state_x000D_
- state may be two-char code or may be full state name._x000D_
- commas: _x000D_
-- last comma is usually city/state separator_x000D_
-- second-to-last comma is possibly street/city separator_x000D_
-- other commas are building-specific stuff that I don't care about right now._x000D_
- token count:_x000D_
-- because units, street names, and city names may contain spaces token count highly variable._x000D_
-- simplest address has at least two tokens: 714 OAK_x000D_
-- common simple address has at least four tokens: 714 S OAK ST_x000D_
-- common full (mailing) address has at least 5-7:_x000D_
--- 714 OAK, RUMTOWN, VA 59201_x000D_
--- 714 S OAK ST, RUMTOWN, VA 59201_x000D_
-- complex address may have a dozen or more:_x000D_
--- MAGICICIAN SUPPLY, LLC, UNIT 213A, MAGIC TOWN MALL, 13 MAGIC CIRCLE DRIVE, LAND OF MAGIC, MA 73122-3412_x000D_
*/_x000D_
_x000D_
var rawtext = $("textarea").val();_x000D_
var rawlist = rawtext.split("\n");_x000D_
_x000D_
function ParseAddressEsri(singleLineaddressString) {_x000D_
var address = {_x000D_
street: "",_x000D_
city: "",_x000D_
state: "",_x000D_
postalCode: ""_x000D_
};_x000D_
_x000D_
// tokenize by space (retain commas in tokens)_x000D_
var tokens = singleLineaddressString.split(/[\s]+/);_x000D_
var tokenCount = tokens.length;_x000D_
var lastToken = tokens.pop();_x000D_
if (_x000D_
// if numeric assume postal code (ignore length, for now)_x000D_
!isNaN(lastToken) ||_x000D_
// if hyphenated assume long zip code, ignore whether numeric, for now_x000D_
lastToken.split("-").length - 1 === 1) {_x000D_
address.postalCode = lastToken;_x000D_
lastToken = tokens.pop();_x000D_
}_x000D_
_x000D_
if (lastToken && isNaN(lastToken)) {_x000D_
if (address.postalCode.length && lastToken.length === 2) {_x000D_
// assume state/province code ONLY if had postal code_x000D_
// otherwise it could be a simple address like "714 S OAK ST"_x000D_
// where "ST" for "street" looks like two-letter state code_x000D_
// possibly this could be resolved with registry of known state codes, but meh. (and may collide anyway)_x000D_
address.state = lastToken;_x000D_
lastToken = tokens.pop();_x000D_
}_x000D_
if (address.state.length === 0) {_x000D_
// check for special case: might have State name instead of State Code._x000D_
var stateNameParts = [lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken];_x000D_
_x000D_
// check remaining tokens from right-to-left for the first comma_x000D_
while (2 + 2 != 5) {_x000D_
lastToken = tokens.pop();_x000D_
if (!lastToken) break;_x000D_
else if (lastToken.endsWith(",")) {_x000D_
// found separator, ignore stuff on left side_x000D_
tokens.push(lastToken); // put it back_x000D_
break;_x000D_
} else {_x000D_
stateNameParts.unshift(lastToken);_x000D_
}_x000D_
}_x000D_
address.state = stateNameParts.join(' ');_x000D_
lastToken = tokens.pop();_x000D_
}_x000D_
}_x000D_
_x000D_
if (lastToken) {_x000D_
// here is where it gets trickier:_x000D_
if (address.state.length) {_x000D_
// if there is a state, then assume there is also a city and street._x000D_
// PROBLEM: city may be multiple words (spaces)_x000D_
// but we can pretty safely assume next-from-last token is at least PART of the city name_x000D_
// most cities are single-name. It would be very helpful if we knew more context, like_x000D_
// the name of the city user is in. But ignore that for now._x000D_
// ideally would have zip code service or lookup to give city name for the zip code._x000D_
var cityNameParts = [lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken];_x000D_
_x000D_
// assumption / RULE: street and city must have comma delimiter_x000D_
// addresses that do not follow this rule will be wrong only if city has space_x000D_
// but don't care because Esri formats put comma before City_x000D_
var streetNameParts = [];_x000D_
_x000D_
// check remaining tokens from right-to-left for the first comma_x000D_
while (2 + 2 != 5) {_x000D_
lastToken = tokens.pop();_x000D_
if (!lastToken) break;_x000D_
else if (lastToken.endsWith(",")) {_x000D_
// found end of street address (may include building, etc. - don't care right now)_x000D_
// add token back to end, but remove trailing comma (it did its job)_x000D_
tokens.push(lastToken.endsWith(",") ? lastToken.substring(0, lastToken.length - 1) : lastToken);_x000D_
streetNameParts = tokens;_x000D_
break;_x000D_
} else {_x000D_
cityNameParts.unshift(lastToken);_x000D_
}_x000D_
}_x000D_
address.city = cityNameParts.join(' ');_x000D_
address.street = streetNameParts.join(' ');_x000D_
} else {_x000D_
// if there is NO state, then assume there is NO city also, just street! (easy)_x000D_
// reasoning: city names are not very original (Portland, OR and Portland, ME) so if user wants city they need to store state also (but if you are only ever in Portlan, OR, you don't care about city/state)_x000D_
// put last token back in list, then rejoin on space_x000D_
tokens.push(lastToken);_x000D_
address.street = tokens.join(' ');_x000D_
}_x000D_
}_x000D_
// when parsing right-to-left hard to know if street only vs street + city/state_x000D_
// hack fix for now is to shift stuff around._x000D_
// assumption/requirement: will always have at least street part; you will never just get "city, state" _x000D_
// could possibly tweak this with options or more intelligent parsing&sniffing_x000D_
if (!address.city && address.state) {_x000D_
address.city = address.state;_x000D_
address.state = '';_x000D_
}_x000D_
if (!address.street) {_x000D_
address.street = address.city;_x000D_
address.city = '';_x000D_
}_x000D_
_x000D_
return address;_x000D_
}_x000D_
_x000D_
// get list of objects with discrete address properties_x000D_
var addresses = rawlist_x000D_
.filter(function(o) {_x000D_
return o.length > 0_x000D_
})_x000D_
.map(ParseAddressEsri);_x000D_
$("#output").text(JSON.stringify(addresses));_x000D_
console.log(addresses);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<textarea>_x000D_
27488 Stanford Ave, Bowden, North Dakota_x000D_
380 New York St, Redlands, CA 92373_x000D_
13212 E SPRAGUE AVE, FAIR VALLEY, MD 99201_x000D_
1005 N Gravenstein Highway, Sebastopol CA 95472_x000D_
A. P. Croll & Son 2299 Lewes-Georgetown Hwy, Georgetown, DE 19947_x000D_
11522 Shawnee Road, Greenwood, DE 19950_x000D_
144 Kings Highway, S.W. Dover, DE 19901_x000D_
Intergrated Const. Services 2 Penns Way Suite 405, New Castle, DE 19720_x000D_
Humes Realty 33 Bridle Ridge Court, Lewes, DE 19958_x000D_
Nichols Excavation 2742 Pulaski Hwy, Newark, DE 19711_x000D_
2284 Bryn Zion Road, Smyrna, DE 19904_x000D_
VEI Dover Crossroads, LLC 1500 Serpentine Road, Suite 100 Baltimore MD 21_x000D_
580 North Dupont Highway, Dover, DE 19901_x000D_
P.O. Box 778, Dover, DE 19903_x000D_
714 S OAK ST_x000D_
714 S OAK ST, RUM TOWN, VA, 99201_x000D_
3142 E SPRAGUE AVE, WHISKEY VALLEY, WA 99281_x000D_
27488 Stanford Ave, Bowden, North Dakota_x000D_
380 New York St, Redlands, CA 92373_x000D_
</textarea>_x000D_
<div id="output">_x000D_
</div>
_x000D_
You may also verify that if you changed your main website folder (c:\inetpub\wwwroot
) to another folder you must give read permission to the IIS_IUSRS group in the new folder.
If you're trying to do stuff with the Java default system keystore (cacerts
), then the default password is changeit
.
You can list keys without needing the password (even if it prompts you) so don't take that as an indication that it is blank.
(Incidentally who in the history of Java ever has changed the default keystore password? They should have left it blank.)
This is more or less a summary of three answers (by Sara Inés Calderón, klaxon and Gothburz), but as they all added something important, I consider it worth joining the solutions and adding some more explanation.
Considering your example, you can do calculations in your template using:
{{ 100 * (count/total) }}
However, this may result in a whole lot of decimal places, so using filters is a good way to go:
{{ 100 * (count/total) | number }}
By default, the number filter will leave up to three fractional digits, this is where the fractionSize argument comes in quite handy
({{ 100 * (count/total) | number:fractionSize }}
), which in your case would be:
{{ 100 * (count/total) | number:0 }}
This will also round the result already:
angular.module('numberFilterExample', [])_x000D_
.controller('ExampleController', ['$scope',_x000D_
function($scope) {_x000D_
$scope.val = 1234.56789;_x000D_
}_x000D_
]);
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head> _x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
</head>_x000D_
<body ng-app="numberFilterExample">_x000D_
<table ng-controller="ExampleController">_x000D_
<tr>_x000D_
<td>No formatting:</td>_x000D_
<td>_x000D_
<span>{{ val }}</span>_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3 Decimal places:</td>_x000D_
<td>_x000D_
<span>{{ val | number }}</span> (default)_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>2 Decimal places:</td>_x000D_
<td><span>{{ val | number:2 }}</span></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>No fractions: </td>_x000D_
<td><span>{{ val | number:0 }}</span> (rounded)</td>_x000D_
</tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>
_x000D_
Last thing to mention, if you rely on an external data source, it probably is good practise to provide a proper fallback value (otherwise you may see NaN or nothing on your site):
{{ (100 * (count/total) | number:0) || 0 }}
Sidenote: Depending on your specifications, you may even be able to be more precise with your fallbacks/define fallbacks on lower levels already (e.g. {{(100 * (count || 10)/ (total || 100) | number:2)}}
). Though, this may not not always make sense..
Its boils down to this: math.h
is from C
and was created over 10 years ago. In math.h, due to its primitive nature, the abs()
function is "essentially" just for integer types and if you wanted to get the absolute value of a double, you had to use fabs()
.
When C++ was created it took math.h
and made it cmath
. cmath
is essentially math.h but improved for C++. It improved things like having to distinguish between fabs()
and abs, and just made abs()
for both doubles and integer types.
In summary either:
Use math.h and use abs()
for integers, fabs()
for doubles
or
use cmath and just have abs for everything (easier and recommended)
Hope this helps anyone who is having the same problem!
All u need is just use one of the attribute of CSS , which is---->
cursor:pointer
just use this property in css , no matter its inline or internal or external
for example(for inline css)
<form>
<input type="submit" style= "cursor:pointer" value="Button" name="Button">
</form>
Project Properties -> Compiler Tab -> Advanced Compile Options button
Project Properties -> Application Tab
The exec
system call of the Linux kernel understands shebangs (#!
) natively
When you do on bash:
./something
on Linux, this calls the exec
system call with the path ./something
.
This line of the kernel gets called on the file passed to exec
: https://github.com/torvalds/linux/blob/v4.8/fs/binfmt_script.c#L25
if ((bprm->buf[0] != '#') || (bprm->buf[1] != '!'))
It reads the very first bytes of the file, and compares them to #!
.
If the comparison is true, then the rest of the line is parsed by the Linux kernel, which makes another exec
call with path /usr/bin/python3
and current file as the first argument:
/usr/bin/python3 /path/to/script.py
and this works for any scripting language that uses #
as a comment character.
And analogously, if you decide to use env
instead, which you likely should always do to work on systems that have the python3
in a different location, notably pyenv
, see also this question, the shebang:
#!/usr/bin/env python3
ends up calling analogously:
/usr/bin/env python3 /path/to/script.py
which does what you expect from env python3
: searches PATH
for python3
and runs /usr/bin/python3 /path/to/script.py
.
And yes, you can make an infinite loop with:
printf '#!/a\n' | sudo tee /a
sudo chmod +x /a
/a
Bash recognizes the error:
-bash: /a: /a: bad interpreter: Too many levels of symbolic links
#!
just happens to be human readable, but that is not required.
If the file started with different bytes, then the exec
system call would use a different handler. The other most important built-in handler is for ELF executable files: https://github.com/torvalds/linux/blob/v4.8/fs/binfmt_elf.c#L1305 which checks for bytes 7f 45 4c 46
(which also happens to be human readable for .ELF
). Let's confirm that by reading the 4 first bytes of /bin/ls
, which is an ELF executable:
head -c 4 "$(which ls)" | hd
output:
00000000 7f 45 4c 46 |.ELF|
00000004
So when the kernel sees those bytes, it takes the ELF file, puts it into memory correctly, and starts a new process with it. See also: How does kernel get an executable binary file running under linux?
Finally, you can add your own shebang handlers with the binfmt_misc
mechanism. For example, you can add a custom handler for .jar
files. This mechanism even supports handlers by file extension. Another application is to transparently run executables of a different architecture with QEMU.
I don't think POSIX specifies shebangs however: https://unix.stackexchange.com/a/346214/32558 , although it does mention in on rationale sections, and in the form "if executable scripts are supported by the system something may happen". macOS and FreeBSD also seem to implement it however.
PATH
search motivation
Likely, one big motivation for the existence of shebangs is the fact that in Linux, we often want to run commands from PATH
just as:
basename-of-command
instead of:
/full/path/to/basename-of-command
But then, without the shebang mechanism, how would Linux know how to launch each type of file?
Hardcoding the extension in commands:
basename-of-command.py
or implementing PATH search on every interpreter:
python3 basename-of-command
would be a possibility, but this has the major problem that everything breaks if we ever decide to refactor the command into another language.
Shebangs solve this problem beautifully.
See also: Why do people write #!/usr/bin/env python on the first line of a Python script?
Okay, everyone here as a different opinion as to the tradeoffs and advantages of xrange versus range. They're mostly correct, xrange is an iterator, and range fleshes out and creates an actual list. For the majority of cases, you won't really notice a difference between the two. (You can use map with range but not with xrange, but it uses up more memory.)
What I think you rally want to hear, however, is that the preferred choice is xrange. Since range in Python 3 is an iterator, the code conversion tool 2to3 will correctly convert all uses of xrange to range, and will throw out an error or warning for uses of range. If you want to be sure to easily convert your code in the future, you'll use xrange only, and list(xrange) when you're sure that you want a list. I learned this during the CPython sprint at PyCon this year (2008) in Chicago.
Above answers are pretty good, just wanted to add short form for this
<input type="text" name="input_text" onKeyUP="this.value = this.value.toUpperCase();">
Suppose we want to move a disc from A to C through B then:
If you repeat all the above steps, the disc will transfer.
1.) A local temporary table exists only for the duration of a connection or, if defined inside a compound statement, for the duration of the compound statement.
Local temp tables are only available to the SQL Server session or connection (means single user) that created the tables. These are automatically deleted when the session that created the tables has been closed. Local temporary table name is stared with single hash ("#") sign.
CREATE TABLE #LocalTemp
(
UserID int,
Name varchar(50),
Address varchar(150)
)
GO
insert into #LocalTemp values ( 1, 'Name','Address');
GO
Select * from #LocalTemp
The scope of Local temp table exist to the current session of current user means to the current query window. If you will close the current query window or open a new query window and will try to find above created temp table, it will give you the error.
2.) A global temporary table remains in the database permanently, but the rows exist only within a given connection. When connection is closed, the data in the global temporary table disappears. However, the table definition remains with the database for access when database is opened next time.
Global temp tables are available to all SQL Server sessions or connections (means all the user). These can be created by any SQL Server connection user and these are automatically deleted when all the SQL Server connections have been closed. Global temporary table name is stared with double hash ("##") sign.
CREATE TABLE ##GlobalTemp
(
UserID int,
Name varchar(50),
Address varchar(150)
)
GO
insert into ##GlobalTemp values ( 1, 'Name','Address');
GO
Select * from ##GlobalTemp
Global temporary tables are visible to all SQL Server connections while Local temporary tables are visible to only current SQL Server connection.
Use @Kristian Antonsen's answer, or you can use:
$('button').click(function() {
preventDefault();
captureForm();
});
First ask yourself how you would ever expect this code to NOT return an integer:
int num;
scanf("%d",&num);
You specified the variable as type integer, then you scanf
, but only for an integer (%d
).
What else could it possibly contain at this point?
Use .closest()
to traverse up the DOM tree up to the specified selector.
var classes = $(this).parent().closest('div').attr('class').split(' '); // this gets the parent classes.
Replace double quotes with single ones:
INSERT
INTO MY.LOGFILE
(id,severity,category,logdate,appendername,message,extrainfo)
VALUES (
'dee205e29ec34',
'FATAL',
'facade.uploader.model',
'2013-06-11 17:16:31',
'LOGDB',
NULL,
NULL
)
In SQL, double quotes are used to mark identifiers, not string constants.
Read the Apple Human Interaction Guidelines for iPhone. I believe this is not approved behavior in an app.
A solution would be to get the ContentResolver
from the context
ContentResolver contentResolver = getContext().getContentResolver();
Link to the documentation : ContentResolver
[Update]
The original answer was written prior to jQuery 1.3, and the functions that existed at the time where not adequate by themselves to calculate the whole width.
Now, as J-P correctly states, jQuery has the functions outerWidth and outerHeight which include the border
and padding
by default, and also the margin
if the first argument of the function is true
[Original answer]
The width
method no longer requires the dimensions
plugin, because it has been added to the jQuery Core
What you need to do is get the padding, margin and border width-values of that particular div and add them to the result of the width
method
Something like this:
var theDiv = $("#theDiv");
var totalWidth = theDiv.width();
totalWidth += parseInt(theDiv.css("padding-left"), 10) + parseInt(theDiv.css("padding-right"), 10); //Total Padding Width
totalWidth += parseInt(theDiv.css("margin-left"), 10) + parseInt(theDiv.css("margin-right"), 10); //Total Margin Width
totalWidth += parseInt(theDiv.css("borderLeftWidth"), 10) + parseInt(theDiv.css("borderRightWidth"), 10); //Total Border Width
Split into multiple lines to make it more readable
That way you will always get the correct computed value, even if you change the padding or margin values from the css
you could always create a new list which is a result of adding two lists.
>>> k = [1,2,3] + [4,7,9]
>>> k
[1, 2, 3, 4, 7, 9]
Lists are mutable sequences so I guess it makes sense to modify the original lists by extend or append.
Using LINQ to xml if you are using framework 3.5:
using System.Xml.Linq;
XDocument xmlFile = XDocument.Load("books.xml");
var query = from c in xmlFile.Elements("catalog").Elements("book")
select c;
foreach (XElement book in query)
{
book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");
Another option would be:
$scope.parseInt = parseInt;
Then you could do this like you wanted:
{{parseInt(num_str)-1}}
This is because angular expressions don't have access to the window
, only to scope
.
Also, with the number filter, wrapping your expression in parentheses works:
{{(num_str-1) | number}}
I defined own helper function to convert timedelta object to 'HH:MM:SS' format - only hours, minutes and seconds, without changing hours to days.
def format_timedelta(td):
hours, remainder = divmod(td.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
hours, minutes, seconds = int(hours), int(minutes), int(seconds)
if hours < 10:
hours = '0%s' % int(hours)
if minutes < 10:
minutes = '0%s' % minutes
if seconds < 10:
seconds = '0%s' % seconds
return '%s:%s:%s' % (hours, minutes, seconds)
Also as a minor enhancement.
The main reason for the try/catch block is that e1 could be null for the initial movement. in addition to the try/catch, include a test for null and return. similar to the following
if (e1 == null || e2 == null) return false;
try {
...
} catch (Exception e) {}
return false;
$('#mySelect').val('ab').change();
// or
$('#mySelect').val('ab').trigger("change");
You can change the value of a bool all you want. As for an if:
if randombool == True:
works, but you can also use:
if randombool:
If you want to test whether something is false you can use:
if randombool == False
but you can also use:
if not randombool:
A quick & concise difference overview :
attr_accessor
is an easy way to create read and write accessors in your class. It is used when you do not have a column in your database, but still want to show a field in your forms. This field is a“virtual attribute”
in a Rails model.virtual attribute – an attribute not corresponding to a column in the database.
attr_accessible
is used to identify attributes that are accessible by your controller methods makes a property available for mass-assignment.. It will only allow access to the attributes that you specify, denying the rest.
I'm probably late but this worked for me:
<target name="build" />
I stole the logging code from virtualenv for a project of mine. Look in main()
of virtualenv.py
to see how it's initialized. The code is sprinkled with logger.notify()
, logger.info()
, logger.warn()
, and the like. Which methods actually emit output is determined by whether virtualenv was invoked with -v
, -vv
, -vvv
, or -q
.
If you're looking for arbitrary strings, and not just characters, you can use an overload of IndexOfAny which takes string arguments from the new project NLib:
if (s.IndexOfAny("aaa", "bbb", "ccc", StringComparison.Ordinal) >= 0)
I've used this approach to get the right date in one line to get the time plus one day following what people were saying above.
((new Date()).setDate((new Date()).getDate()+1))
I just figured I would build off a normal (new Date())
:
(new Date()).getDate()
> 21
Using the code above I can now set all of that within Date()
in (new Date())
and it behaves normally.
(new Date(((new Date()).setDate((new Date()).getDate()+1)))).getDate()
> 22
or to get the Date
object:
(new Date(((new Date()).setDate((new Date()).getDate()+1))))
To install Open CMD and type in {YourServiceName} -i
once its installed type in NET START {YourserviceName}
to start your service
to uninstall
To uninstall Open CMD and type in NET STOP {YourserviceName}
once stopped type in {YourServiceName} -u
and it should be uninstalled
There are a couple of important things to know about bash's [[ ]]
construction. The first:
Word splitting and pathname expansion are not performed on the words between the
[[
and]]
; tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal are performed.
The second thing:
An additional binary operator, ‘=~’, is available,... the string to the right of the operator is considered an extended regular expression and matched accordingly... Any part of the pattern may be quoted to force it to be matched as a string.
Consequently, $v
on either side of the =~
will be expanded to the value of that variable, but the result will not be word-split or pathname-expanded. In other words, it's perfectly safe to leave variable expansions unquoted on the left-hand side, but you need to know that variable expansions will happen on the right-hand side.
So if you write: [[ $x =~ [$0-9a-zA-Z] ]]
, the $0
inside the regex on the right will be expanded before the regex is interpreted, which will probably cause the regex to fail to compile (unless the expansion of $0
ends with a digit or punctuation symbol whose ascii value is less than a digit). If you quote the right-hand side like-so [[ $x =~ "[$0-9a-zA-Z]" ]]
, then the right-hand side will be treated as an ordinary string, not a regex (and $0
will still be expanded). What you really want in this case is [[ $x =~ [\$0-9a-zA-Z] ]]
Similarly, the expression between the [[
and ]]
is split into words before the regex is interpreted. So spaces in the regex need to be escaped or quoted. If you wanted to match letters, digits or spaces you could use: [[ $x =~ [0-9a-zA-Z\ ] ]]
. Other characters similarly need to be escaped, like #
, which would start a comment if not quoted. Of course, you can put the pattern into a variable:
pat="[0-9a-zA-Z ]"
if [[ $x =~ $pat ]]; then ...
For regexes which contain lots of characters which would need to be escaped or quoted to pass through bash's lexer, many people prefer this style. But beware: In this case, you cannot quote the variable expansion:
# This doesn't work:
if [[ $x =~ "$pat" ]]; then ...
Finally, I think what you are trying to do is to verify that the variable only contains valid characters. The easiest way to do this check is to make sure that it does not contain an invalid character. In other words, an expression like this:
valid='0-9a-zA-Z $%&#' # add almost whatever else you want to allow to the list
if [[ ! $x =~ [^$valid] ]]; then ...
!
negates the test, turning it into a "does not match" operator, and a [^...]
regex character class means "any character other than ...
".
The combination of parameter expansion and regex operators can make bash regular expression syntax "almost readable", but there are still some gotchas. (Aren't there always?) One is that you could not put ]
into $valid
, even if $valid
were quoted, except at the very beginning. (That's a Posix regex rule: if you want to include ]
in a character class, it needs to go at the beginning. -
can go at the beginning or the end, so if you need both ]
and -
, you need to start with ]
and end with -
, leading to the regex "I know what I'm doing" emoticon: [][-]
)
If you need direct access:
WScript.Arguments.Item(0)
WScript.Arguments.Item(1)
...
I was asked to do so without using any inbuilt function. So I wrote three functions for these tasks. Here is the code-
def string_to_list(string):
'''function takes actual string and put each word of string in a list'''
list_ = []
x = 0 #Here x tracks the starting of word while y look after the end of word.
for y in range(len(string)):
if string[y]==" ":
list_.append(string[x:y])
x = y+1
elif y==len(string)-1:
list_.append(string[x:y+1])
return list_
def list_to_reverse(list_):
'''Function takes the list of words and reverses that list'''
reversed_list = []
for element in list_[::-1]:
reversed_list.append(element)
return reversed_list
def list_to_string(list_):
'''This function takes the list and put all the elements of the list to a string with
space as a separator'''
final_string = str()
for element in list_:
final_string += str(element) + " "
return final_string
#Output
text = "I love India"
list_ = string_to_list(text)
reverse_list = list_to_reverse(list_)
final_string = list_to_string(reverse_list)
print("Input is - {}; Output is - {}".format(text, final_string))
#op= Input is - I love India; Output is - India love I
Please remember, This is one of a simpler solution. This can be optimized so try that. Thank you!
I think this should do it:
var arr = ['contains,comma', 3.14, 'contains"quote', "more'quotes"]
var item, i;
var line = [];
for (i = 0; i < arr.length; ++i) {
item = arr[i];
if (item.indexOf && (item.indexOf(',') !== -1 || item.indexOf('"') !== -1)) {
item = '"' + item.replace(/"/g, '""') + '"';
}
line.push(item);
}
document.getElementById('out').innerHTML = line.join(',');
Basically all it does is check if the string contains a comma or quote. If it does, then it doubles all the quotes, and puts quotes on the ends. Then it joins each of the parts with a comma.
Clarification:
Because of a previous phrasing in the original question, a few SO citizens have raised concerns that this answer could be misleading. Note that, in CSS3, styles cannot be applied to a parent node based on the number of children it has. However, styles can be applied to the children nodes based on the number of siblings they have.
Original answer:
Incredibly, this is now possible purely in CSS3.
/* one item */
li:first-child:nth-last-child(1) {
/* -or- li:only-child { */
width: 100%;
}
/* two items */
li:first-child:nth-last-child(2),
li:first-child:nth-last-child(2) ~ li {
width: 50%;
}
/* three items */
li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
width: 33.3333%;
}
/* four items */
li:first-child:nth-last-child(4),
li:first-child:nth-last-child(4) ~ li {
width: 25%;
}
The trick is to select the first child when it's also the nth-from-the-last child. This effectively selects based on the number of siblings.
Credit for this technique goes to André Luís (discovered) & Lea Verou (refined).
Don't you just love CSS3?
CodePen Example:
Sources:
Update 2018
Here's a simple example using Bootstrap 4 with ChartJs. Use an HTML5 Canvas element for the chart...
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="card">
<div class="card-body">
<canvas id="chLine"></canvas>
</div>
</div>
</div>
</div>
</div>
And then the appropriate JS to populate the chart...
var colors = ['#007bff','#28a745'];
var chLine = document.getElementById("chLine");
var chartData = {
labels: ["S", "M", "T", "W", "T", "F", "S"],
datasets: [{
data: [589, 445, 483, 503, 689, 692, 634],
borderColor: colors[0],
borderWidth: 4,
pointBackgroundColor: colors[0]
},
{
data: [639, 465, 493, 478, 589, 632, 674],
borderColor: colors[1],
borderWidth: 4,
pointBackgroundColor: colors[1]
}]
};
if (chLine) {
new Chart(chLine, {
type: 'line',
data: chartData,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
},
legend: {
display: false
}
}
});
}
The .join()
function is using the index
of the passed as argument dataset, so you should use set_index
or use .merge
function instead.
Please find the two examples that should work in your case:
join_df = LS_sgo.join(MSU_pi.set_index('mukey'), on='mukey', how='left')
or
join_df = df_a.merge(df_b, on='mukey', how='left')
You can use the code below to solve the problem or download demo here
Create two functions to handle each.
First, the canvas is drawn and the images are drawn on top of each other from point (0,0)
On button click
public void buttonMerge(View view) {
Bitmap bigImage = BitmapFactory.decodeResource(getResources(), R.drawable.img1);
Bitmap smallImage = BitmapFactory.decodeResource(getResources(), R.drawable.img2);
Bitmap mergedImages = createSingleImageFromMultipleImages(bigImage, smallImage);
img.setImageBitmap(mergedImages);
}
Function to create an overlay.
private Bitmap createSingleImageFromMultipleImages(Bitmap firstImage, Bitmap secondImage){
Bitmap result = Bitmap.createBitmap(firstImage.getWidth(), firstImage.getHeight(), firstImage.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(firstImage, 0f, 0f, null);
canvas.drawBitmap(secondImage, 10, 10, null);
return result;
}
Using a UI Framework would be a lot cleaner (and involve fewer components). Here is an example using wxPython:
import wx
import os
class MyForm(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Launch Scripts")
panel = wx.Panel(self, wx.ID_ANY)
sizer = wx.BoxSizer(wx.VERTICAL)
buttonA = wx.Button(panel, id=wx.ID_ANY, label="App A", name="MYSCRIPT")
buttonB = wx.Button(panel, id=wx.ID_ANY, label="App B", name="MYOtherSCRIPT")
buttonC = wx.Button(panel, id=wx.ID_ANY, label="App C", name="SomeDifferentScript")
buttons = [buttonA, buttonB, buttonC]
for button in buttons:
self.buildButtons(button, sizer)
panel.SetSizer(sizer)
def buildButtons(self, btn, sizer):
btn.Bind(wx.EVT_BUTTON, self.onButton)
sizer.Add(btn, 0, wx.ALL, 5)
def onButton(self, event):
"""
This method is fired when its corresponding button is pressed, taking the script from it's name
"""
button = event.GetEventObject()
os.system('python {}.py'.format(button.GetName()))
button_id = event.GetId()
button_by_id = self.FindWindowById(button_id)
print "The button you pressed was labeled: " + button_by_id.GetLabel()
print "The button's name is " + button_by_id.GetName()
# Run the program
if __name__ == "__main__":
app = wx.App(False)
frame = MyForm()
frame.Show()
app.MainLoop()
I haven't tested this yet, and I'm sure there are cleaner ways of launching a python script form a python script, but the idea I think will still hold. Good luck!
MultipleIE , IETester there are many similar to those.
Multiple IE supports IE3 IE4.01 IE5 IE5.5 and IE6 and "is no longer maintained and there are no plans to continue maintaining it! Thanks and good luck!".
IETester seems a better choice : IE10, IE9, IE8, IE7 IE 6 and IE5.5 on Windows 8 desktop, Windows 7, Vista and XP
If you would like to ignore case you could use the following:
String s = "yip";
String best = "yodel";
int compare = s.compareToIgnoreCase(best);
if(compare < 0){
//-1, --> s is less than best. ( s comes alphabetically first)
}
else if(compare > 0 ){
// best comes alphabetically first.
}
else{
// strings are equal.
}
First of all, I don't see the reason for having an ID that's not unique, but I guess it's an ID that connects to another table. Second there is no need for subqueries, which beats up the server. You do this in one query, like this
SELECT id,GROUP_CONCAT(name, ':', value SEPARATOR "|") FROM sample GROUP BY id
You get fast and correct results, and you can split the result by that SEPARATOR "|". I always use this separator, because it's impossible to find it inside a string, therefor it's unique. There is no problem having two A's, you identify only the value. Or you can have one more colum, with the letter, which is even better. Like this :
SELECT id,GROUP_CONCAT(DISTINCT(name)), GROUP_CONCAT(value SEPARATOR "|") FROM sample GROUP BY name
function isset(element) {
return element.length > 0;
}
Or, as a jQuery extension:
$.fn.exists = function() { return this.length > 0; };
// later ...
if ( $("#id").exists() ) {
// do something
}
You can use this function in your application to add keys to indexed array.
public static function convertIndexedArrayToAssociative($indexedArr, $keys)
{
$resArr = array();
foreach ($indexedArr as $item)
{
$tmpArr = array();
foreach ($item as $key=>$value)
{
$tmpArr[$keys[$key]] = $value;
}
$resArr[] = $tmpArr;
}
return $resArr;
}
Use the instanceof
syntax.
Like so:
Object foo = "";
if( foo instanceof String ) {
// do something String related to foo
}
timedelta
accepts minus(-) time values. so it could be simple as below
import datetime
enter = datetime.time(hour=1, minute=30)
exit = datetime.time(hour=2, minute=0)
duration = datetime.timedelta(hours=exit.hour-enter.hour, minutes=exit.minute-enter.minute)
# duration = datetime.timedelta(hours=1, minutes=-30)
result
>>> duration
datetime.timedelta(seconds=1800)
regular expression starts with number->'^[0-9]'
Pattern pattern = Pattern.compile('^[0-9]');
Matcher matcher = pattern.matcher(String);
if(matcher.find()){
System.out.println("true");
}
Using bootstrap with a little bit of customization, the following seems to work for me:
I need 3 partitions in my container and I tried this:
CSS:
.row.content {height: 100%; width:100%; position: fixed; }
.sidenav {
padding-top: 20px;
border: 1px solid #cecece;
height: 100%;
}
.midnav {
padding: 0px;
}
HTML:
<div class="container-fluid text-center">
<div class="row content">
<div class="col-md-2 sidenav text-left">Some content 1</div>
<div class="col-md-9 midnav text-left">Some content 2</div>
<div class="col-md-1 sidenav text-center">Some content 3</div>
</div>
</div>
I was using python interpolation and forgot the ending s
character:
a = dict(foo='bar')
print("What comes after foo? %(foo)" % a) # Should be %(foo)s
Watch those typos.
As with most answers, it really depends: What are you trying to achieve with your debugging? Basic development, fixing performance issues? For basic development, all the previous answers are more than adequate.
For performance testing specifically, I recommend Firebug. Being able to profile which methods are the most expensive in terms of time has been invaluable for a number of projects I have worked on. As client-side libraries become more and more robust, and more responsibility is placed client-side in general, this type of debugging and profiling will only become more useful.
Firebug Console API: http://getfirebug.com/console.html
Try writting the lambda with the same conditions as the delegate. like this:
List<AnalysisObject> analysisObjects =
analysisObjectRepository.FindAll().Where(
(x =>
(x.ID == packageId)
|| (x.Parent != null && x.Parent.ID == packageId)
|| (x.Parent != null && x.Parent.Parent != null && x.Parent.Parent.ID == packageId)
).ToList();
Boost contains cstdint.hpp header file with the types you are looking for: http://www.boost.org/doc/libs/1_36_0/boost/cstdint.hpp
I had a different cause for this error. I tried to insert a date without using quotes and received a strange error telling me I had tried to insert a date from 2003.
Although I was already using the YYYY-MM-DD format, I forgot to add quotes around the date. Even though it is a date and not a string, quotes are still required.
In my case it was most trivial solution - I just needed to run Vistual Studio as Administrator.
It's trivial thing, but i didn't see this mentioned anywhere.
Laravel raw sql – Insert query:
lets create a get link to insert data which is accessible through url . so our link name is ‘insertintodb’ and inside that function we use db class . db class helps us to interact with database . we us db class static function insert . Inside insert function we will write our PDO query to insert data in database . in below query we will insert ‘ my title ‘ and ‘my content’ as data in posts table .
put below code in your web.php file inside routes directory :
Route::get('/insertintodb',function(){
DB::insert('insert into posts(title,content) values (?,?)',['my title','my content']);
});
Now fire above insert query from browser link below :
localhost/yourprojectname/insertintodb
You can see output of above insert query by going into your database table .you will find a record with id 1 .
Laravel raw sql – Read query :
Now , lets create a get link to read data , which is accessible through url . so our link name is ‘readfromdb’. we us db class static function read . Inside read function we will write our PDO query to read data from database . in below query we will read data of id ‘1’ from posts table .
put below code in your web.php file inside routes directory :
Route::get('/readfromdb',function() {
$result = DB::select('select * from posts where id = ?', [1]);
var_dump($result);
});
now fire above read query from browser link below :
localhost/yourprojectname/readfromdb
You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.
$("button").click(function() {
var $btn = $(this);
$btn.button('loading');
// simulating a timeout
setTimeout(function () {
$btn.button('reset');
}, 1000);
});
Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.
here is how I did it in jquery:
jQuery.get('http://localhost/foo.txt', function(data) {
alert(data);
});
Ref this
SELECT * FROM product WHERE name REGEXP '[0-9]'
For further visitors:
// Executes: SELECT * FROM mytable LIMIT 10 OFFSET 20
// get([$table = ''[, $limit = NULL[, $offset = NULL]]])
$query = $this->db->get('mytable', 10, 20);
// get_where sample,
$query = $this->db->get_where('mytable', array('id' => $id), 10, 20);
// Produces: LIMIT 10
$this->db->limit(10);
// Produces: LIMIT 10 OFFSET 20
// limit($value[, $offset = 0])
$this->db->limit(10, 20);
list is mutable
Change
last_list=last_list.append(p.last_name)
to
last_list.append(p.last_name)
will work
You have more going on than you said. I ran the following expanded test from your example:
public class test {
public static void main(String[] args) {
Object[][] someArray = new Object[5][];
someArray[0] = new Object[10];
someArray[1] = null;
someArray[2] = new Object[1];
someArray[3] = null;
someArray[4] = new Object[5];
for (int i=0; i<=someArray.length-1; i++) {
if (someArray[i] != null) {
System.out.println("not null");
} else {
System.out.println("null");
}
}
}
}
and got the expected output:
$ /cygdrive/c/Program\ Files/Java/jdk1.6.0_03/bin/java -cp . test
not null
null
not null
null
not null
Are you possibly trying to check the lengths of someArray[index]?
For Visual Studio 2017
Find "References" in Solution explorer
Right click "References"
Choose "Add Reference..."
Find "Presentation.Core" list and check checkbox
Click OK
For people Googling,
The solid answer should be.
const substrings = ['connect', 'ready'];
const str = 'disconnect';
if (substrings.some(v => str === v)) {
// Will only return when the `str` is included in the `substrings`
}
Or, for Python 3:
for k,v in dict.items():
print(k, v)
I don't quote understand what you are trying to achieve, but you need an event listener. Something like:
$('#type').change(function() {
alert('Value changed to ' + $(this).attr('value'));
});
This will give you the value of the selected option tag.
If we need only one column to be numeric
yyz$b <- as.numeric(as.character(yyz$b))
But, if all the columns needs to changed to numeric
, use lapply
to loop over the columns and convert to numeric
by first converting it to character
class as the columns were factor
.
yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))
Both the columns in the OP's post are factor
because of the string "n/a"
. This could be easily avoided while reading the file using na.strings = "n/a"
in the read.table/read.csv
or if we are using data.frame
, we can have character
columns with stringsAsFactors=FALSE
(the default is stringsAsFactors=TRUE
)
Regarding the usage of apply
, it converts the dataset to matrix
and matrix
can hold only a single class. To check the class
, we need
lapply(yyz, class)
Or
sapply(yyz, class)
Or check
str(yyz)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_margin="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<SeekBar
android:id="@+id/seekBar"
android:max="100"
android:progress="50"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Notes
max
is the highest value that the seek bar can go to. The default is 100
. The minimum is 0
. The xml min
value is only available from API 26, but you can just programmatically convert the 0-100
range to whatever you need for earlier versions.progress
is the initial position of the slider dot (called a "thumb").android:rotation="270"
.public class MainActivity extends AppCompatActivity {
TextView tvProgressLabel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// set a change listener on the SeekBar
SeekBar seekBar = findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(seekBarChangeListener);
int progress = seekBar.getProgress();
tvProgressLabel = findViewById(R.id.textView);
tvProgressLabel.setText("Progress: " + progress);
}
SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// updated continuously as the user slides the thumb
tvProgressLabel.setText("Progress: " + progress);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// called when the user first touches the SeekBar
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// called after the user finishes moving the SeekBar
}
};
}
Notes
onStopTrackingTouch
.MySQL multiple instances present on Ubuntu.
step 1 : if it's listed as installed, you got it. Else you need to get it.
sudo ps -A | grep mysql
step 2 : remove the one MySQL
sudo apt-get remove mysql
sudo service mysql restart
step 3 : restart lamp
sudo /opt/lampp/lampp restart
Have you tried str = str.replace(/\W|_/g,'');
it will return a string without any character and you can specify if any especial character after the pipe bar |
to catch them as well.
var str = "1324567890abc§$)% John Doe #$@'.replace(/\W|_/g, '');
it will return str = 1324567890abcJohnDoe
or look for digits and letters and replace them for empty string (""):
var str = "1324567890abc§$)% John Doe #$@".replace(/\w|_/g, '');
it will return str = '§$)% #$@';
Try:
maxInt = -1 >>> 1
In Firefox 3.6 it's 2^31 - 1.
This one should be working on iphone etc.
<meta name="viewport" content="width=device-width, initial-scale=1 initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
It depends on the package. If the Makefile is generated by GNU autotools (./configure
) you can usually set the target location like so:
./configure --prefix=/somewhere/else/than/usr/local
If the Makefile is not generated by autotools, but distributed along with the software, simply open it up in an editor and change it. The install target directory is probably defined in a variable somewhere.
where returns ActiveRecord::Relation
Now take a look at find_by implementation:
def find_by
where(*args).take
end
As you can see find_by is the same as where but it returns only one record. This method should be used for getting 1 record and where should be used for getting all records with some conditions.
Find element with id in row using jquery
$(document).ready(function () {
$("button").click(function() {
//find content of different elements inside a row.
var nameTxt = $(this).closest('tr').find('.name').text();
var emailTxt = $(this).closest('tr').find('.email').text();
//assign above variables text1,text2 values to other elements.
$("#name").val( nameTxt );
$("#email").val( emailTxt );
});
});
A more contemporary way of doing it on a separate thread using Tasks and Kotlin
private val mExecutor: Executor = Executors.newSingleThreadExecutor()
private fun createHttpTask(u:String): Task<String> {
return Tasks.call(mExecutor, Callable<String>{
val url = URL(u)
val conn: HttpURLConnection = url.openConnection() as HttpURLConnection
conn.requestMethod = "GET"
conn.connectTimeout = 3000
conn.readTimeout = 3000
val rc = conn.responseCode
if ( rc != HttpURLConnection.HTTP_OK) {
throw java.lang.Exception("Error: ${rc}")
}
val inp: InputStream = BufferedInputStream(conn.inputStream)
val resp: String = inp.bufferedReader(UTF_8).use{ it.readText() }
return@Callable resp
})
}
and now you can use it like below in many places:
createHttpTask("https://google.com")
.addOnSuccessListener {
Log.d("HTTP", "Response: ${it}") // 'it' is a response string here
}
.addOnFailureListener {
Log.d("HTTP", "Error: ${it.message}") // 'it' is an Exception object here
}
The solution given above worked for us as well for a long time:
mvn versions:set -DnewVersion=2.50.1-SNAPSHOT
However it stopped working yesterday, and we found it due to a recent bug in a the versions-maven-plugin
Our (temporary) workaround was to change the parent/pom.xml file as follows:
--- jackrabbit/oak/trunk/oak-parent/pom.xml 2020/08/13 13:43:11 1880829
+++ jackrabbit/oak/trunk/oak-parent/pom.xml 2020/08/13 15:17:59 1880830
@@ -329,6 +329,13 @@
<artifactId>spotbugs-maven-plugin</artifactId>
<version>3.1.11</version>
</plugin>
+
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>versions-maven-plugin</artifactId>
+ <version>2.7</version>
+ </plugin>
+
Perhaps this will help you out - I've done something similar using jquery, except I'm loading up an unknown number of ckeditor objects. It took my a while to stumble onto this - it's not clear in the documentation.
function loadEditors() {
var $editors = $("textarea.ckeditor");
if ($editors.length) {
$editors.each(function() {
var editorID = $(this).attr("id");
var instance = CKEDITOR.instances[editorID];
if (instance) { instance.destroy(true); }
CKEDITOR.replace(editorID);
});
}
}
And here is what I run to get the content from the editors:
var $editors = $("textarea.ckeditor");
if ($editors.length) {
$editors.each(function() {
var instance = CKEDITOR.instances[$(this).attr("id")];
if (instance) { $(this).val(instance.getData()); }
});
}
UPDATE: I've changed my answer to use the correct method - which is .destroy(). .remove() is meant to be internal, and was improperly documented at one point.
Using wxPython on Mac to get the correct DPI as follows:
from wx import ScreenDC
from wx import Size
size: Size = ScreenDC().GetPPI()
print(f'x-DPI: {size.GetWidth()} y-DPI: {size.GetHeight()}')
This yields:
x-DPI: 72 y-DPI: 72
Thus, the formula is:
points: int = (pixelNumber * 72) // 72
If you are using Angular, you can use the angular.isArray() function
var myArray = [];
angular.isArray(myArray); // returns true
var myObj = {};
angular.isArray(myObj); //returns false
From the docs:
To extract the files from a jar file, use
x
, as in:C:\Java> jar xf myFile.jar
To extract only certain files from a jar file, supply their filenames:
C:\Java> jar xf myFile.jar foo bar
The folder where jar
is probably isn't C:\Java
for you, on my Windows partition it's:
C:\Program Files (x86)\Java\jdk[some_version_here]\bin
Unless the location of jar
is in your path environment variable, you'll have to specify the full path/run the program from inside the folder.
EDIT: Here's another article, specifically focussed on extracting JARs: http://docs.oracle.com/javase/tutorial/deployment/jar/unpack.html
@Frode F. gave the right answer.
By the Way Invoke-WebRequest
also prints you the 200 OK
and a lot of bla, bla, bla... which might be useful but I still prefer the Invoke-RestMethod
which is lighter.
Also, keep in mind that you need to use | ConvertTo-Json
for the body only, not the header:
$body = @{
"UserSessionId"="12345678"
"OptionalEmail"="[email protected]"
} | ConvertTo-Json
$header = @{
"Accept"="application/json"
"connectapitoken"="97fe6ab5b1a640909551e36a071ce9ed"
"Content-Type"="application/json"
}
Invoke-RestMethod -Uri "http://MyServer/WSVistaWebClient/RESTService.svc/member/search" -Method 'Post' -Body $body -Headers $header | ConvertTo-HTML
and you can then append a | ConvertTo-HTML
at the end of the request for better readability
For example:
var flt = '5.99';
var nt = '6';
var rflt = parseFloat(flt);
var rnt = parseInt(nt);
Instead of LabelEncoder
we can use OrdinalEncoder
from scikit learn, which allows multi-column encoding.
Encode categorical features as an integer array. The input to this transformer should be an array-like of integers or strings, denoting the values taken on by categorical (discrete) features. The features are converted to ordinal integers. This results in a single column of integers (0 to n_categories - 1) per feature.
>>> from sklearn.preprocessing import OrdinalEncoder
>>> enc = OrdinalEncoder()
>>> X = [['Male', 1], ['Female', 3], ['Female', 2]]
>>> enc.fit(X)
OrdinalEncoder()
>>> enc.categories_
[array(['Female', 'Male'], dtype=object), array([1, 2, 3], dtype=object)]
>>> enc.transform([['Female', 3], ['Male', 1]])
array([[0., 2.],
[1., 0.]])
Both the description and example were copied from its documentation page which you can find here:
Custom made :) you can use dropdown hori/vertical offset properties to position the list currently, also try android:spinnerMode="dialog" it is cooler.
Layout
<LinearLayout
android:layout_marginBottom="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<AutoCompleteTextView
android:layout_weight="1"
android:id="@+id/edit_ip"
android:text="default value"
android:layout_width="0dp"
android:layout_height= "wrap_content"/>
<Spinner
android:layout_marginRight="20dp"
android:layout_width="30dp"
android:layout_height="50dp"
android:id="@+id/spinner_ip"
android:spinnerMode="dropdown"
android:entries="@array/myarray"/>
</LinearLayout>
Java
//set auto complete
final AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.edit_ip);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, getResources().getStringArray(R.array.myarray));
textView.setAdapter(adapter);
//set spinner
final Spinner spinner = (Spinner) findViewById(R.id.spinner_ip);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
textView.setText(spinner.getSelectedItem().toString());
textView.dismissDropDown();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
textView.setText(spinner.getSelectedItem().toString());
textView.dismissDropDown();
}
});
res/values/string
<string-array name="myarray">
<item>value1</item>
<item>value2</item>
</string-array>
Was that useful??
Here's a javasript tool that will convert JSON to XML and vice versa, which should enhance its readability. You could then create a style sheet to color it or do a complete transform to HTML.
http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html
The pointsize command scales the size of points, but does not affect the size of dots.
In other words, plot ... with points ps 2
will generate points of twice the normal size, but for plot ... with dots ps 2
the "ps 2
" part is ignored.
You could use circular points (pt 7
), which look just like dots.
Seems like you expected the query to return running totals, but it must have given you the same values for both partitions of AccountID
.
To obtain running totals with SUM() OVER ()
, you need to add an ORDER BY
sub-clause after PARTITION BY …
, like this:
SUM(Quantity) OVER (PARTITION BY AccountID ORDER BY ID)
But remember, not all database systems support ORDER BY
in the OVER
clause of a window aggregate function. (For instance, SQL Server didn't support it until the latest version, SQL Server 2012.)
Use for of loop instead which is part of ES2015 release. Unlike forEach, we can use return, break and continue. See https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/
let arr = [1,2,3,4,5];
for (let ele of arr) {
if (ele > 3) break;
console.log(ele);
}
Another issue that can cause this behaviour is when you have a setup with 2 possible %HOME%-locations.
I'm using a PC where some of my documents are stored locally, and some of them are stored on a network drive. Some applications think C:\Users\<MyUserName>\
is my %home%
, others think that U:\
is the home.
Turns out ssh-keygen
put my private key under C:\users\<MyUserName>\
, and that ssh -T
and ssh -v
also look there.
So everything seems to work fine, except that git clone
, git push
and others look for a key in U:\
.
Which fails, so I get the aforementioned error.
It took me an hour to find out, but in the end the solution was simple: I copied everything from C:\Users\<MyUserName>\.ssh
to U:\.ssh
According to this post by Stephen Cleary, Task.Factory.StartNew() is dangerous:
I see a lot of code on blogs and in SO questions that use Task.Factory.StartNew to spin up work on a background thread. Stephen Toub has an excellent blog article that explains why Task.Run is better than Task.Factory.StartNew, but I think a lot of people just haven’t read it (or don’t understand it). So, I’ve taken the same arguments, added some more forceful language, and we’ll see how this goes. :) StartNew does offer many more options than Task.Run, but it is quite dangerous, as we’ll see. You should prefer Task.Run over Task.Factory.StartNew in async code.
Here are the actual reasons:
- Does not understand async delegates. This is actually the same as point 1 in the reasons why you would want to use StartNew. The problem is that when you pass an async delegate to StartNew, it’s natural to assume that the returned task represents that delegate. However, since StartNew does not understand async delegates, what that task actually represents is just the beginning of that delegate. This is one of the first pitfalls that coders encounter when using StartNew in async code.
- Confusing default scheduler. OK, trick question time: in the code below, what thread does the method “A” run on?
Task.Factory.StartNew(A);
private static void A() { }
Well, you know it’s a trick question, eh? If you answered “a thread pool thread”, I’m sorry, but that’s not correct. “A” will run on whatever TaskScheduler is currently executing!
So that means it could potentially run on the UI thread if an operation completes and it marshals back to the UI thread due to a continuation as Stephen Cleary explains more fully in his post.
In my case, I was trying to run tasks in the background when loading a datagrid for a view while also displaying a busy animation. The busy animation didn't display when using Task.Factory.StartNew()
but the animation displayed properly when I switched to Task.Run()
.
For details, please see https://blog.stephencleary.com/2013/08/startnew-is-dangerous.html
When I tried '.* in windows (Notepad ++) it would match everything after first ' until end of last line.
To capture everything until end of that line I typed the following:
'.*?\n
This would only capture everything from ' until end of that line.
COUNTIF
function can count cell which specific condition
where as COUNTA
will count all cell which contain any value
Example: Function in A7
: =COUNTA(A1:A6)
Range:
A1| a
A2| b
A3| banana
A4| 42
A5|
A6|
A7| 4 (result)
I created a custom function.
def exists(var):
return var in globals()
Then the call the function like follows replacing variable_name
with the variable you want to check:
exists("variable_name")
Will return True
or False
in textbox write this code onkeypress="return isNumberKey(event)"
and function for this is just below.
<script type="text/javascript">
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
For those of you not about that space bar life (- _ - )( - _ -)
Keybinding for ? Tab isn't set to anything so you have to do it manually
Navigate to Preferences/Environment/Keybindings and search for "tab"
Click on Edit Binding at the bottom and press the tab key.
Press "Apply" then "Ok"
Key bound!
Although many of these answers will work, this shows a straightforward example when using CommandField in GridView using the OnClientClick property.
ASPX:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound"... >
<Columns>
<!-- Data columns here -->
<asp:CommandField ButtonType="Button" ShowEditButton="true" ShowDeleteButton="true" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
ASPX.CS:
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex)
{
(e.Row.Cells[2].Controls[2] as Button).OnClientClick = "return confirm('Do you want to delete this row?');";
}
}
Bruno's answer was the correct one in the end. This is most easily controlled by the https.protocols
system property. This is how you are able to control what the factory method returns. Set to "TLSv1" for example.
You could just use this:
function createObject(propName, propValue){
this[propName] = propValue;
}
var myObj1 = new createObject('string1','string2');
Anything you pass as the first parameter will be the property name, and the second parameter is the property value.
Have you tried using Timestamp.valueOf(String)
? It looks like it should do almost exactly what you want - you just need to change the separator between your date and time to a space, and the ones between hours and minutes, and minutes and hours, to colons:
import java.sql.*;
public class Test {
public static void main(String[] args) {
String text = "2011-10-02 18:48:05.123456";
Timestamp ts = Timestamp.valueOf(text);
System.out.println(ts.getNanos());
}
}
Assuming you've already validated the string length, this will convert to the right format:
static String convertSeparators(String input) {
char[] chars = input.toCharArray();
chars[10] = ' ';
chars[13] = ':';
chars[16] = ':';
return new String(chars);
}
Alternatively, parse down to milliseconds by taking a substring and using Joda Time or SimpleDateFormat
(I vastly prefer Joda Time, but your mileage may vary). Then take the remainder of the string as another string and parse it with Integer.parseInt
. You can then combine the values pretty easily:
Date date = parseDateFromFirstPart();
int micros = parseJustLastThreeDigits();
Timestamp ts = new Timestamp(date.getTime());
ts.setNanos(ts.getNanos() + micros * 1000);
Here, I have coded using single loop. We are getting mode from a[j-1] because localCount was recently updated when j was j-1. Also N is size of the array & counts are initialized to 0.
//After sorting the array
i = 0,j=0;
while(i!=N && j!=N){
if(ar[i] == ar[j]){
localCount++;
j++;
}
else{
i++;
localCount = 0;
}
if(localCount > globalCount){
globalCount = localCount;
mode = ar[j-1];
}
}
You must write onActivityResult() in your FirstActivity.Java as follows
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
fragment.onActivityResult(requestCode, resultCode, data);
}
}
This will trigger onActivityResult method of fragments on FirstActivity.java
top, parent, opener (as well as window, self, and iframe) are all window objects.
window.opener
-> returns the window that opens or launches the current popup window.window.top
-> returns the topmost window, if you're using frames, this is the frameset window, if not using frames, this is the same as window or self.window.parent
-> returns the parent frame of the current frame or iframe. The parent frame may be the frameset window or another frame if you have nested frames. If not using frames, parent is the same as the current window or selfif you omit the format
attribute from the attr
element, you can use it to reference a class from XML layouts.
Refactor > Rename
worksFind Usages
worksdon't specify a format
attribute in .../src/main/res/values/attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyCustomView">
....
<attr name="give_me_a_class"/>
....
</declare-styleable>
</resources>
use it in some layout file .../src/main/res/layout/activity__main_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<SomeLayout
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- make sure to use $ dollar signs for nested classes -->
<MyCustomView
app:give_me_a_class="class.type.name.Outer$Nested/>
<MyCustomView
app:give_me_a_class="class.type.name.AnotherClass/>
</SomeLayout>
parse the class in your view initialization code .../src/main/java/.../MyCustomView.kt
class MyCustomView(
context:Context,
attrs:AttributeSet)
:View(context,attrs)
{
// parse XML attributes
....
private val giveMeAClass:SomeCustomInterface
init
{
context.theme.obtainStyledAttributes(attrs,R.styleable.ColorPreference,0,0).apply()
{
try
{
// very important to use the class loader from the passed-in context
giveMeAClass = context::class.java.classLoader!!
.loadClass(getString(R.styleable.MyCustomView_give_me_a_class))
.newInstance() // instantiate using 0-args constructor
.let {it as SomeCustomInterface}
}
finally
{
recycle()
}
}
}
There should be a way to solve this pretty easily with external config sections and an extra deployment step that drops a deployment specific external .config file into a known location. We typically use this solution to handle the different server configurations for our different deployment environments (Staging, QA, production, etc) with our "dev box" being the default if no special copy occurs.
Hotswap Agent is an extension to DCEVM which supports many Java frameworks (reload Spring bean definition, Hibernate entity mapping, logger level setup, ...).
There is also lot of documentation how to setup DCEVM and compiled binaries for Java 1.7.
For an array of objects you can create an extension from Sequence.
extension Sequence {
func limit(_ max: Int) -> [Element] {
return self.enumerated()
.filter { $0.offset < max }
.map { $0.element }
}
}
Usage:
struct Apple {}
let apples: [Apple] = [Apple(), Apple(), Apple()]
let limitTwoApples = apples.limit(2)
// limitTwoApples: [Apple(), Apple()]
This can be done using the unique function in ufp.path module.
import ufp.path
ufp.path.unique('./test.ext')
if current path exists 'test.ext' file. ufp.path.unique function return './test (d1).ext'.
Yes, that's usually happens after 1440s (24 minutes)
You can write the following:
Path.Combine(Path.GetParentDirectory(GetType(MyClass).Assembly.Location), "Images\image.jpg")
Select the text you want to Block-comment/Block-uncomment.
To comment, Ctrl + 6
To uncomment, Ctrl + 8
Here's how do to it with the SSDB catalog that was introduced with SQL Server 2012...
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.IntegrationServices;
public List<string> ExecutePackage(string folder, string project, string package)
{
// Connection to the database server where the packages are located
SqlConnection ssisConnection = new SqlConnection(@"Data Source=.\SQL2012;Initial Catalog=master;Integrated Security=SSPI;");
// SSIS server object with connection
IntegrationServices ssisServer = new IntegrationServices(ssisConnection);
// The reference to the package which you want to execute
PackageInfo ssisPackage = ssisServer.Catalogs["SSISDB"].Folders[folder].Projects[project].Packages[package];
// Add a parameter collection for 'system' parameters (ObjectType = 50), package parameters (ObjectType = 30) and project parameters (ObjectType = 20)
Collection<PackageInfo.ExecutionValueParameterSet> executionParameter = new Collection<PackageInfo.ExecutionValueParameterSet>();
// Add execution parameter (value) to override the default asynchronized execution. If you leave this out the package is executed asynchronized
executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 50, ParameterName = "SYNCHRONIZED", ParameterValue = 1 });
// Add execution parameter (value) to override the default logging level (0=None, 1=Basic, 2=Performance, 3=Verbose)
executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 50, ParameterName = "LOGGING_LEVEL", ParameterValue = 3 });
// Add a project parameter (value) to fill a project parameter
executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 20, ParameterName = "MyProjectParameter", ParameterValue = "some value" });
// Add a project package (value) to fill a package parameter
executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 30, ParameterName = "MyPackageParameter", ParameterValue = "some value" });
// Get the identifier of the execution to get the log
long executionIdentifier = ssisPackage.Execute(false, null, executionParameter);
// Loop through the log and do something with it like adding to a list
var messages = new List<string>();
foreach (OperationMessage message in ssisServer.Catalogs["SSISDB"].Executions[executionIdentifier].Messages)
{
messages.Add(message.MessageType + ": " + message.Message);
}
return messages;
}
The code is a slight adaptation of http://social.technet.microsoft.com/wiki/contents/articles/21978.execute-ssis-2012-package-with-parameters-via-net.aspx?CommentPosted=true#commentmessage
There is also a similar article at http://domwritescode.com/2014/05/15/project-deployment-model-changes/
Java doesn't support the Net Framework. Java has its own Framework. Visual Studio used to support at one time J++ and J#, which were meant for Java developers who wanted to develop with the .Net, but since that has become extinct.
Most people when they want to develop java, they just go ahead and start with Netbeans, Eclipse, or something equivalent. They don't go around asking on sites like this if they could develop Java stuff in Visual Studio.
In my honest opinion, Java would not do very well in Visual Studio. Oracle and Microsoft are two separate entities and they need to remain that way. The only mix of Oracle and Microsoft I want to see is Java for Windows and Java development tools for Windows. I do not want to see Java in Visual Studio. It would get too confusing with C# lingering around the corner.
You may change the pg_hba.conf and then reload the postgresql. something in the pg_hba.conf may be like below:
# "local" is for Unix domain socket connections only
local all all trust
# IPv4 local connections:
host all all 127.0.0.1/32 trust
then you change your user to postgresql, you may login successfully.
su postgresql
If you'd like to capture all monitors, you can use the following code:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] screens = ge.getScreenDevices();
Rectangle allScreenBounds = new Rectangle();
for (GraphicsDevice screen : screens) {
Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();
allScreenBounds.width += screenBounds.width;
allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height);
}
Robot robot = new Robot();
BufferedImage screenShot = robot.createScreenCapture(allScreenBounds);
import requests
image_file_descriptor = open('test.jpg', 'rb')
# Requests makes it simple to upload Multipart-encoded files
files = {'media': image_file_descriptor}
url = '...'
requests.post(url, files=files)
image_file_descriptor.close()
Don't forget to close the descriptor, it prevents bugs: Is explicitly closing files important?
$('#multiselect1').on('change', function(){
var selected = $(this).find("option:selected");
var arrSelected = [];
selected.each(function(){
arrSelected.push($(this).val());
});
});
Check this.
https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
(Use java.util.Objects.equals
because HashMap can contain null
)
Using JDK8+
/**
* Find any key matching a value.
*
* @param value The value to be matched. Can be null.
* @return Any key matching the value in the team.
*/
private Optional<String> findKey(Integer value){
return team1
.entrySet()
.stream()
.filter(e -> Objects.equals(e.getValue(), value))
.map(Map.Entry::getKey)
.findAny();
}
/**
* Find all keys matching a value.
*
* @param value The value to be matched. Can be null.
* @return all keys matching the value in the team.
*/
private List<String> findKeys(Integer value){
return team1
.entrySet()
.stream()
.filter(e -> Objects.equals(e.getValue(), value))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
More "generic" and as safe as possible
/**
* Find any key matching the value, in the given map.
*
* @param mapOrNull Any map, null is considered a valid value.
* @param value The value to be searched.
* @param <K> Type of the key.
* @param <T> Type of the value.
* @return An optional containing a key, if found.
*/
public static <K, T> Optional<K> findKey(Map<K, T> mapOrNull, T value) {
return Optional.ofNullable(mapOrNull).flatMap(map -> map.entrySet()
.stream()
.filter(e -> Objects.equals(e.getValue(), value))
.map(Map.Entry::getKey)
.findAny());
}
Or if you are on JDK7.
private String findKey(Integer value){
for(String key : team1.keySet()){
if(Objects.equals(team1.get(key), value)){
return key; //return the first found
}
}
return null;
}
private List<String> findKeys(Integer value){
List<String> keys = new ArrayList<String>();
for(String key : team1.keySet()){
if(Objects.equals(team1.get(key), value)){
keys.add(key);
}
}
return keys;
}
if (yourObject instanceof yourClassName)
will evaluate to false
if yourObject
is null
.
try putting a delay on the last color fade.
$("p#44.test").delay(3000).css("background-color","red");
What are valid values for the id attribute in HTML?
ID's cannot start with digits!!!
Documented couple of design issues with this in a comment above. Short story, in Oracle, you need to limit the results manually when you have large tables and/or tables with same column names (and you don't want to explicit type them all out and rename them all). Easy solution is to figure out your breakpoint and limit that in your query. Or you could also do this in the inner query if you don't have the conflicting column names constraint. E.g.
WHERE m_api_log.created_date BETWEEN TO_DATE('10/23/2015 05:00', 'MM/DD/YYYY HH24:MI')
AND TO_DATE('10/30/2015 23:59', 'MM/DD/YYYY HH24:MI')
will cut down the results substantially. Then you can ORDER BY or even do the outer query to limit rows.
Also, I think TOAD has a feature to limit rows; but, not sure that does limiting within the actual query on Oracle. Not sure.
as far as we want to send all the form input fields which have name attribute, you can do this for all forms, regardless of the field names:
First Solution
function submitForm(form){
var url = form.attr("action");
var formData = {};
$(form).find("input[name]").each(function (index, node) {
formData[node.name] = node.value;
});
$.post(url, formData).done(function (data) {
alert(data);
});
}
Second Solution: in this solution you can create an array of input values:
function submitForm(form){
var url = form.attr("action");
var formData = $(form).serializeArray();
$.post(url, formData).done(function (data) {
alert(data);
});
}
To get the specific tag code try to create a new branch add get the tag code in it.
I have done it by command : $git checkout -b newBranchName tagName
maps.google.com has a navigation service which can provide you route information in KML format.
To get kml file we need to form url with start and destination locations:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon) {// connect to map web service
StringBuffer urlString = new StringBuffer();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");// from
urlString.append(Double.toString(fromLat));
urlString.append(",");
urlString.append(Double.toString(fromLon));
urlString.append("&daddr=");// to
urlString.append(Double.toString(toLat));
urlString.append(",");
urlString.append(Double.toString(toLon));
urlString.append("&ie=UTF8&0&om=0&output=kml");
return urlString.toString();
}
Next you will need to parse xml (implemented with SAXParser) and fill data structures:
public class Point {
String mName;
String mDescription;
String mIconUrl;
double mLatitude;
double mLongitude;
}
public class Road {
public String mName;
public String mDescription;
public int mColor;
public int mWidth;
public double[][] mRoute = new double[][] {};
public Point[] mPoints = new Point[] {};
}
Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon)
then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:
public static Road getRoute(InputStream is)
Full source code RoadProvider.java
class MapPathScreen extends MainScreen {
MapControl map;
Road mRoad = new Road();
public MapPathScreen() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
map = new MapControl();
add(new LabelField(mRoad.mName));
add(new LabelField(mRoad.mDescription));
add(map);
}
protected void onUiEngineAttached(boolean attached) {
super.onUiEngineAttached(attached);
if (attached) {
map.drawPath(mRoad);
}
}
private InputStream getConnection(String url) {
HttpConnection urlConnection = null;
InputStream is = null;
try {
urlConnection = (HttpConnection) Connector.open(url);
urlConnection.setRequestMethod("GET");
is = urlConnection.openInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
}
See full code on J2MEMapRouteBlackBerryEx on Google Code
public class MapRouteActivity extends MapActivity {
LinearLayout linearLayout;
MapView mapView;
private Road mRoad;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
new Thread() {
@Override
public void run() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider
.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
mHandler.sendEmptyMessage(0);
}
}.start();
}
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
TextView textView = (TextView) findViewById(R.id.description);
textView.setText(mRoad.mName + " " + mRoad.mDescription);
MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
};
};
private InputStream getConnection(String url) {
InputStream is = null;
try {
URLConnection conn = new URL(url).openConnection();
is = conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
}
See full code on J2MEMapRouteAndroidEx on Google Code
In Windows 10 while installing Android SDK, by default latest SDK gets installed.
Platform List is part of Android SDK and the best way to find the location is to open SDK manager and get the path.
It will be available at:
Android SDK Location: C:\Users\<User Name>\AppData\Local\Android\sdk\platform-tools\
In SDK Manager, SDK path can be found by following the below
Appearance & Behaviour --> System Settings --> Android SDK
You can get the path where SDK is installed and can edit the location as well.
Using Ramda:
import {addIndex, map} from 'ramda';
const list = [ 'h', 'e', 'l', 'l', 'o'];
const mapIndexed = addIndex(map);
mapIndexed((currElement, index) => {
console.log("The current iteration is: " + index);
console.log("The current element is: " + currElement);
console.log("\n");
return 'X';
}, list);
data = File.read("/path/to/file")
You can put the textboxes inside a grid to do percentage values on the rows or columns of the grid and let the textboxes auto-fill to their parent cells (as they will by default). Example:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="3*" />
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" />
<TextBox Grid.Column="1" />
</Grid>
This will make #1 2/5 of the width, and #2 3/5.
You need to use javascript:
<BODY onLoad="document.getElementById('myButton').focus();">
@Ben notes that you should not add event handlers like this. While that is another question, he recommends that you use this function:
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
And then put a call to addLoadEvent on your page and reference a function the sets the focus to you desired textbox.
If you want to fill NaN for a specific column you can use loc:
d1 = {"Col1" : ['A', 'B', 'C'],
"fruits": ['Avocado', 'Banana', 'NaN']}
d1= pd.DataFrame(d1)
output:
Col1 fruits
0 A Avocado
1 B Banana
2 C NaN
d1.loc[ d1.Col1=='C', 'fruits' ] = 'Carrot'
output:
Col1 fruits
0 A Avocado
1 B Banana
2 C Carrot
To extend vsync's code further to have the ability to return the timeEnd as a value in NodeJS use this little piece of code.
console.timeEndValue = function(label) { // Add console.timeEndValue, to add a return value
var time = this._times[label];
if (!time) {
throw new Error('No such label: ' + label);
}
var duration = Date.now() - time;
return duration;
};
Now use the code like so:
console.time('someFunction timer');
someFunction();
var executionTime = console.timeEndValue('someFunction timer');
console.log("The execution time is " + executionTime);
This gives you more possibilities. You can store the execution time to be used for more purposes like using it in equations, or stored in a database, sent to a remote client over websockets, served on a webpage, etc.
# Hide grid lines
ax.grid(False)
# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
Note, you need matplotlib>=1.2 for set_zticks()
to work.
Here is a summary of my understanding after reading what others have posted:
Important!
Base64 encoding is not meant to provide security
Base64 encoding is not meant to compress data
Why do we use Base64
Base64 is a text representation of data that consists of only 64 characters which are the alphanumeric characters (lowercase and uppercase), +, / and =. These 64 characters are considered ‘safe’, that is, they can not be misinterpreted by legacy computers and programs unlike characters such as <, > \n and many others.
You have no need to put for loop to see the data into the array, you can simply do in following manner
<?php
echo "<pre>";
print_r($results);
echo "</pre>";
?>
When we write VBA code it is often desired to have the VBA Macro code not visible to end-users. This is to protect your intellectual property and/or stop users messing about with your code. Just be aware that Excel's protection ability is far from what would be considered secure. There are also many VBA Password Recovery [tools] for sale on the www.
To protect your code, open the Excel Workbook and go to Tools>Macro>Visual Basic Editor (Alt+F11). Now, from within the VBE go to Tools>VBAProject Properties and then click the Protection page tab and then check "Lock project from viewing" and then enter your password and again to confirm it. After doing this you must save, close & reopen the Workbook for the protection to take effect.
(Emphasis mine)
Seems like your best bet. It won't stop people determined to steal your code but it's enough to stop casual pirates.
Remember, even if you were able to distribute a compiled copy of your code there'd be nothing to stop people decompiling it.
concat()
function because this function only applies to a string, not on a integer. but we can concatenate a string to a number(integer) using + operator.<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<p>The concat() method joins two or more strings</p>_x000D_
_x000D_
_x000D_
<p id="demo"></p>_x000D_
<p id="demo1"></p>_x000D_
_x000D_
<script>_x000D_
var text1 = 4;_x000D_
var text2 = "World!";_x000D_
document.getElementById("demo").innerHTML = text1 + text2;_x000D_
//Below Line can't produce result_x000D_
document.getElementById("demo1").innerHTML = text1.concat(text2);_x000D_
</script>_x000D_
<p><strong>The Concat() method can't concatenate a string with a integer </strong></p>_x000D_
</body>_x000D_
</html>
_x000D_
INT(10) does not mean a 10-digit number, it means an integer with a display width of 10 digits. The maximum value for an INT in MySQL is 2147483647 (or 4294967295 if unsigned).
You can use a BIGINT instead of INT to store it as a numeric. Using BIGINT will save you 3 bytes per row over VARCHAR(10).
To Store "Country + area + number separately". You can try using a VARCHAR(20), this allows you the ability to store international phone numbers properly, should that need arise.
To get the actual access_token
, you can also do pro grammatically via the following PHP code:
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
));
// Get User ID
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
$access_token = $facebook->getAccessToken();
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
With modern C++ compilers you can use sanitizers to track.
Sample example :
My program:
$cat d_free.cxx
#include<iostream>
using namespace std;
int main()
{
int * i = new int();
delete i;
//i = NULL;
delete i;
}
Compile with address sanitizers :
# g++-7.1 d_free.cxx -Wall -Werror -fsanitize=address -g
Execute :
# ./a.out
=================================================================
==4836==ERROR: AddressSanitizer: attempting double-free on 0x602000000010 in thread T0:
#0 0x7f35b2d7b3c8 in operator delete(void*, unsigned long) /media/sf_shared/gcc-7.1.0/libsanitizer/asan/asan_new_delete.cc:140
#1 0x400b2c in main /media/sf_shared/jkr/cpp/d_free/d_free.cxx:11
#2 0x7f35b2050c04 in __libc_start_main (/lib64/libc.so.6+0x21c04)
#3 0x400a08 (/media/sf_shared/jkr/cpp/d_free/a.out+0x400a08)
0x602000000010 is located 0 bytes inside of 4-byte region [0x602000000010,0x602000000014)
freed by thread T0 here:
#0 0x7f35b2d7b3c8 in operator delete(void*, unsigned long) /media/sf_shared/gcc-7.1.0/libsanitizer/asan/asan_new_delete.cc:140
#1 0x400b1b in main /media/sf_shared/jkr/cpp/d_free/d_free.cxx:9
#2 0x7f35b2050c04 in __libc_start_main (/lib64/libc.so.6+0x21c04)
previously allocated by thread T0 here:
#0 0x7f35b2d7a040 in operator new(unsigned long) /media/sf_shared/gcc-7.1.0/libsanitizer/asan/asan_new_delete.cc:80
#1 0x400ac9 in main /media/sf_shared/jkr/cpp/d_free/d_free.cxx:8
#2 0x7f35b2050c04 in __libc_start_main (/lib64/libc.so.6+0x21c04)
SUMMARY: AddressSanitizer: double-free /media/sf_shared/gcc-7.1.0/libsanitizer/asan/asan_new_delete.cc:140 in operator delete(void*, unsigned long)
==4836==ABORTING
To learn more about sanitizers you can check this or this or any modern c++ compilers (e.g. gcc, clang etc.) documentations.
We have to differentiate here instead of blindly following general advice for specific cases.
Note that the following ignores the issue of containers of objects and what to do in the face of multiple d'tors of objects inside containers. (And it can be ignored partially, as some objects are just no good fit to put into a container.)
The whole problem becomes easier to think about when we split classes in two types. A class dtor can have two different responsibilities:
If we view the question this way, then I think that it can be argued that (R) semantics should never cause an exception from a dtor as there is a) nothing we can do about it and b) many free-resource operations do not even provide for error checking, e.g. void
free(void* p);
.
Objects with (C) semantics, like a file object that needs to successfully flush it's data or a ("scope guarded") database connection that does a commit in the dtor are of a different kind: We can do something about the error (on the application level) and we really should not continue as if nothing happened.
If we follow the RAII route and allow for objects that have (C) semantics in their d'tors I think we then also have to allow for the odd case where such d'tors can throw. It follows that you should not put such objects into containers and it also follows that the program can still terminate()
if a commit-dtor throws while another exception is active.
With regard to error handling (Commit / Rollback semantics) and exceptions, there is a good talk by one Andrei Alexandrescu: Error Handling in C++ / Declarative Control Flow (held at NDC 2014)
In the details, he explains how the Folly library implements an UncaughtExceptionCounter
for their ScopeGuard
tooling.
(I should note that others also had similar ideas.)
While the talk doesn't focus on throwing from a d'tor, it shows a tool that can be used today to get rid of the problems with when to throw from a d'tor.
In the future, there may be a std feature for this, see N3614, and a discussion about it.
Upd '17: The C++17 std feature for this is std::uncaught_exceptions
afaikt. I'll quickly quote the cppref article:
Notes
An example where
int
-returninguncaught_exceptions
is used is ... ... first creates a guard object and records the number of uncaught exceptions in its constructor. The output is performed by the guard object's destructor unless foo() throws (in which case the number of uncaught exceptions in the destructor is greater than what the constructor observed)
You're returning a tuple
. Index it.
obj=list_benefits()
print obj[0] + " is a benefit of functions!"
print obj[1] + " is a benefit of functions!"
print obj[2] + " is a benefit of functions!"
I see this question is already answered, but wanted to offer an alternative in case someone else finds this later.
Depending on the required delimiter, it is possible to do this without writing any code. The original question does not give details on the desired output type but here is an alternative:
The easiest option is to save the file as a "Formatted Text (Space Delimited)" type. The VBA code line would look similar to this:
ActiveWorkbook.SaveAs FileName:=myFileName, FileFormat:=xlTextPrinter, CreateBackup:=False
In Excel 2007, this will annoyingly put a .prn file extension on the end of the filename, but it can be changed to .txt by renaming manually.
In Excel 2010, you can specify any file extension you want in the Save As dialog.
One important thing to note: the number of delimiters used in the text file is related to the width of the Excel column.
Observe:
Becomes:
There is an Class called ExpectedConditions
:
By loc = ...
Boolean notPresent = ExpectedConditions.not(ExpectedConditions.presenceOfElementLocated(loc)).apply(getDriver());
Assert.assertTrue(notPresent);