This post contains 2 examples. I like the 2nd one:
Sub unique()
Dim arr As New Collection, a
Dim aFirstArray() As Variant
Dim i As Long
aFirstArray() = Array("Banana", "Apple", "Orange", "Tomato", "Apple", _
"Lemon", "Lime", "Lime", "Apple")
On Error Resume Next
For Each a In aFirstArray
arr.Add a, a
Next
On Error Goto 0 ' added to original example by PEH
For i = 1 To arr.Count
Cells(i, 1) = arr(i)
Next
End Sub
Borrowing, slightly enhancing and simplifying from this Blog post the following simple SQL statement seems to do the job quite well:
SELECT DISTINCT (:val) "Search Value", TABLE_NAME "Table", COLUMN_NAME "Column"
FROM cols,
TABLE (XMLSEQUENCE (DBMS_XMLGEN.GETXMLTYPE(
'SELECT "' || COLUMN_NAME || '" FROM "' || TABLE_NAME || '" WHERE UPPER("'
|| COLUMN_NAME || '") LIKE UPPER(''%' || :val || '%'')' ).EXTRACT ('ROWSET/ROW/*')))
ORDER BY "Table";
Killing the Word process outright is possible (see some of the other replies), but outright rude and dangerous: what if the user has important unsaved changes in an open document? Not to mention the stale temporary files this will leave behind...
This is probably as far as you can go in this regard (VB.NET):
Dim proc = Process.GetProcessesByName("winword")
For i As Integer = 0 To proc.Count - 1
proc(i).CloseMainWindow()
Next i
This will close all open Word windows in an orderly fashion (prompting the user to save his/her work if applicable). Of course, the user can always click 'Cancel' in this scenario, so you should be able to handle this case as well (preferably by putting up a "please close all Word instances, otherwise we can't continue" dialog...)
Policykit is a system daemon and policykit authentication agent is used to verify identity of the user before executing actions. The messages logged in /var/log/secure
show that an authentication agent is registered when user logs in and it gets unregistered when user logs out. These messages are harmless and can be safely ignored.
I had the same problem. In the end it turned out that my private key did not allow codesign to access it. One can see this in the info dialog in keychain application.
Try using fake sendmail to send emails in a WAMP enviroment.
I created a small working "migration file generator". It creates files which are working perfectly fine using sequelize db:migrate
- even with foreign keys!
You can find it here: https://gist.github.com/manuelbieh/ae3b028286db10770c81
I tested it in an application with 12 different models covering:
STRING, TEXT, ENUM, INTEGER, BOOLEAN, FLOAT as DataTypes
Foreign key constraints (even reciprocal (user belongsTo team, team belongsTo user as owner))
Indexes with name
, method
and unique
properties
To resolve 'ASP.NET 4.0 has not been registered. You need to manually configure your Web server for ASP.NET 4.0 in order for your site to run correctly' error when opening a solution we can:
1 Ensure the IIS feature is turned on with ASP.NET. Go to Control Panel\All Control Panel Items\Programs and Features then click 'Turn Windows Featrues on. Then in the IIS --> WWW servers --> App Dev Features ensure that ASP.NET is checked.
2 And run the following cmd line to install
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis -i
Hope this helps
Add this to build.gradle
to stop gradle from swallowing stdout and stderr.
test {
testLogging.showStandardStreams = true
}
It's documented here.
I use metaclasses and decorators for generate tests. You can check my implementation python_wrap_cases. This library doesn't require any test frameworks.
Your example:
import unittest
from python_wrap_cases import wrap_case
@wrap_case
class TestSequence(unittest.TestCase):
@wrap_case("foo", "a", "a")
@wrap_case("bar", "a", "b")
@wrap_case("lee", "b", "b")
def testsample(self, name, a, b):
print "test", name
self.assertEqual(a, b)
Console output:
testsample_u'bar'_u'a'_u'b' (tests.example.test_stackoverflow.TestSequence) ... test bar
FAIL
testsample_u'foo'_u'a'_u'a' (tests.example.test_stackoverflow.TestSequence) ... test foo
ok
testsample_u'lee'_u'b'_u'b' (tests.example.test_stackoverflow.TestSequence) ... test lee
ok
Also you may use generators. For example this code generate all possible combinations of tests with arguments a__list
and b__list
import unittest
from python_wrap_cases import wrap_case
@wrap_case
class TestSequence(unittest.TestCase):
@wrap_case(a__list=["a", "b"], b__list=["a", "b"])
def testsample(self, a, b):
self.assertEqual(a, b)
Console output:
testsample_a(u'a')_b(u'a') (tests.example.test_stackoverflow.TestSequence) ... ok
testsample_a(u'a')_b(u'b') (tests.example.test_stackoverflow.TestSequence) ... FAIL
testsample_a(u'b')_b(u'a') (tests.example.test_stackoverflow.TestSequence) ... FAIL
testsample_a(u'b')_b(u'b') (tests.example.test_stackoverflow.TestSequence) ... ok
If you are able to copy the actual SQLite database file to your desktop, you can use this tools to browse the data.
I Want See This
Example http://jsfiddle.net/35vAN/
<html>
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js" > </script>
<script type="text/javascript">
function PrintElem(elem)
{
Popup($(elem).html());
}
function Popup(data)
{
var mywindow = window.open('', 'my div', 'height=400,width=600');
mywindow.document.write('<html><head><title>my div</title>');
/*optional stylesheet*/ //mywindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
mywindow.document.write('</head><body >');
mywindow.document.write(data);
mywindow.document.write('</body></html>');
mywindow.print();
mywindow.close();
return true;
}
</script>
</head>
<body>
<div id="mydiv">
This will be printed. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque a quam at nibh adipiscing interdum. Nulla vitae accumsan ante.
</div>
<div>
This will not be printed.
</div>
<div id="anotherdiv">
Nor will this.
</div>
<input type="button" value="Print Div" onclick="PrintElem('#mydiv')" />
</body>
</html>
Retrieve File name first then in Blade file use anchor(a) tag like below shown. This would works for image view also.
<a href="{{ asset('storage/admission-document-uploads/' . $filename) }}" target="_black"> view Pdf </a>;
This can be done by adding a reference to System.IO.Compression and System.IO.Compression.Filesystem.
A sample createZipFile() method may look as following:
public static void createZipFile(string inputfile, string outputfile, CompressionLevel compressionlevel)
{
try
{
using (ZipArchive za = ZipFile.Open(outputfile, ZipArchiveMode.Update))
{
//using the same file name as entry name
za.CreateEntryFromFile(inputfile, inputfile);
}
}
catch (ArgumentException)
{
Console.WriteLine("Invalid input/output file.");
Environment.Exit(-1);
}
}
where
Example in Swift, picturing the foundry's explanation above and the Apple's documentation:
ViewController.swift
import UIKit
protocol ViewControllerProtocol {
func dismissViewController1AndPresentViewController2()
}
class ViewController: UIViewController, ViewControllerProtocol {
@IBAction func goToViewController1BtnPressed(sender: UIButton) {
let vc1: ViewController1 = self.storyboard?.instantiateViewControllerWithIdentifier("VC1") as ViewController1
vc1.delegate = self
vc1.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal
self.presentViewController(vc1, animated: true, completion: nil)
}
func dismissViewController1AndPresentViewController2() {
self.dismissViewControllerAnimated(false, completion: { () -> Void in
let vc2: ViewController2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as ViewController2
self.presentViewController(vc2, animated: true, completion: nil)
})
}
}
ViewController1.swift
import UIKit
class ViewController1: UIViewController {
var delegate: protocol<ViewControllerProtocol>!
@IBAction func goToViewController2(sender: UIButton) {
self.delegate.dismissViewController1AndPresentViewController2()
}
}
ViewController2.swift
import UIKit
class ViewController2: UIViewController {
}
ViewController.swift
import UIKit
protocol ViewControllerProtocol {
func popViewController1AndPushViewController2()
}
class ViewController: UIViewController, ViewControllerProtocol {
@IBAction func goToViewController1BtnPressed(sender: UIButton) {
let vc1: ViewController1 = self.storyboard?.instantiateViewControllerWithIdentifier("VC1") as ViewController1
vc1.delegate = self
self.navigationController?.pushViewController(vc1, animated: true)
}
func popViewController1AndPushViewController2() {
self.navigationController?.popViewControllerAnimated(false)
let vc2: ViewController2 = self.storyboard?.instantiateViewControllerWithIdentifier("VC2") as ViewController2
self.navigationController?.pushViewController(vc2, animated: true)
}
}
ViewController1.swift
import UIKit
class ViewController1: UIViewController {
var delegate: protocol<ViewControllerProtocol>!
@IBAction func goToViewController2(sender: UIButton) {
self.delegate.popViewController1AndPushViewController2()
}
}
ViewController2.swift
import UIKit
class ViewController2: UIViewController {
}
GregorianCalendar date;
CharSequence dateForMart = android.text.format.DateFormat.format("yyyy-MM-dd", date);
Toast.makeText(LogmeanActivity.this,dateForMart,Toast.LENGTH_LONG).show();
For many it's a permission issue, but for me it turns out the error was brought about by a mistake in the form I was trying to submit. To be specific i had accidentally put a "greater than" sign after the value of "action". So I would suggest you take a second look at your code.
You need to declare the button onclicklistener. Once clicked, it calls AsyncTask class DownloadJson.
The process will be shown below:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new DownloadJson().execute();
}
});
}
// DownloadJSON AsyncTask
private class DownloadJson extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
newlist = new ArrayList<HashMap<String, String>>();
json = jsonParser.makeHttpRequest(json, "POST");
try {
newarray = new JSONArray(json);
for (int i = 0; i < countdisplay; i++) {
HashMap<String, String> eachnew = new HashMap<String, String>();
newobject = newarray.getJSONObject(i);
eachnew.put("id", newobject.getString("ID"));
eachnew.put("name", newobject.getString("Name"));
newlist.add(eachnew);
}
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void args) {
newlisttemp.addAll(newlist);
NewAdapterpager newadapterpager = new NewAdapterpager(ProcesssActivitypager.this, newlisttemp);
newpager.setAdapter(newadapterpager);
}
}
From VS2013 Menu Select "Tools", then Select "External Tools". Enter as below:
C:\Windows\System32\cmd.exe
/k "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\VsDevCmd.bat"
Click OK. Now you have command prompt access under the Tools Menu.
Its another way to declare the constructor. You can also use the class name, for ex:
class Cat
{
function Cat()
{
echo 'meow';
}
}
and
class Cat
{
function __construct()
{
echo 'meow';
}
}
Are equivalent. They are called whenever a new instance of the class is created, in this case, they will be called with this line:
$cat = new Cat();
$("#pageCSS").attr('href', './css/new_css.css');
There is one more alternative module which has more activity than ngStorage
angular-local-storage:
1) HTML is downloaded.
2) HTML is parsed progressively. When a request for an asset is reached the browser will attempt to download the asset. A default configuration for most HTTP servers and most browsers is to process only two requests in parallel. IE can be reconfigured to downloaded an unlimited number of assets in parallel. Steve Souders has been able to download over 100 requests in parallel on IE. The exception is that script requests block parallel asset requests in IE. This is why it is highly suggested to put all JavaScript in external JavaScript files and put the request just prior to the closing body tag in the HTML.
3) Once the HTML is parsed the DOM is rendered. CSS is rendered in parallel to the rendering of the DOM in nearly all user agents. As a result it is strongly recommended to put all CSS code into external CSS files that are requested as high as possible in the <head></head> section of the document. Otherwise the page is rendered up to the occurance of the CSS request position in the DOM and then rendering starts over from the top.
4) Only after the DOM is completely rendered and requests for all assets in the page are either resolved or time out does JavaScript execute from the onload event. IE7, and I am not sure about IE8, does not time out assets quickly if an HTTP response is not received from the asset request. This means an asset requested by JavaScript inline to the page, that is JavaScript written into HTML tags that is not contained in a function, can prevent the execution of the onload event for hours. This problem can be triggered if such inline code exists in the page and fails to execute due to a namespace collision that causes a code crash.
Of the above steps the one that is most CPU intensive is the parsing of the DOM/CSS. If you want your page to be processed faster then write efficient CSS by eliminating redundent instructions and consolidating CSS instructions into the fewest possible element referrences. Reducing the number of nodes in your DOM tree will also produce faster rendering.
Keep in mind that each asset you request from your HTML or even from your CSS/JavaScript assets is requested with a separate HTTP header. This consumes bandwidth and requires processing per request. If you want to make your page load as fast as possible then reduce the number of HTTP requests and reduce the size of your HTML. You are not doing your user experience any favors by averaging page weight at 180k from HTML alone. Many developers subscribe to some fallacy that a user makes up their mind about the quality of content on the page in 6 nanoseconds and then purges the DNS query from his server and burns his computer if displeased, so instead they provide the most beautiful possible page at 250k of HTML. Keep your HTML short and sweet so that a user can load your pages faster. Nothing improves the user experience like a fast and responsive web page.
Alternatively you could use CSS mask
, granted browser support isn't good but you could use a fallback
.frame {
background: blue;
-webkit-mask: url(image.svg) center / contain no-repeat;
}
The easiest way to change the background color of the jumbotron
If you want to change the background color of your jumbotron, then for that you can apply a background color to it using one of your custom class.
HTML Code:
<div class="jumbotron myclass">
<h1>My Heading</h1>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
</div>
CSS Code:
<style>
.myclass{
background-color: red;
}
</style>
You can't set a number in an arbitrary place in the array without telling the array how big it needs to be. For your example: int[] array = new int[4];
You should use the StringFormat
on the Binding
. You can use either standard string formats, or custom string formats:
<TextBox Text="{Binding Value, StringFormat=N2}" />
<TextBox Text="{Binding Value, StringFormat={}{0:#,#.00}}" />
Note that the StringFormat
only works when the target property is of type string. If you are trying to set something like a Content
property (typeof(object)
), you will need to use a custom StringFormatConverter
(like here), and pass your format string as the ConverterParameter
.
Edit for updated question
So, if your ViewModel
defines the precision, I'd recommend doing this as a MultiBinding
, and creating your own IMultiValueConverter
. This is pretty annoying in practice, to go from a simple binding to one that needs to be expanded out to a MultiBinding
, but if the precision isn't known at compile time, this is pretty much all you can do. Your IMultiValueConverter
would need to take the value, and the precision, and output the formatted string. You'd be able to do this using String.Format
.
However, for things like a ContentControl
, you can much more easily do this with a Style
:
<Style TargetType="{x:Type ContentControl}">
<Setter Property="ContentStringFormat"
Value="{Binding Resolution, StringFormat=N{0}}" />
</Style>
Any control that exposes a ContentStringFormat
can be used like this. Unfortunately, TextBox
doesn't have anything like that.
Assuming your array called 'string' already exists, try
string[0] = '\0';
\0
is the explicit NUL terminator, required to mark the end of string.
A solution is to create an Alias in your .gitconfig
and call it easily:
[alias]
tree = log --graph --decorate --pretty=oneline --abbrev-commit
And when you call it next time, you'll use:
git tree
To put it in your ~/.gitconfig without having to edit it, you can do:
git config --global alias.tree "log --graph --decorate --pretty=oneline --abbrev-commit"
(If you don't use the --global it will put it in the .git/config of your current repo.)
For Visual Studio you'll want to right click on your project in the solution explorer and then click on Properties.
Next open Configuration Properties and then Linker.
Now you want to add the folder you have the Allegro libraries in to Additional Library Directories,
Linker -> Input you'll add the actual library files under Additional Dependencies.
For the Header Files you'll also want to include their directories under C/C++ -> Additional Include Directories.
If there is a dll have a copy of it in your main project folder, and done.
I would recommend putting the Allegro files in the your project folder and then using local references in for the library and header directories.
Doing this will allow you to run the application on other computers without having to install Allergo on the other computer.
This was written for Visual Studio 2008. For 2010 it should be roughly the same.
You typically want to render templates like this:
app.get('/', function(req, res){
res.render('index.ejs');
});
However you can also deliver static content - to do so use:
app.use(express.static(__dirname + '/public'));
Now everything in the /public
directory of your project will be delivered as static content at the root of your site e.g. if you place default.htm
in the public folder if will be available by visiting /default.htm
Take a look through the express API and Connect Static middleware docs for more info.
If you don't feel like dropping and recreating the whole shebang just to reload your data, you could use MyModel.destroy_all
(or delete_all
) in the seed.db file to clean out a table before your MyModel.create!(...)
statements load the data. Then, you can redo the db:seed
operation over and over. (Obviously, this only affects the tables you've loaded data into, not the rest of them.)
There's a "dirty hack" at https://stackoverflow.com/a/14957893/4553442 to add a "de-seeding" operation similar to migrating up and down...
I just had a similar problem, the DISTINCT keyword works magic:
INSERT INTO Table2(Id, Name) SELECT DISTINCT Id, Name FROM Table1
If an algorithm is of T(g(n)), it means that the running time of the algorithm as n (input size) gets larger is proportional to g(n).
If an algorithm is of O(g(n)), it means that the running time of the algorithm as n gets larger is at most proportional to g(n).
Normally, even when people talk about O(g(n)) they actually mean T(g(n)) but technically, there is a difference.
O(n) represents upper bound. T(n) means tight bound. O(n) represents lower bound.
f(x) = T(g(x)) iff f(x) = O(g(x)) and f(x) = O(g(x))
Basically when we say an algorithm is of O(n), it's also O(n2), O(n1000000), O(2n), ... but a T(n) algorithm is not T(n2).
In fact, since f(n) = T(g(n)) means for sufficiently large values of n, f(n) can be bound within c1g(n) and c2g(n) for some values of c1 and c2, i.e. the growth rate of f is asymptotically equal to g: g can be a lower bound and and an upper bound of f. This directly implies f can be a lower bound and an upper bound of g as well. Consequently,
f(x) = T(g(x)) iff g(x) = T(f(x))
Similarly, to show f(n) = T(g(n)), it's enough to show g is an upper bound of f (i.e. f(n) = O(g(n))) and f is a lower bound of g (i.e. f(n) = O(g(n)) which is the exact same thing as g(n) = O(f(n))). Concisely,
f(x) = T(g(x)) iff f(x) = O(g(x)) and g(x) = O(f(x))
There are also little-oh and little-omega (?
) notations representing loose upper and loose lower bounds of a function.
To summarize:
f(x) = O(g(x))
(big-oh) means that the growth rate off(x)
is asymptotically less than or equal to to the growth rate ofg(x)
.
f(x) = O(g(x))
(big-omega) means that the growth rate off(x)
is asymptotically greater than or equal to the growth rate ofg(x)
f(x) = o(g(x))
(little-oh) means that the growth rate off(x)
is asymptotically less than the growth rate ofg(x)
.
f(x) = ?(g(x))
(little-omega) means that the growth rate off(x)
is asymptotically greater than the growth rate ofg(x)
f(x) = T(g(x))
(theta) means that the growth rate off(x)
is asymptotically equal to the growth rate ofg(x)
For a more detailed discussion, you can read the definition on Wikipedia or consult a classic textbook like Introduction to Algorithms by Cormen et al.
Maybe it is simple, try this if you have a DataFrame. then make sure that both matrices or vectros that you're trying to combine have the same rows_name/index
I had the same issue. I changed the name indices of the rows to make them match each other here is an example for a matrix (principal component) and a vector(target) have the same row indicies (I circled them in the blue in the leftside of the pic)
Before, "when it was not working", I had the matrix with normal row indicies (0,1,2,3) while I had the vector with row indices (ID0, ID1, ID2, ID3) then I changed the vector's row indices to (0,1,2,3) and it worked for me.
The correct operator to be used are the keywords 'or' and 'and', which in your example, the correct way to express this would be:
if i == 5 and ii == 10:
print "i is 5 and ii is 10"
You can refer the details in the "Boolean Operations" section in the language reference.
We can use another way to edit files inside working containers (this won't work if container is stoped).
Logic is to:
-)copy file from container to host
-)edit file on host using its host editor
-)copy file back to container
We can do all this steps manualy, but i have written simple bash script to make this easy by one call.
/bin/dmcedit:
#!/bin/sh
set -e
CONTAINER=$1
FILEPATH=$2
BASE=$(basename $FILEPATH)
DIR=$(dirname $FILEPATH)
TMPDIR=/tmp/m_docker_$(date +%s)/
mkdir $TMPDIR
cd $TMPDIR
docker cp $CONTAINER:$FILEPATH ./$DIR
mcedit ./$FILEPATH
docker cp ./$FILEPATH $CONTAINER:$FILEPATH
rm -rf $TMPDIR
echo 'END'
exit 1;
Usage example:
dmcedit CONTAINERNAME /path/to/file/in/container
The script is very easy, but it's working fine for me.
Any suggestions are appreciated.
If there is a package.json
, and in it there is lodash
configuration in it. then you should:
npm install
if in the package.json
there is no lodash
:
npm install --save-dev
GZip is simply deflate plus a checksum and header/footer. Deflate is faster, though, as I learned the hard way.
Assuming
source data range is A1:B100.
query cell is D1 (here you will input Police or Fire).
result cell is E1
Formula in E1 = VLOOKUP(D1, A1:B100, 2, FALSE)
Here a little program in Python that uses the angle between vectors to determine if a point is inside or outside a certain polygon
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from shapely.geometry import Point, Polygon
from pprint import pprint
# Plot variables
x_min, x_max = -6, 12
y_min, y_max = -3, 8
tick_interval = 1
FIG_SIZE = (10, 10)
DELTA_ERROR = 0.00001
IN_BOX_COLOR = 'yellow'
OUT_BOX_COLOR = 'black'
def angle_between(v1, v2):
""" Returns the angle in radians between vectors 'v1' and 'v2'
The sign of the angle is dependent on the order of v1 and v2
so acos(norm(dot(v1, v2))) does not work and atan2 has to be used, see:
https://stackoverflow.com/questions/21483999/using-atan2-to-find-angle-between-two-vectors
"""
arg1 = np.cross(v1, v2)
arg2 = np.dot(v1, v2)
angle = np.arctan2(arg1, arg2)
return angle
def point_inside(point, border):
""" Returns True if point is inside border polygon and False if not
Arguments:
:point: x, y in shapely.geometry.Point type
:border: [x1 y1, x2 y2, ... , xn yn] in shapely.geomettry.Polygon type
"""
assert len(border.exterior.coords) > 2,\
'number of points in the polygon must be > 2'
point = np.array(point)
side1 = np.array(border.exterior.coords[0]) - point
sum_angles = 0
for border_point in border.exterior.coords[1:]:
side2 = np.array(border_point) - point
angle = angle_between(side1, side2)
sum_angles += angle
side1 = side2
# if wn is 1 then the point is inside
wn = sum_angles / 2 / np.pi
if abs(wn - 1) < DELTA_ERROR:
return True
else:
return False
class MainMap():
@classmethod
def settings(cls, fig_size):
# set the plot outline, including axes going through the origin
cls.fig, cls.ax = plt.subplots(figsize=fig_size)
cls.ax.set_xlim(-x_min, x_max)
cls.ax.set_ylim(-y_min, y_max)
cls.ax.set_aspect(1)
tick_range_x = np.arange(round(x_min + (10*(x_max - x_min) % tick_interval)/10, 1),
x_max + 0.1, step=tick_interval)
tick_range_y = np.arange(round(y_min + (10*(y_max - y_min) % tick_interval)/10, 1),
y_max + 0.1, step=tick_interval)
cls.ax.set_xticks(tick_range_x)
cls.ax.set_yticks(tick_range_y)
cls.ax.tick_params(axis='both', which='major', labelsize=6)
cls.ax.spines['left'].set_position('zero')
cls.ax.spines['right'].set_color('none')
cls.ax.spines['bottom'].set_position('zero')
cls.ax.spines['top'].set_color('none')
@classmethod
def get_ax(cls):
return cls.ax
@staticmethod
def plot():
plt.tight_layout()
plt.show()
class PlotPointandRectangle(MainMap):
def __init__(self, start_point, rectangle_polygon, tolerance=0):
self.current_object = None
self.currently_dragging = False
self.fig.canvas.mpl_connect('key_press_event', self.on_key)
self.plot_types = ['o', 'o-']
self.plot_type = 1
self.rectangle = rectangle_polygon
# define a point that can be moved around
self.point = patches.Circle((start_point.x, start_point.y), 0.10,
alpha=1)
if point_inside(start_point, self.rectangle):
_color = IN_BOX_COLOR
else:
_color = OUT_BOX_COLOR
self.point.set_color(_color)
self.ax.add_patch(self.point)
self.point.set_picker(tolerance)
cv_point = self.point.figure.canvas
cv_point.mpl_connect('button_release_event', self.on_release)
cv_point.mpl_connect('pick_event', self.on_pick)
cv_point.mpl_connect('motion_notify_event', self.on_motion)
self.plot_rectangle()
def plot_rectangle(self):
x = [point[0] for point in self.rectangle.exterior.coords]
y = [point[1] for point in self.rectangle.exterior.coords]
# y = self.rectangle.y
self.rectangle_plot, = self.ax.plot(x, y,
self.plot_types[self.plot_type], color='r', lw=0.4, markersize=2)
def on_release(self, event):
self.current_object = None
self.currently_dragging = False
def on_pick(self, event):
self.currently_dragging = True
self.current_object = event.artist
def on_motion(self, event):
if not self.currently_dragging:
return
if self.current_object == None:
return
point = Point(event.xdata, event.ydata)
self.current_object.center = point.x, point.y
if point_inside(point, self.rectangle):
_color = IN_BOX_COLOR
else:
_color = OUT_BOX_COLOR
self.current_object.set_color(_color)
self.point.figure.canvas.draw()
def remove_rectangle_from_plot(self):
try:
self.rectangle_plot.remove()
except ValueError:
pass
def on_key(self, event):
# with 'space' toggle between just points or points connected with
# lines
if event.key == ' ':
self.plot_type = (self.plot_type + 1) % 2
self.remove_rectangle_from_plot()
self.plot_rectangle()
self.point.figure.canvas.draw()
def main(start_point, rectangle):
MainMap.settings(FIG_SIZE)
plt_me = PlotPointandRectangle(start_point, rectangle) #pylint: disable=unused-variable
MainMap.plot()
if __name__ == "__main__":
try:
start_point = Point([float(val) for val in sys.argv[1].split()])
except IndexError:
start_point= Point(0, 0)
border_points = [(-2, -2),
(1, 1),
(3, -1),
(3, 3.5),
(4, 1),
(5, 1),
(4, 3.5),
(5, 6),
(3, 4),
(3, 5),
(-0.5, 1),
(-3, 1),
(-1, -0.5),
]
border_points_polygon = Polygon(border_points)
main(start_point, border_points_polygon)
return false
is usually meant to terminate the object creation with a failure. It is as simple as that.
You could .class all the headings in Your document if You would like to target them with a single selector, as follows,
<h1 class="heading">...heading text...</h1>
<h2 class="heading">...heading text...</h2>
and in the css
.heading{
color: #Dad;
background-color: #DadDad;
}
I am not saying this is always best practice, but it can be useful, and for targeting syntax, easier in many ways,
so if You give all h1 through h6 the same .heading class in the html, then You can modify them for any html docs that utilize that css sheet.
upside, more global control versus "section div article h1, etc{}",
downside, instead of calling all the selectors in on place in the css, You will have much more typing in the html, yet I find that having a class in the html to target all headings can be beneficial, just be careful of precedence in the css, because conflicts could arise from
On my Windows 7 laptop, I use 'adb logcat | find "com.example.name"' to filter the system program related logcat output from the rest. The output from the logcat program is piped into the find command. Every line that contains 'com.example.name' is output to the window. The double quotes are part of the find command.
To include the output from my Log commands, I use the package name, here "com.example.name", as part of the first parameter in my Log commands like this:
Log.d("com.example.name activity1", "message");
Note: My Samsung Galaxy phone puts out a lot less program related output than the Level 17 emulator.
foreach (DataColumn col in rightsTable.Columns)
{
foreach (DataRow row in rightsTable.Rows)
{
Console.WriteLine(row[col.ColumnName].ToString());
}
}
I had a same problem. In my case, the user did not have write permission to the destination directory. Following command helped in my case :
chmod 777 University
Another feature is between:
Select * from table where date between '2009/01/30' and '2009/03/30'
DELIMITER $$
CREATE DEFINER=`mysqldb`@`%` PROCEDURE `abc`()
BEGIN
BEGIN
set @value :='11,2,3,1,';
WHILE (LOCATE(',', @value) > 0) DO
SET @V_DESIGNATION = SUBSTRING(@value,1, LOCATE(',',@value)-1);
SET @value = SUBSTRING(@value, LOCATE(',',@value) + 1);
select @V_DESIGNATION;
END WHILE;
END;
END$$
DELIMITER ;
At the moment this doesn't really exist (although you can of course write your own). There is an open connect bug for it: https://connect.microsoft.com/SQLServer/Feedback/Details/3130221, which as of this writing has just 1 vote.
You can not call network on the main thread or UI thread. On Android if you want to call network there are two options -
Personally I prefer asynctask. For further information you can refer this link.
Before I show you how to reload / refresh model data from the server programmatically? I have to explain for you the concept of Data Binding. This is an extremely powerful concept that will truly revolutionize the way you develop. So may be you have to read about this concept from this link or this seconde link in order to unterstand how AngularjS work.
now I'll show you a sample example that exaplain how can you update your model from server.
HTML Code:
<div ng-controller="PersonListCtrl">
<ul>
<li ng-repeat="person in persons">
Name: {{person.name}}, Age {{person.age}}
</li>
</ul>
<button ng-click="updateData()">Refresh Data</button>
</div>
So our controller named: PersonListCtrl and our Model named: persons. go to your Controller js in order to develop the function named: updateData()
that will be invoked when we are need to update and refresh our Model persons.
Javascript Code:
app.controller('adsController', function($log,$scope,...){
.....
$scope.updateData = function(){
$http.get('/persons').success(function(data) {
$scope.persons = data;// Update Model-- Line X
});
}
});
Now I explain for you how it work:
when user click on button Refresh Data, the server will call to function updateData() and inside this function we will invoke our web service by the function $http.get()
and when we have the result from our ws we will affect it to our model (Line X).Dice that affects the results for our model, our View of this list will be changed with new Data.
For those who like me doing same mistake. Here is the elaborated answer Tested in Laravel 5.7
UserFile::orderBy('created_at','desc')->get()->toArray();
Array
(
[0] => Array
(
[id] => 2073
[type] => 'DL'
[url] => 'https://i.picsum.photos/12/884/200/300.jpg'
[created_at] => 2020-08-05 17:16:48
[updated_at] => 2020-08-06 18:08:38
)
[1] => Array
(
[id] => 2074
[type] => 'PROFILE'
[url] => 'https://i.picsum.photos/13/884/200/300.jpg'
[created_at] => 2020-08-05 17:20:06
[updated_at] => 2020-08-06 18:08:38
)
[2] => Array
(
[id] => 2076
[type] => 'PROFILE'
[url] => 'https://i.picsum.photos/13/884/200/300.jpg'
[created_at] => 2020-08-05 17:22:01
[updated_at] => 2020-08-06 18:08:38
)
[3] => Array
(
[id] => 2086
[type] => 'PROFILE'
[url] => 'https://i.picsum.photos/13/884/200/300.jpg'
[created_at] => 2020-08-05 19:22:41
[updated_at] => 2020-08-06 18:08:38
)
)
UserFile::select('type','url','updated_at)->distinct('type')->get()->toArray();
Array
(
[0] => Array
(
[type] => 'DL'
[url] => 'https://i.picsum.photos/12/884/200/300.jpg'
[updated_at] => 2020-08-06 18:08:38
)
[1] => Array
(
[type] => 'PROFILE'
[url] => 'https://i.picsum.photos/13/884/200/300.jpg'
[updated_at] => 2020-08-06 18:08:38
)
)
So Pass only those columns in "select()"
, values of which are same.
For example: 'type','url'
. You can add more columns provided they have same value like 'updated_at'
.
If you try to pass "created_at"
or "id"
in "select()"
, then you will get the records same as A.
Because they are different for each row in DB.
The string literal is pased according to the current dateformat setting, see SET DATEFORMAT
. One format which will always work is the '20090525' one.
Now, of course, you need to define 'does not work'. No records gets updated? Perhaps the Id=1
doesn't match any record...
If it says 'One record changed' then perhaps you need to show us how you verify...
i think you try to align the content to the right within the div, the div with offset already push itself to the right, here some code and LIVE sample:
FYI: .pull-right
only push the div to the right, but not the content inside the div.
HTML:
<div class="row">
<div class="container">
<div class="col-md-4 someclass">
left content
</div>
<div class="col-md-4 col-md-offset-4 someclass">
<div class="yellow_background totheright">right content</div>
</div>
</div>
</div>
CSS:
.someclass{ /*this class for testing purpose only*/
border:1px solid blue;
line-height:2em;
}
.totheright{ /*this will align the text to the right*/
text-align:right;
}
.yellow_background{
background-color:yellow;
}
Another modification:
...
<div class="yellow_background totheright">
<span>right content</span>
<br/>image also align-right<br/>
<img width="15%" src="https://www.google.com/images/srpr/logo11w.png"/>
</div>
...
hope it will clear your problem
Also check that your package name is correctly accepted:
{
"name":"My Awesome Package"
}
{
"name": "my-awesome-package-name"
}
What does shapiro.test do?
shapiro.test
tests the Null hypothesis that "the samples come from a Normal distribution" against the alternative hypothesis "the samples do not come from a Normal distribution".
How to perform shapiro.test in R?
The R help page for ?shapiro.test
gives,
x - a numeric vector of data values. Missing values are allowed,
but the number of non-missing values must be between 3 and 5000.
That is, shapiro.test
expects a numeric vector as input, that corresponds to the sample you would like to test and it is the only input required. Since you've a data.frame, you'll have to pass the desired column as input to the function as follows:
> shapiro.test(heisenberg$HWWIchg)
# Shapiro-Wilk normality test
# data: heisenberg$HWWIchg
# W = 0.9001, p-value = 0.2528
Interpreting results from shapiro.test:
First, I strongly suggest you read this excellent answer from Ian Fellows on testing for normality
.
As shown above, the shapiro.test
tests the NULL hypothesis that the samples came from a Normal distribution. This means that if your p-value <= 0.05, then you would reject the NULL hypothesis that the samples came from a Normal distribution. As Ian Fellows nicely put it, you are testing against the assumption of Normality". In other words (correct me if I am wrong), it would be much better if one tests the NULL hypothesis that the samples do not come from a Normal distribution. Why? Because, rejecting a NULL hypothesis is not the same as accepting the alternative hypothesis.
In case of the null hypothesis of shapiro.test
, a p-value <= 0.05 would reject the null hypothesis that the samples come from normal distribution. To put it loosely, there is a rare chance that the samples came from a normal distribution. The side-effect of this hypothesis testing is that this rare chance happens very rarely. To illustrate, take for example:
set.seed(450)
x <- runif(50, min=2, max=4)
shapiro.test(x)
# Shapiro-Wilk normality test
# data: runif(50, min = 2, max = 4)
# W = 0.9601, p-value = 0.08995
So, this (particular) sample runif(50, min=2, max=4)
comes from a normal distribution according to this test. What I am trying to say is that, there are many many cases under which the "extreme" requirements (p < 0.05) are not satisfied which leads to acceptance of "NULL hypothesis" most of the times, which might be misleading.
Another issue I'd like to quote here from @PaulHiemstra from under comments about the effects on large sample size:
An additional issue with the Shapiro-Wilk's test is that when you feed it more data, the chances of the null hypothesis being rejected becomes larger. So what happens is that for large amounts of data even very small deviations from normality can be detected, leading to rejection of the null hypothesis event though for practical purposes the data is more than normal enough.
Although he also points out that R's data size limit protects this a bit:
Luckily shapiro.test protects the user from the above described effect by limiting the data size to 5000.
If the NULL hypothesis were the opposite, meaning, the samples do not come from a normal distribution, and you get a p-value < 0.05, then you conclude that it is very rare that these samples do not come from a normal distribution (reject the NULL hypothesis). That loosely translates to: It is highly likely that the samples are normally distributed (although some statisticians may not like this way of interpreting). I believe this is what Ian Fellows also tried to explain in his post. Please correct me if I've gotten something wrong!
@PaulHiemstra also comments about practical situations (example regression) when one comes across this problem of testing for normality:
In practice, if an analysis assumes normality, e.g. lm, I would not do this Shapiro-Wilk's test, but do the analysis and look at diagnostic plots of the outcome of the analysis to judge whether any assumptions of the analysis where violated too much. For linear regression using lm this is done by looking at some of the diagnostic plots you get using plot(lm()). Statistics is not a series of steps that cough up a few numbers (hey p < 0.05!) but requires a lot of experience and skill in judging how to analysis your data correctly.
Here, I find the reply from Ian Fellows to Ben Bolker's comment under the same question already linked above equally (if not more) informative:
For linear regression,
Don't worry much about normality. The CLT takes over quickly and if you have all but the smallest sample sizes and an even remotely reasonable looking histogram you are fine.
Worry about unequal variances (heteroskedasticity). I worry about this to the point of (almost) using HCCM tests by default. A scale location plot will give some idea of whether this is broken, but not always. Also, there is no a priori reason to assume equal variances in most cases.
Outliers. A cooks distance of > 1 is reasonable cause for concern.
Those are my thoughts (FWIW).
Hope this clears things up a bit.
I had two interfaces. First was child of other. I did following:
as
keyword.Complete code is as below:
Child Interface:
interface UVAmount {
amount: number;
price: number;
quantity: number;
};
Parent Interface:
interface UVItem {
// This is index signature which compiler is complaining about.
// Here we are mentioning key will string and value will any of the types mentioned.
[key: string]: UVAmount | string | number | object;
name: string;
initial: UVAmount;
rating: number;
others: object;
};
React Component:
let valueType = 'initial';
function getTotal(item: UVItem) {
// as keyword is the dealbreaker.
// If you don't use it, it will take string type by default and show errors.
let itemValue = item[valueType] as UVAmount;
return itemValue.price * itemValue.quantity;
}
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
Where str
is your XML string. See the MSDN article for more info.
You can either
import * as abc from './abc';
abc.xyz();
or
import { xyz } from './abc';
xyz()
Marked with @IBInspectable
in swift (or IBInspectable in Objective-C), they are easily editable in Interface Builder’s attributes inspector panel.
You can directly set borderWidth,cornerRadius,borderColor in attributes inspector
extension UIView {
@IBInspectable var cornerRadius: CGFloat {
get{
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
@IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
@IBInspectable var borderColor: UIColor? {
get {
return UIColor(cgColor: layer.borderColor!)
}
set {
layer.borderColor = borderColor?.cgColor
}
}
}
To merge any number of raw objects
function merge_obj(){
foreach(func_get_args() as $a){
$objects[]=(array)$a;
}
return (object)call_user_func_array('array_merge', $objects);
}
Tip for 1 website resizing the height. But you can change to 2 websites.
Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.
Local:
<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>
<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>
You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).
Remote:
You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).
<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>
So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.
The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".
Hope this helps. Sorry for my english.
Can I pass parameters by reference in Java?
No.
Why ? Java has only one mode of passing arguments to methods: by value.
Note:
For primitives this is easy to understand: you get a copy of the value.
For all other you get a copy of the reference and this is called also passing by value.
It is all in this picture:
No, you need to wrap your TextBlock in a Border. Example:
<Border BorderThickness="1" BorderBrush="Black">
<TextBlock ... />
</Border>
Of course, you can set these properties (BorderThickness
, BorderBrush
) through styles as well:
<Style x:Key="notCalledBorder" TargetType="{x:Type Border}">
<Setter Property="BorderThickness" Value="1" />
<Setter Property="BorderBrush" Value="Black" />
</Style>
<Border Style="{StaticResource notCalledBorder}">
<TextBlock ... />
</Border>
To get it as a list:
% npx npm-remote-ls --flatten dugite -d false -o false
[
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'@szmarczak/[email protected]',
'[email protected]',
'@sindresorhus/[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]'
]
Try using MS Access instead. Create a new file and select 'Project using existing data' template. This will create .adp file.
Then simply open your table and press Ctrl+Enter for new line.
Pasting from clipboard also works correctly.
Try to replace the \n
with %0A
just like you have spaces replaced with %20
.
The base64 encoding of Content-Type: multipart/form-data
adds an extra 33% overhead. If the server supports it, it is more efficient to send the files directly:
$scope.upload = function(url, file) {
var config = { headers: { 'Content-Type': undefined },
transformResponse: angular.identity
};
return $http.post(url, file, config);
};
When sending a POST with a File object, it is important to set 'Content-Type': undefined
. The XHR send method will then detect the File object and automatically set the content type.
To send multiple files, see Doing Multiple $http.post
Requests Directly from a FileList
I figured I should start with input type="file", but then found out that AngularJS can't bind to that..
The <input type=file>
element does not by default work with the ng-model directive. It needs a custom directive:
ng-model
1angular.module("app",[]);
angular.module("app").directive("selectNgFiles", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<h1>AngularJS Input `type=file` Demo</h1>
<input type="file" select-ng-files ng-model="fileArray" multiple>
<h2>Files</h2>
<div ng-repeat="file in fileArray">
{{file.name}}
</div>
</body>
_x000D_
$http.post
with content type multipart/form-data
If one must send multipart/form-data
:
<form role="form" enctype="multipart/form-data" name="myForm">
<input type="text" ng-model="fdata.UserName">
<input type="text" ng-model="fdata.FirstName">
<input type="file" select-ng-files ng-model="filesArray" multiple>
<button type="submit" ng-click="upload()">save</button>
</form>
$scope.upload = function() {
var fd = new FormData();
fd.append("data", angular.toJson($scope.fdata));
for (i=0; i<$scope.filesArray.length; i++) {
fd.append("file"+i, $scope.filesArray[i]);
};
var config = { headers: {'Content-Type': undefined},
transformRequest: angular.identity
}
return $http.post(url, fd, config);
};
When sending a POST with the FormData API, it is important to set 'Content-Type': undefined
. The XHR send method will then detect the FormData
object and automatically set the content type header to multipart/form-data with the proper boundary.
Multitasking - This is basically multiprogramming in the context of a single-user interactive environment, in which the OS switches between several programs in main memory so as to give the illusion that several are running at once. Common scheduling algorithms used for multitasking are: Round-Robin, Priority Scheduling (multiple queues), Shortest-Process-Next.
MULTIPROCESSING is like the OS handling the different jobs in main memory in such a way that it gives its time to each and every job when other is busy for some task such as I/O operation. So as long as at least one job needs to execute, the cpu never sit idle. and here it is automatically handled by the OS,
Try hitting the URL with "https://" instead of "http://"
Tested and working 100%
public class MainActivity extends ActionBarActivity {
Context context = this;
MediaPlayer mp;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
mp = MediaPlayer.create(context, R.raw.sound);
final Button b = (Button) findViewById(R.id.Button);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.sound);
} mp.start();
} catch(Exception e) { e.printStackTrace(); }
}
});
}
}
This was all we had to do
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = MediaPlayer.create(context, R.raw.sound);
}
5623125698541159
is treated as a single number (out of range of int
on most architecture). You need to write numbers in your file as
5 6 2 3 1 2 5 6 9 8 5 4 1 1 5 9
for 16 numbers.
If your file has input
5,6,2,3,1,2,5,6,9,8,5,4,1,1,5,9
then change %d
specifier in your fscanf
to %d,
.
fscanf(myFile, "%d,", &numberArray[i] );
Here is your full code after few modifications:
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *myFile;
myFile = fopen("somenumbers.txt", "r");
//read file into array
int numberArray[16];
int i;
if (myFile == NULL){
printf("Error Reading File\n");
exit (0);
}
for (i = 0; i < 16; i++){
fscanf(myFile, "%d,", &numberArray[i] );
}
for (i = 0; i < 16; i++){
printf("Number is: %d\n\n", numberArray[i]);
}
fclose(myFile);
return 0;
}
$user_agent = 'yandeX';
$bots = ['Google','Yahoo','Yandex'];
foreach($bots as $b){
if( stripos( $user_agent, $b ) !== false ) return $b;
}
In Python 3, print
became a function. This means that you need to include parenthesis now like mentioned below:
print("Hello World")
I call a scheduled script who must connect to a list of Server this way:
Powershell.exe -File "YourScriptPath" "Par1,Par2,Par3"
Then inside the script:
param($list_of_servers)
...
Connect-Viserver $list_of_servers.split(",")
The split operator returns an array of string
To draw Horizontal
************************
<Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Center" Fill="DarkCyan" Height="4"/>
To draw vertical
*******************
<Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Center" Fill="DarkCyan" Height="4" Width="Auto" >
<Rectangle.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform Angle="90"/>
<TranslateTransform/>
</TransformGroup>
</Rectangle.RenderTransform>
</Rectangle>
The fix is really simple: just replace YOUR_API_KEY on the last line of your code with your actual API key!
If you don't have one, you can get it for free on the Google Developers Website.
Two very different types of Pipes Angular - Pipes and RxJS - Pipes
A pipe takes in data as input and transforms it to a desired output. In this page, you'll use pipes to transform a component's birthday property into a human-friendly date.
import { Component } from '@angular/core';
@Component({
selector: 'app-hero-birthday',
template: `<p>The hero's birthday is {{ birthday | date }}</p>`
})
export class HeroBirthdayComponent {
birthday = new Date(1988, 3, 15); // April 15, 1988
}
Observable operators are composed using a pipe method known as Pipeable Operators. Here is an example.
import {Observable, range} from 'rxjs';
import {map, filter} from 'rxjs/operators';
const source$: Observable<number> = range(0, 10);
source$.pipe(
map(x => x * 2),
filter(x => x % 3 === 0)
).subscribe(x => console.log(x));
The output for this in the console would be the following:
0
6
12
18
For any variable holding an observable, we can use the .pipe() method to pass in one or multiple operator functions that can work on and transform each item in the observable collection.
So this example takes each number in the range of 0 to 10, and multiplies it by 2. Then, the filter function to filter the result down to only the odd numbers.
If() is the closest equivalent but beware of implicit conversions going on if you have set "Option Strict off"
For example, if your not careful you may be tempted to try something like:
Dim foo As Integer? = If(someTrueExpression, Nothing, 2)
Will give "foo" a value of 0!
I think the '?' operator equivalent in C# would instead fail compilation
If you are using Update Panel and link button to download excel is inside the panel than add postback trigger
<asp:PostBackTrigger ControlID="lnkTemplate" />
and in Code behind inside click event
string ServerPath = System.Configuration.ConfigurationManager.AppSettings["FilePath"] + "Template.xlsx";
System.IO.FileInfo file = new System.IO.FileInfo(Server.MapPath(ServerPath));
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.TransmitFile(file.FullName);
HttpContext.Current.Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
My Problem was that I was not in the correct git directory that I just cloned.
In ES6, just one line.
const arr = arr.filter(item => item.key !== "some value");
:)
With React Functional way
import React, { useEffect } from "react";
import ReactDOM from "react-dom";
import Button from "@material-ui/core/Button";
const App = () => {
const saySomething = (something) => {
console.log(something);
};
useEffect(() => {
saySomething("from useEffect");
});
const handleClick = (e) => {
saySomething("element clicked");
};
return (
<Button variant="contained" color="primary" onClick={handleClick}>
Hello World
</Button>
);
};
ReactDOM.render(<App />, document.querySelector("#app"));
Lots of good answers, but here is one more ;)
You can add handler for the click to the table
<table id = 'dsTable' onclick="tableclick(event)">
And then just find out what the target of the event was
function tableclick(e) {
if(!e)
e = window.event;
if(e.target.value == "Delete")
deleteRow( e.target.parentNode.parentNode.rowIndex );
}
Then you don't have to add event handlers for each row and your html looks neater. If you don't want any javascript in your html you can even add the handler when page loads:
document.getElementById('dsTable').addEventListener('click',tableclick,false);
??
Here is working code: http://jsfiddle.net/hX4f4/2/
For Python 2.x, use python's hashlib
import hashlib
m = hashlib.md5()
m.update("000005fab4534d05api_key9a0554259914a86fb9e7eb014e4e5d52permswrite")
print m.hexdigest()
Output: a02506b31c1cd46c2e0b6380fb94eb3d
USE MyDB;
GO
ALTER SCHEMA dbo TRANSFER jonathan.MovieData;
GO
Ref: ALTER SCHEMA
def Isprime(z):
'''returns True if the number is prime OTW returns false'''
if z<1:
return False
elif z==1:
return False
elif z==2:
return True
else:
for i in range(2,z):
if z%i==0:
return False
else:
return True
This is the way I did it. Of course, there are so many ways you can do it.
Just a quick note with a xlsm with spaces.
file = 'file with spaces.xlsm'
excel_macro.Application.Run('\'' + file + '\'' + "!Module1.Macro1")
In my case mongodb
packages are named mongodb-org
and mongodb-org-*
So when I type sudo apt purge mongo
then tab
(for auto-completion) I can see all installed packages that start with mongo
.
Another option is to run the following command (which will list all packages that contain mongo
in their names or their descriptions):
dpkg -l | grep mongo
In summary, I would do (to purge all packages that start with mongo
):
sudo apt purge mongo*
and then (to make sure that no mongo packages are left):
dpkg -l | grep mongo
Of course, as mentioned by @alicanozkara, you will need to manually remove some directories like /var/log/mongodb
and /var/lib/mongodb
Running the following find
commands:
sudo find /etc/ -name "*mongo*"
and sudo find /var/ -name "*mongo*"
may also show some files that you may want to remove, like:
/etc/systemd/system/mongodb.service
/etc/apt/sources.list.d/mongodb-org-3.2.list
and:
/var/lib/apt/lists/repo.mongodb.*
You may also want to remove user and group mongodb
, to do so you need to run:
sudo userdel -r mongodb
sudo groupdel mongodb
To check whether mongodb
user/group exists or not, try:
cut -d: -f1 /etc/passwd | grep mongo
cut -d: -f1 /etc/group | grep mongo
Ed_Cat_Search = (EditText) findViewById(R.id.editText_Searc_Categories);
Ed_Cat_Search.setInputType(InputType.TYPE_NULL);
Ed_Cat_Search.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
Ed_Cat_Search.setInputType(InputType.TYPE_CLASS_TEXT);
Ed_Cat_Search.onTouchEvent(event); // call native handler
return true; // consume touch even
}
});
this one worked for me
You would typically first read from the input stream and then close it. You can wrap the FileInputStream in another InputStream (or Reader). It will be automatically closed when you close the wrapping stream/reader.
If this is a method returning an InputStream to the caller, then it is the caller's responsibility to close the stream when finished with it. If you close it in your method, the caller will not be able to use it.
To answer some of your comments...
To send the contents InputStream to a remote consumer, you would write the content of the InputStream to an OutputStream, and then close both streams.
The remote consumer does not know anything about the stream objects you have created. He just receives the content, in an InputStream which he will create, read from and close.
You can write a pretty simple embedded Jetty Java server.
Embedded Jetty means that the server (Jetty) shipped together with the application as opposed of deploying the application on external Jetty server.
So if in non-embedded approach your webapp built into WAR file which deployed to some external server (Tomcat / Jetty / etc), in embedded Jetty, you write the webapp and instantiate the jetty server in the same code base.
An example for embedded Jetty Java server you can git clone and use: https://github.com/stas-slu/embedded-jetty-java-server-example
In fact to stopping the service we must use the method stopService()
and you are doing in right way:
Start service:
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
startService(myService);
Stop service:
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
stopService(myService);
if you call stopService()
, then the method onDestroy()
in the service is called (NOT the stopService()
method):
@Override
public void onDestroy() {
timer.cancel();
task.cancel();
Log.i(TAG, "onCreate() , service stopped...");
}
you must implement the onDestroy()
method!.
Here is a complete example including how to start/stop the service.
So, after adding the NuGet the deployment doesn't copy down the Interops. You can add this to your csproj file and it should fix that behavior:
<PropertyGroup>
<ContentSQLiteInteropFiles>true</ContentSQLiteInteropFiles>
<CopySQLiteInteropFiles>false</CopySQLiteInteropFiles>
<CleanSQLiteInteropFiles>false</CleanSQLiteInteropFiles>
<CollectSQLiteInteropFiles>false</CollectSQLiteInteropFiles>
</PropertyGroup>
If you look in the source for NuGet for SQLite you can see what these are doing specifically. This allowed me to get a deploy working with ASP.Net Core.
You can enable connection logging. For SQL Server 2008, you can enable Login Auditing. In SQL Server Management Studio, open SQL Server Properties > Security > Login Auditing select "Both failed and successful logins".
Make sure to restart the SQL Server service.
Once you've done that, connection attempts should be logged into SQL's error log. The physical logs location can be determined here.
This worked form me.. PHP Code on page.php
$query_de="sql statements here";
$sql_de = sqlsrv_query($conn,$query_de);
if ($sql_de)
{
echo "SQLSuccess";
}
exit();
and then AJAX Code has bellow
jQuery.ajax({
url : "page.php",
type : "POST",
data : {
buttonsave : 1,
var1 : val1,
var2 : val2,
},
success:function(data)
{
if(jQuery.trim(data) === "SQLSuccess")
{
alert("Se agrego correctamente");
// alert(data);
} else { alert(data);}
},
error: function(error)
{
alert("Error AJAX not working: "+ error );
}
});
NOTE: the word 'SQLSuccess' must be received from PHP
Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID
before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.
You have to nest the requests:
$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE" , function(name){ obj = name; // sID is only now available! sID = obj.id; console.log(sID); });
name.id
is sufficient unless you really need the other variables outside the function.$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE" , function(name){ // We don't need sID or obj here - name.id is sufficient console.log(name.id); doSecondRequest(name.id); }); /// TODO Choose a better name function doSecondRequest(sID) { $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){ console.log(stats); }); }
Hapy New Year :)
In Pycharm Just use Shift+Tab to move a block of code left.
I used to solve this issue by deleting the corresponding failed to download artifact directory in my local repo. Next time I run the maven command the artifact download is triggered again. Therefore I'd say it's a client side setting.
Nexus side (server repo side), this issue is solved configuring a scheduled task.
Client side, this is done using -U
, as you already pointed out.
There are three solution for clear activity history.
1) You can write finish()
at the time of start new activity through intent.
2) Write android:noHistory="true"
in all <activity>
tag in Androidmanifest.xml file, using this if you are open new activity and you don't write finish() at that time previous activity is always finished, after write your activity look like this.
<activity
android:name=".Splash_Screen_Activity"
android:label="@string/app_name"
android:noHistory="true">
</activity>
3) write system.exit(0)
for exit from the application.
String[] a= {"tube", "are", "fun"};
Arrays.asList(a).contains("any");
You can a constructor from another constructor of same class by using "this" keyword. Example -
class This1
{
This1()
{
this("Hello");
System.out.println("Default constructor..");
}
This1(int a)
{
this();
System.out.println("int as arg constructor..");
}
This1(String s)
{
System.out.println("string as arg constructor..");
}
public static void main(String args[])
{
new This1(100);
}
}
Output - string as arg constructor.. Default constructor.. int as arg constructor..
My problem was solved by entering the correct key as shown below.
Copy Server key like this picture
And then copy this code in post man like this picture
and Body is row like this picture
You can do multicolor outputs without any external programs.
@echo off
SETLOCAL EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
set "DEL=%%a"
)
echo say the name of the colors, don't read
call :ColorText 0a "blue"
call :ColorText 0C "green"
call :ColorText 0b "red"
echo(
call :ColorText 19 "yellow"
call :ColorText 2F "black"
call :ColorText 4e "white"
goto :eof
:ColorText
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1
goto :eof
It uses the color feature of the findstr command.
Findstr can be configured to output line numbers or filenames in a defined color.
So I first create a file with the text as filename, and the content is a single <backspace>
character (ASCII 8).
Then I search all non empty lines in the file and in nul, so the filename will be output in the correct color appended with a colon, but the colon is immediatly removed by the <backspace>
.
EDIT: One year later ... all characters are valid
@echo off
setlocal EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
set "DEL=%%a"
)
rem Prepare a file "X" with only one dot
<nul > X set /p ".=."
call :color 1a "a"
call :color 1b "b"
call :color 1c "^!<>&| %%%%"*?"
exit /b
:color
set "param=^%~2" !
set "param=!param:"=\"!"
findstr /p /A:%1 "." "!param!\..\X" nul
<nul set /p ".=%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%"
exit /b
This uses the rule for valid path/filenames.
If a \..\
is in the path the prefixed elemet will be removed completly and it's not necessary that this element contains only valid filename characters.
for(j = 0; j<=90; j = j+3)
{
}
j+3
will not assign the new value to j, add j=j+3
will assign the new value to j and the loop will move up by 3.
j++
is like saying j = j+1
, so in that case your assigning the new value to j just like the one above.
No, because it contains items there must be an instance of it. Its items being null is irrelevant, so the statment ((arrayList) != null) == true
I recently used this to read all the lines from a file:
alist = open('maze.txt').read().split()
or you can use this for that little bit of extra added safety:
with f as open('maze.txt'):
alist = f.read().split()
It doesn't work with whitespace in-between text in a single line, but it looks like your example file might not have whitespace splitting the values. It is a simple solution and it returns an accurate list of values, and does not add an empty string: ''
for every empty line, such as a newline at the end of the file.
The key parameter is: innodb_page_size
Support for 32k and 64k page sizes was added in MySQL 5.7. For both 32k and 64k page sizes, the maximum row length is approximately 16000 bytes.
The trick is that this parameter can be only changed during the INITIALIZATION of the mysql service instance, so it does not have any affect if you change this parameter after the instance is already initialized (the very first run of the instance).
innodb_page_size can only be configured prior to initializing the MySQL instance and cannot be changed afterward. If no value is specified, the instance is initialized using the default page size. See Section 14.6.1, “InnoDB Startup Configuration”.
So if you do not change this value in my.ini before initialization, the default value will be 16K, which will have row size limit of ~8K. Thats why the error comes up.
If you increase the innodb_page_size, the innodb_log_buffer_size must be also increased. Set it at least to 16M. Also if the ROW_FORMAT is set to COMPRESSED you cannot increase innodb_page_size to 32k, or 64K. It should be DYNAMIC (default in 5.7).
ROW_FORMAT=COMPRESSED is not supported when innodb_page_size is set to 32KB or 64KB. For innodb_page_size=32k, extent size is 2MB. For innodb_page_size=64k, extent size is 4MB. innodb_log_buffer_size should be set to at least 16M (the default) when using 32k or 64k page sizes.
Furthermore the innodb_buffer_pool_size should be increased from 128M to 512M at least, otherwise you will get an error on initialization of the instance (I do not have the exact error).
After this, the row size error gone.
The problem with this is that you have to create a new MySql instance, and migrate data to your new DataBase instance, from old one.
Parameters that I changed and works (after creating a new instance and initialized with the my.ini that is first modified with these settings):
innodb_page_size=64k
innodb_log_buffer_size=32M
innodb_buffer_pool_size=512M
All the settings and descriptions in which I found the solution can be found here:
https://dev.mysql.com/doc/refman/5.7/en/innodb-parameters.html
Hope this helps!
Regards!
the above all look good
but do you want to keep the result?
if so...
you can use the following
result = [element for element in data if element[1] == search]
then a simple
len(result)
lets you know if anything was found (and now you can do stuff with the results)
of course this does not handle elements which are length less than one (which you should be checking unless you know they always are greater than length 1, and in that case should you be using a tuple? (tuples are immutable))
if you know all items are a set length you can also do:
any(second == search for _, second in data)
or for len(data[0]) == 4:
any(second == search for _, second, _, _ in data)
...and I would recommend using
for element in data:
...
instead of
for i in range(len(data)):
...
(for future uses, unless you want to save or use 'i', and just so you know the '0' is not required, you only need use the full syntax if you are starting at a non zero value)
http://www.firstobject.com/dn_editor.htm is so far the best and lightest editor available with handful of utilities. I recommend using it - tried with up to 400 MB of files and more than a million records :)
maybe this will help you out:
or this page:
www.scala-lang.org/node/6372
If you don't set an expiration date the cookie will expire at the end of the user's session. I recommend using the date right before unix epoch time will extend passed a 32-bit integer. To put that in the cookie you would use document.cookie = "randomCookie=true; expires=Tue, 19 Jan 2038 03:14:07 UTC;
, assuming that randomCookie
is the cookie you are setting and true
is it's respective value.
SimpleDateFormat has a constructor which takes the locale, have you tried that?
http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html
Something like
new SimpleDateFormat("your-pattern-here", Locale.getDefault());
PriorityQueue<Integer> pq = new PriorityQueue<Integer> (
new Comparator<Integer> () {
public int compare(Integer a, Integer b) {
return b - a;
}
}
);
You can control select all customised classes and methods, and right-click, choose "Source", then select "Generate Element Comment". You should get what you want.
If you want to modify the Code Template then you can go to Preferences -- Java -- Code Style -- Code Templates, then do whatever you want.
This should do what you need
use this,it got fixed for me, over centOS 7
<Directory /usr/share/phpMyAdmin/>
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Require all granted
</Directory>
Just to add my two cents. I've put myself into the same situation, while searching the minimum required privileges of a db login to run successfully the statement:
ALTER DATABASE ... SET SINGLE_USER WITH ROLLBACK IMMEDIATE
It seems that the ALTER statement completes successfully, when executed with a sysadmin login, but it requires the connections cleanup part, when executed under a login which has "only" limited permissions like:
ALTER ANY DATABASE
P.S. I've spent hours trying to figure out why the "ALTER DATABASE.." does not work when executed under a login that has dbcreator role + ALTER ANY DATABASE privileges. Here's my MSDN thread!
Scanner sc=new Scanner(System.in) ;
int p[][] = new int[n][] ;
for(int i=0 ; i<n ; i++)
{
int m = sc.nextInt() ; //Taking input from user in JAVA.
p[i]=new int[m] ; //Allocating memory block of 'm' int size block.
for(int j=0 ; j<m ; j++)
{
p[i][j]=sc.nextInt(); //Initializing 2D array block.
}
}
I have done for
private void addOrRemoveProperty(View view, int property, boolean flag){
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
if(flag){
layoutParams.addRule(property);
}else {
layoutParams.removeRule(property);
}
view.setLayoutParams(layoutParams);
}
How to call method:
centerInParent - true
addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, true);
centerInParent - false
addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, false);
centerHorizontal - true
addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, true);
centerHorizontal - false
addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, false);
centerVertical - true
addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, true);
centerVertical - false
addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, false);
Hope this would help you.
I think what you want is this:
last_list=[]
if p.last_name != None and p.last_name != "":
last_list.append(p.last_name)
print last_list
Your current if statement:
if p.last_name == None or p.last_name == "":
pass
Effectively never does anything. If p.last_name is none or the empty string, it does nothing inside the loop. If p.last_name is something else, the body of the if statement is skipped.
Also, it looks like your statement pan_list.append(p.last)
is a typo, because I see neither pan_list nor p.last getting used anywhere else in the code you have posted.
I have found this and it works fine for me:
Calculating the Difference between Two Known Dates
Unfortunately, calculating a date interval such as days, weeks, or months between two known dates is not as easy because you can't just add Date objects together. In order to use a Date object in any sort of calculation, we must first retrieve the Date's internal millisecond value, which is stored as a large integer. The function to do that is Date.getTime(). Once both Dates have been converted, subtracting the later one from the earlier one returns the difference in milliseconds. The desired interval can then be determined by dividing that number by the corresponding number of milliseconds. For instance, to obtain the number of days for a given number of milliseconds, we would divide by 86,400,000, the number of milliseconds in a day (1000 x 60 seconds x 60 minutes x 24 hours):
Date.daysBetween = function( date1, date2 ) {
//Get 1 day in milliseconds
var one_day=1000*60*60*24;
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = date2_ms - date1_ms;
// Convert back to days and return
return Math.round(difference_ms/one_day);
}
//Set the two dates
var y2k = new Date(2000, 0, 1);
var Jan1st2010 = new Date(y2k.getFullYear() + 10, y2k.getMonth(), y2k.getDate());
var today= new Date();
//displays 726
console.log( 'Days since '
+ Jan1st2010.toLocaleDateString() + ': '
+ Date.daysBetween(Jan1st2010, today));
The rounding is optional, depending on whether you want partial days or not.
I use this handy function:
By downloading it with a 4094 byte step it will not full your memory
function download($file_source, $file_target) {
$rh = fopen($file_source, 'rb');
$wh = fopen($file_target, 'w+b');
if (!$rh || !$wh) {
return false;
}
while (!feof($rh)) {
if (fwrite($wh, fread($rh, 4096)) === FALSE) {
return false;
}
echo ' ';
flush();
}
fclose($rh);
fclose($wh);
return true;
}
Usage:
$result = download('http://url','path/local/file');
You can then check if everything is ok with:
if (!$result)
throw new Exception('Download error...');
While you cannot modify a column as such, you may operate on a column and return a new DataFrame reflecting that change. For that you'd first create a UserDefinedFunction
implementing the operation to apply and then selectively apply that function to the targeted column only. In Python:
from pyspark.sql.functions import UserDefinedFunction
from pyspark.sql.types import StringType
name = 'target_column'
udf = UserDefinedFunction(lambda x: 'new_value', StringType())
new_df = old_df.select(*[udf(column).alias(name) if column == name else column for column in old_df.columns])
new_df
now has the same schema as old_df
(assuming that old_df.target_column
was of type StringType
as well) but all values in column target_column
will be new_value
.
predQuery[preId]=='undefined'
You're testing against the string 'undefined'
; you've confused this test with the typeof
test which would return a string. You probably mean to be testing against the special value undefined
:
predQuery[preId]===undefined
Note the strict-equality operator to avoid the generally-unwanted match null==undefined
.
However there are two ways you can get an undefined
value: either preId
isn't a member of predQuery
, or it is a member but has a value set to the special undefined
value. Often, you only want to check whether it's present or not; in that case the in
operator is more appropriate:
!(preId in predQuery)
run the following code in a .py file:
import sys
print(sys.version)
print(sys.executable)
DataRow's are nice in the way that they have their underlying table linked to them. With the underlying table you can verify that a specific row has a specific column in it.
If DataRow.Table.Columns.Contains("column") Then
MsgBox("YAY")
End If
You can do that using the thenAnswer
method (when chaining with when
):
when(someMock.someMethod()).thenAnswer(new Answer() {
private int count = 0;
public Object answer(InvocationOnMock invocation) {
if (count++ == 1)
return 1;
return 2;
}
});
Or using the equivalent, static doAnswer
method:
doAnswer(new Answer() {
private int count = 0;
public Object answer(InvocationOnMock invocation) {
if (count++ == 1)
return 1;
return 2;
}
}).when(someMock).someMethod();
With es6 syntax you can use:
console.log(`x = ${x}`);
You need to use BLOB, there's TINY, MEDIUM, LONG, and just BLOB, as with other types, choose one according to your size needs.
TINYBLOB 255
BLOB 65535
MEDIUMBLOB 16777215
LONGBLOB 4294967295
(in bytes)
The insert statement would be fairly normal. You need to read the file using fread
and then addslashes
to it.
Most importantly make sure your file name is Dockerfile
if you use another name it won't work(at least it did not for me.)
Also if you are in the same dir where the Dockerfile is use a .
i.e.
docker build -t Myubuntu1:v1 .
or use the absolute path i.e
docker build -t Myubuntu1:v1 /Users/<username>/Desktop/Docker
const is similar to static we can access both varables with class name but diff is static variables can be modified and const can not.
value_counts
is a Series method rather than a DataFrame method (and you are trying to use it on a DataFrame, clean
). You need to perform this on a specific column:
clean[column_name].value_counts()
It doesn't usually make sense to perform value_counts
on a DataFrame, though I suppose you could apply it to every entry by flattening the underlying values array:
pd.value_counts(df.values.flatten())
Have a look at the Python tutorial on tuples:
A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:
>>> empty = () >>> singleton = 'hello', # <-- note trailing comma >>> len(empty) 0 >>> len(singleton) 1 >>> singleton ('hello',)
If you put just a pair of parentheses around your string object, they will only turn that expression into an parenthesized expression (emphasis added):
A parenthesized expression list yields whatever that expression list yields: if the list contains at least one comma, it yields a tuple; otherwise, it yields the single expression that makes up the expression list.
An empty pair of parentheses yields an empty tuple object. Since tuples are immutable, the rules for literals apply (i.e., two occurrences of the empty tuple may or may not yield the same object).
Note that tuples are not formed by the parentheses, but rather by use of the comma operator. The exception is the empty tuple, for which parentheses are required — allowing unparenthesized “nothing” in expressions would cause ambiguities and allow common typos to pass uncaught.
That is (assuming Python 2.7),
a = 'Quattro TT'
print tuple(a) # <-- you create a tuple from a sequence
# (which is a string)
print tuple([a]) # <-- you create a tuple from a sequence
# (which is a list containing a string)
print tuple(list(a)) # <-- you create a tuple from a sequence
# (which you create from a string)
print (a,) # <-- you create a tuple containing the string
print (a) # <-- it's just the string wrapped in parentheses
The output is as expected:
('Q', 'u', 'a', 't', 't', 'r', 'o', ' ', 'T', 'T')
('Quattro TT',)
('Q', 'u', 'a', 't', 't', 'r', 'o', ' ', 'T', 'T')
('Quattro TT',)
Quattro TT
To add some notes on the print statement. When you try to create a single-element tuple as part of a print statement in Python 2.7 (as in print (a,)
) you need to use the parenthesized form, because the trailing comma of print a,
would else be considered part of the print statement and thus cause the newline to be suppressed from the output and not a tuple being created:
A '\n' character is written at the end, unless the print statement ends with a comma.
In Python 3.x most of the above usages in the examples would actually raise SyntaxError
, because in Python 3 print
turns into a function (you need to add an extra pair of parentheses).
But especially this may cause confusion:
print (a,) # <-- this prints a tuple containing `a` in Python 2.x
# but only `a` in Python 3.x
It's not possible to clear user history without plugins. And also it's not an issue at developer's perspective, it's the burden of the user to clear his history.
For information refer to How to clear browsers (IE, Firefox, Opera, Chrome) history using JavaScript or Java except from browser itself?
PEP-8 recommends you indent lines to the opening parentheses if you put anything on the first line, so it should either be indenting to the opening bracket:
urlpatterns = patterns('',
url(r'^$', listing, name='investment-listing'))
or not putting any arguments on the starting line, then indenting to a uniform level:
urlpatterns = patterns(
'',
url(r'^$', listing, name='investment-listing'),
)
urlpatterns = patterns(
'', url(r'^$', listing, name='investment-listing'))
I suggest taking a read through PEP-8 - you can skim through a lot of it, and it's pretty easy to understand, unlike some of the more technical PEPs.
Another option is Visual Studio, which has prerelease support for debugging Cordova apps:
Unified debugging experience. Cross-platform development often requires a different tool for debugging each device, emulator, or simulator. Different tools mean different workflows and lost productivity every time you switch devices. With Visual Studio, you can use the same world-class debugging tools for all deployment targets, including Windows, the Android emulator, attached Android devices, iOS devices and emulators, and the Apache Ripple emulator.
Now that Microsoft has released Visual Studio Community edition for free, you can give this a try at no cost. You will need to download both Visual Studio, and Visual Studio Tools for Apache Cordova.
The proper way as of now is to use a solution recommended by @Roman Kuzmin in comments to @M. Dudley answer:
[IO.File]::WriteAllLines($filename, $content)
(I've also shortened it a bit by stripping unnecessary System
namespace clarification - it will be substituted automatically by default.)
Here is a simple answer in basically one line of code.
var value = 35 // the numerical value
var x = 5 // the minimum length of the string
var padded = ("00000" + value).substr(-x);
Make sure the number of characters in you padding, zeros here, is at least as many as your intended minimum length. So really, to put it into one line, to get a result of "00035" in this case is:
var padded = ("00000" + 35).substr(-5);
Since no one has shared a neat two liner, I will share my own:
logging.basicConfig(filename='logs.log', level=logging.DEBUG, format="%(asctime)s:%(levelname)s: %(message)s")
logging.getLogger().addHandler(logging.StreamHandler())
As Dumb Guy points out, it's important to note whether the array starts at zero and is sequential. Since you can make assignments to and unset non-contiguous indices ${#array[@]}
is not always the next item at the end of the array.
$ array=(a b c d e f g h)
$ array[42]="i"
$ unset array[2]
$ unset array[3]
$ declare -p array # dump the array so we can see what it contains
declare -a array='([0]="a" [1]="b" [4]="e" [5]="f" [6]="g" [7]="h" [42]="i")'
$ echo ${#array[@]}
7
$ echo ${array[${#array[@]}]}
h
Here's how to get the last index:
$ end=(${!array[@]}) # put all the indices in an array
$ end=${end[@]: -1} # get the last one
$ echo $end
42
That illustrates how to get the last element of an array. You'll often see this:
$ echo ${array[${#array[@]} - 1]}
g
As you can see, because we're dealing with a sparse array, this isn't the last element. This works on both sparse and contiguous arrays, though:
$ echo ${array[@]: -1}
i
Just change
C:\Users\Giacomo B\AppData\Local\Android\sdk
to
C:\Users\Giacomo_B\AppData\Local\Android\sdk
You forgot the C: after the file:///
This works for me
<!DOCTYPE html>
<html>
<head>
<title>Experiment</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style>
html,body { width: 100%; height: 100%; }
</style>
</head>
<body style="background: url('file:///C:/Users/Roby/Pictures/battlefield-3.jpg')">
</body>
</html>
Bind variable can be used in Oracle SQL query with "in" clause.
Works in 10g; I don't know about other versions.
Bind variable is varchar up to 4000 characters.
Example: Bind variable containing comma-separated list of values, e.g.
:bindvar = 1,2,3,4,5
select * from mytable
where myfield in
(
SELECT regexp_substr(:bindvar,'[^,]+', 1, level) items
FROM dual
CONNECT BY regexp_substr(:bindvar, '[^,]+', 1, level) is not null
);
(Same info as I posted here: How do you specify IN clause in a dynamic query using a variable? )
This script is a improvement of the script from Vector. I have made a little change to it. So this script works for every link with the class page-scroll in it.
At first without easing:
$("a.page-scroll").click(function() {
var targetDiv = $(this).attr('href');
$('html, body').animate({
scrollTop: $(targetDiv).offset().top
}, 1000);
});
For easing you will need Jquery UI:
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
Add this to the script:
'easeOutExpo'
Final
$("a.page-scroll").click(function() {
var targetDiv = $(this).attr('href');
$('html, body').animate({
scrollTop: $(targetDiv).offset().top
}, 1000, 'easeOutExpo');
});
All the easings you can find here: Cheat Sheet.
I was looking to do this myself, and I wasnt satisfied with any of the answers provided simply because, I believe, they are quadratic time, and I need to do this on lists hundreds of items long.
I ended up extending jquery, and my solution uses jquery, but could easily be modified to use straight javascript.
I only access each item twice, and perform one linearithmic sort, so this should, I think, work out to be a lot faster on large datasets, though I freely confess I could be mistaken there:
sortList: function() {
if (!this.is("ul") || !this.length)
return
else {
var getData = function(ul) {
var lis = ul.find('li'),
liData = {
liTexts : []
};
for(var i = 0; i<lis.length; i++){
var key = $(lis[i]).text().trim().toLowerCase().replace(/\s/g, ""),
attrs = lis[i].attributes;
liData[key] = {},
liData[key]['attrs'] = {},
liData[key]['html'] = $(lis[i]).html();
liData.liTexts.push(key);
for (var j = 0; j < attrs.length; j++) {
liData[key]['attrs'][attrs[j].nodeName] = attrs[j].nodeValue;
}
}
return liData;
},
processData = function (obj){
var sortedTexts = obj.liTexts.sort(),
htmlStr = '';
for(var i = 0; i < sortedTexts.length; i++){
var attrsStr = '',
attributes = obj[sortedTexts[i]].attrs;
for(attr in attributes){
var str = attr + "=\'" + attributes[attr] + "\' ";
attrsStr += str;
}
htmlStr += "<li "+ attrsStr + ">" + obj[sortedTexts[i]].html+"</li>";
}
return htmlStr;
};
this.html(processData(getData(this)));
}
}
I assume you are using windows. Open the command prompt and type ipconfig
and find out your local address (on your pc) it should look something like 192.168.1.13
or 192.168.0.5
where the end digit is the one that changes. It should be next to IPv4 Address.
If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13
If you have a virtual host then you will need root to edit the hosts file.
If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.
See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.
Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).
If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow
to allow,deny
in the httpd.conf
file. You can access this by the WAMP menu.
To eliminate possible causes of the issue for now set your config file to
<Directory />
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
<RequireAll>
Require all granted
</RequireAll>
</Directory>
As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.
Config file that fixed the problem:
https://gist.github.com/samvaughton/6790739
Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.
git push origin --delete <branch Name>
is easier to remember than
git push origin :branchName
Try onclick function separately it can give you access to execute your function which can be used to open up a new window, for this purpose you first need to create a javascript function there you can define it and in your anchor tag you just need to call your function.
Example:
function newwin() {
myWindow=window.open('lead_data.php?leadid=1','myWin','width=400,height=650')
}
See how to call it from your anchor tag
<a onclick='newwin()'>Anchor</a>
Visit this jsbin
http://jsbin.com/icUTUjI/1/edit
May be this will help you a lot to understand your problem.
$image
is in your case the value of the item and not the key. Use the following syntax to get the key too:
foreach ($images as $key => $value) {
/* … */
}
Now you can delete the item with unset($images[$key])
.
Use commons-io IOUtils.toByteArray(URL):
String url = "http://localhost:8080/images/anImage.jpg";
byte[] fileContent = IOUtils.toByteArray(new URL(url));
Maven dependency:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
Here is a code snippet taken from a blog article written by Anubhav Goyal:
// this code will mark the forms authentication cookie and the
// session cookie as Secure.
if (Response.Cookies.Count > 0)
{
foreach (string s in Response.Cookies.AllKeys)
{
if (s == FormsAuthentication.FormsCookieName || "asp.net_sessionid".Equals(s, StringComparison.InvariantCultureIgnoreCase))
{
Response.Cookies[s].Secure = true;
}
}
}
Adding this to the EndRequest event handler in the global.asax should make this happen for all page calls.
Note: An edit was proposed to add a break;
statement inside a successful "secure" assignment. I've rejected this edit based on the idea that it would only allow 1 of the cookies to be forced to secure and the second would be ignored. It is not inconceivable to add a counter or some other metric to determine that both have been secured and to break at that point.
You need convert list
to numpy array
and then reshape
:
df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
a b c
0 1 2 3
1 4 5 6
2 7 8 9
Next time, use a single "alter table" statement to update the primary key.
alter table xx drop primary key, add primary key(k1, k2, k3);
To fix things:
create table fixit (user_2, user_1, type, timestamp, n, primary key( user_2, user_1, type) );
lock table fixit write, user_interactions u write, user_interactions write;
insert into fixit
select user_2, user_1, type, max(timestamp), count(*) n from user_interactions u
group by user_2, user_1, type
having n > 1;
delete u from user_interactions u, fixit
where fixit.user_2 = u.user_2
and fixit.user_1 = u.user_1
and fixit.type = u.type
and fixit.timestamp != u.timestamp;
alter table user_interactions add primary key (user_2, user_1, type );
unlock tables;
The lock should stop further updates coming in while your are doing this. How long this takes obviously depends on the size of your table.
The main problem is if you have some duplicates with the same timestamp.
Bootstrapping has yet another meaning in the context of reinforcement learning that may be useful to know for developers, in addition to its use in software development (most answers here, e.g. by kdgregory) and its use in statistics as discussed by Dirk Eddelbuettel.
From Sutton and Barto:
Widrow, Gupta, and Maitra (1973) modified the Least-Mean-Square (LMS) algorithm of Widrow and Hoff (1960) to produce a reinforcement learning rule that could learn from success and failure signals instead of from training examples. They called this form of learning “selective bootstrap adaptation” and described it as “learning with a critic” instead of “learning with a teacher.” They analyzed this rule and showed how it could learn to play blackjack. This was an isolated foray into reinforcement learning by Widrow, whose contributions to supervised learning were much more influential.
The book describes various reinforcement algorithms where the target value is based on a previous approximation as bootstrap methods:
Finally, we note one last special property of DP [Dynamic Programming] methods. All of them update estimates of the values of states based on estimates of the values of successor states. That is, they update estimates on the basis of other estimates. We call this general idea bootstrapping. Many reinforcement learning methods perform bootstrapping, even those that do not require, as DP requires, a complete and accurate model of the environment.
Note that this differs from bootstrap aggregating and intelligence explosion that is mentioned on the wikipedia page on bootstrapping.
It's part of Xcode. You'll need to reinstall the developer tools.
Importing .cer
certificate file downloaded from browser (open the url and dig for details) into cacerts keystore in java_home\jre\lib\security
worked for me, as opposed to attemps to generate and use my own keystore.
java_home\jre\lib\security
cmd
and CTRL+SHIFT+ENTERyourAliasName
and path\to\certificate.cer
respectively) ..\..\bin\keytool -import -trustcacerts -keystore cacerts -storepass changeit -noprompt -alias yourAliasName -file path\to\certificate.cer
This way you don't have to specify any additional JVM options and the certificate should be recognized by the JRE.
==
is the correct operator to compare strings in Go. However, the strings that you read from STDIN with reader.ReadString
do not contain "a"
, but "a\n"
(if you look closely, you'll see the extra line break in your example output).
You can use the strings.TrimRight
function to remove trailing whitespaces from your input:
if strings.TrimRight(input, "\n") == "a" {
// ...
}
If you want a list of lists:
>>> [list(t) for t in zip(*l)]
[[1, 3, 8], [2, 4, 9]]
If a list of tuples is OK:
>>> zip(*l)
[(1, 3, 8), (2, 4, 9)]
You can use input text with "list" attribute, which refers to the datalist of values.
<input type="text" name="city" list="cityname">_x000D_
<datalist id="cityname">_x000D_
<option value="Boston">_x000D_
<option value="Cambridge">_x000D_
</datalist>
_x000D_
This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist
Say the 1st date is in A1 cell
& the 2nd date is in B1 cell
Make sure that the cell type of both A1
& B1
is DATE
.
Then simply put the following formula in C1:
=A1-B1
The result of this formula may look funny to you.
Then Change the Cell type of C1
to GENERAL
.
It will give you the difference in Days.
You can also use this formula to get the remaining days of year or change the formula as you need:
=365-(A1-B1)
Here is the typical structure of new Codeigniter project:
- application/
- system/
- user_guide/
- index.php <- this is the file you need to change
I usually use this code in my CI index.php. Just change local_server_name to the name of your local webserver.
With this code you can deploy your site to your production server without changing index.php each time.
// Domain-based environment
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
define('ENVIRONMENT', 'development');
} else {
define('ENVIRONMENT', 'production');
}
/*
*---------------------------------------------------------------
* ERROR REPORTING
*---------------------------------------------------------------
*
* Different environments will require different levels of error reporting.
* By default development will show errors but testing and live will hide them.
*/
if (defined('ENVIRONMENT')) {
switch (ENVIRONMENT) {
case 'development':
error_reporting(E_ALL);
break;
case 'testing':
case 'production':
error_reporting(0);
ini_set('display_errors', 0);
break;
default:
exit('The application environment is not set correctly.');
}
}
A query (modification of https://stackoverflow.com/a/7892349/1737819) to find a custom name table size in GB. You might try this, replace 'YourTableName' with the name of your table.
SELECT
t.NAME AS TableName,
p.rows AS RowCounts,
CONVERT(DECIMAL,SUM(a.total_pages)) * 8 / 1024 / 1024 AS TotalSpaceGB,
SUM(a.used_pages) * 8 / 1024 / 1024 AS UsedSpaceGB ,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 / 1024 / 1024 AS UnusedSpaceGB
FROM
sys.tables t
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN
sys.schemas s ON t.schema_id = s.schema_id
WHERE
t.NAME = 'YourTable'
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY
t.Name, s.Name, p.Rows
ORDER BY
UsedSpaceGB DESC, t.Name
Maybe you can use float:right;:
.one {_x000D_
padding-left: 1em;_x000D_
text-color: white;_x000D_
display:inline; _x000D_
}_x000D_
.two {_x000D_
background-color: #00ffff;_x000D_
}_x000D_
.pull-right{_x000D_
float:right;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div class="row">_x000D_
<h3 class="one">Text</h3>_x000D_
<button class="btn btn-secondary pull-right">Button</button>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
\\d{3}
matches any sequence of three digits in Java.
If you are using latest Android Studio, then v7 libraries contradict with AndroidX, only you have to do is:
In Project files go in gradle.properties
Find outandroid.useAndroidX=true
then set it toandroid.useAndroidX=false
Find outandroid.enableJetifier=true
then set it toandroid.enableJetifier=false
Rebuild your project, all will working fine.
There are two "generations" of python-docx. The initial generation ended with the 0.2.x versions and the "new" generation started at v0.3.0. The new generation is a ground-up, object-oriented rewrite of the legacy version. It has a distinct repository located here.
The opendocx() function is part of the legacy API. The documentation is for the new version. The legacy version has no documentation to speak of.
Neither reading nor writing hyperlinks are supported in the current version. That capability is on the roadmap, and the project is under active development. It turns out to be quite a broad API because Word has so much functionality. So we'll get to it, but probably not in the next month unless someone decides to focus on that aspect and contribute it. UPDATE Hyperlink support was added subsequent to this answer.
For newer versions of Laravel, please replace protected $redirectTo = RouteServiceProvider::HOME;
with protected $redirectTo = '/newurl';
and replace newurl
accordingly.
Tested with Laravel version-6
Try this:
var setCanvasSize = function() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
If time_created is a unix timestamp (int), you should be able to use something like this:
DELETE FROM locks WHERE time_created < (UNIX_TIMESTAMP() - 600);
(600 seconds = 10 minutes - obviously)
Otherwise (if time_created is mysql timestamp), you could try this:
DELETE FROM locks WHERE time_created < (NOW() - INTERVAL 10 MINUTE)
There is a property of the built-in window.location
object that will provide that for the current window.
// If URL is http://www.somedomain.com/account/search?filter=a#top
window.location.pathname // /account/search
// For reference:
window.location.host // www.somedomain.com (includes port if there is one)
window.location.hostname // www.somedomain.com
window.location.hash // #top
window.location.href // http://www.somedomain.com/account/search?filter=a#top
window.location.port // (empty string)
window.location.protocol // http:
window.location.search // ?filter=a
It turns out that this schema is being standardized as an interface called URLUtils, and guess what? Both the existing window.location
object and anchor elements implement the interface.
So you can use the same properties above for any URL — just create an anchor with the URL and access the properties:
var el = document.createElement('a');
el.href = "http://www.somedomain.com/account/search?filter=a#top";
el.host // www.somedomain.com (includes port if there is one[1])
el.hostname // www.somedomain.com
el.hash // #top
el.href // http://www.somedomain.com/account/search?filter=a#top
el.pathname // /account/search
el.port // (port if there is one[1])
el.protocol // http:
el.search // ?filter=a
[1]: Browser support for the properties that include port is not consistent, See: http://jessepollak.me/chrome-was-wrong-ie-was-right
This works in the latest versions of Chrome and Firefox. I do not have versions of Internet Explorer to test, so please test yourself with the JSFiddle example.
There's also a coming URL
object that will offer this support for URLs themselves, without the anchor element. Looks like no stable browsers support it at this time, but it is said to be coming in Firefox 26. When you think you might have support for it, try it out here.
I am using a bit different overloading approach based on arguments number. However i believe John Fawcett's approach is also good. Here the example, code based on John Resig's (jQuery's Author) explanations.
// o = existing object, n = function name, f = function.
function overload(o, n, f){
var old = o[n];
o[n] = function(){
if(f.length == arguments.length){
return f.apply(this, arguments);
}
else if(typeof o == 'function'){
return old.apply(this, arguments);
}
};
}
usability:
var obj = {};
overload(obj, 'function_name', function(){ /* what we will do if no args passed? */});
overload(obj, 'function_name', function(first){ /* what we will do if 1 arg passed? */});
overload(obj, 'function_name', function(first, second){ /* what we will do if 2 args passed? */});
overload(obj, 'function_name', function(first,second,third){ /* what we will do if 3 args passed? */});
//... etc :)
I found Steve Hibbert's response to be very helpful. The problem the OP seemed to be describing is that of an AutoGeneratedColumns on a GridView.
In this instance you can set which columns will be "visible" and which will be hidden when you bind a data table in the code behind.
For example: A Gridview is on the page as follows.
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False" >
</asp:GridView>
And then in the code behind a PopulateGridView routine is called during the page load event.
protected void PopulateGridView()
{
DataTable dt = GetDataSource();
gv.DataSource = dt;
foreach (DataColumn col in dt.Columns)
{
BoundField field = new BoundField();
field.DataField = col.ColumnName;
field.HeaderText = col.ColumnName;
if (col.ColumnName.EndsWith("ID"))
{
field.Visible = false;
}
gv.Columns.Add(field);
}
gv.DataBind();
}
In the above the GridView AutoGenerateColumns is set to False and the codebehind is used to create the bound fields. One is obtaining the datasource as a datatable through one's own process which here I labeled GetDataSource(). Then one loops through the columns collection of the datatable. If the column name meets a given criteria, you can set the bound field visible property accordingly. Then you bind the data to the gridview. This is very similar to AutoGenerateColumns="True" but you get to have criteria for the columns. This approach is most useful when the criteria for hiding and un-hiding is based upon the column name.
This works in all browsers:
window.location.href = '...';
If you wanted to change the page without it reflecting in the browser back history, you can do:
window.location.replace('...');
had the same problem and just solved it, i used string [variable_Name] =dropdownlist1.SelectedItem.Text;
The question has already been answered, but I thought I'd add an answer with more precise terminology and references to the C++ standard.
Two things are going on here, array parameters being adjusted to pointer parameters, and array arguments being converted to pointer arguments. These are two quite different mechanisms, the first is an adjustment to the actual type of the parameter, whereas the other is a standard conversion which introduces a temporary pointer to the first element.
Adjustments to your function declaration:
After determining the type of each parameter, any parameter of type “array of T” (...) is adjusted to be “pointer to T”.
So int arg[]
is adjusted to be int* arg
.
Conversion of your function argument:
An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The temporary materialization conversion is applied. The result is a pointer to the first element of the array.
So in printarray(firstarray, 3);
, the lvalue firstarray
of type "array of 3 int" is converted to a prvalue (temporary) of type "pointer to int", pointing to the first element.
there is a alternative to margin-left:auto; margin-right: auto;
or margin:0 auto;
for the ones that use position:absolute;
this is how:
you set the left position of the element to 50% (left:50%;
) but that will not center it correctly in order for the element to be centered correctly you need to give it a margin of minus half of it`s width, that will center your element perfectly
here is an example: http://jsfiddle.net/35ERq/3/
Here is an efficient python solution:
def solution(A):
m = max(A)
if m < 1:
return 1
A = set(A)
B = set(range(1, m + 1))
D = B - A
if len(D) == 0:
return m + 1
else:
return min(D)
Old topic, but I think I found another descent solution. Adding class="row"
to a div will result in this CSS configuration:
.row {
display: -webkit-box;
display: flex;
flex-wrap: wrap;
margin-right: -15px;
margin-left: -15px;
}
We want to keep the first 3 rules and we can do this with class="d-flex flex-wrap"
(see https://getbootstrap.com/docs/4.1/utilities/flex/):
.flex-wrap {
flex-wrap: wrap !important;
}
.d-flex {
display: -webkit-box !important;
display: flex !important;
}
It adds !important rules though but it shouldn't be a problem in most cases...
I realize that this question is over 10 years old, but it appears to me that not only has the most obvious answer not been addressed, but that maybe its not really clear from the question a good understanding of what goes on under the covers. In addition, there are other questions about late binding and what that means with regards to delegates and lambdas (more on that later).
First to address the 800 lb elephant/gorilla in the room, when to choose event
vs Action<T>
/Func<T>
:
event
when you
want more of a pub/sub model with multiple
statements/lambdas/functions that will execute (this is a major
difference right off the bat).As an example of an event, lets wire up a simple and 'standard' set of events using a small console application as follows:
public delegate void FireEvent(int num);
public delegate void FireNiceEvent(object sender, SomeStandardArgs args);
public class SomeStandardArgs : EventArgs
{
public SomeStandardArgs(string id)
{
ID = id;
}
public string ID { get; set; }
}
class Program
{
public static event FireEvent OnFireEvent;
public static event FireNiceEvent OnFireNiceEvent;
static void Main(string[] args)
{
OnFireEvent += SomeSimpleEvent1;
OnFireEvent += SomeSimpleEvent2;
OnFireNiceEvent += SomeStandardEvent1;
OnFireNiceEvent += SomeStandardEvent2;
Console.WriteLine("Firing events.....");
OnFireEvent?.Invoke(3);
OnFireNiceEvent?.Invoke(null, new SomeStandardArgs("Fred"));
//Console.WriteLine($"{HeightSensorTypes.Keyence_IL030}:{(int)HeightSensorTypes.Keyence_IL030}");
Console.ReadLine();
}
private static void SomeSimpleEvent1(int num)
{
Console.WriteLine($"{nameof(SomeSimpleEvent1)}:{num}");
}
private static void SomeSimpleEvent2(int num)
{
Console.WriteLine($"{nameof(SomeSimpleEvent2)}:{num}");
}
private static void SomeStandardEvent1(object sender, SomeStandardArgs args)
{
Console.WriteLine($"{nameof(SomeStandardEvent1)}:{args.ID}");
}
private static void SomeStandardEvent2(object sender, SomeStandardArgs args)
{
Console.WriteLine($"{nameof(SomeStandardEvent2)}:{args.ID}");
}
}
The output will look as follows:
If you did the same with Action<int>
or Action<object, SomeStandardArgs>
, you would only see SomeSimpleEvent2
and SomeStandardEvent2
.
So whats going on inside of event
?
If we expand out FireNiceEvent
, the compiler is actually generating the following (I have omitted some details with respect to thread synchronization that isn't relevant to this discussion):
private EventHandler<SomeStandardArgs> _OnFireNiceEvent;
public void add_OnFireNiceEvent(EventHandler<SomeStandardArgs> handler)
{
Delegate.Combine(_OnFireNiceEvent, handler);
}
public void remove_OnFireNiceEvent(EventHandler<SomeStandardArgs> handler)
{
Delegate.Remove(_OnFireNiceEvent, handler);
}
public event EventHandler<SomeStandardArgs> OnFireNiceEvent
{
add
{
add_OnFireNiceEvent(value)
}
remove
{
remove_OnFireNiceEvent(value)
}
}
The compiler generates a private delegate variable which is not visible to the class namespace in which it is generated. That delegate is what is used for subscription management and late binding participation, and the public facing interface is the familiar +=
and -=
operators we have all come to know and love : )
You can customize the code for the add/remove handlers by changing the scope of the FireNiceEvent
delegate to protected. This now allows developers to add custom hooks to the hooks, such as logging or security hooks. This really makes for some very powerful features that now allows for customized accessibility to subscription based on user roles, etc. Can you do that with lambdas? (Actually you can by custom compiling expression trees, but that's beyond the scope of this response).
To address a couple of points from some of the responses here:
There really is no difference in the 'brittleness' between changing
the args list in Action<T>
and changing the properties in a class
derived from EventArgs
. Either will not only require a compile
change, they will both change a public interface and will require
versioning. No difference.
With respect to which is an industry standard, that depends on where
this is being used and why. Action<T>
and such is often used in IoC
and DI, and event
is often used in message routing such as GUI and
MQ type frameworks. Note that I said often, not always.
Delegates have different lifetimes than lambdas. One also has to be aware of capture... not just with closure, but also with the notion of 'look what the cat dragged in'. This does affect memory footprint/lifetime as well as management a.k.a. leaks.
One more thing, something I referenced earlier... the notion of late binding. You will often see this when using framework like LINQ, regarding when a lambda becomes 'live'. That is very different than late binding of a delegate, which can happen more than once (i.e. the lambda is always there, but binding occurs on demand as often as is needed), as opposed to a lambda, which once it occurs, its done -- the magic is gone, and the method(s)/property(ies) will always bind. Something to keep in mind.
In your router.php file, you should use the model class like this
use App\Post;
and use the model class like this.
Route::get('/posts', function() {
$results = Post::all();
return $results; });
using webpack and vue loader you can do something like this
it waits for the external script to load before creating the component, so globar vars etc are available in the component
components: {
SomeComponent: () => {
return new Promise((resolve, reject) => {
let script = document.createElement('script')
script.onload = () => {
resolve(import(someComponent))
}
script.async = true
script.src = 'https://maps.googleapis.com/maps/api/js?key=APIKEY&libraries=places'
document.head.appendChild(script)
})
}
},
Looking at the "effective POM" will probably help too. For instance, if you wanted to know what the path is for ${project.build.sourceDirectory}
you would find the related XML in the effective POM, such as:
<project>
<build>
<sourceDirectory>/my/path</sourceDirectory>
Also helpful - you can do a real time evaluation of properties via the command line execution of mvn help:evaluate
while in the same dir as the POM.
Try this:
System.Windows.Forms.MessageBox.Show("Here's a message!");
KEYPRESS (enter key)
Click inside the snippet and press Enter key.
Vanilla
document.addEventListener("keypress", function(event) {
if (event.keyCode == 13) {
alert('hi.');
}
});
_x000D_
Vanilla shorthand (ES6)
this.addEventListener('keypress', event => {
if (event.keyCode == 13) {
alert('hi.')
}
})
_x000D_
jQuery
$(this).on('keypress', function(event) {
if (event.keyCode == 13) {
alert('hi.')
}
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
jQuery classic
$(this).keypress(function(event) {
if (event.keyCode == 13) {
alert('hi.')
}
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
jQuery shorthand (ES6)
$(this).keypress((e) => {
if (e.keyCode == 13)
alert('hi.')
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
Even shorter (ES6)
$(this).keypress(e=>
e.which==13?
alert`hi.`:null
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
Due some requests, here an explanation:
I rewrote this answer as things have become deprecated over time so I updated it.
I used this
to focus on the window scope inside the results when document is ready and for the sake of brevity but it's not necessary.
Deprecated:
The .which
and .keyCode
methods are actually considered deprecated so I would recommend .code
but I personally still use keyCode as the performance is much faster and only that counts for me.
The jQuery classic version .keypress()
is not officially deprecated as some people say but they are no more preferred like .on('keypress')
as it has a lot more functionality(live state, multiple handlers, etc.).
The 'keypress'
event in the Vanilla version is also deprecated. People should prefer beforeinput or keydown today. (Note: It has nothing to do with jQuery's events, they are called the same but execute differently.)
All examples above are no biggies regarding deprecated or not. Consoles or any browser should be able to notify you with that if this happens. And if this ever does in future, just fix it.
Readablity:
Despite the ease making it too short and snippy isn't always good either. If you work in a team, your code must be readable and detailed. I recommend the jQuery version .on('keypress')
, this is the way to go and understandable by most people.
Performance:
I always follow my phrase Performance over Effectiveness as anything can be more effective if there is the option but it just should function and execute only what I want, the faster the better. This is why I prefer .keyCode
even if it's considered deprecated(in most cases). It's all up to you though.
It can be due to psql not being in PATH
$ locate psql
/usr/lib/postgresql/9.6/bin/psql
Then create a link in /usr/bin
ln -s /usr/lib/postgresql/9.6/bin/psql /usr/bin/psql
Then try to execute psql it should work.
From SQL Server 2012 you can use a native pagination in order to have semplicity and best performance:
Your query become:
SELECT * FROM Reflow
WHERE ReflowProcessID = somenumber
ORDER BY ID DESC;
OFFSET 20 ROWS
FETCH NEXT 20 ROWS ONLY;
Because datetime
is the module. The class is datetime.datetime
.
import datetime
dtDate = datetime.datetime.strptime(sDate,"%m/%d/%Y")
As Michelle Tilley said, but with the appropriate control flow:
var http = require('http');
var fs = require('fs');
var download = function(url, dest, cb) {
var file = fs.createWriteStream(dest);
http.get(url, function(response) {
response.pipe(file);
file.on('finish', function() {
file.close(cb);
});
});
}
Without waiting for the finish
event, naive scripts may end up with an incomplete file.
Edit: Thanks to @Augusto Roman for pointing out that cb
should be passed to file.close
, not called explicitly.
https://github.com/nodejs/node-gyp#on-windows
try
npm config set python D:\Library\Python\Python27\python.exe
In Nexus 5, Go to Settings -> Google -> Security and uncheck "Scan device for Security threats" and "Improve harmful app detection".
textBox1.Text = "Line1\r\r\Line2";
Solved the problem.
As Christian's answer with assign()
shows, there is a way to assign in the global environment. A simpler, shorter (but not better ... stick with assign) way is to use the <<-
operator, ie
a <<- "new"
inside the function.
sudo xcodebuild -license
will take care of it with no trouble on the command line. Note that you'll have to manually scroll through the license, and agree to its terms at the end, unless you add "accept" to the command line :
sudo xcodebuild -license accept
If the UIButton
is in the combined state of selected
and disabled
, its state is UIControlStateSelected | UIControlStateDisabled
.
So its state needs to be adjusted like this:
[button setTitleColor:color UIControlStateSelected | UIControlStateDisabled];
[button setImage:image forState:UIControlStateSelected | UIControlStateDisabled];
One approach is to subclass UIButton
as follows:
@implementation TTButton
- (void)awakeFromNib {
[super awakeFromNib];
//! Fix behavior when `disabled && selected`
//! Load settings in `xib` or `storyboard`, and apply it again.
UIColor *color = [self titleColorForState:UIControlStateDisabled];
[self setTitleColor:color forState:UIControlStateDisabled];
UIImage *img = [self imageForState:UIControlStateDisabled];
[self setImage:img forState:UIControlStateDisabled];
}
- (void)setTitleColor:(UIColor *)color forState:(UIControlState)state {
[super setTitleColor:color forState:state];
//
if (UIControlStateDisabled == state) {
[super setTitleColor:color forState:UIControlStateSelected | state];
[super setTitleColor:color forState:UIControlStateHighlighted | state];
}
}
- (void)setImage:(UIImage *)image forState:(UIControlState)state {
[super setImage:image forState:state];
if (UIControlStateDisabled == state) {
[super setImage:image forState:UIControlStateSelected | state];
[super setImage:image forState:UIControlStateHighlighted | state];
}
}
@end