ConfigurationManager.AppSettings returns the settings defined for the application, not for the specific DLL, you can access them but it's the application settings that will be returned.
If you're using you dll from another application then the ConnectionString shall be in the app.settings of the application.
*Using Robot class you can do this, Try following code:
Actions action = new Actions(driver);
action.contextClick(WebElement).build().perform();
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
[UPDATE]
CAUTION: Your Browser should always be in focus i.e. running in foreground while performing Robot Actions, other-wise any other application in foreground will receive the actions.
Just to simplify -
Entity framework doesn't support primitives. You either create a class to wrap it or add another property to format the list as a string:
public ICollection<string> List { get; set; }
public string ListString
{
get { return string.Join(",", List); }
set { List = value.Split(',').ToList(); }
}
If you're going across machines, you either need to be using NETWORK SERVICE, LOCAL SYSTEM, a domain account, or a SQL 2008 R2 (if you have it) Managed Service Account (which is my preference if you had such an infrastructure). You can not use an account which is not visible to the Active Directory domain.
function disableItems(divSelector){
var disableInputs = $(divSelector).find(":input").not("[disabled]");
disableInputs.attr("data-reenable", true);
disableInputs.attr("disabled", true);
}
function reEnableItems(divSelector){
var reenableInputs = $(divSelector).find("[data-reenable]");
reenableInputs.removeAttr("disabled");
reenableInputs.removeAttr("data-reenable");
}
You can use RIGHT :
select RIGHT(123.45,2) return => 45
Here's one way:
Stream myStream = null;
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = theDialog.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
Modified from here:MSDN OpenFileDialog.OpenFile
EDIT Here's another way more suited to your needs:
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog theDialog = new OpenFileDialog();
theDialog.Title = "Open Text File";
theDialog.Filter = "TXT files|*.txt";
theDialog.InitialDirectory = @"C:\";
if (theDialog.ShowDialog() == DialogResult.OK)
{
string filename = theDialog.FileName;
string[] filelines = File.ReadAllLines(filename);
List<Employee> employeeList = new List<Employee>();
int linesPerEmployee = 4;
int currEmployeeLine = 0;
//parse line by line into instance of employee class
Employee employee = new Employee();
for (int a = 0; a < filelines.Length; a++)
{
//check if to move to next employee
if (a != 0 && a % linesPerEmployee == 0)
{
employeeList.Add(employee);
employee = new Employee();
currEmployeeLine = 1;
}
else
{
currEmployeeLine++;
}
switch (currEmployeeLine)
{
case 1:
employee.EmployeeNum = Convert.ToInt32(filelines[a].Trim());
break;
case 2:
employee.Name = filelines[a].Trim();
break;
case 3:
employee.Address = filelines[a].Trim();
break;
case 4:
string[] splitLines = filelines[a].Split(' ');
employee.Wage = Convert.ToDouble(splitLines[0].Trim());
employee.Hours = Convert.ToDouble(splitLines[1].Trim());
break;
}
}
//Test to see if it works
foreach (Employee emp in employeeList)
{
MessageBox.Show(emp.EmployeeNum + Environment.NewLine +
emp.Name + Environment.NewLine +
emp.Address + Environment.NewLine +
emp.Wage + Environment.NewLine +
emp.Hours + Environment.NewLine);
}
}
}
Android Text Justify For TextView XML
Simply android text-justify using in XML. You can simply implement in textview widget.
<TextView
android:justificationMode="inter_word"
/>
Default is android:justificationMode="none"
As Constructor should be at the starting of the Class , you are facing the above issue . So, you can either change the name or if you want to use it as a constructor just copy the method at the beginning of the class.
Also use NVL2
as below if you want to return other value from the field_to_check
:
NVL2( field_to_check, value_if_NOT_null, value_if_null )
Usage: ORACLE/PLSQL: NVL2 FUNCTION
Like Other said you can use something like that:
IF NOT EXISTS (SELECT 1 FROM Table)
BEGIN
--Do Something
END
ELSE
BEGIN
--Do Another Thing
END
For further visitors:
// Executes: SELECT * FROM mytable LIMIT 10 OFFSET 20
// get([$table = ''[, $limit = NULL[, $offset = NULL]]])
$query = $this->db->get('mytable', 10, 20);
// get_where sample,
$query = $this->db->get_where('mytable', array('id' => $id), 10, 20);
// Produces: LIMIT 10
$this->db->limit(10);
// Produces: LIMIT 10 OFFSET 20
// limit($value[, $offset = 0])
$this->db->limit(10, 20);
There is also the strncmp()
function and strncasecmp()
function which is perfect for this situation:
if (strncmp($string_n, "http", 4) === 0)
In general:
if (strncmp($string_n, $prefix, strlen($prefix)) === 0)
The advantage over the substr()
approach is that strncmp()
just does what needs to be done, without creating a temporary string.
Roughly you can do it like that :
try
{
//do something
}
catch (Exception ex)
{
string script = "<script>alert('" + ex.Message + "');</script>";
if (!Page.IsStartupScriptRegistered("myErrorScript"))
{
Page.ClientScript.RegisterStartupScript("myErrorScript", script);
}
}
But I recommend you to define your custom Exception and throw it anywhere you need. At your page catch this custom exception and register your message box script.
I think that you are looking for something like this:
function rightclick() {
var rightclick;
var e = window.event;
if (e.which) rightclick = (e.which == 3);
else if (e.button) rightclick = (e.button == 2);
alert(rightclick); // true or false, you can trap right click here by if comparison
}
(http://www.quirksmode.org/js/events_properties.html)
And then use the onmousedown even with the function rightclick() (if you want to use it globally on whole page you can do this <body onmousedown=rightclick(); >
INTRO: This answer was written in a time when Numpy was version 1.11 and behaviour of NAT comparison was supposed to change since version 1.12. Clearly that wasn't the case and the second part of answer became wrong. The first part of answer may be not applicable for new versions of numpy. Be sure you've checked MSeifert's answers below.
import numpy as np
nat = np.datetime64('NaT')
def nat_check(nat):
return nat == np.datetime64('NaT')
nat_check(nat)
Out[4]: FutureWarning: In the future, 'NAT == x' and 'x == NAT' will always be False.
True
nat_check(nat)
Out[5]: True
If you want to suppress the warning you can use the catch_warnings context manager:
import numpy as np
import warnings
nat = np.datetime64('NaT')
def nat_check(nat):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return nat == np.datetime64('NaT')
nat_check(nat)
Out[5]: True
And finally you might check numpy version to handle changed behavior since version 1.12.0:
def nat_check(nat):
if [int(x) for x in np.__version__.split('.')[:-1]] > [1, 11]:
return nat != nat
with warnings.catch_warnings():
warnings.simplefilter("ignore")
return nat == np.datetime64('NaT')
isnat
function since version 1.13.
I would like to add a word of warning when you are dealing with C++11-style allocator-aware containers. Swapping and assignment have subtly different semantics.
For concreteness, let us consider a container std::vector<T, A>
, where A
is some stateful allocator type, and we'll compare the following functions:
void fs(std::vector<T, A> & a, std::vector<T, A> & b)
{
a.swap(b);
b.clear(); // not important what you do with b
}
void fm(std::vector<T, A> & a, std::vector<T, A> & b)
{
a = std::move(b);
}
The purpose of both functions fs
and fm
is to give a
the state that b
had initially. However, there is a hidden question: What happens if a.get_allocator() != b.get_allocator()
? The answer is: It depends. Let's write AT = std::allocator_traits<A>
.
If AT::propagate_on_container_move_assignment
is std::true_type
, then fm
reassigns the allocator of a
with the value of b.get_allocator()
, otherwise it does not, and a
continues to use its original allocator. In that case, the data elements need to be swapped individually, since the storage of a
and b
is not compatible.
If AT::propagate_on_container_swap
is std::true_type
, then fs
swaps both data and allocators in the expected fashion.
If AT::propagate_on_container_swap
is std::false_type
, then we need a dynamic check.
a.get_allocator() == b.get_allocator()
, then the two containers use compatible storage, and swapping proceeds in the usual fashion.a.get_allocator() != b.get_allocator()
, the program has undefined behaviour (cf. [container.requirements.general/8].The upshot is that swapping has become a non-trivial operation in C++11 as soon as your container starts supporting stateful allocators. That's a somewhat "advanced use case", but it's not entirely unlikely, since move optimizations usually only become interesting once your class manages a resource, and memory is one of the most popular resources.
check properties->java build path -> libraries. there should be no errors, in my case there was errors in the maven. once I put the required jar in the maven repo, it worked fine
You can use ng-include
directive.
Try something like this:
emanuel.directive('hymn', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
scope.getContentUrl = function() {
return 'content/excerpts/hymn-' + attrs.ver + '.html';
}
},
template: '<div ng-include="getContentUrl()"></div>'
}
});
UPD. for watching ver
attribute
emanuel.directive('hymn', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
scope.contentUrl = 'content/excerpts/hymn-' + attrs.ver + '.html';
attrs.$observe("ver",function(v){
scope.contentUrl = 'content/excerpts/hymn-' + v + '.html';
});
},
template: '<div ng-include="contentUrl"></div>'
}
});
The pack() method is defined in Window class in Java and it sizes the frame so that all its contents are at or above their preferred sizes.
I found a solution in the guide here:
http://www.samontab.com/web/2014/06/installing-opencv-2-4-9-in-ubuntu-14-04-lts/
I resorted to compiling and installing from source. The process was very smooth, had I known, I would have started with that instead of trying to find a more simple way to install. Hopefully this information is helpful to someone.
The same dialog asking for the KeyChain password has 3 buttons. Most likely the wanted password is that for logging in to your Mac. If you press "Allow" it only works for some tiny aspect and will ask again, which is very puzzling. You need to press "Always Allow". The verification team at Apple is very weak, they need some 'normal' developers in the design team for the chain of events to get an app in the app store. Normal developers have very sketchy ideas about KeyChains and Certificates and Profiles.
These parameters are typically used for proxy functions, so the proxy can pass any input parameter to the target function.
def foo(bar=2, baz=5):
print bar, baz
def proxy(x, *args, **kwargs): # reqire parameter x and accept any number of additional arguments
print x
foo(*args, **kwargs) # applies the "non-x" parameter to foo
proxy(23, 5, baz='foo') # calls foo with bar=5 and baz=foo
proxy(6)# calls foo with its default arguments
proxy(7, bar='asdas') # calls foo with bar='asdas' and leave baz default argument
But since these parameters hide the actual parameter names, it is better to avoid them.
Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.
This will be a JRE and JDK package.
There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.
It's useful in situations where you have hidden internal state such as a cache. For example:
class HashTable { ... public: string lookup(string key) const { if(key == lastKey) return lastValue; string value = lookupInternal(key); lastKey = key; lastValue = value; return value; } private: mutable string lastKey, lastValue; };
And then you can have a const HashTable
object still use its lookup()
method, which modifies the internal cache.
This answer is for anyone encountering pdfs with images and needing to use OCR. I could not find a workable off-the-shelf solution; nothing that gave me the accuracy I needed.
Here are the steps I found to work.
Use pdfimages
from https://poppler.freedesktop.org/ to turn the pages of the pdf into images.
Use Tesseract to detect rotation and ImageMagick mogrify
to fix it.
Use OpenCV to find and extract tables.
Use OpenCV to find and extract each cell from the table.
Use OpenCV to crop and clean up each cell so that there is no noise that will confuse OCR software.
Use Tesseract to OCR each cell.
Combine the extracted text of each cell into the format you need.
I wrote a python package with modules that can help with those steps.
Repo: https://github.com/eihli/image-table-ocr
Docs & Source: https://eihli.github.io/image-table-ocr/pdf_table_extraction_and_ocr.html
Some of the steps don't require code, they take advantage of external tools like pdfimages
and tesseract
. I'll provide some brief examples for a couple of the steps that do require code.
This link was a good reference while figuring out how to find tables. https://answers.opencv.org/question/63847/how-to-extract-tables-from-an-image/
import cv2
def find_tables(image):
BLUR_KERNEL_SIZE = (17, 17)
STD_DEV_X_DIRECTION = 0
STD_DEV_Y_DIRECTION = 0
blurred = cv2.GaussianBlur(image, BLUR_KERNEL_SIZE, STD_DEV_X_DIRECTION, STD_DEV_Y_DIRECTION)
MAX_COLOR_VAL = 255
BLOCK_SIZE = 15
SUBTRACT_FROM_MEAN = -2
img_bin = cv2.adaptiveThreshold(
~blurred,
MAX_COLOR_VAL,
cv2.ADAPTIVE_THRESH_MEAN_C,
cv2.THRESH_BINARY,
BLOCK_SIZE,
SUBTRACT_FROM_MEAN,
)
vertical = horizontal = img_bin.copy()
SCALE = 5
image_width, image_height = horizontal.shape
horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (int(image_width / SCALE), 1))
horizontally_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, horizontal_kernel)
vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, int(image_height / SCALE)))
vertically_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, vertical_kernel)
horizontally_dilated = cv2.dilate(horizontally_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (40, 1)))
vertically_dilated = cv2.dilate(vertically_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (1, 60)))
mask = horizontally_dilated + vertically_dilated
contours, hierarchy = cv2.findContours(
mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE,
)
MIN_TABLE_AREA = 1e5
contours = [c for c in contours if cv2.contourArea(c) > MIN_TABLE_AREA]
perimeter_lengths = [cv2.arcLength(c, True) for c in contours]
epsilons = [0.1 * p for p in perimeter_lengths]
approx_polys = [cv2.approxPolyDP(c, e, True) for c, e in zip(contours, epsilons)]
bounding_rects = [cv2.boundingRect(a) for a in approx_polys]
# The link where a lot of this code was borrowed from recommends an
# additional step to check the number of "joints" inside this bounding rectangle.
# A table should have a lot of intersections. We might have a rectangular image
# here though which would only have 4 intersections, 1 at each corner.
# Leaving that step as a future TODO if it is ever necessary.
images = [image[y:y+h, x:x+w] for x, y, w, h in bounding_rects]
return images
This is very similar to 2, so I won't include all the code. The part I will reference will be in sorting the cells.
We want to identify the cells from left-to-right, top-to-bottom.
We’ll find the rectangle with the most top-left corner. Then we’ll find all of the rectangles that have a center that is within the top-y and bottom-y values of that top-left rectangle. Then we’ll sort those rectangles by the x value of their center. We’ll remove those rectangles from the list and repeat.
def cell_in_same_row(c1, c2):
c1_center = c1[1] + c1[3] - c1[3] / 2
c2_bottom = c2[1] + c2[3]
c2_top = c2[1]
return c2_top < c1_center < c2_bottom
orig_cells = [c for c in cells]
rows = []
while cells:
first = cells[0]
rest = cells[1:]
cells_in_same_row = sorted(
[
c for c in rest
if cell_in_same_row(c, first)
],
key=lambda c: c[0]
)
row_cells = sorted([first] + cells_in_same_row, key=lambda c: c[0])
rows.append(row_cells)
cells = [
c for c in rest
if not cell_in_same_row(c, first)
]
# Sort rows by average height of their center.
def avg_height_of_center(row):
centers = [y + h - h / 2 for x, y, w, h in row]
return sum(centers) / len(centers)
rows.sort(key=avg_height_of_center)
You don't need to set name , just giving an id is enough.
<input type="hidden" id="testId" />
and than with jquery you can use 'val()' method like below:
$('#testId').val("work");
AskTom is probably the single most helpful resource on best practices on Oracle DBs. (I usually just type "asktom" as the first word of a google query on a particular topic)
I don't think it's really appropriate to speak of design patterns with relational databases. Relational databases are already the application of a "design pattern" to a problem (the problem being "how to represent, store and work with data while maintaining its integrity", and the design being the relational model). Other approches (generally considered obsolete) are the Navigational and Hierarchical models (and I'm nure many others exist).
Having said that, you might consider "Data Warehousing" as a somewhat separate "pattern" or approach in database design. In particular, you might be interested in reading about the Star schema.
Content-Type: application/json
is just the content header. The content header is just information about the type of returned data, ex::JSON,image(png,jpg,etc..),html.
Keep in mind, that JSON in JavaScript is an array or object. If you want to see all the data, use console.log instead of alert:
alert(response.text); // Will alert "[object Object]" string
console.log(response.text); // Will log all data objects
If you want to alert the original JSON content as a string, then add single quotation marks ('):
echo "'" . json_encode(array('text' => 'omrele')) . "'";
// alert(response.text) will alert {"text":"omrele"}
Do not use double quotes. It will confuse JavaScript, because JSON uses double quotes on each value and key:
echo '<script>var returndata=';
echo '"' . json_encode(array('text' => 'omrele')) . '"';
echo ';</script>';
// It will return the wrong JavaScript code:
<script>var returndata="{"text":"omrele"}";</script>
On my Windows 7 machine I have the following environment variables:
JAVA_HOME=C:\Program Files\Java\jdk1.7.0_07
M2_HOME=C:\apache-maven-3.0.3
On my PATH
variable, I have (among others) the following:
I tried doing what you've done with %M2%
having the nested %M2_HOME%
and it also works.
If you use read_excel()
on a file opened using the function open()
, make sure to add rb
to the open function to avoid encoding errors
I have used YouTube thumbnails in this way:
$url = 'http://img.youtube.com/vi/' . $youtubeId . '/0.jpg';
$img = dirname(__FILE__) . '/youtubeThumbnail_' . $youtubeId . '.jpg';
file_put_contents($img, file_get_contents($url));
Remember YouTube prevents to include images directly from their server.
I specify the name by defining inside the VagrantFile and also specify the hostname so i enjoy seeing the name of my project while executing Linux commands independently from my device's OS. ??
config.vm.define "abc"
config.vm.hostname = "abc"
Issue the following command to reseed mytable to start at 1:
DBCC CHECKIDENT (mytable, RESEED, 0)
Read about it in the Books on Line (BOL, SQL help). Also be careful that you don't have records higher than the seed you are setting.
Extension class:
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace MyProj.Extensions
{
public static class XmlExtension
{
public static string Serialize<T>(this T value)
{
if (value == null) return string.Empty;
var xmlSerializer = new XmlSerializer(typeof(T));
using (var stringWriter = new StringWriter())
{
using (var xmlWriter = XmlWriter.Create(stringWriter,new XmlWriterSettings{Indent = true}))
{
xmlSerializer.Serialize(xmlWriter, value);
return stringWriter.ToString();
}
}
}
}
}
Usage:
Foo foo = new Foo{MyProperty="I have been serialized"};
string xml = foo.Serialize();
Just reference the namespace holding your extension method in the file you would like to use it in and it'll work (in my example it would be: using MyProj.Extensions;
)
Note that if you want to make the extension method specific to only a particular class(eg., Foo
), you can replace the T
argument in the extension method, eg.
public static string Serialize(this Foo value){...}
<?php
function info($name="George",$age=18) {
echo "$name is $age years old.<br>";
}
info(); // prints default values(number of values = 2)
info("Nick"); // changes first default argument from George to Nick
info("Mark",17); // changes both default arguments' values
?>
An option for your application would be to write a replacement Home Screen using the android.intent.category.HOME Intent. I believe this type of Intent you can see the home button.
More details:
http://developer.android.com/guide/topics/intents/intents-filters.html#imatch
CSS3 flexbox can also be used to align button at the bottom of parent element.
Required HTML:
<div class="container">
<div class="btn-holder">
<button type="button">Click</button>
</div>
</div>
Necessary CSS:
.container {
justify-content: space-between;
flex-direction: column;
height: 100vh;
display: flex;
}
.container .btn-holder {
justify-content: flex-end;
display: flex;
}
Screenshot:
Useful Resources:
* {box-sizing: border-box;}_x000D_
body {_x000D_
background: linear-gradient(orange, yellow);_x000D_
font: 14px/18px Arial, sans-serif;_x000D_
margin: 0;_x000D_
}_x000D_
.container {_x000D_
justify-content: space-between;_x000D_
flex-direction: column;_x000D_
height: 100vh;_x000D_
display: flex;_x000D_
padding: 10px;_x000D_
}_x000D_
.container .btn-holder {_x000D_
justify-content: flex-end;_x000D_
display: flex;_x000D_
}_x000D_
.container .btn-holder button {_x000D_
padding: 10px 25px;_x000D_
background: blue;_x000D_
font-size: 16px;_x000D_
border: none;_x000D_
color: #fff;_x000D_
}
_x000D_
<div class="container">_x000D_
<p>Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... </p>_x000D_
<div class="btn-holder">_x000D_
<button type="button">Click</button>_x000D_
</div>_x000D_
</div>
_x000D_
Remove duplicate values from NSMutableArray in Objective-C
NSMutableArray *datelistArray = [[NSMutableArray alloc]init];
for (Student * data in fetchStudentDateArray)
{
if([datelistArray indexOfObject:data.date] == NSNotFound)
[datelistArray addObject:data.date];
}
When a JSF view (Facelets/JSP file) get built/restored, a JSF component tree will be produced. At that moment, the view build time, all binding
attributes are evaluated (along with id
attribtues and taghandlers like JSTL). When the JSF component needs to be created before being added to the component tree, JSF will check if the binding
attribute returns a precreated component (i.e. non-null
) and if so, then use it. If it's not precreated, then JSF will autocreate the component "the usual way" and invoke the setter behind binding
attribute with the autocreated component instance as argument.
In effects, it binds a reference of the component instance in the component tree to a scoped variable. This information is in no way visible in the generated HTML representation of the component itself. This information is in no means relevant to the generated HTML output anyway. When the form is submitted and the view is restored, the JSF component tree is just rebuilt from scratch and all binding
attributes will just be re-evaluated like described in above paragraph. After the component tree is recreated, JSF will restore the JSF view state into the component tree.
Important to know and understand is that the concrete component instances are effectively request scoped. They're newly created on every request and their properties are filled with values from JSF view state during restore view phase. So, if you bind the component to a property of a backing bean, then the backing bean should absolutely not be in a broader scope than the request scope. See also JSF 2.0 specitication chapter 3.1.5:
3.1.5 Component Bindings
...
Component bindings are often used in conjunction with JavaBeans that are dynamically instantiated via the Managed Bean Creation facility (see Section 5.8.1 “VariableResolver and the Default VariableResolver”). It is strongly recommend that application developers place managed beans that are pointed at by component binding expressions in “request” scope. This is because placing it in session or application scope would require thread-safety, since UIComponent instances depends on running inside of a single thread. There are also potentially negative impacts on memory management when placing a component binding in “session” scope.
Otherwise, component instances are shared among multiple requests, possibly resulting in "duplicate component ID" errors and "weird" behaviors because validators, converters and listeners declared in the view are re-attached to the existing component instance from previous request(s). The symptoms are clear: they are executed multiple times, one time more with each request within the same scope as the component is been bound to.
And, under heavy load (i.e. when multiple different HTTP requests (threads) access and manipulate the very same component instance at the same time), you may face sooner or later an application crash with e.g. Stuck thread at UIComponent.popComponentFromEL, or Java Threads at 100% CPU utilization using richfaces UIDataAdaptorBase and its internal HashMap, or even some "strange" IndexOutOfBoundsException
or ConcurrentModificationException
coming straight from JSF implementation source code while JSF is busy saving or restoring the view state (i.e. the stack trace indicates saveState()
or restoreState()
methods and like).
binding
on a bean property is bad practiceRegardless, using binding
this way, binding a whole component instance to a bean property, even on a request scoped bean, is in JSF 2.x a rather rare use case and generally not the best practice. It indicates a design smell. You normally declare components in the view side and bind their runtime attributes like value
, and perhaps others like styleClass
, disabled
, rendered
, etc, to normal bean properties. Then, you just manipulate exactly that bean property you want instead of grabbing the whole component and calling the setter method associated with the attribute.
In cases when a component needs to be "dynamically built" based on a static model, better is to use view build time tags like JSTL, if necessary in a tag file, instead of createComponent()
, new SomeComponent()
, getChildren().add()
and what not. See also How to refactor snippet of old JSP to some JSF equivalent?
Or, if a component needs to be "dynamically rendered" based on a dynamic model, then just use an iterator component (<ui:repeat>
, <h:dataTable>
, etc). See also How to dynamically add JSF components.
Composite components is a completely different story. It's completely legit to bind components inside a <cc:implementation>
to the backing component (i.e. the component identified by <cc:interface componentType>
. See also a.o. Split java.util.Date over two h:inputText fields representing hour and minute with f:convertDateTime and How to implement a dynamic list with a JSF 2.0 Composite Component?
binding
in local scopeHowever, sometimes you'd like to know about the state of a different component from inside a particular component, more than often in use cases related to action/value dependent validation. For that, the binding
attribute can be used, but not in combination with a bean property. You can just specify an in the local EL scope unique variable name in the binding
attribute like so binding="#{foo}"
and the component is during render response elsewhere in the same view directly as UIComponent
reference available by #{foo}
. Here are several related questions where such a solution is been used in the answer:
Use an EL expression to pass a component ID to a composite component in JSF
(and that's only from the last month...)
Strange, but the accepted answer seems wrong about the cast and the Convert in the mean that from my tests and reading the documentation too it should not take into account implicit or explicit operators.
So, if I have a variable of type object and the "boxed" class has some implicit operators defined they won't work.
Instead another simple way, but really performance costing is to cast before in dynamic.
(int)(dynamic)myObject.
You can try it in the Interactive window of VS.
public class Test
{
public static implicit operator int(Test v)
{
return 12;
}
}
(int)(object)new Test() //this will fail
Convert.ToInt32((object)new Test()) //this will fail
(int)(dynamic)(object)new Test() //this will pass
The problem is likely to lie with the line:
window.onload = onPageLoad();
By including the brackets you are saying onload
should equal the return value of onPageLoad()
. For example:
/*Example function*/
function onPageLoad()
{
return "science";
}
/*Set on load*/
window.onload = onPageLoad()
If you print out the value of window.onload
to the console it will be:
science
The solution is remove the brackets:
window.onload = onPageLoad;
So, you're using onPageLoad
as a reference to the so-named function.
Finally, in order to get the response value you'll need a readystatechange
listener for your XMLHttpRequest
object, since it's asynchronous:
xmlDoc = xmlhttp.responseXML;
parser = new DOMParser(); // This code is untested as it doesn't run this far.
Here you add the listener:
xmlHttp.onreadystatechange = function() {
if(this.readyState == 4) {
// Do something
}
}
You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save
(or the before_validation
) callback. Here's an example of the relevant code for a model like yours:
class Place < ActiveRecord::Base before_save do |place| place.city = place.city.downcase.titleize place.country = place.country.downcase.titleize end end
You can also check out the Ruby on Rails guide for more info.
To answer you question more directly, something like this would work:
<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>
This just means if f.object.city
exists, display the titlecase
version of it, and if it doesn't display a blank string.
I prefer to work with the PSDrive WSMan:\
.
Get TrustedHosts
Get-Item WSMan:\localhost\Client\TrustedHosts
Set TrustedHosts
provide a single, comma-separated, string of computer names
Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'machineA,machineB'
or (dangerous) a wild-card
Set-Item WSMan:\localhost\Client\TrustedHosts -Value '*'
to append to the list, the -Concatenate
parameter can be used
Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'machineC' -Concatenate
div{
border-left:solid red 3px;
border-right:solid violet 4px;
border-top:solid blue 4px;
border-bottom:solid green 4px;
background:grey;
width:100px; height:50px
}
The ioctl
function is useful for implementing a device driver to set the configuration on the device. e.g. a printer that has configuration options to check and set the font family, font size etc. ioctl
could be used to get the current font as well as set the font to a new one. A user application uses ioctl
to send a code to a printer telling it to return the current font or to set the font to a new one.
int ioctl(int fd, int request, ...)
fd
is file descriptor, the one returned by open
;request
is request code. e.g GETFONT
will get the current font from the printer, SETFONT
will set the font on the printer;void *
. Depending on the second argument, the third may or may not be present,
e.g. if the second argument is SETFONT
, the third argument can be the font name such as "Arial"
;int request
is not just a macro. A user application is required to generate a request code and the device driver module to determine which configuration on device must be played with. The application sends the request code using ioctl
and then uses the request code in the device driver module to determine which action to perform.
A request code has 4 main parts
1. A Magic number - 8 bits
2. A sequence number - 8 bits
3. Argument type (typically 14 bits), if any.
4. Direction of data transfer (2 bits).
If the request code is SETFONT
to set font on a printer, the direction for data transfer will be from user application to device driver module (The user application sends the font name "Arial"
to the printer).
If the request code is GETFONT
, direction is from printer to the user application.
In order to generate a request code, Linux provides some predefined function-like macros.
1._IO(MAGIC, SEQ_NO)
both are 8 bits, 0 to 255, e.g. let us say we want to pause printer.
This does not require a data transfer. So we would generate the request code as below
#define PRIN_MAGIC 'P'
#define NUM 0
#define PAUSE_PRIN __IO(PRIN_MAGIC, NUM)
and now use ioctl
as
ret_val = ioctl(fd, PAUSE_PRIN);
The corresponding system call in the driver module will receive the code and pause the printer.
__IOW(MAGIC, SEQ_NO, TYPE)
MAGIC
and SEQ_NO
are the same as above, and TYPE
gives the type of the next argument, recall the third argument of ioctl
is void *
. W in __IOW
indicates that the data flow is from user application to driver module. As an example,
suppose we want to set the printer font to "Arial"
.#define PRIN_MAGIC 'S'
#define SEQ_NO 1
#define SETFONT __IOW(PRIN_MAGIC, SEQ_NO, unsigned long)
further,
char *font = "Arial";
ret_val = ioctl(fd, SETFONT, font);
Now font
is a pointer, which means it is an address best represented as unsigned long
, hence the third part of _IOW
mentions type as such. Also, this address of font is passed to corresponding system call implemented in device driver module as unsigned long
and we need to cast it to proper type before using it. Kernel space can access user space and hence this works. other two function-like macros are __IOR(MAGIC, SEQ_NO, TYPE)
and __IORW(MAGIC, SEQ_NO, TYPE)
where the data flow will be from kernel space to user space and both ways respectively.
Please let me know if this helps!
Without sharex=True, sharey=True
you get:
With it you should get it nicer:
fig, axes2d = plt.subplots(nrows=3, ncols=3,
sharex=True, sharey=True,
figsize=(6,6))
for i, row in enumerate(axes2d):
for j, cell in enumerate(row):
cell.imshow(np.random.rand(32,32))
plt.tight_layout()
But if you want to add additional labels, you should add them only to the edge plots:
fig, axes2d = plt.subplots(nrows=3, ncols=3,
sharex=True, sharey=True,
figsize=(6,6))
for i, row in enumerate(axes2d):
for j, cell in enumerate(row):
cell.imshow(np.random.rand(32,32))
if i == len(axes2d) - 1:
cell.set_xlabel("noise column: {0:d}".format(j + 1))
if j == 0:
cell.set_ylabel("noise row: {0:d}".format(i + 1))
plt.tight_layout()
Adding label for each plot would spoil it (maybe there is a way to automatically detect repeated labels, but I am not aware of one).
you can save the model in json and weights in a hdf5 file format.
# keras library import for Saving and loading model and weights
from keras.models import model_from_json
from keras.models import load_model
# serialize model to JSON
# the keras model which is trained is defined as 'model' in this example
model_json = model.to_json()
with open("model_num.json", "w") as json_file:
json_file.write(model_json)
# serialize weights to HDF5
model.save_weights("model_num.h5")
files "model_num.h5" and "model_num.json" are created which contain our model and weights
To use the same trained model for further testing you can simply load the hdf5 file and use it for the prediction of different data. here's how to load the model from saved files.
# load json and create model
json_file = open('model_num.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
# load weights into new model
loaded_model.load_weights("model_num.h5")
print("Loaded model from disk")
loaded_model.save('model_num.hdf5')
loaded_model=load_model('model_num.hdf5')
To predict for different data you can use this
loaded_model.predict_classes("your_test_data here")
Javascript is pretty good at manipulating css.
document.body.style.cursor = *cursor-url*;
//OR
var elementToChange = document.getElementsByTagName("body")[0];
elementToChange.style.cursor = "url('cursor url with protocol'), auto";
or with jquery:
$("html").css("cursor: url('cursor url with protocol'), auto");
Firefox will not work unless you specify a default cursor after the imaged one!
Also remember that IE6 only supports .cur and .ani cursors.
If cursor doesn't change: In case you are moving the element under the cursor relative to the cursor position (e.g. element dragging) you have to force a redraw on the element:
// in plain js
document.getElementById('parentOfElementToBeRedrawn').style.display = 'none';
document.getElementById('parentOfElementToBeRedrawn').style.display = 'block';
// in jquery
$('#parentOfElementToBeRedrawn').hide().show(0);
working sample:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>First jQuery-Enabled Page</title>
<style type="text/css">
div {
height: 100px;
width: 1000px;
background-color: red;
}
</style>
<script type="text/javascript" src="jquery-1.3.2.js"></script></head>
<body>
<div>
hello with a fancy cursor!
</div>
</body>
<script type="text/javascript">
document.getElementsByTagName("body")[0].style.cursor = "url('http://wiki-devel.sugarlabs.org/images/e/e2/Arrow.cur'), auto";
</script>
</html>
According to @Shovalt's answer, but in short:
Alternatively you could use the following lines of code
from sklearn.metrics import f1_score
metrics.f1_score(y_test, y_pred, labels=np.unique(y_pred))
This should remove your warning and give you the result you wanted, because it no longer considers the difference between the sets, by using the unique mode.
For Mac OSX: There is a way to install Visual Studio Code through Brew-Cask.
Now run following command and it will install latest Visual Studio Code on your Mac.
$> brew cask install visual-studio-code
Above command should install Visual Studio Code and also set up the command-line calling of Visual Studio Code.
If above steps don't work then you can do it manually. By following Microsoft Visual Studio Code documentation given here.
Bind & protected-mode both are the essential steps. But if ufw is enabled then you will have to make redis port allow in ufw.
ufw status
if Status: active
then allow redis-port ufw allow 6379
vi /etc/redis/redis.conf
bind 127.0.0.1
to bind 0.0.0.0
protected-mode yes
to protected-mode no
for me, (OSX) the problem was solved doing this:
brew install pkg-config
You can even use a version range with pip install
command. Something like this:
pip install 'stevedore>=1.3.0,<1.4.0'
And if the package is already installed and you want to downgrade it add --force-reinstall
like this:
pip install 'stevedore>=1.3.0,<1.4.0' --force-reinstall
Just to add to roya's answer. In c# 6.0 you can now use string interpolation:
Console.WriteLine($"{customer[DisplayPos],10}" +
$"{salesFigures[DisplayPos],10}" +
$"{feePayable[DisplayPos],10}" +
$"{seventyPercentValue,10}" +
$"{thirtyPercentValue,10}");
This can actually be one line without all the extra dollars, I just think it makes it a bit easier to read like this.
And you could also use a static import on System.Console, allowing you to do this:
using static System.Console;
WriteLine(/* write stuff */);
I did a quick experiment after looking at a number of potential solutions all over the place. This is what I ended up with:
There are various ways to take a comma-separated list and parse it into multiple rows of data. In SQL
SQL> ed
Wrote file afiedt.buf
1 with x as (
2 select '1,2,3,a,b,c,d' str from dual
3 )
4 select regexp_substr(str,'[^,]+',1,level) element
5 from x
6* connect by level <= length(regexp_replace(str,'[^,]+')) + 1
SQL> /
ELEMENT
----------------------------------------------------
1
2
3
a
b
c
d
7 rows selected.
Or in PL/SQL
SQL> create type str_tbl is table of varchar2(100);
2 /
Type created.
SQL> create or replace function parse_list( p_list in varchar2 )
2 return str_tbl
3 pipelined
4 is
5 begin
6 for x in (select regexp_substr( p_list, '[^,]', 1, level ) element
7 from dual
8 connect by level <= length( regexp_replace( p_list, '[^,]+')) + 1)
9 loop
10 pipe row( x.element );
11 end loop
12 return;
13 end;
14
15 /
Function created.
SQL> select *
2 from table( parse_list( 'a,b,c,1,2,3,d,e,foo' ));
COLUMN_VALUE
--------------------------------------------------------------------------------
a
b
c
1
2
3
d
e
f
9 rows selected.
I'm used it and worked perfectly...
startActivity(new Intent(getApplicationContext(),MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
because Finish() use for 2 activities, not for multiple activities
PHP foreach loop can be used with Indexed arrays
, Associative arrays
and Object public variables
.
In foreach loop, the first thing php does is that it creates a copy of the array which is to be iterated over. PHP then iterates over this new copy
of the array rather than the original one. This is demonstrated in the below example:
<?php
$numbers = [1,2,3,4,5,6,7,8,9]; # initial values for our array
echo '<pre>', print_r($numbers, true), '</pre>', '<hr />';
foreach($numbers as $index => $number){
$numbers[$index] = $number + 1; # this is making changes to the origial array
echo 'Inside of the array = ', $index, ': ', $number, '<br />'; # showing data from the copied array
}
echo '<hr />', '<pre>', print_r($numbers, true), '</pre>'; # shows the original values (also includes the newly added values).
Besides this, php does allow to use iterated values as a reference to the original array value
as well. This is demonstrated below:
<?php
$numbers = [1,2,3,4,5,6,7,8,9];
echo '<pre>', print_r($numbers, true), '</pre>';
foreach($numbers as $index => &$number){
++$number; # we are incrementing the original value
echo 'Inside of the array = ', $index, ': ', $number, '<br />'; # this is showing the original value
}
echo '<hr />';
echo '<pre>', print_r($numbers, true), '</pre>'; # we are again showing the original value
Note: It does not allow original array indexes
to be used as references
.
Source: http://dwellupper.io/post/47/understanding-php-foreach-loop-with-examples
According to MSDN, timestamp
Is a data type that exposes automatically generated, unique binary numbers within a database. timestamp is generally used as a mechanism for version-stamping table rows. The storage size is 8 bytes. The timestamp data type is just an incrementing number and does not preserve a date or a time. To record a date or time, use a datetime data type.
You're probably looking for the datetime
data type instead.
Assuming the changes you want are at the head of the branch you want the changes from, use git checkout
for a single file :
git checkout branch_that_has_the_changes_you_want path/to/file.rb
for multiple files just daisy chain :
git checkout branch_that_has_the_changes_you_want path/to/file.rb path/to/other_file.rb
Is there any 64 bit Visual Studio at all?
Yes literally there is one called "Visual Studio" and is 64bit, but well,, on Mac not on Windows
Why not?
Decision making is electro-chemical reaction made in our brain and that have an activation point (Nerdest answer I can come up with, but follow). Same situation happened in history: Windows 64!...
So in order to answer this fully I want you to remember old days. Imagine reasons for "why not we see 64bit Windows" are there at the time. I think at the time for Windows64 they had exact same reasons others have enlisted here about "reasons why not 64bit VS on windows" were on "reasons why not 64bit Windows" too. Then why they did start development for Windows 64bit? Simple! If they didn't succeed in making 64bit Windows I bet M$ would have been a history nowadays. If same reasons forcing M$ making 64bit Windows starts to appear on need for 64Bit VS then I bet we will see 64bit VS, even though very same reasons everyone else here enlisted will stay same! In time the limitations of 32bit may hit VS as well, so most likely something like below start to happen:
I put my bets on Visual Studio Code taking the place in time; I guess bifurcation point for it will be some CPU manufacturer X starts to compete x86_64 architecture taking its place on mainstream market for laptop and/or workstation,
echo date_format(date_create('17 Oct 2008'), 'c');
// Output : 2008-10-17T00:00:00+02:00
$formatteddate = new DateTime('17 Oct 2008');
echo $datetime->format('c');
// Output : 2008-10-17T00:00:00+02:00
echo date_format(new DateTime('17 Oct 2008'), 'c');
// Output : 2008-10-17T00:00:00+02:00
echo date_create('17 Oct 2008')->format('c');
// Output : 2008-10-17T00:00:00+02:00
1) You could also use 'Y-m-d\TH:i:sP'
as an alternative to 'c'
for your format.
2) The default time zone of your input is the time zone of your server. If you want the input to be for a different time zone, you need to set your time zone explicitly. This will also impact your output, however :
echo date_format(date_create('17 Oct 2008 +0800'), 'c');
// Output : 2008-10-17T00:00:00+08:00
3) If you want the output to be for a time zone different from that of your input, you can set your time zone explicitly :
echo date_format(date_create('17 Oct 2008')->setTimezone(new DateTimeZone('America/New_York')), 'c');
// Output : 2008-10-16T18:00:00-04:00
Your group statement will group by group ID. For example, if you then write:
foreach (var group in groupedCustomerList)
{
Console.WriteLine("Group {0}", group.Key);
foreach (var user in group)
{
Console.WriteLine(" {0}", user.UserName);
}
}
that should work fine. Each group has a key, but also contains an IGrouping<TKey, TElement>
which is a collection that allows you to iterate over the members of the group. As Lee mentions, you can convert each group to a list if you really want to, but if you're just going to iterate over them as per the code above, there's no real benefit in doing so.
public class ForEachLoopExample {
public static void main(String[] args) {
System.out.println("For Each Loop Example: ");
int[] intArray = { 1,2,3,4,5 };
//Here iteration starts from index 0 to last index
for(int i : intArray)
System.out.println(i);
}
}
There is only one reason when one needs to pass props
to super()
:
When you want to access this.props
in constructor.
Passing:
class MyComponent extends React.Component {
constructor(props) {
super(props)
console.log(this.props)
// -> { icon: 'home', … }
}
}
Not passing:
class MyComponent extends React.Component {
constructor(props) {
super()
console.log(this.props)
// -> undefined
// Props parameter is still available
console.log(props)
// -> { icon: 'home', … }
}
render() {
// No difference outside constructor
console.log(this.props)
// -> { icon: 'home', … }
}
}
Note that passing or not passing props
to super
has no effect on later uses of this.props
outside constructor
. That is render
, shouldComponentUpdate
, or event handlers always have access to it.
This is explicitly said in one Sophie Alpert's answer to a similar question.
The documentation—State and Lifecycle, Adding Local State to a Class, point 2—recommends:
Class components should always call the base constructor with
props
.
However, no reason is provided. We can speculate it is either because of subclassing or for future compatibility.
(Thanks @MattBrowne for the link)
You can't do this with a UNIQUE
constraint, but you can do this in a trigger.
CREATE TRIGGER [dbo].[OnInsertMyTableTrigger]
ON [dbo].[MyTable]
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Column1 INT;
DECLARE @Column2 INT; -- allow nulls on this column
SELECT @Column1=Column1, @Column2=Column2 FROM inserted;
-- Check if an existing record already exists, if not allow the insert.
IF NOT EXISTS(SELECT * FROM dbo.MyTable WHERE Column1=@Column1 AND Column2=@Column2 @Column2 IS NOT NULL)
BEGIN
INSERT INTO dbo.MyTable (Column1, Column2)
SELECT @Column2, @Column2;
END
ELSE
BEGIN
RAISERROR('The unique constraint applies on Column1 %d, AND Column2 %d, unless Column2 is NULL.', 16, 1, @Column1, @Column2);
ROLLBACK TRANSACTION;
END
END
I like to look at generating passwords, just like generating software keys. You should choose from an array of characters that follow a good practice. Take what @Radu094 answered with and modify it to follow good practice. Don't put every single letter in the character array. Some letters are harder to say or understand over the phone.
You should also consider using a checksum on the password that was generated to make sure that it was generated by you. A good way of accomplishing this is to use the LUHN algorithm.
Why didn't you try to define is_private
in your models as default=False
?
class Foo(models.Models):
is_private = models.BooleanField(default=False)
Note: imp is deprecated since Python 3.4 in favor of importlib
As mentioned the imp module provides you loading functions:
imp.load_source(name, path)
imp.load_compiled(name, path)
I've used these before to perform something similar.
In my case I defined a specific class with defined methods that were required. Once I loaded the module I would check if the class was in the module, and then create an instance of that class, something like this:
import imp
import os
def load_from_file(filepath):
class_inst = None
expected_class = 'MyClass'
mod_name,file_ext = os.path.splitext(os.path.split(filepath)[-1])
if file_ext.lower() == '.py':
py_mod = imp.load_source(mod_name, filepath)
elif file_ext.lower() == '.pyc':
py_mod = imp.load_compiled(mod_name, filepath)
if hasattr(py_mod, expected_class):
class_inst = getattr(py_mod, expected_class)()
return class_inst
To provide numerical values rounded to two decimal places but right-padded with zeros if required I have:
DECLARE @value = 20.1
SET @value = ROUND(@value,2) * 100
PRINT LEFT(CAST(@value AS VARCHAR(20)), LEN(@value)-2) + '.' + RIGHT(CAST(@value AS VARCHAR(20)),2)
If anyone can think of a neater way, that would be appreciated - the above seems clumsy.
Note: in this instance, I'm using SQL Server to email reports in HTML format and so wish to format the information without involving an additional tool to parse the data.
int intVar = (int)ds.Tables[0].Rows[0][n]; // n = column index
float RandomFloat(float min, float max)
{
float r = (float)rand() / (float)RAND_MAX;
return min + r * (max - min);
}
You could apply both background-color and border to make it look like 2 colors.
div.A { width: 50px; background-color: #9c9e9f; border-right: 50px solid #f6f6f6; }
The border should have the same size as the width.
use sql server manegement studio or netcat and that will be easier to manipulate sql
Simple
function timeToSeconds($time)
{
$timeExploded = explode(':', $time);
if (isset($timeExploded[2])) {
return $timeExploded[0] * 3600 + $timeExploded[1] * 60 + $timeExploded[2];
}
return $timeExploded[0] * 3600 + $timeExploded[1] * 60;
}
I think the solution can be less clunky by using method toISOString()
, it has a wide browser compatibility.
So your expression will be a one-liner:
new Date().toISOString().slice(0, 19).replace('T', ' ');
The generated output:
"2017-06-29 17:54:04"
$('.input').keypress(function (e) {
if (e.which == 13) {
$('form#login').submit();
return false; //<---- Add this line
}
});
Check out this stackoverflow answer: event.preventDefault() vs. return false
Essentially, "return false" is the same as calling e.preventDefault
and e.stopPropagation()
.
Suppose there are 3 non-negative integers: a
, b
, and c
. Mathematically speaking, if we want to determine if c
is between a
and b
, inclusively, one can use this formula:
(c - a) * (b - c) >= 0
or in Python:
> print((c - a) * (b - c) >= 0)
True
What I use for IsNotNullOrEmptyOrWhiteSpace
in T-SQL is:
SELECT [column_name] FROM [table_name]
WHERE LEN(RTRIM(ISNULL([column_name], ''))) > 0
You can't. Variables defined inside a method are local to that method.
If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).
Looks like you're using instance methods instead of static ones.
If you don't want to create an object, you should declare all your methods static, so something like
private static void methodName(Argument args...)
If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.
private static int[][] array = new int[3][5];
Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.
Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.
Here's a final (shortened) example of what your code should be like:
public class Test3 {
//Use this array in your methods
private static int[][] scores = new int[3][5];
/* Rather than just "Scores" name it so people know what
* to expect
*/
private static void createScores() {
//Code...
}
//Other methods...
/* Since you're now using static methods, you don't
* have to initialise an object and call its methods.
*/
public static void main(String[] args){
createScores();
MD(); //Don't know what these do
sumD(); //so I'll leave them.
}
}
Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.
For images, you could get the available codecs from GDI (System.Drawing) and build your list from that with a little work. This would be the most flexible way to go.
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
Install
npm i core-js
Modular standard library for JavaScript. Includes polyfills for ECMAScript up to 2019: promises, symbols, collections, iterators, typed arrays, many other features, ECMAScript proposals, some cross-platform WHATWG / W3C features and proposals like URL. You can load only required features or use it without global namespace pollution.
If you want to hide search for a specific drop down use the id attribute for that.
$('#select_id').select2({ minimumResultsForSearch: -1 });
I don't know if it's possible but I always pictured myself being able to do this with the CSV storage engine in MySQL. I don't know the details of this engine: http://dev.mysql.com/doc/refman/5.7/en/csv-storage-engine.html but you can look into it and have a file watcher in your operating system that triggers a PHP call if the file is modified.
There are a couple of steps to take:
*
by .
to include hidden files as well.--exclude=workspace.tar.gz
can be used to exclude the archive itself.tar: .: file changed as we read it
error when the archive is not yet created, make sure it exists (e.g. using touch
), so the --exclude matches with the archive filename. (It does not match it the file does not exists)Combined this results in the following script:
touch workspace.tar.gz
tar -czf workspace.tar.gz --exclude=workspace.tar.gz .
Annotate class public static void main
with, for example: @SpringBootApplication
The part you should be interested in is the /?
part, which should solve most other questions you have with the tool.
Microsoft Windows XP [Version 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\>cmd /? Starts a new instance of the Windows XP command interpreter CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF] [[/S] [/C | /K] string] /C Carries out the command specified by string and then terminates /K Carries out the command specified by string but remains /S Modifies the treatment of string after /C or /K (see below) /Q Turns echo off /D Disable execution of AutoRun commands from registry (see below) /A Causes the output of internal commands to a pipe or file to be ANSI /U Causes the output of internal commands to a pipe or file to be Unicode /T:fg Sets the foreground/background colors (see COLOR /? for more info) /E:ON Enable command extensions (see below) /E:OFF Disable command extensions (see below) /F:ON Enable file and directory name completion characters (see below) /F:OFF Disable file and directory name completion characters (see below) /V:ON Enable delayed environment variable expansion using ! as the delimiter. For example, /V:ON would allow !var! to expand the variable var at execution time. The var syntax expands variables at input time, which is quite a different thing when inside of a FOR loop. /V:OFF Disable delayed environment expansion.
In my case I have used context for startActivity
, after changing that with ActivityName.this
. it solves. I'm using method from util class so this happens.
Hope it help some one.
I know this is a late entry but I have created a simple upload directive. Which you can get working in no time!
<input type="file" multiple ng-simple-upload web-api-url="/api/post"
callback-fn="myCallback" />
ng-simple-upload more on Github with an example using Web API.
For me the problem was a configuration file that was missing an Element.
Yes you can use:
With this all you will need is to supply the wsdl, and the client which is the Java classes will be automatically generated for you.
Microsoft doesn't feel like implementing this useful tool, but if by chance you can have Visual Assist, you have it in VAssistX > Tools > VA Outline. The plugin is not free though.
# To do it for all names
df[] <- lapply( df, factor) # the "[]" keeps the dataframe structure
col_names <- names(df)
# to do it for some names in a vector named 'col_names'
df[col_names] <- lapply(df[col_names] , factor)
Explanation. All dataframes are lists and the results of [
used with multiple valued arguments are likewise lists, so looping over lists is the task of lapply
. The above assignment will create a set of lists that the function data.frame.[<-
should successfully stick back into into the dataframe, df
Another strategy would be to convert only those columns where the number of unique items is less than some criterion, let's say fewer than the log of the number of rows as an example:
cols.to.factor <- sapply( df, function(col) length(unique(col)) < log10(length(col)) )
df[ cols.to.factor] <- lapply(df[ cols.to.factor] , factor)
Had the same problem. Unfortunately
dos2unix winfile.sh
bash: dos2unix: command not found
so I did this to convert.
awk '{ sub("\r$", ""); print }' winfile.sh > unixfile.sh
and then
bash unixfile.sh
I usually start mysql server by typing
$ mysql.server start
without sudo. But in error I type sudo before the command. Now I have to remove the error file to start the server.
$ sudo rm /usr/local/var/mysql/`hostname`.err
To read the result you can read it like a simple php array.
For example, getting the name
can be done like $user['name']
, and so on. The method fetch(PDO::FETCH_ASSOC)
will only return 1 tuple tho. If you want to get all tuples, you can use fetchall(PDO::FETCH_ASSOC)
. You can go through the multidimensional array and get the values just the same.
IntelliJ IDEA 14+
Show diagram popup
Right click on a type/class/package > Diagrams > Show Diagram Popup...
or
Ctrl+Alt+U
Show diagram (opens a new tab)
Right click on a type/class/package > Diagrams > Show Diagram...
or
Ctrl+Alt+Shift+U
By default, you see only the classes/interfaces names. If you want to see more details, go to File > Settings... > Tools > Diagrams and check what you want (E.g.: Fields, Methods, etc.)
P.S.: You need IntelliJ IDEA Ultimate, because this feature is not supported in Community Edition. If you go to File > Settings... > Plugins, you can see that there is not UML Support plugin in Community Edition.
Use { before $ sign. And also add addslashes function to escape special characters.
$sqlupdate1 = "UPDATE table SET commodity_quantity=".$qty."WHERE user=".addslashes($rows['user'])."'";
The closest thing to renaming is deleting and then re-creating on the remote. For example:
git branch -m master master-old
git push remote :master # delete master
git push remote master-old # create master-old on remote
git checkout -b master some-ref # create a new local master
git push remote master # create master on remote
However this has a lot of caveats. First, no existing checkouts will know about the rename - git does not attempt to track branch renames. If the new master
doesn't exist yet, git pull will error out. If the new master
has been created. the pull will attempt to merge master
and master-old
. So it's generally a bad idea unless you have the cooperation of everyone who has checked out the repository previously.
Note: Newer versions of git will not allow you to delete the master branch remotely by default. You can override this by setting the receive.denyDeleteCurrent
configuration value to warn
or ignore
on the remote repository. Otherwise, if you're ready to create a new master right away, skip the git push remote :master
step, and pass --force
to the git push remote master
step. Note that if you're not able to change the remote's configuration, you won't be able to completely delete the master branch!
This caveat only applies to the current branch (usually the master
branch); any other branch can be deleted and recreated as above.
With Java:
For int
values:
public static int[] primeFactors(int value) {
int[] a = new int[31];
int i = 0, j;
int num = value;
while (num % 2 == 0) {
a[i++] = 2;
num /= 2;
}
j = 3;
while (j <= Math.sqrt(num) + 1) {
if (num % j == 0) {
a[i++] = j;
num /= j;
} else {
j += 2;
}
}
if (num > 1) {
a[i++] = num;
}
int[] b = Arrays.copyOf(a, i);
return b;
}
For long
values:
static long[] getFactors(long value) {
long[] a = new long[63];
int i = 0;
long num = value;
while (num % 2 == 0) {
a[i++] = 2;
num /= 2;
}
long j = 3;
while (j <= Math.sqrt(num) + 1) {
if (num % j == 0) {
a[i++] = j;
num /= j;
} else {
j += 2;
}
}
if (num > 1) {
a[i++] = num;
}
long[] b = Arrays.copyOf(a, i);
return b;
}
Edittext cursor color you want changes your color.
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textCursorDrawable="@drawable/color_cursor"
/>
Then create drawalble xml: color_cursor
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<size android:width="3dp" />
<solid android:color="#FFFFFF" />
</shape>
How about User-Defined Type Guards? https://www.typescriptlang.org/docs/handbook/advanced-types.html
interface Bird {
fly();
layEggs();
}
interface Fish {
swim();
layEggs();
}
function isFish(pet: Fish | Bird): pet is Fish { //magic happens here
return (<Fish>pet).swim !== undefined;
}
// Both calls to 'swim' and 'fly' are now okay.
if (isFish(pet)) {
pet.swim();
}
else {
pet.fly();
}
OK, what you can try is
Cntrl+H (Find and Replace), leave Find What blank and change Replace With to NULL.
That should replace all blank cells in the USED range with NULL
An example of an IF Statement that can be used to add a calculation into the cell you wish to hide if value = 0 but displayed upon another cell value reference.
=IF(/Your reference cell/=0,"",SUM(/Here you put your SUM/))
If you happen to be an iOS developer
:
Check how many simulators that you have downloaded as they take up a lot of space:
Go to: ~/Library/Developer/Xcode/iOS DeviceSupport
Also delete old archived apps:
Go to: ~/Library/Developer/Xcode/Archives
I cleared 100GB doing this.
=(((A1/60)/60)/24)+DATE(1970,1,1)+(-5/24)
assuming A1
is the cell where your time stamp is located and dont forget to adjust to account for the time zone you are in (5 assuming you are on EST)
The best answer is...
The expression in the accepted answer misses many cases. Among other things, URLs can have unicode characters in them. The regex you want is here, and after looking at it, you may conclude that you don't really want it after all. The most correct version is ten-thousand characters long.
Admittedly, if you were starting with plain, unstructured text with a bunch of URLs in it, then you might need that ten-thousand-character-long regex. But if your input is structured, use the structure. Your stated aim is to "extract the url, inside the anchor tag's href." Why use a ten-thousand-character-long regex when you can do something much simpler?
For many tasks, using Beautiful Soup will be far faster and easier to use:
>>> from bs4 import BeautifulSoup as Soup
>>> html = Soup(s, 'html.parser') # Soup(s, 'lxml') if lxml is installed
>>> [a['href'] for a in html.find_all('a')]
['http://example.com', 'http://example2.com']
If you prefer not to use external tools, you can also directly use Python's own built-in HTML parsing library. Here's a really simple subclass of HTMLParser
that does exactly what you want:
from html.parser import HTMLParser
class MyParser(HTMLParser):
def __init__(self, output_list=None):
HTMLParser.__init__(self)
if output_list is None:
self.output_list = []
else:
self.output_list = output_list
def handle_starttag(self, tag, attrs):
if tag == 'a':
self.output_list.append(dict(attrs).get('href'))
Test:
>>> p = MyParser()
>>> p.feed(s)
>>> p.output_list
['http://example.com', 'http://example2.com']
You could even create a new method that accepts a string, calls feed
, and returns output_list
. This is a vastly more powerful and extensible way than regular expressions to extract information from html.
It can also be solved using quaternion theory:
def angle_axis_quat(theta, axis):
"""
Given an angle and an axis, it returns a quaternion.
"""
axis = np.array(axis) / np.linalg.norm(axis)
return np.append([np.cos(theta/2)],np.sin(theta/2) * axis)
def mult_quat(q1, q2):
"""
Quaternion multiplication.
"""
q3 = np.copy(q1)
q3[0] = q1[0]*q2[0] - q1[1]*q2[1] - q1[2]*q2[2] - q1[3]*q2[3]
q3[1] = q1[0]*q2[1] + q1[1]*q2[0] + q1[2]*q2[3] - q1[3]*q2[2]
q3[2] = q1[0]*q2[2] - q1[1]*q2[3] + q1[2]*q2[0] + q1[3]*q2[1]
q3[3] = q1[0]*q2[3] + q1[1]*q2[2] - q1[2]*q2[1] + q1[3]*q2[0]
return q3
def rotate_quat(quat, vect):
"""
Rotate a vector with the rotation defined by a quaternion.
"""
# Transfrom vect into an quaternion
vect = np.append([0],vect)
# Normalize it
norm_vect = np.linalg.norm(vect)
vect = vect/norm_vect
# Computes the conjugate of quat
quat_ = np.append(quat[0],-quat[1:])
# The result is given by: quat * vect * quat_
res = mult_quat(quat, mult_quat(vect,quat_)) * norm_vect
return res[1:]
v = [3, 5, 0]
axis = [4, 4, 1]
theta = 1.2
print(rotate_quat(angle_axis_quat(theta, axis), v))
# [2.74911638 4.77180932 1.91629719]
Change the key of the component.
<Component key="1" />
<Component key="2" />
Component will be unmounted and a new instance of Component will be mounted since the key has changed.
edit: Documented on You Probably Don't Need Derived State:
When a key changes, React will create a new component instance rather than update the current one. Keys are usually used for dynamic lists but are also useful here.
Go to http://dev.mysql.com/downloads/connector/j and with in the dropdown select "Platform Independent" then it will show you the options to download tar.gz file or zip file.
Download zip file and extract it, with in that you will find mysql-connector-XXX.jar
file
If you are using maven then you can add the dependency from the link http://mvnrepository.com/artifact/mysql/mysql-connector-java
Select the version you want to use and add the dependency in your pom.xml
file
Yes we can, "Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name"->>Java Doc
The error is because of the sql mode which can be strict mode as per latest MYSQL 5.7 documentation.
For more information read this.
Hope it helps.
@@ROWCOUNT will give the number of rows affected by the last SQL statement, it is best to capture it into a local variable following the command in question, as its value will change the next time you look at it:
DECLARE @Rows int
DECLARE @TestTable table (col1 int, col2 int)
INSERT INTO @TestTable (col1, col2) select 1,2 union select 3,4
SELECT @Rows=@@ROWCOUNT
SELECT @Rows AS Rows,@@ROWCOUNT AS [ROWCOUNT]
OUTPUT:
(2 row(s) affected)
Rows ROWCOUNT
----------- -----------
2 1
(1 row(s) affected)
you get Rows
value of 2, the number of inserted rows, but ROWCOUNT is 1 because the SELECT @Rows=@@ROWCOUNT
command affected 1 row
if you have multiple INSERTs or UPDATEs, etc. in your transaction, you need to determine how you would like to "count" what is going on. You could have a separate total for each table, a single grand total value, or something completely different. You'll need to DECLARE a variable for each total you want to track and add to it following each operation that applies to it:
--note there is no error handling here, as this is a simple example
DECLARE @AppleTotal int
DECLARE @PeachTotal int
SELECT @AppleTotal=0,@PeachTotal=0
BEGIN TRANSACTION
INSERT INTO Apple (col1, col2) Select col1,col2 from xyz where ...
SET @AppleTotal=@AppleTotal+@@ROWCOUNT
INSERT INTO Apple (col1, col2) Select col1,col2 from abc where ...
SET @AppleTotal=@AppleTotal+@@ROWCOUNT
INSERT INTO Peach (col1, col2) Select col1,col2 from xyz where ...
SET @PeachTotal=@PeachTotal+@@ROWCOUNT
INSERT INTO Peach (col1, col2) Select col1,col2 from abc where ...
SET @PeachTotal=@PeachTotal+@@ROWCOUNT
COMMIT
SELECT @AppleTotal AS AppleTotal, @PeachTotal AS PeachTotal
For read a cookie i've made little modifications of the Miquel version that doesn't work for me:
getCookie(name: string) {
let ca: Array<string> = document.cookie.split(';');
let cookieName = name + "=";
let c: string;
for (let i: number = 0; i < ca.length; i += 1) {
if (ca[i].indexOf(name, 0) > -1) {
c = ca[i].substring(cookieName.length +1, ca[i].length);
console.log("valore cookie: " + c);
return c;
}
}
return "";
For people using Kotlin you can put this in your MainActivity.kt:
window.navigationBarColor = ContextCompat.getColor(this@MainActivity, R.color.yourColor)
With window
being:
val window: Window = [email protected]
Or you can put this in your themes.xml or styles.xml (requires API level 21):
<item name='android:navigationBarColor'>@color/yourColor</item>
The documentation in the w3 link
http://www.w3.org/TR/REC-xml/#sec-starttags
says that this are the recomended forms.
<test></test>
<test/>
The attribute mentioned in the other answer is validation mechanism and not a representation of state. Please refer to the http://www.w3.org/TR/xmlschema-1/#xsi_nil
XML Schema: Structures introduces a mechanism for signaling that an element should be accepted as ·valid· when it has no content despite a content type which does not require or even necessarily allow empty content. An element may be ·valid· without content if it has the attribute xsi:nil with the value true. An element so labeled must be empty, but can carry attributes if permitted by the corresponding complex type.
To clarify this answer: Content
<Book>
<!--Invalid construct since the element attribute xsi:nil="true" signal that the element must be empty-->
<BuildAttributes HardCover="true" Glued="true" xsi:nil="true">
<anotherAttribute name="Color">Blue</anotherAttribute>
</BuildAttributes>
<Index></Index>
<pages>
<page pageNumber="1">Content</page>
</pages>
<!--Missing ISBN number could be confusing and misguiding since its not present-->
</Book>
</Books>
I took the liberty of feeding your classes into the CGbR generator. Because it is in an early stage it doesn't support The generated serialization code looks like this:DateTime
yet, so I simply replaced it with long.
public int Size
{
get
{
var size = 24;
// Add size for collections and strings
size += Cts == null ? 0 : Cts.Count * 4;
size += Tes == null ? 0 : Tes.Count * 4;
size += Code == null ? 0 : Code.Length;
size += Message == null ? 0 : Message.Length;
return size;
}
}
public byte[] ToBytes(byte[] bytes, ref int index)
{
if (index + Size > bytes.Length)
throw new ArgumentOutOfRangeException("index", "Object does not fit in array");
// Convert Cts
// Two bytes length information for each dimension
GeneratorByteConverter.Include((ushort)(Cts == null ? 0 : Cts.Count), bytes, ref index);
if (Cts != null)
{
for(var i = 0; i < Cts.Count; i++)
{
var value = Cts[i];
value.ToBytes(bytes, ref index);
}
}
// Convert Tes
// Two bytes length information for each dimension
GeneratorByteConverter.Include((ushort)(Tes == null ? 0 : Tes.Count), bytes, ref index);
if (Tes != null)
{
for(var i = 0; i < Tes.Count; i++)
{
var value = Tes[i];
value.ToBytes(bytes, ref index);
}
}
// Convert Code
GeneratorByteConverter.Include(Code, bytes, ref index);
// Convert Message
GeneratorByteConverter.Include(Message, bytes, ref index);
// Convert StartDate
GeneratorByteConverter.Include(StartDate.ToBinary(), bytes, ref index);
// Convert EndDate
GeneratorByteConverter.Include(EndDate.ToBinary(), bytes, ref index);
return bytes;
}
public Td FromBytes(byte[] bytes, ref int index)
{
// Read Cts
var ctsLength = GeneratorByteConverter.ToUInt16(bytes, ref index);
var tempCts = new List<Ct>(ctsLength);
for (var i = 0; i < ctsLength; i++)
{
var value = new Ct().FromBytes(bytes, ref index);
tempCts.Add(value);
}
Cts = tempCts;
// Read Tes
var tesLength = GeneratorByteConverter.ToUInt16(bytes, ref index);
var tempTes = new List<Te>(tesLength);
for (var i = 0; i < tesLength; i++)
{
var value = new Te().FromBytes(bytes, ref index);
tempTes.Add(value);
}
Tes = tempTes;
// Read Code
Code = GeneratorByteConverter.GetString(bytes, ref index);
// Read Message
Message = GeneratorByteConverter.GetString(bytes, ref index);
// Read StartDate
StartDate = DateTime.FromBinary(GeneratorByteConverter.ToInt64(bytes, ref index));
// Read EndDate
EndDate = DateTime.FromBinary(GeneratorByteConverter.ToInt64(bytes, ref index));
return this;
}
I created a list of sample objects like this:
var objects = new List<Td>();
for (int i = 0; i < 1000; i++)
{
var obj = new Td
{
Message = "Hello my friend",
Code = "Some code that can be put here",
StartDate = DateTime.Now.AddDays(-7),
EndDate = DateTime.Now.AddDays(2),
Cts = new List<Ct>(),
Tes = new List<Te>()
};
for (int j = 0; j < 10; j++)
{
obj.Cts.Add(new Ct { Foo = i * j });
obj.Tes.Add(new Te { Bar = i + j });
}
objects.Add(obj);
}
Results on my machine in Release
build:
var watch = new Stopwatch();
watch.Start();
var bytes = BinarySerializer.SerializeMany(objects);
watch.Stop();
Size: 149000 bytes
Time: 2.059ms 3.13ms
Edit: Starting with CGbR 0.4.3 the binary serializer supports DateTime. Unfortunately the DateTime.ToBinary
method is insanely slow. I will replace it with somehting faster soon.
Edit2: When using UTC DateTime
by invoking ToUniversalTime()
the performance is restored and clocks in at 1.669ms.
In case you need to find documents which contain NULL elements inside an array of sub-documents, I've found this query which works pretty well:
db.collection.find({"keyWithArray":{$elemMatch:{"$in":[null], "$exists":true}}})
This query is taken from this post: MongoDb query array with null values
It was a great find and it works much better than my own initial and wrong version (which turned out to work fine only for arrays with one element):
.find({
'MyArrayOfSubDocuments': { $not: { $size: 0 } },
'MyArrayOfSubDocuments._id': { $exists: false }
})
In practice, the models are used as follows.
In discriminative models, to predict the label y
from the training example x
, you must evaluate:
which merely chooses what is the most likely class y
considering x
. It's like we were trying to model the decision boundary between the classes. This behavior is very clear in neural networks, where the computed weights can be seen as a complexly shaped curve isolating the elements of a class in the space.
Now, using Bayes' rule, let's replace the in the equation by . Since you are just interested in the arg max, you can wipe out the denominator, that will be the same for every y
. So, you are left with
which is the equation you use in generative models.
While in the first case you had the conditional probability distribution p(y|x)
, which modeled the boundary between classes, in the second you had the joint probability distribution p(x, y)
, since p(x | y) p(y) = p(x, y)
, which explicitly models the actual distribution of each class.
With the joint probability distribution function, given a y
, you can calculate ("generate") its respective x
. For this reason, they are called "generative" models.
You can do either, but never both. Usually you do it at function declaration and then all callers can use that default value. However you can do that at function definition instead and then only those who see the definition will be able to use the default value.
node-cron does just what I described
I got it to work by doing this, assuming you are using PDO.
//Place query here, let's say you want all the users that have blue as their favorite color
$sql = "SELECT name FROM user WHERE favorite_color = :color";
//set parameters
//you may set as many parameters as you have on your query
$params['color'] = blue;
//create the prepared statement, by getting the doctrine connection
$stmt = $this->entityManager->getConnection()->prepare($sql);
$stmt->execute($params);
//I used FETCH_COLUMN because I only needed one Column.
return $stmt->fetchAll(PDO::FETCH_COLUMN);
You can change the FETCH_TYPE to suit your needs.
How to properly ignore Exceptions?
There are several ways of doing this.
However, the choice of example has a simple solution that does not cover the general case.
Instead of
try:
shutil.rmtree(path)
except:
pass
Do this:
shutil.rmtree(path, ignore_errors=True)
This is an argument specific to shutil.rmtree
. You can see the help on it by doing the following, and you'll see it can also allow for functionality on errors as well.
>>> import shutil
>>> help(shutil.rmtree)
Since this only covers the narrow case of the example, I'll further demonstrate how to handle this if those keyword arguments didn't exist.
Since the above only covers the narrow case of the example, I'll further demonstrate how to handle this if those keyword arguments didn't exist.
You can import the suppress
context manager:
from contextlib import suppress
But only suppress the most specific exception:
with suppress(FileNotFoundError):
shutil.rmtree(path)
You will silently ignore a FileNotFoundError
:
>>> with suppress(FileNotFoundError):
... shutil.rmtree('bajkjbkdlsjfljsf')
...
>>>
From the docs:
As with any other mechanism that completely suppresses exceptions, this context manager should be used only to cover very specific errors where silently continuing with program execution is known to be the right thing to do.
Note that suppress
and FileNotFoundError
are only available in Python 3.
If you want your code to work in Python 2 as well, see the next section:
When you just want to do a try/except without handling the exception, how do you do it in Python?
Is the following the right way to do it?
try : shutil.rmtree ( path ) except : pass
For Python 2 compatible code, pass
is the correct way to have a statement that's a no-op. But when you do a bare except:
, that's the same as doing except BaseException:
which includes GeneratorExit
, KeyboardInterrupt
, and SystemExit
, and in general, you don't want to catch those things.
In fact, you should be as specific in naming the exception as you can.
Here's part of the Python (2) exception hierarchy, and as you can see, if you catch more general Exceptions, you can hide problems you did not expect:
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StandardError
| +-- BufferError
| +-- ArithmeticError
| | +-- FloatingPointError
| | +-- OverflowError
| | +-- ZeroDivisionError
| +-- AssertionError
| +-- AttributeError
| +-- EnvironmentError
| | +-- IOError
| | +-- OSError
| | +-- WindowsError (Windows)
| | +-- VMSError (VMS)
| +-- EOFError
... and so on
You probably want to catch an OSError here, and maybe the exception you don't care about is if there is no directory.
We can get that specific error number from the errno
library, and reraise if we don't have that:
import errno
try:
shutil.rmtree(path)
except OSError as error:
if error.errno == errno.ENOENT: # no such file or directory
pass
else: # we had an OSError we didn't expect, so reraise it
raise
Note, a bare raise raises the original exception, which is probably what you want in this case. Written more concisely, as we don't really need to explicitly pass
with code in the exception handling:
try:
shutil.rmtree(path)
except OSError as error:
if error.errno != errno.ENOENT: # no such file or directory
raise
I had similar issue when connecting to RDS Oracle even when client and server were both set to TLSv1.2 the certs was right and java was 1.8.0_141 So Finally I had to apply patch at Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files
After applying the patch the issue went away and connection went fine.
You could use JSON.stringify(array)
to encode your array in JavaScript, and then use $array=json_decode($_POST['jsondata']);
in your PHP script to retrieve it.
I have on several projects.
The biggest difference in my opinion
jQuery UI is fallback safe, it works correctly and looks good in old browsers, where Bootstrap is based on CSS3 which basically means GREAT in new browsers, not so great in old
Update frequency: Bootstrap is getting some great big updates with awesome new features, but sadly they might break previous code, so you can't just install bootstrap and update when there is a new major release, it basically requires a lot of new coding
jQuery UI is based on good html structure with transformations from JavaScript, while Bootstrap is based on visually and customizable inline structure. (calling a widget in JQUERY UI, defining it in Bootstrap)
So what to choose?
That always depends on the type of project you are working on. Is cool and fast looking widgets better, or are your users often using old browsers?
I always end up using both, so I can use the best of both worlds.
Here are the links to both frameworks, if you decide to use them.
Here's also nice way to achieve this via UI.
0) Right click on PowerShell icon when on task bar
1) Shift + right click on Windows PowerShell
2) "Run as different user"
meshgrid helps in creating a rectangular grid from two 1-D arrays of all pairs of points from the two arrays.
x = np.array([0, 1, 2, 3, 4])
y = np.array([0, 1, 2, 3, 4])
Now, if you have defined a function f(x,y) and you wanna apply this function to all the possible combination of points from the arrays 'x' and 'y', then you can do this:
f(*np.meshgrid(x, y))
Say, if your function just produces the product of two elements, then this is how a cartesian product can be achieved, efficiently for large arrays.
Referred from here
Wildcard method: Add the following entry into your DNS server and change the domain and IP address accordingly.
*.example.com IN A 1.2.3.4
Team Foundation Sidekicks has a Status sidekick that allows you to query for checked out work items. Once a work item is selected, click the "Undo lock" buttons on the toolbar.
Rights
Keep in mind that you will need the appropriate rights. The permissions are called "Undo other users' changes" and "Unlock other users' changes". These permissions can be viewed by:
Disclaimer: this answer is an edited repost of Brett Roger's answer to a similar question.
Faster way to create folder:
if (!is_dir('path/to/directory')) {
mkdir('path/to/directory', 0777, true);
}
Your example code is wrong. This works:
import datetime
datetime.datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")
The call to strptime() parses the first argument according to the format specified in the second, so those two need to match. Then you can call strftime() to format the result into the desired final format.
You might encounter one of these three problems:
A blog post with the summary for all three possible problems might be found here: https://cms4j.wordpress.com/2016/11/29/0x851c0001-the-credentials-you-provided-for-the-sqlserveragent-service-is-invalid/
Try to restart the adb server as follows:
adb kill-server
adb start-server
I have also came across the same problems as yours. And restarting the adb server will resolve this problem.
Swift 5 & 4.2 one liner:
label.attributedText = NSAttributedString(string: "Text", attributes:
[.underlineStyle: NSUnderlineStyle.single.rawValue])
Swift 4 one liner:
label.attributedText = NSAttributedString(string: "Text", attributes:
[.underlineStyle: NSUnderlineStyle.styleSingle.rawValue])
Swift 3 one liner:
label.attributedText = NSAttributedString(string: "Text", attributes:
[NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue])
You can use the ThenBy and ThenByDescending extension methods:
foobarList.OrderBy(x => x.Foo).ThenBy( x => x.Bar)
The type of expression
" quickscan.exe resolution 300 selectscanner jpg showui showprogress filename '"+name+".jpg'"
is std::string
. However function system has declaration
int system(const char *s);
that is it accepts an argumnet of type const char *
There is no conversion operator that would convert implicitly an object of type std::string
to object of type const char *
.
Nevertheless class std::string
has two functions that do this conversion explicitly. They are c_str()
and data()
(the last can be used only with compiler that supports C++11)
So you can write
string name = "john";
system( (" quickscan.exe resolution 300 selectscanner jpg showui showprogress filename '"+name+".jpg'").c_str() );
There is no need to use an intermediate variable for the expression.
The common practice nowadays is to generate a content hash code as part of the file name to force the browser especially IE to reload the javascript files or css files.
For example,
vendor.a7561fb0e9a071baadb9.js
main.b746e3eb72875af2caa9.js
It is generally the job for the build tools such as webpack. Here is more details if anyone wants to try out if you are using webpack.
On ASP.net web forms use in the @page AspCompat="true", add the system.windows.forms to you project. At your web.config add:
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="false" />
</appSettings>
Then you can use:
Clipboard.SetText(CreateDescription());
When embedding same-origin SVGs using <object>
, you can access the internal contents using objectElement.contentDocument.rootElement
. From there, you can easily attach event handlers (e.g. via onclick
, addEventListener()
, etc.)
For example:
var object = /* get DOM node for <object> */;
var svg = object.contentDocument.rootElement;
svg.addEventListener('click', function() {
console.log('hooray!');
});
Note that this is not possible for cross-origin <object>
elements unless you also control the <object>
origin server and can set CORS headers there. For cross-origin cases without CORS headers, access to contentDocument
is blocked.
@echo off
set NUM=0 1 2 3 4 5 6 7 8 9 A B C D E F 31 32 33 34 35 36 37 41 42 43 44 45 46 90 91 92 93 94 95 96 97 100 101 102 103 104 105 106 107
for %%x in (%NUM%) do (
for %%y in (%NUM%) do (
color %%x%%y
cls
echo Himel Sarkar
timeout 1 >nul
)
)
pause
in response to Dan's comment above:
I am using this method to implement the same thing, but for some reason I am getting an exception on the ReadObject method: "Expecting element 'root' from namespace ''.. Encountered 'None' with name '', namespace ''." Any ideas why? – Dan Appleyard Apr 6 '10 at 17:57
I had the same problem (MVC 3 build 3.0.11209.0), and the post below solved it for me. Basically the json serializer is trying to read a stream which is not at the beginning, so repositioning the stream to 0 'fixed' it...
It depends on what type of fading you are looking for.
But with shadow and rounded corners you can get a nice result. Rounded corners because the bigger the shadow, the weirder it will look in the edges unless you balance it out with rounded corners.
also.. http://css3pie.com/
You seem to be unnecessarily setting properties on your ComboBox
. You can remove the DisplayMemberPath
and SelectedValuePath
properties which have different uses. It might be an idea for you to take a look at the Difference between SelectedItem, SelectedValue and SelectedValuePath post here for an explanation of these properties. Try this:
<ComboBox Name="cbxSalesPeriods"
ItemsSource="{Binding SalesPeriods}"
SelectedItem="{Binding SelectedSalesPeriod}"
IsSynchronizedWithCurrentItem="True"/>
Furthermore, it is pointless using your displayPeriod
property, as the WPF Framework would call the ToString
method automatically for objects that it needs to display that don't have a DataTemplate
set up for them explicitly.
UPDATE >>>
As I can't see all of your code, I cannot tell you what you are doing wrong. Instead, all I can do is to provide you with a complete working example of how to achieve what you want. I've removed the pointless displayPeriod
property and also your SalesPeriodVO
property from your class as I know nothing about it... maybe that is the cause of your problem??. Try this:
public class SalesPeriodV
{
private int month, year;
public int Year
{
get { return year; }
set
{
if (year != value)
{
year = value;
NotifyPropertyChanged("Year");
}
}
}
public int Month
{
get { return month; }
set
{
if (month != value)
{
month = value;
NotifyPropertyChanged("Month");
}
}
}
public override string ToString()
{
return String.Format("{0:D2}.{1}", Month, Year);
}
public virtual event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyPropertyChanged(params string[] propertyNames)
{
if (PropertyChanged != null)
{
foreach (string propertyName in propertyNames) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
PropertyChanged(this, new PropertyChangedEventArgs("HasError"));
}
}
}
Then I added two properties into the view model:
private ObservableCollection<SalesPeriodV> salesPeriods = new ObservableCollection<SalesPeriodV>();
public ObservableCollection<SalesPeriodV> SalesPeriods
{
get { return salesPeriods; }
set { salesPeriods = value; NotifyPropertyChanged("SalesPeriods"); }
}
private SalesPeriodV selectedItem = new SalesPeriodV();
public SalesPeriodV SelectedItem
{
get { return selectedItem; }
set { selectedItem = value; NotifyPropertyChanged("SelectedItem"); }
}
Then initialised the collection with your values:
SalesPeriods.Add(new SalesPeriodV() { Month = 3, Year = 2013 } );
SalesPeriods.Add(new SalesPeriodV() { Month = 4, Year = 2013 } );
And then data bound only these two properties to a ComboBox
:
<ComboBox ItemsSource="{Binding SalesPeriods}" SelectedItem="{Binding SelectedItem}" />
That's it... that's all you need for a perfectly working example. You should see that the display of the items comes from the ToString
method without your displayPeriod
property. Hopefully, you can work out your mistakes from this code example.
Create epoll
object,
open many client TCP sockets,
adjust their send buffers to be a bit more than request header,
send a request header — it should be immediate, just placing into a buffer,
register socket in epoll
object,
do .poll
on epoll
obect,
read first 3 bytes from each socket from .poll
,
write them to sys.stdout
followed by \n
(don't flush),
close the client socket.
Limit number of sockets opened simultaneously — handle errors when sockets are created. Create a new socket only if another is closed.
Adjust OS limits.
Try forking into a few (not many) processes: this may help to use CPU a bit more effectively.
Use this code to check the internet connection
ConnectivityManager connectivityManager = (ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE);
if ((connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null && connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)
|| (connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null && connectivityManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.getState() == NetworkInfo.State.CONNECTED)) {
return true;
} else {
return false;
}
if __name__ == '__main__':
n = int(input())
arr = list(map(float, input().split()))
high = max(arr)
secondhigh = min(arr)
for x in arr:
if x < high and x > secondhigh:
secondhigh = x
print(secondhigh)
The above code is when we are setting the elements value in the list as per user requirements. And below code is as per the question asked
#list
numbers = [20, 67, 3 ,2.6, 7, 74, 2.8, 90.8, 52.8, 4, 3, 2, 5, 7]
#find the highest element in the list
high = max(numbers)
#find the lowest element in the list
secondhigh = min(numbers)
for x in numbers:
'''
find the second highest element in the list,
it works even when there are duplicates highest element in the list.
It runs through the entire list finding the next lowest element
which is less then highest element but greater than lowest element in
the list set initially. And assign that value to secondhigh variable, so
now this variable will have next lowest element in the list. And by end
of loop it will have the second highest element in the list
'''
if (x<high and x>secondhigh):
secondhigh=x
print(secondhigh)
The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.
That being said, I suggest looking at buildwith.com
You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.
Here is an overlay using a pseudo-element (eg: no need to add more markup to do it)
.box {_x000D_
background: 0 0 url(http://ianfarb.com/wp-content/uploads/2013/10/nicholas-hodag.jpg);_x000D_
width: 300px;_x000D_
height: 200px;_x000D_
}_x000D_
_x000D_
.box:after {_x000D_
content: "";_x000D_
display: block;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background: rgba(0, 0, 0, 0.4);_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
Try this:
string command = "...";
var process = Process.Start(command);
process.WaitForExit();
Just to add to the other answers, the documentation gives this explanation:
KEY
is normally a synonym forINDEX
. The key attributePRIMARY KEY
can also be specified as justKEY
when given in a column definition. This was implemented for compatibility with other database systems.A
UNIQUE
index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, aUNIQUE
index permits multipleNULL
values for columns that can containNULL
.A
PRIMARY KEY
is a unique index where all key columns must be defined asNOT NULL
. If they are not explicitly declared asNOT NULL
, MySQL declares them so implicitly (and silently). A table can have only onePRIMARY KEY
. The name of aPRIMARY KEY
is alwaysPRIMARY
, which thus cannot be used as the name for any other kind of index.
SHA1
is a cryptographic hash function, so the intention of the design was to avoid what you are trying to do.
However, breaking a SHA1
hash is technically possible. You can do so by just trying to guess what was hashed. This brute-force approach is of course not efficient, but that's pretty much the only way.
So to answer your question: yes, it is possible, but you need significant computing power. Some researchers estimate that it costs $70k - $120k.
As far as we can tell today, there is also no other way but to guess the hashed input. This is because operations such as mod
eliminate information from your input. Suppose you calculate mod 5
and you get 0
. What was the input? Was it 0
, 5
or 500
? You see, you can't really 'go back' in this case.
Use double braces {{
or }}
so your code becomes:
sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}",
prop.Type, prop.Name));
// For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
// public Foo Bar { get; private set; }
I use a hash and a salt for my password encryption (it's the same hash that Asp.Net Membership uses):
private string PasswordSalt
{
get
{
var rng = new RNGCryptoServiceProvider();
var buff = new byte[32];
rng.GetBytes(buff);
return Convert.ToBase64String(buff);
}
}
private string EncodePassword(string password, string salt)
{
byte[] bytes = Encoding.Unicode.GetBytes(password);
byte[] src = Encoding.Unicode.GetBytes(salt);
byte[] dst = new byte[src.Length + bytes.Length];
Buffer.BlockCopy(src, 0, dst, 0, src.Length);
Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
HashAlgorithm algorithm = HashAlgorithm.Create("SHA1");
byte[] inarray = algorithm.ComputeHash(dst);
return Convert.ToBase64String(inarray);
}
[<1000]0" GB";[>999]0.0," TB"
OR
[<1000]0" GB";[>=1000]0.0," TB"
I ran into the problem with openJDK on ubuntu, had to install Oracle JDK to get it working.
You can follow this guide on google sites to do that.
Using a null reference as the first operand to instanceof
returns false
.
How and where is
app.run()
used? After module definition or afterapp.config()
, afterapp.controller()
?
In your package.js E.g. /packages/dashboard/public/controllers/dashboard.js
Make it look like this
var app = angular.module('mean.dashboard', ['ui.bootstrap']);
app.controller('DashboardController', ['$scope', 'Global', 'Dashboard',
function($scope, Global, Dashboard) {
$scope.global = Global;
$scope.package = {
name: 'dashboard'
};
// ...
}
]);
app.run(function(editableOptions) {
editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});
For the final, compiled code of your application, the short answer is “no”. Different tools are able to extract different information from the code (e.g. the forms setups) and there are P code decompilers (see Edgar's excellent link for such tools). However, up to this day, there is no decompiler for native code. I'm not aware of anything similar for other high-level languages either.
This answer is similar to @PaulMcG's answer but doesn't require sorting the input.
For those into functional programming, groupBy
can be written in one line (not including imports!), and unlike itertools.groupby
it doesn't require the input to be sorted:
from functools import reduce # import needed for python3; builtin in python2
from collections import defaultdict
def groupBy(key, seq):
return reduce(lambda grp, val: grp[key(val)].append(val) or grp, seq, defaultdict(list))
(The reason for ... or grp
in the lambda
is that for this reduce()
to work, the lambda
needs to return its first argument; because list.append()
always returns None
the or
will always return grp
. I.e. it's a hack to get around python's restriction that a lambda can only evaluate a single expression.)
This returns a dict whose keys are found by evaluating the given function and whose values are a list of the original items in the original order. For the OP's example, calling this as groupBy(lambda pair: pair[1], input)
will return this dict:
{'KAT': [('11013331', 'KAT'), ('9843236', 'KAT')],
'NOT': [('9085267', 'NOT'), ('11788544', 'NOT')],
'ETH': [('5238761', 'ETH'), ('5349618', 'ETH'), ('962142', 'ETH'), ('7795297', 'ETH'), ('7341464', 'ETH'), ('5594916', 'ETH'), ('1550003', 'ETH')]}
And as per @PaulMcG's answer the OP's requested format can be found by wrapping that in a list comprehension. So this will do it:
result = {key: [pair[0] for pair in values],
for key, values in groupBy(lambda pair: pair[1], input).items()}
It seems that for ignoring files and directories there are two main ways:
.gitignore
.gitignore
file into the root of your repository besides the .git
folder (in Windows, make sure you see the true file extension and then make .gitignore.
(with the point at the end to make an empty file extension))~/.gitignore_global
and running git config --global core.excludesfile ~/.gitignore_global
to add this to your Git configurationNote: files tracked before can be untracked by running git rm --cached filename
Repository exclude - For local files that do not need to be shared, you just add the file pattern or directory to the file .git/info/exclude
. Theses rules are not committed, so they are not seen by other users. More information is here.
To make exceptions in the list of ignored files, see this question.
I had this problem.When I define firefox path my problem had been solved.
import webbrowser
urL='https://www.python.org'
mozilla_path="C:\\Program Files\\Mozilla Firefox\\firefox.exe"
webbrowser.register('firefox', None,webbrowser.BackgroundBrowser(mozilla_path))
webbrowser.get('firefox').open_new_tab(urL)
Set a cookie:
res.cookie('cookie', 'monster')
https://expressjs.com/en/4x/api.html#res.cookie
Read a cookie:
(using cookie-parser middleware)
req.cookies['cookie']
These methods worked for me, it maybe useful for anyone: MapOptions interface
set min zoom: mMap.setMinZoomPreference(N);
set max zoom: mMap.setMaxZoomPreference(N);
where N can equal to:
20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9 : 2311162.307000
8 : 4622324.614000
7 : 9244649.227000
6 : 18489298.450000
5 : 36978596.910000
4 : 73957193.820000
3 : 147914387.600000
2 : 295828775.300000
1 : 591657550.500000
you could also try: instance_of?
p 1.instance_of? Fixnum #=> True
p "1".instance_of? String #=> True
p [1,2].instance_of? Array #=> True
To answer your question, these should work as long as:
But, if I remember correctly, these values can be faked to an extent, so it's best not to rely on them.
My personal preference is to set the domain name as an environment variable in the apache2 virtual host:
# Virtual host
setEnv DOMAIN_NAME example.com
And read it in PHP:
// PHP
echo getenv(DOMAIN_NAME);
This, however, isn't applicable in all circumstances.
ln -s /mnt/usr/lib/* /usr/lib/
private boolean deleteFromExternalStorage(File file) {
String fileName = "/Music/";
String myPath= Environment.getExternalStorageDirectory().getAbsolutePath() + fileName;
file = new File(myPath);
System.out.println("fullPath - " + myPath);
if (file.exists() && file.canRead()) {
System.out.println(" Test - ");
file.delete();
return false; // File exists
}
System.out.println(" Test2 - ");
return true; // File not exists
}
I think you're looking for this:
elements = [10, 11, 12, 13, 14, 15]
indices = (1,1,2,1,5)
result_list = [elements[i] for i in indices]
select convert(varchar(10), fmdate, 101) from sery
101 is a style argument.
Rest of 'em can be found here.
Try the below complete example for the same
<?php
$objPHPExcel = new PHPExcel();
$query1 = "SELECT * FROM employee";
$exec1 = mysql_query($query1) or die ("Error in Query1".mysql_error());
$serialnumber=0;
//Set header with temp array
$tmparray =array("Sr.Number","Employee Login","Employee Name");
//take new main array and set header array in it.
$sheet =array($tmparray);
while ($res1 = mysql_fetch_array($exec1))
{
$tmparray =array();
$serialnumber = $serialnumber + 1;
array_push($tmparray,$serialnumber);
$employeelogin = $res1['employeelogin'];
array_push($tmparray,$employeelogin);
$employeename = $res1['employeename'];
array_push($tmparray,$employeename);
array_push($sheet,$tmparray);
}
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="name.xlsx"');
$worksheet = $objPHPExcel->getActiveSheet();
foreach($sheet as $row => $columns) {
foreach($columns as $column => $data) {
$worksheet->setCellValueByColumnAndRow($column, $row + 1, $data);
}
}
//make first row bold
$objPHPExcel->getActiveSheet()->getStyle("A1:I1")->getFont()->setBold(true);
$objPHPExcel->setActiveSheetIndex(0);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));
?>
Another thing to be careful of (I did this so I know, duh). Be sure not to enable Proguard for debug!
First of all, you need to check that the IIS is installed in your machine, for that you can go to:
Control Panel --> Add or Remove Programs --> Windows Features --> And Check if Internet Information Services is installed with at least the 'Web Administration Tools' Enabled and The 'World Wide Web Service'
If not, check it, and Press Accept to install it.
Once that is done, you need to go to Administrative Tools in Control Panel and the IIS Will be there. Or simply run inetmgr (after Win+R).
Edit: You should have something like this:
import time
time.strftime('%H:%M%p %Z on %b %d, %Y')
YaLinqo library* is well suited for this sort of task. It's a port of LINQ from .NET which fully supports values and keys in all callbacks and resembles SQL. For example:
$mapped_array = from($test_array)
->select(function ($v, $k) { return "$k loves $v"; })
->toArray();
or just:
$mapped_iterator = from($test_array)->select('"$k loves $v"');
Here, '"$k loves $v"'
is a shortcut for full closure syntax which this library supports. toArray()
in the end is optional. The method chain returns an iterator, so if the result just needs to be iterated over using foreach
, toArray
call can be removed.
* developed by me
git stash drop
takes no parameter - which drops the top stash - or a stash reference which looks like: stash@{n}
which n
nominates which stash to drop. You can't pass a commit id to git stash drop
.
git stash drop # drop top hash, stash@{0}
git stash drop stash@{n} # drop specific stash - see git stash list
Dropping a stash will change the stash@{n}
designations of all stashes further down the stack.
I'm not sure why you think need to drop a stash because if you are using stash create
a stash entry isn't created for your "stash" so there isn't anything to drop.
If you're running these commands in a Docker container on Windows, it may mean that your docker machine's network connection is stale and needs to be rebuilt. To fix it, run these commands:
docker-machine stop
docker-machine start
@FOR /f "tokens=*" %i IN ('docker-machine env') DO @%i
This error also occurs if you did not upload the various rsl/swc/flash-library that your swf file might expect. You may upload this RSL or missing swc or tweak your compiler options cf. http://help.adobe.com/en_US/flashbuilder/using/WSe4e4b720da9dedb5-1a92eab212e75b9d8b2-7ffe.html#WSe4e4b720da9dedb5-1a92eab212e75b9d8b2-7ff5
DISTINCT
is always a right choice to get unique values. Also you can do it alternatively without using it. That's GROUP BY
. Which has simply add at the end of the query and followed by the column name.
SELECT * FROM buy GROUP BY date,description
I found the following solution to be easiest to setup environment variable for Webpack 2:
For example we have a webpack settings:
var webpack = require('webpack')
let webpackConfig = (env) => { // Passing envirmonment through
// function is important here
return {
entry: {
// entries
},
output: {
// outputs
},
plugins: [
// plugins
],
module: {
// modules
},
resolve: {
// resolves
}
}
};
module.exports = webpackConfig;
Add Environment Variable in Webpack:
plugins: [
new webpack.EnvironmentPlugin({
NODE_ENV: 'development',
}),
]
Define Plugin Variable and add it to plugins
:
new webpack.DefinePlugin({
'NODE_ENV': JSON.stringify(env.NODE_ENV || 'development')
}),
Now when running webpack command, pass env.NODE_ENV
as argument:
webpack --env.NODE_ENV=development
// OR
webpack --env.NODE_ENV development
Now you can access NODE_ENV
variable anywhere in your code.
Enumerate the subkeys of HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP
. Each subkey is a .NET version. It should have Install=1
value if it's present on the machine, an SP value that shows the service pack and an MSI=1
value if it was installed using an MSI. (.NET 2.0 on Windows Vista doesn't have the last one for example, as it is part of the OS.)
Why can't I use a list as a dict key in python?
>>> d = {repr([1,2,3]): 'value'}
{'[1, 2, 3]': 'value'}
(for anybody who stumbles on this question looking for a way around it)
as explained by others here, indeed you cannot. You can however use its string representation instead if you really want to use your list.
lastInsertId() only work after the INSERT query.
Correct:
$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass)
VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();
Incorrect:
$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0
result() returns Object type data. . . . result_array() returns Associative Array type data.
SQL Server :
SELECT [activity_dt], count(*)
FROM table1
GROUP BY DATEPART(day, [activity_dt]), DATEPART(hour, [activity_dt]);
Oracle :
SELECT [activity_dt], count(*)
FROM table1
GROUP BY TO_CHAR(activity_dt, 'DD'), TO_CHAR(activity_dt, 'hh');
MySQL :
SELECT [activity_dt], count(*)
FROM table1
GROUP BY hour( activity_dt ) , day( activity_dt )
enum Enum{ Banana, Orange, Apple } ;
static const char * EnumStrings[] = { "bananas & monkeys", "Round and orange", "APPLE" };
const char * getTextForEnum( int enumVal )
{
return EnumStrings[enumVal];
}
One way I found after some struggling is creating a function which gets data_plot matrix, file name and order as parameter to create boxplots from the given data in the ordered figure (different orders = different figures) and save it under the given file_name.
def plotFigure(data_plot,file_name,order):
fig = plt.figure(order, figsize=(9, 6))
ax = fig.add_subplot(111)
bp = ax.boxplot(data_plot)
fig.savefig(file_name, bbox_inches='tight')
plt.close()
In case you want to sort in more than one direction
public static void sortOutputTable(ref DataTable output)
{
DataView dv = output.DefaultView;
dv.Sort = "specialCode ASC, otherCode DESC";
DataTable sortedDT = dv.ToTable();
output = sortedDT;
}
The other answers to this question seem to hit it spot on. Now how would you figure this out for yourself without stack overflow? Check out IPython, an interactive Python shell that has tab auto-complete.
> ipython
import Python 2.5 (r25:51908, Nov 6 2007, 16:54:01)
Type "copyright", "credits" or "license" for more information.
IPython 0.8.2.svn.r2750 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
In [1]: import datetime
In [2]: now=datetime.datetime.now()
In [3]: now.
press tab a few times and you'll be prompted with the members of the "now" object:
now.__add__ now.__gt__ now.__radd__ now.__sub__ now.fromordinal now.microsecond now.second now.toordinal now.weekday
now.__class__ now.__hash__ now.__reduce__ now.astimezone now.fromtimestamp now.min now.strftime now.tzinfo now.year
now.__delattr__ now.__init__ now.__reduce_ex__ now.combine now.hour now.minute now.strptime now.tzname
now.__doc__ now.__le__ now.__repr__ now.ctime now.isocalendar now.month now.time now.utcfromtimestamp
now.__eq__ now.__lt__ now.__rsub__ now.date now.isoformat now.now now.timetuple now.utcnow
now.__ge__ now.__ne__ now.__setattr__ now.day now.isoweekday now.replace now.timetz now.utcoffset
now.__getattribute__ now.__new__ now.__str__ now.dst now.max now.resolution now.today now.utctimetuple
and you'll see that now.year is a member of the "now" object.
I think you can try add parameter axis=1
to concat
, because output of df.iloc[0,:]
and df.iloc[-1,:]
are Series
and transpose by T
:
print df.iloc[0,:]
a 1
b a
Name: 0, dtype: object
print df.iloc[-1,:]
a 4
b d
Name: 3, dtype: object
print pd.concat([df.iloc[0,:], df.iloc[-1,:]], axis=1)
0 3
a 1 4
b a d
print pd.concat([df.iloc[0,:], df.iloc[-1,:]], axis=1).T
a b
0 1 a
3 4 d
You can consider to replace default WordPress jQuery script with Google Library by adding something like the following into theme functions.php file:
function modify_jquery() {
if (!is_admin()) {
wp_deregister_script('jquery');
wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', false, '1.10.2');
wp_enqueue_script('jquery');
}
}
add_action('init', 'modify_jquery');
Code taken from here: http://www.wpbeginner.com/wp-themes/replace-default-wordpress-jquery-script-with-google-library/
The definitions are detailed at the Maven site's page Introduction to the Build Lifecycle, but I have tried to summarize:
Maven defines 4 items of a build process:
Lifecycle
Three built-in lifecycles (aka build lifecycles): default
, clean
, site
. (Lifecycle Reference)
Phase
Each lifecycle is made up of phases, e.g. for the default
lifecycle: compile
, test
, package
, install
, etc.
Plugin
An artifact that provides one or more goals.
Based on packaging type (jar
, war
, etc.) plugins' goals are bound to phases by default. (Built-in Lifecycle Bindings)
Goal
The task (action) that is executed. A plugin can have one or more goals.
One or more goals need to be specified when configuring a plugin in a POM. Additionally, in case a plugin does not have a default phase defined, the specified goal(s) can be bound to a phase.
Maven can be invoked with:
clean
, package
)<plugin-prefix>:<goal>
(e.g. dependency:copy-dependencies
)<plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>
(e.g. org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile
)with one or more combinations of any or all, e.g.:
mvn clean dependency:copy-dependencies package
VERSION=$(head -50 pom.xml | awk -F'>' '/SNAPSHOT/ {print $2}' | awk -F'<' '{print $1}')
This is what I used to get the version number, thought there would have been a better maven way to do so
It is the severity level of the error
. The levels are from 11 - 20 which throw an error in SQL
. The higher the level, the more severe the level and the transaction
should be aborted.
You will get the syntax error when you do:
RAISERROR('Cannot Insert where salary > 1000').
Because you have not specified the correct parameters
(severity level
or state
).
If you wish to issue a warning and not an exception
, use levels 0 - 10.
From MSDN:
severity
Is the user-defined severity level associated with this message. When using msg_id to raise a user-defined message created using sp_addmessage, the severity specified on RAISERROR overrides the severity specified in sp_addmessage. Severity levels from 0 through 18 can be specified by any user. Severity levels from 19 through 25 can only be specified by members of the sysadmin fixed server role or users with ALTER TRACE permissions. For severity levels from 19 through 25, the WITH LOG option is required.
state
Is an integer from 0 through 255. Negative values or values larger than 255 generate an error. If the same user-defined error is raised at multiple locations, using a unique state number for each location can help find which section of code is raising the errors. For detailed description here
It's not smart enough to realize it's still a "vector" in math terms.
Say rather that it's smart enough to recognize a difference in dimensionality. :-)
I think the simplest thing you can do is select that row positionally using iloc
, which gives you a Series with the columns as the new index and the values as the values:
>>> df = pd.DataFrame([list(range(5))], columns=["a{}".format(i) for i in range(5)])
>>> df
a0 a1 a2 a3 a4
0 0 1 2 3 4
>>> df.iloc[0]
a0 0
a1 1
a2 2
a3 3
a4 4
Name: 0, dtype: int64
>>> type(_)
<class 'pandas.core.series.Series'>
There is also this:
select m from table where not regexp_like(m, '^[0-9]\d+$')
which selects the rows that contains characters from the column you want (which is m in the example but you can change).
Most of the combinations don't work properly in Oracle platforms but this does. Sharing for future reference.
As several people have already said, this is due to autoboxing.
You could create a utility method to check whether the object's class is Integer
, Double
, etc. But there is no way to know whether an object was created by autoboxing a primitive; once it's boxed, it looks just like an object created explicitly.
So unless you know for sure that your array will never contain a wrapper class without autoboxing, there is no real solution.
Try this first, you may be passing a Null Model:
@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
<label for="Image">Change picture</label>
}
else
{
<label for="Image">Add picture</label>
}
Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.
<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>
Add multiple classes:
$("p").addClass("class1 class2 class3");
or in cascade:
$("p").addClass("class1").addClass("class2").addClass("class3");
Very similar also to remove more classes:
$("p").removeClass("class1 class2 class3");
or in cascade:
$("p").removeClass("class1").removeClass("class2").removeClass("class3");