Canvas
text support is actually pretty good - you can control font
, size
, color
, horizontal alignment
, vertical alignment
, and you can also get text metrics to get the text width in pixels. In addition, you can also use canvas transforms
to rotate
, stretch
and even invert
text.
Setting Tomcat to listen to port 80 is WRONG , for development the 8080 is a good port to use. For production use, just set up an apache that shall forward your requests to your tomcat. Here is a how to.
From http://docs.python.org/library/csv.html#csv.writer:
If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.
In other words, when opening the file you pass 'wb' as opposed to 'w'.
You can also use a with
statement to close the file when you're done writing to it.
Tested example below:
from __future__ import with_statement # not necessary in newer versions
import csv
headers=['id', 'year', 'activity', 'lineitem', 'datum']
with open('file3.csv','wb') as fou: # note: 'wb' instead of 'w'
output = csv.DictWriter(fou,delimiter=',',fieldnames=headers)
output.writerow(dict((fn,fn) for fn in headers))
output.writerows(rows)
You may store the parameters for the blob detector in a file, but this is not necessary. Example:
// set up the parameters (check the defaults in opencv's code in blobdetector.cpp)
cv::SimpleBlobDetector::Params params;
params.minDistBetweenBlobs = 50.0f;
params.filterByInertia = false;
params.filterByConvexity = false;
params.filterByColor = false;
params.filterByCircularity = false;
params.filterByArea = true;
params.minArea = 20.0f;
params.maxArea = 500.0f;
// ... any other params you don't want default value
// set up and create the detector using the parameters
cv::SimpleBlobDetector blob_detector(params);
// or cv::Ptr<cv::SimpleBlobDetector> detector = cv::SimpleBlobDetector::create(params)
// detect!
vector<cv::KeyPoint> keypoints;
blob_detector.detect(image, keypoints);
// extract the x y coordinates of the keypoints:
for (int i=0; i<keypoints.size(); i++){
float X = keypoints[i].pt.x;
float Y = keypoints[i].pt.y;
}
pyspark version:
df = <source data>
df.printSchema()
from pyspark.sql.types import *
# Change column type
df_new = df.withColumn("myColumn", df["myColumn"].cast(IntegerType()))
df_new.printSchema()
df_new.select("myColumn").show()
Spring dependency inject help you to remove coupling from your classes. Instead of creating object like this:
UserService userService = new UserServiceImpl();
You will be using this after introducing DI:
@Autowired
private UserService userService;
For achieving this you need to create a bean of your service in your ServiceConfiguration
file. After that you need to import that ServiceConfiguration
class to your WebApplicationConfiguration
class so that you can autowire that bean into your Controller like this:
public class AccController {
@Autowired
private UserService userService;
}
You can find a java configuration based POC here example.
You've got it nearly correct, but you haven't accounted for the this
value supplied to the inline code.
<a href="#" onclick="alert(this)">Click Me</a>
is actually closer to:
<a href="#" id="click_me">Click Me</a>
<script type="text/javascript">
document.getElementById('click_me').addEventListener("click", function(event) {
(function(event) {
alert(this);
}).call(document.getElementById('click_me'), event);
});
</script>
Inline event handlers set this
equal to the target of the event.
You can also use anonymous function in inline script
<a href="#" onclick="(function(){alert(this);})()">Click Me</a>
about:config -> security.fileuri.strict_origin_policy -> false
I just came up with a general solution, which should work on most websites. I tried this on Chrome only, but this method should work with any other browser, though, as Dev Tools are pretty much the same in them all.
Steps:
.m3u8
extension. There may be many of them, but most likely the first you find is the one you are looking for. It may have any name, e.g. playlist.m3u8
.I know this won't be popular but here goes:
myISAM lacks support for database essentials like transactions and referential integrity which often results in glitchy / buggy applications. You cannot not learn proper database design fundamentals if they are not even supported by your db engine.
Not using referential integrity or transactions in the database world is like not using object oriented programming in the software world.
InnoDB exists now, use that instead! Even MySQL developers have finally conceded to change this to the default engine in newer versions, despite myISAM being the original engine that was the default in all legacy systems.
No it does not matter if you are reading or writing or what performance considerations you have, using myISAM can result in a variety of problems, such as this one I just ran into: I was performing a database sync and at the same time someone else accessed an application that accessed a table set to myISAM. Due to the lack of transaction support and the generally poor reliability of this engine, this crashed the entire database and I had to manually restart mysql!
Over the past 15 years of development I have used many databases and engines. myISAM crashed on me about a dozen times during this period, other databases, only once! And that was a microsoft SQL database where some developer wrote faulty CLR code (common language runtime - basically C# code that executes inside the database) by the way, it was not the database engine's fault exactly.
I agree with the other answers here that say that quality high-availability, high-performance applications should not use myISAM as it will not work, it is not robust or stable enough to result in a frustration-free experience. See Bill Karwin's answer for more details.
P.S. Gotta love it when myISAM fanboys downvote but can't tell you which part of this answer is incorrect.
First, make sure that the source page and the target page are both served through the file
URI scheme. You can't force an http
page to open a file
page (but it works the other way around).
Next, your script that calls window.open()
should be invoked by a user-initiated event, such as clicks, keypresses and the like. Simply calling window.open()
won't work.
You can test this right here in this question page. Run these in Chrome's JavaScript console:
// Does nothing
window.open('http://google.com');
// Click anywhere within this page and the new window opens
$(document.body).unbind('click').click(function() { window.open('http://google.com'); });
// This will open a new window, but it would be blank
$(document.body).unbind('click').click(function() { window.open('file:///path/to/a/local/html/file.html'); });
You can also test if this works with a local file. Here's a sample HTML file that simply loads jQuery:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
</head>
<body>
<h5>Feel the presha</h5>
<h3>Come play my game, I'll test ya</h3>
<h1>Psycho- somatic- addict- insane!</h1>
</body>
</html>
Then open Chrome's JavaScript console and run the statements above. The 3rd one will now work.
For Ubuntu 18.04 and mysql 5.7
step 1: sudo mkdir /var/run/mysqld;
step 2: sudo chown mysql /var/run/mysqld
step 3: sudo mysqld_safe --skip-grant-tables
& quit (use quit if its
stuck )
login to mysql without password
step 4: sudo mysql --user=root mysql
step 5: SELECT user,authentication_string,plugin,host FROM mysql.user;
step 6: ALTER USER 'root'@'localhost' IDENTIFIED WITH
mysql_native_password BY 'root'
now login with
mysql -u root -p <root>
Create a class that inherits from IActionFilter.
public class NoCacheAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
filterContext.HttpContext.Response.Cache.SetNoStore();
base.OnResultExecuting(filterContext);
}
}
Then put attributes where needed...
[NoCache]
[HandleError]
public class AccountController : Controller
{
[NoCache]
[Authorize]
public ActionResult ChangePassword()
{
return View();
}
}
I was facing the same problem with clj-webdriver (clojure port of Selenium). I just translated the previous solution to clojure for convenience. You can call this function before doing click or whatever to avoid that problem.
(defn scrollTo
"Scrolls to the position of the given css selector if found"
[q]
(if (exists? q)
(let [ loc (location-once-visible q) jscript (str "window.scrollTo(" (:x loc) "," (:y loc) ")") ]
(execute-script jscript))))
Just add background-attachment to your code
body {
background-position: center;
background-image: url(../images/images5.jpg);
background-attachment: fixed;
}
On the i/o 2019 the following solution was presented:
/**
* Blurs the given Bitmap image
* @param bitmap Image to blur
* @param applicationContext Application context
* @return Blurred bitmap image
*/
@WorkerThread
fun blurBitmap(bitmap: Bitmap, applicationContext: Context): Bitmap {
lateinit var rsContext: RenderScript
try {
// Create the output bitmap
val output = Bitmap.createBitmap(
bitmap.width, bitmap.height, bitmap.config)
// Blur the image
rsContext = RenderScript.create(applicationContext, RenderScript.ContextType.DEBUG)
val inAlloc = Allocation.createFromBitmap(rsContext, bitmap)
val outAlloc = Allocation.createTyped(rsContext, inAlloc.type)
val theIntrinsic = ScriptIntrinsicBlur.create(rsContext, Element.U8_4(rsContext))
theIntrinsic.apply {
setRadius(10f)
theIntrinsic.setInput(inAlloc)
theIntrinsic.forEach(outAlloc)
}
outAlloc.copyTo(output)
return output
} finally {
rsContext.finish()
}
}
With PostgreSQL 8.4 or newer there is no need to specify the WITH 1
anymore. The start value that was recorded by CREATE SEQUENCE
or last set by ALTER SEQUENCE START WITH
will be used (most probably this will be 1).
Reset the sequence:
ALTER SEQUENCE seq RESTART;
Then update the table's ID column:
UPDATE foo SET id = DEFAULT;
Source: PostgreSQL Docs
I wouldn't use the debian packages, have a look at RVM or Rbenv.
on OS X you can use the -v option for netstat to give the associated pid.
type:
netstat -anv | grep [.]PORT
the output will look like this:
tcp46 0 0 *.8080 *.* LISTEN 131072 131072 3105 0
The PID is the number before the last column, 3105 for this case
Use the following code in your controller:
return Json(new { success = string }, JsonRequestBehavior.AllowGet);
and in JavaScript:
success: function (data) {
var response = data.success;
....
}
In linux i'm a fun of Nano or vim, i used to use nano and now vim, and they are really good choices. There is a version for windows. Here is the link https://nano-editor.org/dist/win32-support/
However more often we need to open the file in question, from the command line as quick as possible, to not loose time. We can use notepad.exe, we can use notepad++, and yea, we can use sublim text. I think there is no greater then a lightweight, Too powerful editor. Sublime text here. for the thing, we just don't want to get out of the command line, or we want to use the command line to be fast. and yea. We can use sublime text for that. it contain a command line that let you quickly open a file in sublime text. Also there is different options arguments you can make use of. Here how you do it.
First you need to know that there is subl.exe. a command line interface for sublim.
1-> first we create a batch file. the content is
@ECHO OFF
"C:\Program Files\Sublime Text 3\subl.exe" %*
We can save that wherever we want. I preferred to create a directory on sublime text installation directory. And saved there the batch file we come to write and create.
(Remark: change the path above fallowing your installation).
2-> we add that folder to the path system environment variable. and that's it.
or from system config (windows 7/8/10)
then:
then:
then we copy the path:
then we add that to the path variable:
too quick!
launch a new cmd and now you've got subl command working well!
to open a file you need just to use subl command as fellow:
subl myfileToOpen.txt
you can also use one of the options arguments (type --help to see them as in the image above).
Also note that you can apply the same method with mostly any editor of your choice.
It is usually much faster to script out all the objects in the database, and create an empty one, that to delete from or truncate tables.
Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.
>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False
Edit
Further explanation: How does Python compare string and int?
If you want to effect on the menu options for changing the locale immediately.You have to do like this.
//onCreate method calls only once when menu is called first time.
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//1.Here you can add your locale settings .
//2.Your menu declaration.
}
//This method is called when your menu is opend to again....
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
menu.clear();
onCreateOptionsMenu(menu);
return super.onMenuOpened(featureId, menu);
}
In the picture you can see. In the set script options, choose the last option: Types of data to script you click at the right side and you choose what you want. This is the option you should choose to export a schema and data
yyp - remember it with "yippee!"
Multiple lines with a number in between:
y7yp
In order to distinct all datatable columns, you can easily retrieve the names of the columns in a string array
public static DataTable RemoveDuplicateRows(this DataTable dataTable)
{
List<string> columnNames = new List<string>();
foreach (DataColumn col in dataTable.Columns)
{
columnNames.Add(col.ColumnName);
}
return dataTable.DefaultView.ToTable(true, columnNames.Select(c => c.ToString()).ToArray());
}
As you can notice, I thought of using it as an extension to DataTable class
This works, as long as you remove the height attribute from the table.
<table id="content" border="0px" cellspacing="0px" cellpadding="0px">
<tr><td height='9px' bgcolor="#990000">Upper</td></tr>
<tr><td height='100px' bgcolor="#990099">Lower</td></tr>
</table>
Paul's answer is very good and it is actually how Kafka & Zk work together from a broker point of view.
I would say that another easy option to check if a Kafka server is running is to create a simple KafkaConsumer pointing to the cluste and try some action, for example, listTopics(). If kafka server is not running, you will get a TimeoutException and then you can use a try-catch
sentence.
def validateKafkaConnection(kafkaParams : mutable.Map[String, Object]) : Unit = {
val props = new Properties()
props.put("bootstrap.servers", kafkaParams.get("bootstrap.servers").get.toString)
props.put("group.id", kafkaParams.get("group.id").get.toString)
props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
val simpleConsumer = new KafkaConsumer[String, String](props)
simpleConsumer.listTopics()
}
Make it
float b= 3.6f;
A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d
The APK file is in the /workspace/PROJECT_FOLDER/bin
directory. To install the APK file in a real device:
Connect your real device with a PC/laptop.
Go to sdk/tools/
using a terminal or command prompt.
adb install <FILE PATH OF .APK FILE>
That's it...
I faced the same error, in my case I miss-spelled ng-model directive something like "ng-moel"
Wrong one: ng-moel="user.name" Right one: ng-model="user.name"
@Chris Noe
Note that the space in front of the & becomes part of the previous command. That has bitten me with SET, which happily puts trailing blanks into the value.
To get around the trailing-space being added to an environment variable, wrap the set command in parens.
E.g. FOR /F %%I IN ('DIR "*.*" /B /O:D') DO (SET NewestFile=%%I)
One of the common mistakes people do when change the image source is not waiting for image load to do afterward actions like maturing image size etc.
You will need to use jQuery .load()
method to do stuff after image load.
$('yourimageselector').attr('src', 'newsrc').load(function(){
this.width; // Note: $(this).width() will not work for in memory images
});
Reason for editing: https://stackoverflow.com/a/670433/561545
via Is there a way to link someone to a YouTube Video in HD 1080p quality?
Yes there is:
https://www.youtube.com/embed/Susj4jVWs0s?version=3&vq=hd720
options are:
default|none: vq=auto;
Code for auto: vq=auto;
Code for 2160p: vq=hd2160;
Code for 1440p: vq=hd1440;
Code for 1080p: vq=hd1080;
Code for 720p: vq=hd720;
Code for 480p: vq=large;
Code for 360p: vq=medium;
Code for 240p: vq=small;
As mentioned, you have to use the /embed/
or /v/
URL.
Note: Some copyrighted content doesn't support be played in this way
I ran into this exact problem too. In my case, adding parenthesis around any internal functions (to get them to evaluate first) seemed to do the trick:
Changed
=SUM(A1, SUBSTITUTE(A2,"x","3",1), A3)
to
=SUM(A1, (SUBSTITUTE(A2,"x","3",1)), A3)
A great way of handling this is with regular expressions.
string modifiedString = Regex.Replace(originalString, @"(\r\n)|\n|\r", "<br/>");
This will replace any of the 3 legal types of newline with the html tag.
You'll want to use a number of layout managers to help you achieve the basic results you want.
Check out A Visual Guide to Layout Managers for a comparision.
You could use a GridBagLayout
but that's one of the most complex (and powerful) layout managers available in the JDK.
You could use a series of compound layout managers instead.
I'd place the graphics component and text area on a single JPanel
, using a BorderLayout
, with the graphics component in the CENTER
and the text area in the SOUTH
position.
I'd place the text field and button on a separate JPanel
using a GridBagLayout
(because it's the simplest I can think of to achieve the over result you want)
I'd place these two panels onto a third, master, panel, using a BorderLayout
, with the first panel in the CENTER
and the second at the SOUTH
position.
But that's me
tuple(set([6, 7, 8, 9, 10, 11, 12]).difference([6, 9, 12]))
I use it all the time in my coding.
The -ansi
flag is equivalent to -std=c89
. As noted, it turns off some extensions of GCC. Adding -pedantic
turns off more extensions and generates more warnings. For example, if you have a string literal longer than 509 characters, then -pedantic
warns about that because it exceeds the minimum limit required by the C89 standard. That is, every C89 compiler must accept strings of length 509; they are permitted to accept longer, but if you are being pedantic, it is not portable to use longer strings, even though a compiler is permitted to accept longer strings and, without the pedantic warnings, GCC will accept them too.
To see the public tables you can do
list tables
\dt
list table, view, and access privileges
\dp or \z
or just the table names
select table_name from information_schema.tables where table_schema = 'public';
As mentioned in a comment to ephrion's answer above, filter() can be slow, especially with large arrays, as it loops to look for an index that appears to have been determined already. This is a clean, but inefficient solution.
As an alternative one can simply 'slice' out the desired element and concatenate the fragments.
var dummyArray = [];
this.setState({data: dummyArray.concat(this.state.data.slice(0, index), this.state.data.slice(index))})
Hope this helps!
Details
http://msdn.microsoft.com/en-us/library/hh169179(v=nav.71).aspx
"This error can occur when there are multiple versions of the .NET Framework on the computer that is running IIS..."
Following Jaro's advice, I was able to get this working under Windows XP and IIS Express (installed via Web Matrix) with a small modification and was not limited to only localhost. It's just a matter of setting the bindings correctly.
%USERPROFILE%\My Documents\IISExpress\config\applicationhost.config
(Windows XP. Vista and 7 paths will be similar) and edit the site definition in the <sites>
config block to be along the lines of the following:<site name="DevExample" id="997005936">
<application path="/" applicationPool="Clr2IntegratedAppPool">
<virtualDirectory
path="/"
physicalPath="C:\path\to\application\root" />
</application>
<bindings>
<binding
protocol="http"
bindingInformation="*:80:dev.example.com" />
</bindings>
<applicationDefaults applicationPool="Clr2IntegratedAppPool" />
</site>
If running MVC, then keep the applicationPool set to one of the "Integrated" options.
// In Fragment_1.java
Bundle bundle = new Bundle();
bundle.putString("key","abc"); // Put anything what you want
Fragment_2 fragment2 = new Fragment_2();
fragment2.setArguments(bundle);
getFragmentManager()
.beginTransaction()
.replace(R.id.content, fragment2)
.commit();
// In Fragment_2.java
Bundle bundle = this.getArguments();
if(bundle != null){
// handle your code here.
}
Hope this help you.
Try this:
declare @var char(3)
set @var='[%]'
select Address from Accomodation where Address like '%'+@var+'%'
You must use [] cancels the effect of wildcard, so you read % as a normal character, idem about character _
SELECT
DB_NAME(dbid) as DBName,
COUNT(dbid) as NumberOfConnections,
loginame as LoginName
FROM
sys.sysprocesses
WHERE
dbid > 0
GROUP BY
dbid, loginame
;
See also the Microsoft documentation for sys.sysprocesses.
Cannot update first answer.
Anyway, after Go1 release, there are some breaking changes, so I updated as shown below:
package main
import (
"os"
"bufio"
"bytes"
"io"
"fmt"
"strings"
)
// Read a whole file into the memory and store it as array of lines
func readLines(path string) (lines []string, err error) {
var (
file *os.File
part []byte
prefix bool
)
if file, err = os.Open(path); err != nil {
return
}
defer file.Close()
reader := bufio.NewReader(file)
buffer := bytes.NewBuffer(make([]byte, 0))
for {
if part, prefix, err = reader.ReadLine(); err != nil {
break
}
buffer.Write(part)
if !prefix {
lines = append(lines, buffer.String())
buffer.Reset()
}
}
if err == io.EOF {
err = nil
}
return
}
func writeLines(lines []string, path string) (err error) {
var (
file *os.File
)
if file, err = os.Create(path); err != nil {
return
}
defer file.Close()
//writer := bufio.NewWriter(file)
for _,item := range lines {
//fmt.Println(item)
_, err := file.WriteString(strings.TrimSpace(item) + "\n");
//file.Write([]byte(item));
if err != nil {
//fmt.Println("debug")
fmt.Println(err)
break
}
}
/*content := strings.Join(lines, "\n")
_, err = writer.WriteString(content)*/
return
}
func main() {
lines, err := readLines("foo.txt")
if err != nil {
fmt.Println("Error: %s\n", err)
return
}
for _, line := range lines {
fmt.Println(line)
}
//array := []string{"7.0", "8.5", "9.1"}
err = writeLines(lines, "foo2.txt")
fmt.Println(err)
}
Surely using array_map
and if using a container implementing ArrayAccess
to derive objects is just a smarter, semantic way to go about this?
Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.
For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN()
clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait
cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.
<?php
$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);
vs
<?php
$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
$arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);
If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr
you could always $arr = array_map
and be explicit.
Kill process and close the terminal which you used for running the app on that port.
Personally I'd go with AJAX.
If you cannot switch to @Ajax...
helpers, I suggest you to add a couple of properties in your model
public bool TriggerOnLoad { get; set; }
public string TriggerOnLoadMessage { get; set: }
Change your view to a strongly typed Model via
@using MyModel
Before returning the View, in case of successfull creation do something like
MyModel model = new MyModel();
model.TriggerOnLoad = true;
model.TriggerOnLoadMessage = "Object successfully created!";
return View ("Add", model);
then in your view, add this
@{
if (model.TriggerOnLoad) {
<text>
<script type="text/javascript">
alert('@Model.TriggerOnLoadMessage');
</script>
</text>
}
}
Of course inside the tag you can choose to do anything you want, event declare a jQuery ready function:
$(document).ready(function () {
alert('@Model.TriggerOnLoadMessage');
});
Please remember to reset the Model properties upon successfully alert emission.
Another nice thing about MVC is that you can actually define an EditorTemplate for all this, and then use it in your view via:
@Html.EditorFor (m => m.TriggerOnLoadMessage)
But in case you want to build up such a thing, maybe it's better to define your own C# class:
class ClientMessageNotification {
public bool TriggerOnLoad { get; set; }
public string TriggerOnLoadMessage { get; set: }
}
and add a ClientMessageNotification
property in your model. Then write EditorTemplate / DisplayTemplate for the ClientMessageNotification
class and you're done. Nice, clean, and reusable.
LIFO is the way browser parses CSS properties..If you are using Sass declare a variable called as
"$header-background: red;"
use it instead of directly assigning values like red or blue. When you want to override just reassign the value to
"$header-background:blue"
then
background-color:$header-background;
it should smoothly override. Using "!important" is not always the right choice..Its just a hotfix
command > file >&1
On top of what the others have already stated, some sort of server-side scripting is necessary in order for the server to read and save the file.
Using PHP might be a good choice, but you're free to use any server-side scripting language. http://www.w3schools.com/php/php_file_upload.asp may be of use on that end.
You can also try:
string res = string.Join("", sample.Split(Environment.NewLine.ToCharArray())
Environment.NewLine should make it independent of platform.
Environment.NewLine Property
Here is what I have for mine.
Essentially you are utilizing the onfocus and onblur commands in the tag to trigger the appropriate javascript. It could be as simple as:
<span><input name="login_text_password" type="text" value="Password" onfocus="this.select(); this.setAttribute('type','password');" onblur="this.select(); this.setAttribute('type','text');" /></span>
An evolved version of this basic functionality checks for and empty string and returns the password input back to the original "Password" in the event of a null textbox:
<script type="text/javascript">
function password_set_attribute() {
if (document.getElementsByName("login_text_password")[0].value.replace(/\s+/g, ' ') == "" || document.getElementsByName[0].value == null) {
document.getElementsByName("login_text_password")[0].setAttribute('type','text')
document.getElementsByName("login_text_password")[0].value = 'Password';
}
else {
document.getElementsByName("login_text_password")[0].setAttribute('type','password')
}
}
</script>
Where HTML looks like:
<span><input name="login_text_password" class="roundCorners" type="text" value="Password" onfocus="this.select(); this.setAttribute('type','password');" onblur="password_set_attribute();" /></span>
The number in parentheses specifies the precision of fractional seconds to be stored. So, (0)
would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.
So an unspecified value would store a date like:
TIMESTAMP 24-JAN-2012 08.00.05.993847 AM
And specifying (0)
stores only:
TIMESTAMP(0) 24-JAN-2012 08.00.05 AM
Here's a benchmark to compare a Go for
statement with a ForClause and a Go range
statement using the iter
package.
iter_test.go
package main
import (
"testing"
"github.com/bradfitz/iter"
)
const loops = 1e6
func BenchmarkForClause(b *testing.B) {
b.ReportAllocs()
j := 0
for i := 0; i < b.N; i++ {
for j = 0; j < loops; j++ {
j = j
}
}
_ = j
}
func BenchmarkRangeIter(b *testing.B) {
b.ReportAllocs()
j := 0
for i := 0; i < b.N; i++ {
for j = range iter.N(loops) {
j = j
}
}
_ = j
}
// It does not cause any allocations.
func N(n int) []struct{} {
return make([]struct{}, n)
}
func BenchmarkIterAllocs(b *testing.B) {
b.ReportAllocs()
var n []struct{}
for i := 0; i < b.N; i++ {
n = iter.N(loops)
}
_ = n
}
Output:
$ go test -bench=. -run=.
testing: warning: no tests to run
PASS
BenchmarkForClause 2000 1260356 ns/op 0 B/op 0 allocs/op
BenchmarkRangeIter 2000 1257312 ns/op 0 B/op 0 allocs/op
BenchmarkIterAllocs 20000000 82.2 ns/op 0 B/op 0 allocs/op
ok so/test 7.026s
$
If you want all groups known to the system, I would recommend using getent group
instead of parsing /etc/group
:
getent group
The reason is that on networked systems, groups may not only read from /etc/group
file, but also obtained through LDAP or Yellow Pages (the list of known groups comes from the local group file plus groups received via LDAP or YP in these cases).
If you want just the group names you can use:
getent group | cut -d: -f1
Implement the Comparable interface on your customObject.
I prefer to use <script>console.log({$varname|@json_encode})</script>
to log to the console.
building on @ltamar's answer:
Use summary and munge the output into something useful!
library(tidyr)
library(dplyr)
df %>%
summary %>%
data.frame %>%
select(-Var1) %>%
separate(data=.,col=Freq,into = c('metric','value'),sep = ':') %>%
rename(column_name=Var2) %>%
mutate(value=as.numeric(value),
metric = trimws(metric,'both')
) %>%
filter(!is.na(value)) -> metrics
It's not pretty and it is certainly not fast but it gets the job done!
sum(l) / float(len(l))
is the right answer, but just for completeness you can compute an average with a single reduce:
>>> reduce(lambda x, y: x + y / float(len(l)), l, 0)
20.111111111111114
Note that this can result in a slight rounding error:
>>> sum(l) / float(len(l))
20.111111111111111
you can install the script ;
pip3 install --user advance-touch
After installed, you can use ad command
ad airport/plane/captain.txt
airport/
+-- plane/
¦ +-- captain.txt
If you didn't add pip when creating conda environment
conda create -n env_name pip
and also didn't install pip inside the environment
source activate env_name
conda install pip
then the only pip you got is the system pip, which will install packages globally.
Bus as you can see in this issue, even if you did either of the procedure mentioned above, the behavior of pip inside conda environment is still kind of undefined.
To ensure using the pip installed inside conda environment without having to type the lengthy /home/username/anaconda/envs/env_name/bin/pip
, I wrote a shell function:
# Using pip to install packages inside conda environments.
cpip() {
ERROR_MSG="Not in a conda environment."
ERROR_MSG="$ERROR_MSG\nUse \`source activate ENV\`"
ERROR_MSG="$ERROR_MSG to enter a conda environment."
[ -z "$CONDA_DEFAULT_ENV" ] && echo "$ERROR_MSG" && return 1
ERROR_MSG='Pip not installed in current conda environment.'
ERROR_MSG="$ERROR_MSG\nUse \`conda install pip\`"
ERROR_MSG="$ERROR_MSG to install pip in current conda environment."
[ -e "$CONDA_PREFIX/bin/pip" ] || (echo "$ERROR_MSG" && return 2)
PIP="$CONDA_PREFIX/bin/pip"
"$PIP" "$@"
}
Hope this is helpful to you.
Here you go, no frameworks, short and simple:
var el = document.getElementById('elId');
var elTop = el.getBoundingClientRect().top - document.body.getBoundingClientRect().top;
window.addEventListener('scroll', function(){
if (document.documentElement.scrollTop > elTop){
el.style.position = 'fixed';
el.style.top = '0px';
}
else
{
el.style.position = 'static';
el.style.top = 'auto';
}
});
Ok, I think I was able to find a proper solution for that.
Now, instead of sending <Link/>
as prop to Document, I send <NextLink/>
which is a custom wrapper for the react-router Link. By doing that, I'm able to have the right arrow as part of the Link structure while still avoiding to have routing code inside Document object.
The updated code looks like follows:
//in NextLink.js
var React = require('react');
var Right = require('./Right');
var NextLink = React.createClass({
propTypes: {
link: React.PropTypes.node.isRequired
},
contextTypes: {
transitionTo: React.PropTypes.func.isRequired
},
_onClickRight: function() {
this.context.transitionTo(this.props.link.props.to);
},
render: function() {
return (
<div>
{this.props.link}
<Right onClick={this._onClickRight} />
</div>
);
}
});
module.exports = NextLink;
...
//in MasterPage.js
var sampleLink = <Link to="/sample">Go To Sample</Link>
var nextLink = <NextLink link={sampleLink} />
<Document next={nextLink} />
//in Document.js
...
var Document = React.createClass({
render: function() {
return (
...
<div>{this.props.next}</div>
...
);
}
});
...
P.S: If you are using the latest version of react-router you may need to use this.context.router.transitionTo
instead of this.context.transitionTo
. This code will work fine for react-router version 0.12.X.
To supplement, here is an example expanded from the documentation, which nicely wraps all you need to know about accessing the paths/URLs in all cases with express:
app.use('/admin', function (req, res, next) { // GET 'http://www.example.com/admin/new?a=b'
console.dir(req.originalUrl) // '/admin/new?a=b' (WARNING: beware query string)
console.dir(req.baseUrl) // '/admin'
console.dir(req.path) // '/new'
console.dir(req.baseUrl + req.path) // '/admin/new' (full path without query string)
next()
})
Based on: https://expressjs.com/en/api.html#req.originalUrl
Conclusion: As c1moore's answer states, use:
var fullPath = req.baseUrl + req.path;
A Stack
allows you to stack elements on top of each other, with the last element in the array taking the highest priority. You can use Align
, Positioned
, or Container
to position the children of a stack.
Align
Widgets are moved by setting the alignment with Alignment
, which has static properties like topCenter
, bottomRight, and so on. Or you can take full control and set Alignment(1.0, -1.0)
, which takes x,y values ranging from 1.0 to -1.0, with (0,0) being the center of the screen.
Stack(
children: [
Align(
alignment: Alignment.topCenter,
child: Container(
height: 80,
width: 80, color: Colors.blueAccent
),
),
Align(
alignment: Alignment.center,
child: Container(
height: 80,
width: 80, color: Colors.deepPurple
),
),
Container(
alignment: Alignment.bottomCenter,
// alignment: Alignment(1.0, -1.0),
child: Container(
height: 80,
width: 80, color: Colors.amber
),
)
]
)
Having seen your fiddle in the comments the issue is quite easy to fix. You just need to add overflow:auto
or set a specific height to your div
. Live example: http://jsfiddle.net/tw16/xRcXL/3/
.Tab{
overflow:auto; /* add this */
border:solid 1px #faa62a;
border-bottom:none;
padding:7px 10px;
background:-moz-linear-gradient(center top , #FAD59F, #FA9907) repeat scroll 0 0 transparent;
background:-webkit-gradient(linear, left top, left bottom, from(#fad59f), to(#fa9907));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907)";
}
You can change the index as explained already using set_index
.
You don't need to manually swap rows with columns, there is a transpose (data.T
) method in pandas that does it for you:
> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
['ABERFELDIE', 534000, 600000]],
columns=['Locality', 2005, 2006])
> newdf = df.set_index('Locality').T
> newdf
Locality ABBOTSFORD ABERFELDIE
2005 427000 534000
2006 448000 600000
then you can fetch the dataframe column values and transform them to a list:
> newdf['ABBOTSFORD'].values.tolist()
[427000, 448000]
Worked this out, turns out that android.R.color.black is not the same as Color.BLACK. Changed the code to:
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStyle(Style.FILL);
canvas.drawPaint(paint);
paint.setColor(Color.BLACK);
paint.setTextSize(20);
canvas.drawText("Some Text", 10, 25, paint);
and it all works fine now!!
if you are using IIS, maybe you should try
"application pools" --> "DefaultAppPool" --> "application pools default value"
--> "32-Bit-application-activ" --> set false
try this;
select gid
from `gd`
group by gid
having count(*) > 10
order by lastupdated desc
It should be on Project -> app
folder
Please find the screenshot from Firebase website
Use the SingleOrDefault() instead of FirstOrDefault().
You can use this
var fs = require('fs');
var myCss = {
style : fs.readFileSync('./style.css','utf8');
};
app.get('/', function(req, res){
res.render('index.ejs', {
title: 'My Site',
myCss: myCss
});
});
put this on template
<%- myCss.style %>
just build style.css
<style>
body {
background-color: #D8D8D8;
color: #444;
}
</style>
I try this for some custom css. It works for me
As we are now running PHP 7, answers given here are not correct any more. The only one still OK is the one from Frank Forte, as he talks about PHP 7.
On the other side, rather than trying to catch errors with a try/catch you can use a trick: use include.
Here three pieces of code:
File: tst1.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
// Missing " and ;
echo "Testing
?>
Running this in PHP 7 will show nothing.
Now, try this:
File: tst2.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
include ("tst3.php");
?>
File: tst3.php
<?php
// Missing " and ;
echo "Testing
?>
Now run tst2 which sets the error reporting, and then include tst3. You will see:
Parse error: syntax error, unexpected end of file, expecting variable (T_VARIABLE) or ${ (T_DOLLAR_OPEN_CURLY_BRACES) or {$ (T_CURLY_OPEN) in tst3.php on line 4
If it needs to run on the onload
event of the page, meaning that the document and all its assets have loaded, this needs to be in a content script embedded in each page for which you wish to track onload
.
Here is a shorter bit of code that reenables scroll bars across your entire website. I'm not sure if it's much different than the current most popular answer but here it is:
::-webkit-scrollbar {
-webkit-appearance: none;
width: 7px;
}
::-webkit-scrollbar-thumb {
border-radius: 4px;
background-color: rgba(0,0,0,.5);
box-shadow: 0 0 1px rgba(255,255,255,.5);
}
Found at this link: http://simurai.com/blog/2011/07/26/webkit-scrollbar
function Copy-File ([System.String] $sourceFile, [System.String] $destinationFile, [Switch] $overWrite) {
if ($sourceFile -notlike "filesystem::*") {
$sourceFile = "filesystem::$sourceFile"
}
if ($destinationFile -notlike "filesystem::*") {
$destinationFile = "filesystem::$destinationFile"
}
$destinationFolder = $destinationFile.Replace($destinationFile.Split("\")[-1],"")
if (!(Test-Path -path $destinationFolder)) {
New-Item $destinationFolder -Type Directory
}
try {
Copy-Item -Path $sourceFile -Destination $destinationFile -Recurse -Force
Return $true
} catch [System.IO.IOException] {
# If overwrite enabled, then delete the item from the destination, and try again:
if ($overWrite) {
try {
Remove-Item -Path $destinationFile -Recurse -Force
Copy-Item -Path $sourceFile -Destination $destinationFile -Recurse -Force
Return $true
} catch {
Write-Error -Message "[Copy-File] Overwrite error occurred!`n$_" -ErrorAction SilentlyContinue
#$PSCmdlet.WriteError($Global:Error[0])
Return $false
}
} else {
Write-Error -Message "[Copy-File] File already exists!" -ErrorAction SilentlyContinue
#$PSCmdlet.WriteError($Global:Error[0])
Return $false
}
} catch {
Write-Error -Message "[Copy-File] File move failed!`n$_" -ErrorAction SilentlyContinue
#$PSCmdlet.WriteError($Global:Error[0])
Return $false
}
}
Use Rafael's solution: http://social.msdn.microsoft.com/Forums/en/sqlsetupandupgrade/thread/dddf0349-557b-48c7-bf82-6bd1adb5c694..
Added data from link to avoid link rot..
put this at any Console application:
string.Format("{0,3}", CultureInfo.InstalledUICulture.Parent.LCID.ToString("X")).Replace(" ", "0");
Watch the result. At mine it was "016".
Then you go to the registry at this key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib
and create another one with the name you got from the string.Format result.
In my case:
"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\016"
and copy the info that is on any other key in this Perflib to this key you just created. Run the instalation again.
Just run the script and get your 3 digit code. Then follow his simple and quick steps, and you're ready to go!
Cheers
This worked for me:
import re
text = 'how are u? umberella u! u. U. U@ U# u '
rex = re.compile(r'\bu\b', re.IGNORECASE)
print(rex.sub('you', text))
It pre-compiles the regular expression and makes use of re.IGNORECASE so that we don't have to worry about case in our regular expression! BTW, I love the funky spelling of umbrella! :-)
One way to do it will be to move all the php code above the HTML, copy the result to a variable and then add the result in the <input>
tag.
Try this -
<?php
//Adding the php to the top.
if(isset($_POST['submit']))
{
$value1=$_POST['value1'];
$value2=$_POST['value2'];
$sign=$_POST['sign'];
...
//Adding to $result variable
if($sign=='-') {
$result = $value1-$value2;
}
//Rest of your code...
}
?>
<html>
<!--Rest of your tags...-->
Result:<br><input type"text" name="result" value = "<?php echo (isset($result))?$result:'';?>">
The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date')
declare the date property like so: private _date: string;
. Also, make sure you are instantiating the model with the new
keyword. Lastly, access the property using regular dot notation.
Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :
let passcode = "secret passcode";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "secret passcode") {
this._fullName = newName;
}
else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
console.log(employee.fullName);
}
And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview
I never bother creating with my own regular expression, because chances are that someone else has already come up with a better version. I always use regexlib to find one to my liking.
user1594322 gave a correct answer but when I tried it I ran into admin/permission problems. I was able to copy 'mingw32-make.exe' and paste it, over-ruling/by-passing admin issues and then editing the copy to 'make.exe'. On VirtualBox in a Win7 guest.
t = datetime.strptime('Jul 9, 2009 @ 20:02:58 UTC',"%b %d, %Y @ %H:%M:%S %Z")
After placing the jar file in desired location, you need to add the jar file by right click on
Project --> properties --> Java Build Path --> Libraries --> Add Jar.
Double colon i.e. ::
operator is introduced in Java 8 as a method reference. Method reference is a form of lambda expression which is used to refer the existing method by its name.
classname::methodName
ex:-
stream.forEach(element -> System.out.println(element))
By using Double Colon ::
stream.forEach(System.out::println(element))
My attempt to summarize and correct the existing answers:
First, char
and nchar
will always use a fixed amount of storage space, even when the string to be stored is smaller than the available space, whereas varchar
and nvarchar
will use only as much storage space as is needed to store that string (plus two bytes of overhead, presumably to store the string length). So remember, "var" means "variable", as in variable space.
The second major point to understand is that, nchar
and nvarchar
store strings using exactly two bytes per character, whereas char
and varchar
use an encoding determined by the collation code page, which will usually be exactly one byte per character (though there are exceptions, see below). By using two bytes per character, a very wide range of characters can be stored, so the basic thing to remember here is that nchar
and nvarchar
tend to be a much better choice when you want internationalization support, which you probably do.
Now for some some finer points.
First, nchar
and nvarchar
columns always store data using UCS-2. This means that exactly two bytes per character will be used, and any Unicode character in the Basic Multilingual Plane (BMP) can be stored by an nchar
or nvarchar
field. However, it is not the case that any Unicode character can be stored. For example, according to Wikipedia, the code points for Egyptian hieroglyphs fall outside of the BMP. There are, therefore, Unicode strings that can be represented in UTF-8 and other true Unicode encodings that cannot be stored in a SQL Server nchar
or nvarchar
field, and strings written in Egyptian hieroglyphs would be among them. Fortunately your users probably don't write in that script, but it's something to keep in mind!
Another confusing but interesting point that other posters have highlighted is that char
and varchar
fields may use two bytes per character for certain characters if the collation code page requires it. (Martin Smith gives an excellent example in which he shows how Chinese_Traditional_Stroke_Order_100_CS_AS_KS_WS exhibits this behavior. Check it out.)
UPDATE: As of SQL Server 2012, there are finally code pages for UTF-16, for example Latin1_General_100_CI_AS_SC, which can truly cover the entire Unicode range.
I experimented a little bit and I managed to find clean solution for this problem. The approach is based on the view tagging via view->tag
In the target ViewController just assign the tag to the root view like in the following code example:
class MyViewController: BaseViewController {
// declare unique view tag identifier
static let ViewTag = 2105981;
override func viewDidLoad()
{
super.viewDidLoad();
// assign the value to the current root view
self.view.tag = MyViewController.ViewTag;
}
And finally in the AppDelegate.swift check if the currently shown view is the one we tagged:
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask
{
if (window?.viewWithTag(DesignerController.ViewTag)) != nil {
return .portrait;
}
return .all;
}
This approach has been tested with my simulator and seems it works fine.
Note: the marked view will be also found if current MVC is overlapped with some child ViewController in navigation stack.
np.random.random_sample(size)
will generate random floats in the half-open interval [0.0, 1.0).
For all that struggle with theoretical file paths and examples like I did, here a real world example: Microsoft offers their docs and examples on git hub, unfortunately they do gather all their example files for a large amount of topics in this repository:
https://github.com/microsoftarchive/msdn-code-gallery-community-s-z
I only was interested in the Microsoft Dynamics js files in the path
msdn-code-gallery-community-s-z/Sdk.Soap.js/
so I did the following
create a
msdn-code-gallery-community-s-zSdkSoapjs\.git\info\sparse-checkout
file in my repositories folder on the disk
git sparse-checkout init
in that directory using cmd on windows
The file contents of
msdn-code-gallery-community-s-zSdkSoapjs\.git\info\sparse-checkout
is
Sdk.Soap.js/*
finally do a
git pull origin master
You could add the default rule with the alter table,
ALTER TABLE mytable ADD COLUMN created_at TIMESTAMP DEFAULT NOW()
then immediately set to null all the current existing rows:
UPDATE mytable SET created_at = NULL
Then from this point on the DEFAULT
will take effect.
array_count_values
only works for integers and strings. If you happen to want counts for float/numeric values (and you are heedless of small variations in precision or representation), this works:
function arrayCountValues($arr) {
$vals = [];
foreach ($arr as $val) { array_push($vals,strval($val)); }
$cnts = array_count_values($vals);
arsort($cnts);
return $cnts;
}
Note that I return $cnts
with the keys as strings. It would be easy to reconvert them, but I'm trying to determine the mode for the values, so I only need to re-convert the first (several) values.
I tested a version which looped, creating an array of counts rather than using array_count_values
, and this turned out to be more efficient (by maybe 8-10%)!
In C++20 you'll be able to do:
auto result = std::format("{}{}", name, age);
In the meantime you can use the {fmt} library, std::format
is based on:
auto result = fmt::format("{}{}", name, age);
Disclaimer: I'm the author of the {fmt} library and C++20 std::format
.
Mind you that in my experience and also of other (PHP - Why is new SQLSRV driver slower than the old mssql driver?) that using PDO_SQLSRV is way slower than through PDO_ODBC.
If you want to use the faster PDO_ODBC you can use:
//use any of these or check exact MSSQL ODBC drivername in "ODBC Data Source Administrator"
$mssqldriver = '{SQL Server}';
$mssqldriver = '{SQL Server Native Client 11.0}';
$mssqldriver = '{ODBC Driver 11 for SQL Server}';
$hostname='127.0.0.1';
$dbname='test';
$username='user';
$password='pw';
$dbDB = new PDO("odbc:Driver=$mssqldriver;Server=$hostname;Database=$dbname", $username, $password);
A word of caution: “the w
in bw
does not stand for write but for wipeout!”
More from manuals:
:bd
Unload buffer [N] (default: current buffer) and delete it from the buffer list. If the buffer was changed, this fails, unless when [!] is specified, in which case changes are lost. The file remains unaffected.
If you know what you’re doing, you can also use :bw
:bw
Like |:bdelete|, but really delete the buffer.
Pythonic way to do this is ...
np.divide(data.T,vector).T
This takes care of reshaping and also the results are in floating point format. In other answers results are in rounded integer format.
#NOTE: No of columns in both data and vector should match
"Commercial use" in cases like this is actually just a shorthand to indicate that the product is dual-licensed under both an open source and a traditional paid-for commercial license.
Any "true" open source license will not discriminate against commercial use. (See clause 6 of the Open Source Definition.) However, open source licenses like the GPL contain clauses that are incompatible with most companies' approach to commercial software (since the GPL requires that you make your source code available if you incorporate GPL'ed code into your product).
Duel-licensing is a way to accommodate this and also provides a revenue stream for the company providing the software. For users that don't mind the restrictions of the GPL and don't need support, the product is available under an open source license. For users for whom the GPL's restrictions would be incompatible with their business model, and for users that do need support, a commercial license is available.
You gave the specific example of the Screwturn wiki, which is dual-licensed under the GPL and a commercial license. Under the terms of the GPL (i.e., without getting a "commercial" license), you can do the following:
In other words, there's a lot that you can do without getting a commercial license. This is especially true for web-based software, since people can use web-based software without it being distributed to them. Screwturn's web site even acknowledges this: they state that the commercial license is for "either integrating it in a commercial application, or using it in an enterprise environment where free software is not allowed," not for any use related to commerce.
All of the preceding is merely my understanding and is not intended to be legal advice. Consult your lawyer to be certain.
Access has some sort of system tables You can read about it a little here you can fire the folowing query to see if it exists ( 1 = it exists, 0 = it doesnt ;))
SELECT Count([MSysObjects].[Name]) AS [Count]
FROM MSysObjects
WHERE (((MSysObjects.Name)="TblObject") AND ((MSysObjects.Type)=1));
One way to do this is to insert a dummy column with the sums in order to sort:
In [10]: sum_B_over_A = df.groupby('A').sum().B
In [11]: sum_B_over_A
Out[11]:
A
bar 0.253652
baz -2.829711
foo 0.551376
Name: B
in [12]: df['sum_B_over_A'] = df.A.apply(sum_B_over_A.get_value)
In [13]: df
Out[13]:
A B C sum_B_over_A
0 foo 1.624345 False 0.551376
1 bar -0.611756 True 0.253652
2 baz -0.528172 False -2.829711
3 foo -1.072969 True 0.551376
4 bar 0.865408 False 0.253652
5 baz -2.301539 True -2.829711
In [14]: df.sort(['sum_B_over_A', 'A', 'B'])
Out[14]:
A B C sum_B_over_A
5 baz -2.301539 True -2.829711
2 baz -0.528172 False -2.829711
1 bar -0.611756 True 0.253652
4 bar 0.865408 False 0.253652
3 foo -1.072969 True 0.551376
0 foo 1.624345 False 0.551376
and maybe you would drop the dummy row:
In [15]: df.sort(['sum_B_over_A', 'A', 'B']).drop('sum_B_over_A', axis=1)
Out[15]:
A B C
5 baz -2.301539 True
2 baz -0.528172 False
1 bar -0.611756 True
4 bar 0.865408 False
3 foo -1.072969 True
0 foo 1.624345 False
answering your question 2:
I would use option b
simply because it consumes much less resources. with option 'a', every client will cause the server to consume a lot of memory, loading all the files you need (even though i like php, this is one of the problems with it). With option 'b' you can load your libraries (reusable code) and share them among all client requests.
But be ware that if you have multiple cores you should tweak node.js to use all of them.
I just want to ensure something gets selected (using jQuery):
// html
<input name="gender" type="radio" value="M" /> Male <input name="gender" type="radio" value="F" /> Female
// gender (required)
var gender_check = $('input:radio[name=gender]:checked').val();
if ( !gender_check ) {
alert("Please select your gender.");
return false;
}
My issue has been resolved after I deleted the redundant assembly files from the bin
folder.
In static class, if you are getting information from xml or reg, class tries to initialize all properties. therefore, you should control if the config variable is there otherwise properties will not initialize so the class.
Check xml referance variable is there, Check reg referance variable is is there, Make sure you handle if they are not there.
to pass many options you can pass a object to a @Input decorator with custom data in a single line.
In the template
<li *ngFor = 'let opt of currentQuestion.options'
[selectable] = 'opt'
[myOptions] ="{first: opt.val1, second: opt.val2}" // these are your multiple parameters
(selectedOption) = 'onOptionSelection($event)' >
{{opt.option}}
</li>
so in Directive class
@Directive({
selector: '[selectable]'
})
export class SelectableDirective{
private el: HTMLElement;
@Input('selectable') option:any;
@Input('myOptions') data;
//do something with data.first
...
// do something with data.second
}
I found this, hope it helps http://www.zackgrossbart.com/hackito/touchslider/
Add:
function my_url(){
$url = (!empty($_SERVER['HTTPS'])) ?
"https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] :
"http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
echo $url;
}
Then just call the my_url
function.
Simply call list
on the generator.
lst = list(gen)
lst
Be aware that this affects the generator which will not return any further items.
You also cannot directly call list
in IPython, as it conflicts with a command for listing lines of code.
Tested on this file:
def gen():
yield 1
yield 2
yield 3
yield 4
yield 5
import ipdb
ipdb.set_trace()
g1 = gen()
text = "aha" + "bebe"
mylst = range(10, 20)
which when run:
$ python code.py
> /home/javl/sandbox/so/debug/code.py(10)<module>()
9
---> 10 g1 = gen()
11
ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
11
---> 12 text = "aha" + "bebe"
13
ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.
There are debugger commands p
and pp
that will print
and prettyprint
any expression following them.
So you could use it as follows:
$ python code.py
> /home/javl/sandbox/so/debug/code.py(10)<module>()
9
---> 10 g1 = gen()
11
ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
11
---> 12 text = "aha" + "bebe"
13
ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c
There is also an exec
command, called by prefixing your expression with !
, which forces debugger to take your expression as Python one.
ipdb> !list(g1)
[]
For more details see help p
, help pp
and help exec
when in debugger.
ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']
@tableName
Table variables are alive for duration of the script running only i.e. they are only session level objects.
To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName
object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.
There is another type of table object which can be created for temporary use. They are #tableName
objects declared like similar create statement for physical tables:
Create table #test (Id int, Name varchar(50))
This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.
IF OBJECT_ID('tempdb..#test') IS NOT NULL
DROP TABLE #test
Hope this makes sense !
I'd recommend this article on CSS Tricks by Chris Coyier entitled Better Helvetica:
http://css-tricks.com/snippets/css/better-helvetica/
He basically recommends the following declaration for covering all the bases:
body {
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
font-weight: 300;
}
Since Java 11 you may use that:
public FileReader(String fileName, Charset charset) throws IOException;
TrNgGrid is working great so far. Here are the reasons I prefer it to ng-grid and moved to this component
It makes table elements so it can be bootswatched and use all the power of bootstrap .css (ng-grid uses jQuery UI themes).
Simple, well documented grid options.
Server size paging works
I like opening Visual Studio Code from the run prompt/dialog instead, with a sweet and simple cmd /c code -n
. Since the run dialog also maintains your command history on a per user basis, it is very convenient. One click and go -
You are experiencing this issue for two reasons.
When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)
User.java
@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="iduser")
private Long idUser;
@Column(name="user_name")
private String userName;
@OneToOne()
@JoinColumn(name="idarea")
private Area area;
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
}
Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:
@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")
While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.
Area.java
@Entity
@Table(name = "area")
public class Area {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="idarea")
private Long idArea;
@Column(name="area_name")
private String areaName;
@OneToOne(fetch=FetchType.LAZY, mappedBy="area")
private User user;
public Long getIdArea() {
return idArea;
}
public void setIdArea(Long idArea) {
this.idArea = idArea;
}
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
As said by jensgram, IE6 does not support attribute selector. You could add a class="disabled" to select the disabled inputs so that this can work in IE6.
the solution lies in creating a new key when generating the signed apk. this worked for me without a fuss.
when you install, the warning will not come.
Personally I'd use <code>
because that's the most semantically correct. Then to differentiate between inline and block code I'd add a class either:
<code class="inlinecode"></code>
for inline code or:
<code class="codeblock"></code>
for code block. Depending on which is less common.
Ignoring the specific needs of this question, and while its never a good idea to cast a string to a bool, one way would be to use the ToBoolean() method on the Convert class:
bool val = Convert.ToBoolean("true");
or an extension method to do whatever weird mapping you're doing:
public static class StringExtensions
{
public static bool ToBoolean(this string value)
{
switch (value.ToLower())
{
case "true":
return true;
case "t":
return true;
case "1":
return true;
case "0":
return false;
case "false":
return false;
case "f":
return false;
default:
throw new InvalidCastException("You can't cast that value to a bool!");
}
}
}
We can use the CONCAT
SQL function.
PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM analysis WHERE notes like CONCAT( '%',?,'%')";
pstmt.setString(1, notes);
ResultSet rs = pstmt.executeQuery();
This works perfectly for my case.
You can download the older SDK and install it in
Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/
folder. Logout + Login just to make sure the changes take effect and you should see the older SDK in your new XCode
In my opinion, no answer covers all edge cases as parsing a float should result in an error.
function parseInteger(value) {
if(value === '') return NaN;
const number = Number(value);
return Number.isInteger(number) ? number : NaN;
}
parseInteger("4") // 4
parseInteger("5aaa") // NaN
parseInteger("4.33333") // NaN
parseInteger("aaa"); // NaN
Make sure you are using this org.json: https://mvnrepository.com/artifact/org.json/json
if you are using Java 8 then you can use
import org.json.JSONArray;
import org.json.JSONObject;
JSONArray array = ...;
array.forEach(item -> {
JSONObject obj = (JSONObject) item;
parse(obj);
});
Just added a simple test to prove that it works:
Add the following dependency into your pom.xml
file (To prove that it works, I have used the old jar which was there when I have posted this answer)
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
And the simple test code snippet will be:
import org.json.JSONArray;
import org.json.JSONObject;
public class Test {
public static void main(String args[]) {
JSONArray array = new JSONArray();
JSONObject object = new JSONObject();
object.put("key1", "value1");
array.put(object);
array.forEach(item -> {
System.out.println(item.toString());
});
}
}
output:
{"key1":"value1"}
The solution with TextBoxFor is OK, but if you don't want to see the field like EditBox stylish (it might be a little confusing for the user) involve changes as follows:
Razor code before changes
<div class="editor-field">
@Html.EditorFor(model => model.Text)
@Html.ValidationMessageFor(model => model.Text)
</div>
After changes
<!-- New div display-field (after div editor-label) -->
<div class="display-field">
@Html.DisplayFor(model => model.Text)
</div>
<div class="editor-field">
<!-- change to HiddenFor in existing div editor-field -->
@Html.HiddenFor(model => model.Text)
@Html.ValidationMessageFor(model => model.Text)
</div>
Generally, this solution prevents field from editing, but shows value of it. There is no need for code-behind modifications.
Just include the standard library in your code.
#include<algorithm>
Array size will be denoted as n
Your old Array
int oldArray[n]={10,20,30,40,50};
Declare New Array in which you have to copy your old array value
int newArray[n];
Use this
copy_n(oldArray,n,newArray);
I have faced similar problem, 'int' object has no attribute 'DataFrame',
This was because i have mistakenly used pd as a variable in my code and assigned an integer to it, while using the same pd as my pandas dataframe object by declaring - import pandas as pd.
I realized this, and changed my variable to something else, and fixed the error.
To enable production mode in angular 6.X.X Just go to environment file
Like this path
Your path: project>\src\environments\environment.ts
Change production: false
from :
export const environment = {
production: false
};
To
export const environment = {
production: true
};
It's pretty simple :
public function myAction()
{
$url = $this->generateUrl('blog_show', array('slug' => 'my-blog-post'));
}
Inside an action, $this->generateUrl is an alias that will use the router to get the wanted route, also you could do this that is the same :
$this->get('router')->generate('blog_show', array('slug' => 'my-blog-post'));
A regular expression can be used to offer more control over the whitespace characters that are combined.
To match unicode whitespace:
import re
_RE_COMBINE_WHITESPACE = re.compile(r"\s+")
my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str).strip()
To match ASCII whitespace only:
import re
_RE_COMBINE_WHITESPACE = re.compile(r"(?a:\s+)")
_RE_STRIP_WHITESPACE = re.compile(r"(?a:^\s+|\s+$)")
my_str = _RE_COMBINE_WHITESPACE.sub(" ", my_str)
my_str = _RE_STRIP_WHITESPACE.sub("", my_str)
Matching only ASCII whitespace is sometimes essential for keeping control characters such as x0b, x0c, x1c, x1d, x1e, x1f.
About \s
:
For Unicode (str) patterns: Matches Unicode whitespace characters (which includes [ \t\n\r\f\v], and also many other characters, for example the non-breaking spaces mandated by typography rules in many languages). If the ASCII flag is used, only [ \t\n\r\f\v] is matched.
About re.ASCII
:
Make \w, \W, \b, \B, \d, \D, \s and \S perform ASCII-only matching instead of full Unicode matching. This is only meaningful for Unicode patterns, and is ignored for byte patterns. Corresponds to the inline flag (?a).
strip()
will remote any leading and trailing whitespaces.
You may use an iterator over each byte in the output of the subprocess. This allows inline update (lines ending with '\r' overwrite previous output line) from the subprocess:
from subprocess import PIPE, Popen
command = ["my_command", "-my_arg"]
# Open pipe to subprocess
subprocess = Popen(command, stdout=PIPE, stderr=PIPE)
# read each byte of subprocess
while subprocess.poll() is None:
for c in iter(lambda: subprocess.stdout.read(1) if subprocess.poll() is None else {}, b''):
c = c.decode('ascii')
sys.stdout.write(c)
sys.stdout.flush()
if subprocess.returncode != 0:
raise Exception("The subprocess did not terminate correctly.")
The dot is not part of the class name. It's only used in CSS/jQuery selector notation. Try this instead:
if ($('#navigation a').hasClass('active')) {
$(this).parent().addClass('active');
}
If $(this)
refers to that anchor, you have to change it to $('#navigation a')
as well because the if condition does not have jQuery callback scope.
I had a similar problem and tested different ways to solve it.
Eventually I understood that my index.htm file had been saved with "Unicode" encoding (for using Farsi characters in my page) while my .css file had been save with "ANSI" format.
I changed the encoding of my .css file to "Unicode" with Notepad and the problem got solved.
let urlString = "http://heyhttp.org/me.json"
var request = URLRequest(url: URL(string: urlString)!)
let session = URLSession.shared
session.dataTask(with: request) {data, response, error in
if error != nil {
print(error!.localizedDescription)
return
}
do {
let jsonResult: NSDictionary? = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
print("Synchronous\(jsonResult)")
} catch {
print(error.localizedDescription)
}
}.resume()
Since I have to store various types of content in my blob field/column, I am suppose to update my code like this:
echo "data: $mime" $result['$data']";
where:
mime
can be an image of any kind, text, word document, text document, PDF document, etc... content datatype is blob
in database.
In your case you can use __FILE__
variable !
It should help.
It is one of predefined.
Read more about predefined constants in PHP http://php.net/manual/en/language.constants.predefined.php
The MultiCell
is used for print text with multiple lines. It has the same atributes of Cell
except for ln
and link
.
$pdf->MultiCell( 200, 40, $reportSubtitle, 1);
What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).
MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])
You can read the full documentation here.
It is better to process HTML as a template than to build nodes via JavaScript (HTML is not XML after all.) You can keep your IFRAME's HTML syntax clean by using a template and then appending the template's contents into another DIV.
<div id="placeholder"></div>
<script id="iframeTemplate" type="text/html">
<iframe src="...">
<!-- replace this line with alternate content -->
</iframe>
</script>
<script type="text/javascript">
var element,
html,
template;
element = document.getElementById("placeholder");
template = document.getElementById("iframeTemplate");
html = template.innerHTML;
element.innerHTML = html;
</script>
Try the following
var original = 'www.test.com';
var stripped = original.substring(4);
@Provider
public class BadURIExceptionMapper implements ExceptionMapper<NotFoundException> {
public Response toResponse(NotFoundException exception){
return Response.status(Response.Status.NOT_FOUND).
entity(new ErrorResponse(exception.getClass().toString(),
exception.getMessage()) ).
build();
}
}
Create above class. This will handle 404 (NotFoundException) and here in toResponse method you can give your custom response. Similarly there are ParamException etc. which you would need to map to provide customized responses.
(Look at the last edit in this answer if you need to use .on()
with elements populated with JavaScript)
Use this for elements that are not populated using JavaScript:
$(".selector").on("mouseover", function () {
//stuff to do on mouseover
});
.hover()
has it's own handler: http://api.jquery.com/hover/
If you want to do multiple things, chain them in the .on()
handler like so:
$(".selector").on({
mouseenter: function () {
//stuff to do on mouse enter
},
mouseleave: function () {
//stuff to do on mouse leave
}
});
According to the answers provided below you can use hover
with .on()
, but:
Although strongly discouraged for new code, you may see the pseudo-event-name "hover" used as a shorthand for the string "mouseenter mouseleave". It attaches a single event handler for those two events, and the handler must examine event.type to determine whether the event is mouseenter or mouseleave. Do not confuse the "hover" pseudo-event-name with the .hover() method, which accepts one or two functions.
Also, there are no performance advantages to using it and it's more bulky than just using mouseenter
or mouseleave
. The answer I provided requires less code and is the proper way to achieve something like this.
EDIT
It's been a while since this question was answered and it seems to have gained some traction. The above code still stands, but I did want to add something to my original answer.
While I prefer using mouseenter
and mouseleave
(helps me understand whats going on in the code) with .on()
it is just the same as writing the following with hover()
$(".selector").hover(function () {
//stuff to do on mouse enter
},
function () {
//stuff to do on mouse leave
});
Since the original question did ask how they could properly use on()
with hover()
, I thought I would correct the usage of on()
and didn't find it necessary to add the hover()
code at the time.
EDIT DECEMBER 11, 2012
Some new answers provided below detail how .on()
should work if the div
in question is populated using JavaScript. For example, let's say you populate a div
using jQuery's .load()
event, like so:
(function ($) {
//append div to document body
$('<div class="selector">Test</div>').appendTo(document.body);
}(jQuery));
The above code for .on()
would not stand. Instead, you should modify your code slightly, like this:
$(document).on({
mouseenter: function () {
//stuff to do on mouse enter
},
mouseleave: function () {
//stuff to do on mouse leave
}
}, ".selector"); //pass the element as an argument to .on
This code will work for an element populated with JavaScript after a .load()
event has happened. Just change your argument to the appropriate selector.
You need to write this in the command prompt:
set HTTP_PROXY=http://your_proxy:your_port
Can be written using composite join key. Also if there is need to select properties from both left and right sides the LINQ can be written as
var result = context.Periods
.Where(p => p.companyid == 100)
.GroupJoin(
context.Facts,
p => new {p.id, otherid = 17},
f => new {id = f.periodid, f.otherid},
(p, f) => new {p, f})
.SelectMany(
pf => pf.f.DefaultIfEmpty(),
(pf, f) => new MyJoinEntity
{
Id = pf.p.id,
Value = f.value,
// and so on...
});
For what it's worth, if you're using NumPy distutils, numpy.distutils.misc_util.Configuration
has a make_svn_version_py()
method that embeds the revision number inside package.__svn_version__
in the variable version
.
Here is how I solved the issue, might be useful to some:
Ajax modal doesn't seem to be available with boostrap 2.1.1
So I ended up coding it myself:
$('[data-toggle="modal"]').click(function(e) {
e.preventDefault();
var url = $(this).attr('href');
//var modal_id = $(this).attr('data-target');
$.get(url, function(data) {
$(data).modal();
});
});
Example of a link that calls a modal:
<a href="{{ path('ajax_get_messages', { 'superCategoryID': 6, 'sex': sex }) }}" data-toggle="modal">
<img src="{{ asset('bundles/yopyourownpoet/images/messageCategories/BirthdaysAnniversaries.png') }}" alt="Birthdays" height="120" width="109"/>
</a>
I now send the whole modal markup through ajax.
Credits to drewjoh
WORKING SOLUTION
Let me add to this old post, a working solution I used to use that works in probably 80% or more of all browsers both new and old.
The solution is complex yet simple. The first step is to make use of CSS and guise the input file type with "under-elements" that show through as it has an opacity of 0. The next step is to use JavaScript to update its label as needed.
HTML The ID's are simply inserted if you wanted a quick way to access a specific element, the classes however, are a must as they relate to the CSS that sets this whole process up
<div class="file-input wrapper">
<input id="inpFile0" type="file" class="file-input control" />
<div class="file-input content">
<label id="inpFileOutput0" for="inpFileButton" class="file-input output">Click Here</label>
<input id="inpFileButton0" type="button" class="file-input button" value="Select File" />
</div>
</div>
CSS Keep in mind, coloring and font-styles and such are totally your preference, if you use this basic CSS, you can always use after-end mark up to style as you please, this is shown in the jsFiddle listed at the end.
.file-test-area {
border: 1px solid;
margin: .5em;
padding: 1em;
}
.file-input {
cursor: pointer !important;
}
.file-input * {
cursor: pointer !important;
display: inline-block;
}
.file-input.wrapper {
display: inline-block;
font-size: 14px;
height: auto;
overflow: hidden;
position: relative;
width: auto;
}
.file-input.control {
-moz-opacity:0 ;
filter:alpha(opacity: 0);
opacity: 0;
height: 100%;
position: absolute;
text-align: right;
width: 100%;
z-index: 2;
}
.file-input.content {
position: relative;
top: 0px;
left: 0px;
z-index: 1;
}
.file-input.output {
background-color: #FFC;
font-size: .8em;
padding: .2em .2em .2em .4em;
text-align: center;
width: 10em;
}
.file-input.button {
border: none;
font-weight: bold;
margin-left: .25em;
padding: 0 .25em;
}
JavaScript Pure and true, however, some OLDER (retired) browsers may still have trouble with it (like Netscrape 2!)
var inp = document.getElementsByTagName('input');
for (var i=0;i<inp.length;i++) {
if (inp[i].type != 'file') continue;
inp[i].relatedElement = inp[i].parentNode.getElementsByTagName('label')[0];
inp[i].onchange /*= inp[i].onmouseout*/ = function () {
this.relatedElement.innerHTML = this.value;
};
};
for complete this script , the function for draw circle ,
function drawCircle(coordon)
{
var coord = coordon.split(',');
var c = document.getElementById("myCanvas");
var hdc = c.getContext("2d");
hdc.beginPath();
hdc.arc(coord[0], coord[1], coord[2], 0, 2 * Math.PI);
hdc.stroke();
}
Do not use Bitmap.Config.ARGB_8888
Instead use int w = WIDTH_PX, h = HEIGHT_PX;
Bitmap.Config conf = Bitmap.Config.ARGB_4444; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);
// ready to draw on that bitmap through that canvas
ARGB_8888 can land you in OutOfMemory issues when dealing with more bitmaps or large bitmaps. Or better yet, try avoiding usage of ARGB option itself.
var eventids = GetEventIdsByEventDate(DateTime.Now);
var result = eventsdb.Where(e => eventids.Contains(e));
If you are returnning List<EventFeed>
inside the method, you should change the method return type from IEnumerable<EventFeed>
to List<EventFeed>
.
If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super
to call the parent method, inside the body of the child method.
public class PolyTest{
public static void main(String args[]){
new Child().foo();
}
}
class Parent{
public void foo(){
System.out.println("I'm the parent.");
}
}
class Child extends Parent{
@Override
public void foo(){
//super.foo();
System.out.println("I'm the child.");
}
}
This would print:
I'm the child.
Uncomment the commented line and it would print:
I'm the parent.
I'm the child.
You should look for the concept of Polymorphism.
What exactly are the rules for requesting retransmission of lost data?
The receiver does not request the retransmission. The sender waits for an ACK for the byte-range sent to the client and when not received, resends the packets, after a particular interval. This is ARQ (Automatic Repeat reQuest). There are several ways in which this is implemented.
Stop-and-wait ARQ
Go-Back-N ARQ
Selective Repeat ARQ
are detailed in the RFC 3366.
At what time frequency are the retransmission requests performed?
The retransmissions-times and the number of attempts isn't enforced by the standard. It is implemented differently by different operating systems, but the methodology is fixed. (One of the ways to fingerprint OSs perhaps?)
The timeouts are measured in terms of the RTT (Round Trip Time) times. But this isn't needed very often due to Fast-retransmit which kicks in when 3 Duplicate ACKs are received.
Is there an upper bound on the number?
Yes there is. After a certain number of retries, the host is considered to be "down" and the sender gives up and tears down the TCP connection.
Is there functionality for the client to indicate to the server to forget about the whole TCP segment for which part went missing when the IP packet went missing?
The whole point is reliable communication. If you wanted the client to forget about some part, you wouldn't be using TCP in the first place. (UDP perhaps?)
The online documentation seems a little unclear, so I just performed a little test. Choosing to break on Thrown from the Exceptions dialog box causes the program execution to break on any exception, handled or unhandled. If you want to break on handled exceptions only, it seems your only recourse is to go through your code and put breakpoints on all your handled exceptions. This seems a little excessive, so it might be better to add a debug statement whenever you handle an exception. Then when you see that output, you can set a breakpoint at that line in the code.
You need to use the various Bootstrap 4 centering methods...
text-center
for inline elements.justify-content-center
for flexbox elements (ie; form-inline
)https://codeply.com/go/Am5LvvjTxC
Also, to offset the column, the col-sm-*
must be contained within a .row
, and the .row
must be in a container...
<section id="cover">
<div id="cover-caption">
<div id="container" class="container">
<div class="row">
<div class="col-sm-10 offset-sm-1 text-center">
<h1 class="display-3">Welcome to Bootstrap 4</h1>
<div class="info-form">
<form action="" class="form-inline justify-content-center">
<div class="form-group">
<label class="sr-only">Name</label>
<input type="text" class="form-control" placeholder="Jane Doe">
</div>
<div class="form-group">
<label class="sr-only">Email</label>
<input type="text" class="form-control" placeholder="[email protected]">
</div>
<button type="submit" class="btn btn-success ">okay, go!</button>
</form>
</div>
<br>
<a href="#nav-main" class="btn btn-secondary-outline btn-sm" role="button">?</a>
</div>
</div>
</div>
</div>
</section>
Make sure that this element you would like to control with z-index does not have a parent with z-index property, because element is in a lower stacking context due to its parent’s z-index level.
Here's an example:
<section class="content">
<div class="modal"></div>
</section>
<div class="side-tab"></div>
// CSS //
.content {
position: relative;
z-index: 1;
}
.modal {
position: fixed;
z-index: 100;
}
.side-tab {
position: fixed;
z-index: 5;
}
In the example above, the modal has a higher z-index than the content, although the content will appear on top of the modal because "content" is the parent with a z-index property.
Here's an article that explains 4 reasons why z-index might not work: https://coder-coder.com/z-index-isnt-working/
You can also try: (I tried this and it worked for me)
SELECT ISNULL((SELECT SUM(columnA) FROM my_table WHERE columnB = 1),0)) INTO res;
You will never get a result, it's a simple logic error.
You're asking your database to return a row which has style_id = 24 AND style_id = 25 AND style_id = 26
. Since 24 is niether 25 nor 26, you will get no result.
You have to use OR
, then it makes some sense.
The most efficient way (before django 1.2) is this:
if orgs.count() == 0:
# no results
else:
# alrigh! let's continue...
For Angular 6 check the Official documentation
Note: For @angular/cli
versions older than 6.0.0-beta.6
use ng set
in place of ng config
.
In an existing angular-cli project that was set up with the default css
styles you will need to do a few things:
scss
Manually change in
.angular-cli.json
(Angular 5.x and older) orangular.json
(Angular 6+) or run:ng config defaults.styleExt=scss
if you get an error: Value cannot be found.
use the command:
ng config schematics.@schematics/angular:component.styleext scss
(*source: Angular CLI SASS options)
Rename your existing .css
files to .scss
(i.e. styles.css and app/app.component.css)
Point the CLI to find styles.scss
Manually change the file extensions in
apps[0].styles
inangular.json
Change the
styleUrls
in your components to match your new file names
As @Serginho mentioned you can set the style extension when running the ng new
command
ng new your-project-name --style=scss
If you want to set the default for all projects you create in the future run the following command:
ng config --global defaults.styleExt=scss
ul {
padding-left: 0;
list-style-position: inside;
}
Explanation:
The first property padding-left: 0
clears the default padding/spacing for the ul
element while list-style-position: inside
makes the dots/bullets of li
aligned like a normal text.
So this code
<p>The ul element</p>
<ul>
asdfas
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
without any CSS will give us this:
but if we add in the CSS give at the top, that will give us this:
If all you want to do is conditionally show or hide a <div>, then you could declare it as an <asp:panel > (renders to html as a div tag) and set it's .Visible property.
Also add cursor:hand. Some browsers need that instead.
The answer was surprisingly simple. I had to add a Content-Type
header in the POST
request with a value of application/json
. Without this header Jersey did not know what to do with the request body (in spite of the @Consumes(MediaType.APPLICATION_JSON)
annotation)!
From .NET 4.5 on, there is the Stream.CopyToAsync
method
input.CopyToAsync(output);
This will return a Task
that can be continued on when completed, like so:
await input.CopyToAsync(output)
// Code from here on will be run in a continuation.
Note that depending on where the call to CopyToAsync
is made, the code that follows may or may not continue on the same thread that called it.
The SynchronizationContext
that was captured when calling await
will determine what thread the continuation will be executed on.
Additionally, this call (and this is an implementation detail subject to change) still sequences reads and writes (it just doesn't waste a threads blocking on I/O completion).
From .NET 4.0 on, there's is the Stream.CopyTo
method
input.CopyTo(output);
For .NET 3.5 and before
There isn't anything baked into the framework to assist with this; you have to copy the content manually, like so:
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[32768];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write (buffer, 0, read);
}
}
Note 1: This method will allow you to report on progress (x bytes read so far ...)
Note 2: Why use a fixed buffer size and not input.Length
? Because that Length may not be available! From the docs:
If a class derived from Stream does not support seeking, calls to Length, SetLength, Position, and Seek throw a NotSupportedException.
below code works for me,
$("#btn").click(function () {
if ($("#frm")[0].checkValidity())
alert('sucess');
else
//Validate Form
$("#frm")[0].reportValidity()
});
UPDATE: As mentioned by Richard Grimes in my cited post, @Iain and @Dmitry Lobanov, my answer is right in theory but wrong in practice.
As I should have remembered from countless books, etc., while one sets these properties using the [assembly: XXXAttribute]
, they get highjacked by the compiler and placed into the VERSIONINFO
resource.
For the above reason, you need to use the approach in @Xiaofu's answer as the attributes are stripped after the signal has been extracted from them.
public static string GetProductVersion() { var attribute = (AssemblyVersionAttribute)Assembly .GetExecutingAssembly() .GetCustomAttributes( typeof(AssemblyVersionAttribute), true ) .Single(); return attribute.InformationalVersion; }
(From http://bytes.com/groups/net/420417-assemblyversionattribute - as noted there, if you're looking for a different attribute, substitute that into the above)
Another option is to use the package require-dir which let's you do the following. It supports recursion as well.
var requireDir = require('require-dir');
var dir = requireDir('./path/to/dir');
Example using std::vector
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
int main()
{
/// Initilaize vector using intitializer list ( requires C++11 )
std::vector<std::string> names = {"john", "bobby", "dear", "test1", "catherine", "nomi", "shinta", "martin", "abe", "may", "zeno", "zack", "angeal", "gabby"};
// Sort names using std::sort
std::sort(names.begin(), names.end() );
// Print using range-based and const auto& for ( both requires C++11 )
for(const auto& currentName : names)
{
std::cout << currentName << std::endl;
}
//... or by using your orignal for loop ( vector support [] the same way as plain arrays )
for(int y = 0; y < names.size(); y++)
{
std:: cout << names[y] << std::endl; // you were outputting name[z], but only increasing y, thereby only outputting element z ( 14 )
}
return 0;
}
This completely avoids using plain arrays, and lets you use the std::sort function. You might need to update you compiler to use the = {...}
You can instead add them by using vector.push_back("name")
Now W3c provides an official difference on their site:
It could very well be the case that people who sign up for your service are entering emails with typing mistakes that you do not correct. For example: chris@gmial.com -or- james@hotnail.com.
And such domains are configured to be used as spamtraps which will automatically flag your email server's IP and/or domain and hurt its reputation.
To avoid this, do a double-check for the email address that is entered upon your product subscription. Also, send a confirmation email to really ensure that this email address is 100% validated by a human being that is entering the confirmation email, before you send them the product key or accept their subscription. The verification email should require the recipient to click a link or reply in order to really confirm that the owner of the mailbox is the person who signed up.
Player.cpp
require the definition of Ball
class. So simply add #include "Ball.h"
Player.cpp:
#include "Player.h"
#include "Ball.h"
void Player::doSomething(Ball& ball) {
ball.ballPosX += 10; // incomplete type error occurs here.
}
In case my I try to set up proxy from android studio Appearance & Behaviour => System Settings => HTTP Proxy. But the proxy did not worked out so I click no proxy.
Checking NO PROXY will not remove the proxy setting from the gradle.properties(Global). You need to manually remove it.
So I remove all the properties starting with systemProp for example - systemProp.http.nonProxyHosts=*.local, localhost
MajorLeo's answer point me in the right direction but it didn't worked for me. I've found this site that follows the same approach and did work.
$dir = "path/to/file/";
$filename = "backup" . date("YmdHis") . ".sql.gz";
$db_host = "host";
$db_username = "username";
$db_password = "password";
$db_database = "database";
$cmd = "mysqldump -h {$db_host} -u {$db_username} --password={$db_password} {$db_database} | gzip > {$dir}{$filename}";
exec($cmd);
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$filename\"");
passthru("cat {$dir}{$filename}");
I hope it helps someone else!
I had many users controls but one refused to show in the Toolbox, even though I rebuilt the solution and it was checked in the Choose Items... dialog.
Solution:
Note this also requires you have the AutoToolboxPopulate option enabled. As @DaveF answer suggests.
Alternate Solution: I'm not sure if this works, and I couldn't try it since I already resolved my issue, but if you unchecked the user control from the Choose Items... dialog, hit OK, then opened it back up and checked the user control. That might also work.
Consider the following case:
First, o1.compareTo(o2)
is called. card1.getSet() == card2.getSet()
happens to be true and so is card1.getRarity() < card2.getRarity()
, so you return 1.
Then, o2.compareTo(o1)
is called. Again, card1.getSet() == card2.getSet()
is true. Then, you skip to the following else
, then card1.getId() == card2.getId()
happens to be true, and so is cardType > item.getCardType()
. You return 1 again.
From that, o1 > o2
, and o2 > o1
. You broke the contract.
import json
myDict = {'dict': [{'a': 'none', 'b': 'none', 'c': 'none'}]}
test = json.dumps(myDict)
print(test)
{"dict": [{"a": "none", "b": "none", "c": "none"}]}
myDict['dict'].append(({'a': 'aaaa', 'b': 'aaaa', 'c': 'aaaa'}))
test = json.dumps(myDict)
print(test)
{"dict": [{"a": "none", "b": "none", "c": "none"}, {"a": "aaaa", "b": "aaaa", "c": "aaaa"}]}
I had the issue where after updating the SDK it would only update to version 20 and kept telling me that ANDROID 4.1 (API16) was available and only part of ANDROID 4.2 (API17) was available and there was no update to version 21.
After restarting several times and digging I found (was not obvious to me) going to the SDK Manager and going to FILE -> RELOAD solved the problem. Immediately the other uninstalled parts of API17 were there and I was able to update the SDK. Once updated to 4.2 then I could re-update to version 21 and voila.
Good luck! David
echo json_encode($array); //outputs---> "name1":"value1", "name2":"value2", ...
OR
echo print_r($array, true);
On archlinux pip cache is located at ~/.cache/pip, I could solve my issue by removing the http folder inside it.
Another just for testing solution to this is by simply changing your bundle id. Just don't forget to change it back once you're done!
F.ex. http://docs.oracle.com/javase/7/docs/ has a link to download "JDK 7 Documentation" in the sidebar under "Downloads". I'd expect the same for other versions.
POCO is simply an object that does not take a dependency on an external framework. It is PLAIN.
Whether a POCO has behaviour or not it's immaterial.
A DTO may be POCO as may a domain object (which would typically be rich in behaviour).
Typically DTOs are more likely to take dependencies on external frameworks (eg. attributes) for serialisation purposes as typically they exit at the boundary of a system.
In typical Onion style architectures (often used within a broadly DDD approach) the domain layer is placed at the centre and so its objects should not, at this point, have dependencies outside of that layer.
The latest google api docs document how to write to a spreadsheet with python but it's a little difficult to navigate to. Here is a link to an example of how to append.
The following code is my first successful attempt at appending to a google spreadsheet.
import httplib2
import os
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'
def get_credentials():
"""Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
"""
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'mail_to_g_app.json')
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def add_todo():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
'version=v4')
service = discovery.build('sheets', 'v4', http=http,
discoveryServiceUrl=discoveryUrl)
spreadsheetId = 'PUT YOUR SPREADSHEET ID HERE'
rangeName = 'A1:A'
# https://developers.google.com/sheets/guides/values#appending_values
values = {'values':[['Hello Saturn',],]}
result = service.spreadsheets().values().append(
spreadsheetId=spreadsheetId, range=rangeName,
valueInputOption='RAW',
body=values).execute()
if __name__ == '__main__':
add_todo()
For me simply run:
npm install cross-env
was enough
If you need more fine-grade control, you can also go the fork
pipe
exec
route. This will allow your application to retrieve the data outputted from the shell script.
In your Fragments onCreateView(...)
you can remove a view by calling container.removeView(view);
.
So if you want to remove the fragment, then view
should be the return value of onCreateView
,
for example
public View onCreateView(...){
final View view = inflater.inflate(R.layout.your_fragments_layout,container,false);
//Do something
finishButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
container.removeView(view);
}
});
return view;
}
The best solution is the word-spacing
property.
Add the <p>
in a container with a specific size (example 300px
) and after you have to add that size as the value in the word-spacing.
HTML
<div>
<p>Sentence Here</p>
</div>
CSS
div {
width: 300px;
}
p {
width: auto;
text-align: center;
word-spacing: 300px;
}
In this way, your sentence will be always broken and set in a column, but the with of the paragraph will be dynamic.
Here an example Codepen
Thanks to everyone for responding so fast. Joel, I used your option 2 and added a registry key to the "Run" folder of the current user. Here's the code I used for anyone else who's interested.
using Microsoft.Win32;
private void SetStartup()
{
RegistryKey rk = Registry.CurrentUser.OpenSubKey
("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (chkStartUp.Checked)
rk.SetValue(AppName, Application.ExecutablePath);
else
rk.DeleteValue(AppName,false);
}
You can use:
df.set_value('Row_index', 'Column_name', value)
set_valye
is ~100 times faster than .ix
method. It also better then use df['Row_index']['Column_name'] = value
.
But since set_value
is deprecated now so .iat
/.at
are good replacements.
For example if we have this data_frame
A B C
0 1 8 4
1 3 9 6
2 22 33 52
if we want to modify the value of the cell [0,"A"] we can do
df.iat[0,0] = 2
or df.at[0,'A'] = 2
Anacoda3-4.2.0 Uses python 3.5 You can find the same in the link given below : https://repo.continuum.io/archive/Anaconda3-4.2.0-Windows-x86_64.exe
I faced the same problem and found the correct version by checking the available Anaconda 4.2.0 distributions in installer archive here
1) To access DOM in component.
import {BrowserDomAdapter } from '@angular/platform-browser/src/browser/browser_adapter';
constructor(el: ElementRef,public zone:NgZone) {
this.el = el.nativeElement;
this.dom = new BrowserDomAdapter();
}
ngOnInit() {
this.dom.setValue(this.el,"Adding some content from ngOnInit");
}
You can include jQuery in following way. 2) Include you jquery file in index.html before angular2 loads
<head>
<title>Angular 2 QuickStart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">
<!-- jquery file -->
<script src="js/jquery-2.0.3.min.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="node_modules/es6-shim/es6-shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
You can use Jquery in following way, Here i am using JQuery Ui date picker.
import { Directive, ElementRef} from '@angular/core';
declare var $:any;
@Directive({
selector: '[uiDatePicker]',
})
export class UiDatePickerDirective {
private el: HTMLElement;
constructor(el: ElementRef) {
this.el = el.nativeElement;
}
ngOnInit() {
$(this.el).datepicker({
onSelect: function(dateText:string) {
//do something on select
}
});
}
}
This work for me.
To answer the question in your subject line,* yes, there are closures in Python, except they only apply inside a function, and also (in Python 2.x) they are read-only; you can't re-bind the name to a different object (though if the object is mutable, you can modify its contents). In Python 3.x, you can use the nonlocal
keyword to modify a closure variable.
def incrementer():
counter = 0
def increment():
nonlocal counter
counter += 1
return counter
return increment
increment = incrementer()
increment() # 1
increment() # 2
* The question origially asked about closures in Python.
As of Angular2 RC6, you can set default locale in your app module, by adding a provider:
@NgModule({
providers: [
{ provide: LOCALE_ID, useValue: "en-US" }, //replace "en-US" with your locale
//otherProviders...
]
})
The Currency/Date/Number pipes should pick up the locale. LOCALE_ID is an OpaqueToken, to be imported from angular/core.
import { LOCALE_ID } from '@angular/core';
For a more advanced use case, you may want to pick up locale from a service. Locale will be resolved (once) when component using date pipe is created:
{
provide: LOCALE_ID,
deps: [SettingsService], //some service handling global settings
useFactory: (settingsService) => settingsService.getLanguage() //returns locale string
}
Hope it works for you.
Use this
openssl ciphers -v | awk '{print $2}' | sort | uniq
Try using:
ActionBar ab = getSupportActionBar();
ab.setHomeButtonEnabled(true);
ab.setDisplayUseLogoEnabled(true);
ab.setLogo(R.drawable.ic_launcher);
Java has a method for this, "convertStringArrayToIntArray".
String numbers = sc.nextLine();
int[] intArray = convertStringArrayToIntArray(numbers.split(", "));
just remove z-index: 1040
;
from this file bootstrap.css
class .modal-backdrop