def replaceslug
slug = "" + name
@replacements = [
[ "," , ""],
[ "\\?" , ""],
[ " " , "-"],
[ "'" , "-"],
[ "Ç" , "c"],
[ "S" , "s"],
[ "I" , "i"],
[ "I" , "i"],
[ "Ü" , "u"],
[ "Ö" , "o"],
[ "G" , "g"],
[ "ç" , "c"],
[ "s" , "s"],
[ "i" , "i"],
[ "ü" , "u"],
[ "ö" , "o"],
[ "g" , "g"],
]
@replacements.each do |pair|
slug.gsub!(pair[0], pair[1])
end
self.slug = slug.downcase
end
I have also faced the same problem and this is how i resolved it.
First of all you need to make sure that your node and npm versions are up to date. if not please upgrade your node and npm packages to latest versions.
nvm install 12.18.3 // update node version through node version manager
npm install npm // update your npm version to latest
Delete your node_modules
folder and package-lock.json
file.
Force clean the entire NPM cache by using following comand.
npm cache clean --force
Re-Install all the dependencies.
npm install
If above step didn't resolve your problem, try to re-install your dependencies after executing following command.
npm rebuild
Another solution could be something like following (works depending on your element's display property):
HTML:
<div class="left-align">Left</div>
<div class="right-align">Right</div>
CSS:
.left-align {
margin-left: 0;
margin-right: auto;
}
.right-align {
margin-left: auto;
margin-right: 0;
}
String clsName = "Ex"; // use fully qualified name
Class cls = Class.forName(clsName);
Object clsInstance = (Object) cls.newInstance();
Check the Java Tutorial trail on Reflection at http://java.sun.com/docs/books/tutorial/reflect/TOC.html for further details.
If you need a function that behaves as a nop, try
nop = lambda *a, **k: None
nop()
Sometimes I do stuff like this when I'm making dependencies optional:
try:
import foo
bar=foo.bar
baz=foo.baz
except:
bar=nop
baz=nop
# Doesn't break when foo is missing:
bar()
baz()
In windows, If the user is using your script locally, it will be very simple :
<?php
// get all the informations about the client's network
$ipconfig = shell_exec ("ipconfig/all"));
// display those informations
echo $ipconfig;
/*
look for the value of "physical adress" and use substr() function to
retrieve the adress from this long string.
here in my case i'm using a french cmd.
you can change the numbers according adress mac position in the string.
*/
echo substr(shell_exec ("ipconfig/all"),1821,18);
?>
Don't know (as for now) why, but this one helped:
@media print {
html, body {
border: 1px solid white;
height: 99%;
page-break-after: avoid;
page-break-before: avoid;
}
}
Hope someone will save his hair while fighting with the problem... ;)
Yet another cause - I was trying to include a module in settings.gradle using
include ':MyModule'
project(':MyModule').projectDir = new File(settingsDir, '../../MyModule')
Only problem was, I had just imported the module from Eclipse an forgot to move the directory outside my application project, i.e. the path '../../MyModule'
didn't exist.
I remember the StaticSelectedStyle-CssClass attribute used to work in ASP.NET 2.0. And in .NET 4.0 if you change the Menu control's RenderingMode attribute "Table" (thus making it render the menu as s and sub-s like it did back '05) it will at least write your specified StaticSelectedStyle-CssClass into the proper html element.
That may be enough for you page to work like you want. However my work-around for the selected menu item in ASP 4.0 (when leaving RenderingMode to its default), is to mimic the control's generated "selected" CSS class but give mine the "!important" CSS declaration so my styles take precedence where needed.
For instance by default the Menu control renders an "li" element and child "a" for each menu item and the selected menu item's "a" element will contain class="selected" (among other control generated CSS class names including "static" if its a static menu item), therefore I add my own selector to the page (or in a separate stylesheet file) for "static" and "selected" "a" tags like so:
a.selected.static
{
background-color: #f5f5f5 !important;
border-top: Red 1px solid !important;
border-left: Red 1px solid !important;
border-right: Red 1px solid !important;
}
The first thing you should do with date variables is confirm that R reads it as a Date. To do this, for the variable (i.e. vector/column) called Date, in the data frame called EPL2011_12, input
class(EPL2011_12$Date)
The output should read [1] "Date". If it doesn't, you should format it as a date by inputting
EPL2011_12$Date <- as.Date(EPL2011_12$Date, "%d-%m-%y")
Note that the hyphens in the date format ("%d-%m-%y") above can also be slashes ("%d/%m/%y"). Confirm that R sees it as a Date. If it doesn't, try a different formatting command
EPL2011_12$Date <- format(EPL2011_12$Date, format="%d/%m/%y")
Once you have it in Date format, you can use the subset
command, or you can use brackets
WhateverYouWant <- EPL2011_12[EPL2011_12$Date > as.Date("2014-12-15"),]
The date time you're passing is not a iso local date time format.
Change to
@Column(name = "start_date")
@DateTimeFormat(iso = DateTimeFormatter.ISO_LOCAL_DATE_TIME)
@JsonFormat(pattern = "YYYY-MM-dd HH:mm")
private LocalDateTime startDate;
and pass date string in the format '2011-12-03T10:15:30'.
But if you still want to pass your custom format, use just have to specify the right formatter.
Change to
@Column(name = "start_date")
@DateTimeFormat(iso = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))
@JsonFormat(pattern = "YYYY-MM-dd HH:mm")
private LocalDateTime startDate;
I think your problem is the @DateTimeFormat has no effect at all. As the jackson is doing the deseralization and it doesnt know anything about spring annotation and I dont see spring scanning this annotation in the deserialization context.
Alternatively, you can try setting the formatter while registering the java time module.
LocalDateTimeDeserializer localDateTimeDeserializer = new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
module.addDeserializer(LocalDateTime.class, localDateTimeDeserializer);
Here is the test case with the deseralizer which works fine. May be try to get rid of that DateTimeFormat annotation altogether.
@RunWith(JUnit4.class)
public class JacksonLocalDateTimeTest {
private ObjectMapper objectMapper;
@Before
public void init() {
JavaTimeModule module = new JavaTimeModule();
LocalDateTimeDeserializer localDateTimeDeserializer = new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
module.addDeserializer(LocalDateTime.class, localDateTimeDeserializer);
objectMapper = Jackson2ObjectMapperBuilder.json()
.modules(module)
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.build();
}
@Test
public void test() throws IOException {
final String json = "{ \"date\": \"2016-11-08 12:00\" }";
final JsonType instance = objectMapper.readValue(json, JsonType.class);
assertEquals(LocalDateTime.parse("2016-11-08 12:00",DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm") ), instance.getDate());
}
}
class JsonType {
private LocalDateTime date;
public LocalDateTime getDate() {
return date;
}
public void setDate(LocalDateTime date) {
this.date = date;
}
}
Well, since your on a shared server, you can't do anything about it. They usually set the max execution time so that you can't override it. I suggest you contact them.
Use split()
var s = 'MyLongString:StringIWant;';
var arrStr = s.split(/[:;]/);
alert(arrStr);
arrStr
will contain all the string delimited by :
or ;
So access every string through for-loop
for(var i=0; i<arrStr.length; i++)
alert(arrStr[i]);
The original post had some bugs... so I re-wrote and packaged it as a UDF.
CREATE FUNCTION FullMonthsSeparation
(
@DateA DATETIME,
@DateB DATETIME
)
RETURNS INT
AS
BEGIN
DECLARE @Result INT
DECLARE @DateX DATETIME
DECLARE @DateY DATETIME
IF(@DateA < @DateB)
BEGIN
SET @DateX = @DateA
SET @DateY = @DateB
END
ELSE
BEGIN
SET @DateX = @DateB
SET @DateY = @DateA
END
SET @Result = (
SELECT
CASE
WHEN DATEPART(DAY, @DateX) > DATEPART(DAY, @DateY)
THEN DATEDIFF(MONTH, @DateX, @DateY) - 1
ELSE DATEDIFF(MONTH, @DateX, @DateY)
END
)
RETURN @Result
END
GO
SELECT dbo.FullMonthsSeparation('2009-04-16', '2009-05-15') as MonthSep -- =0
SELECT dbo.FullMonthsSeparation('2009-04-16', '2009-05-16') as MonthSep -- =1
SELECT dbo.FullMonthsSeparation('2009-04-16', '2009-06-16') as MonthSep -- =2
Try something like this:
Bitmap bmp = intent.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
bmp.recycle();
If you want to install ASP.NET MVC 5 and ASP.NET Web API 2 into VS 2012 Ultimage so, you can download MSI installer from
http://www.microsoft.com/en-us/download/details.aspx?id=41532.
I have downloaded and intalled just know. I got MVC 5 and Web API 2
:)
td.setAttribute('rowspan',x);
Try adding a pair of class attributes, say 'even' and 'odd', to alternating list elements, e.g.
<ul>
<li class="even"><a href="link">Link 1</a></li>
<li class="odd"><a href="link">Link 2</a></li>
<li class="even"><a href="link">Link 3</a></li>
<li class="odd"><a href="link">Link 4</a></li>
<li class="even"><a href="link">Link 5</a></li>
</ul>
In a <style> section of the HTML page, or in a linked stylesheet, you would define those same classes, specifying your desired background colours:
li.even { background-color: red; }
li.odd { background-color: blue; }
You might want to use a template library as your needs evolve to provide you with greater flexibility and to cut down on the typing. Why type all those list elements by hand?
C# has a lot of reference types. Even if a container stores the references contiguously, the objects themselves may be scattered through the heap
While astype
is probably the "best" option there are several other ways to convert it to an integer array. I'm using this arr
in the following examples:
>>> import numpy as np
>>> arr = np.array([1,2,3,4], dtype=float)
>>> arr
array([ 1., 2., 3., 4.])
int*
functions from NumPy>>> np.int64(arr)
array([1, 2, 3, 4])
>>> np.int_(arr)
array([1, 2, 3, 4])
*array
functions themselves:>>> np.array(arr, dtype=int)
array([1, 2, 3, 4])
>>> np.asarray(arr, dtype=int)
array([1, 2, 3, 4])
>>> np.asanyarray(arr, dtype=int)
array([1, 2, 3, 4])
astype
method (that was already mentioned but for completeness sake):>>> arr.astype(int)
array([1, 2, 3, 4])
Note that passing int
as dtype to astype
or array
will default to a default integer type that depends on your platform. For example on Windows it will be int32
, on 64bit Linux with 64bit Python it's int64
. If you need a specific integer type and want to avoid the platform "ambiguity" you should use the corresponding NumPy types like np.int32
or np.int64
.
What about:
from operator import add
reduce(add, map(lambda x: list(x.image_set.all()), [mi for mi in list_of_menuitems]))
But, Guido is recommending against performing too much in a single line of code since it reduces readability. There is minimal, if any, performance gain by performing what you want in a single line vs. multiple lines.
appsettings.json:
"MySetting": {
"MyValues": [
"C#",
"ASP.NET",
"SQL"
]
},
MySetting class:
namespace AspNetCore.API.Models
{
public class MySetting : IMySetting
{
public string[] MyValues { get; set; }
}
public interface IMySetting
{
string[] MyValues { get; set; }
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.Configure<MySetting>(Configuration.GetSection(nameof(MySetting)));
services.AddSingleton<IMySetting>(sp => sp.GetRequiredService<IOptions<MySetting>>().Value);
...
}
Controller.cs
public class DynamicController : ControllerBase
{
private readonly IMySetting _mySetting;
public DynamicController(IMySetting mySetting)
{
this._mySetting = mySetting;
}
}
Access values:
var myValues = this._mySetting.MyValues;
This may be overkill for this simple problem. But for Try-Do methods in connection with Linq, I tend to use anonymous classes for more expressive code. It is similar to the answers from Olivier Jacot-Descombes and BA TabNabber:
List<int> ints = strings
.Select(idString => new { ParseSuccessful = Int32.TryParse(idString, out var id), Value = id })
.Where(id => id.ParseSuccessful)
.Select(id => id.Value)
.ToList();
Always use static in .c
files unless you need to reference the object from a different .c
module.
Never use static in .h
files, because you will create a different object every time it is included.
Just a note: if you use arrow functions you don't need the const that = this part. It might look like this:
fetch('http://jsonplaceholder.typicode.com/posts')
.then((response) => { return response.json(); })
.then((myJson) => {
this.setState({data: myJson}); // for example
});
My own template functions which performs upper / lower case.
#include <string>
#include <algorithm>
//
// Lowercases string
//
template <typename T>
std::basic_string<T> lowercase(const std::basic_string<T>& s)
{
std::basic_string<T> s2 = s;
std::transform(s2.begin(), s2.end(), s2.begin(), tolower);
return std::move(s2);
}
//
// Uppercases string
//
template <typename T>
std::basic_string<T> uppercase(const std::basic_string<T>& s)
{
std::basic_string<T> s2 = s;
std::transform(s2.begin(), s2.end(), s2.begin(), toupper);
return std::move(s2);
}
Constructing a new dict:
dict_you_want = { your_key: old_dict[your_key] for your_key in your_keys }
Uses dictionary comprehension.
If you use a version which lacks them (ie Python 2.6 and earlier), make it dict((your_key, old_dict[your_key]) for ...)
. It's the same, though uglier.
Note that this, unlike jnnnnn's version, has stable performance (depends only on number of your_keys) for old_dict
s of any size. Both in terms of speed and memory. Since this is a generator expression, it processes one item at a time, and it doesn't looks through all items of old_dict.
Removing everything in-place:
unwanted = set(keys) - set(your_dict)
for unwanted_key in unwanted: del your_dict[unwanted_key]
You don't "commit the folder" - you add the folder, as you have done, and then simply commit all changes. The command should be:
git add foldername
git commit -m "commit operation"
In your specific case you can use the following bash
command (bash
is the default shell on macOS):
for f in *.png; do echo mv "$f" "${f/_*_/_}"; done
Note: If there's a chance that your filenames start with -
, place --
before them[1]:
mv -- "$f" "${f/_*_/_}"
Note: echo
is prepended to mv
so as to perform a dry run. Remove it to perform actual renaming.
You can run it from the command line or use it in a script.
"${f/_*_/_}"
is an application of bash
parameter expansion: the (first) substring matching pattern _*_
is replaced with literal _
, effectively cutting the middle token from the name._*_
is a pattern (a wildcard expression, as also used for globbing), not a regular expression (to learn about patterns, run man bash
and search for Pattern Matching
).If you find yourself batch-renaming files frequently, consider installing a specialized tool such as the Perl-based rename
utility.
On macOS you can install it using popular package manager Homebrew as follows:
brew install rename
Here's the equivalent of the command at the top using rename
:
rename -n -e 's/_.*_/_/' *.png
Again, this command performs a dry run; remove -n
to perform actual renaming.
bash
solution, s/.../.../
performs text substitution, but - unlike in bash
- true regular expressions are used.[1] The purpose of special argument --
, which is supported by most utilities, is to signal that subsequent arguments should be treated as operands (values), even if they look like options due to starting with -
, as Jacob C. notes.
If you prefer to use CSS to get rid of the dotted outline:
/*for FireFox*/
input[type="submit"]::-moz-focus-inner, input[type="button"]::-moz-focus-inner
{
border : 0;
}
/*for IE8 and below */
input[type="submit"]:focus, input[type="button"]:focus
{
outline : none;
}
I was using Angular, and needed the same thing, and landed at this post.
@ViewChild('myHTML', {static: false}) _html: ElementRef;
this._html.nativeElement;
Every time you execute
Random random = new Random (15);
It does not matter if you execute it millions of times, you will always use the same seed.
If you use
Random random = new Random ();
You get different random number sequence, if a hacker guesses the seed and your algorithm is related to the security of your system - your algorithm is broken. I you execute mult. In this constructor the seed is specified by the system clock and if several instances are created in a very short period of time (milliseconds) it is possible that they may have the same seed.
If you need safe random numbers you must use the class
System.Security.Cryptography.RNGCryptoServiceProvider
public static int Next(int min, int max)
{
if(min >= max)
{
throw new ArgumentException("Min value is greater or equals than Max value.");
}
byte[] intBytes = new byte[4];
using(RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
rng.GetNonZeroBytes(intBytes);
}
return min + Math.Abs(BitConverter.ToInt32(intBytes, 0)) % (max - min + 1);
}
Usage:
int randomNumber = Next(1,100);
The third template parameter must be a class who has operator()(Node,Node)
overloaded.
So you will have to create a class this way:
class ComparisonClass {
bool operator() (Node, Node) {
//comparison code here
}
};
And then you will use this class as the third template parameter like this:
priority_queue<Node, vector<Node>, ComparisonClass> q;
As detailed in the jTDS Frequenlty Asked Questions, the URL format for jTDS is:
jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]
So, to connect to a database called "Blog" hosted by a MS SQL Server running on MYPC
, you may end up with something like this:
jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS;user=sa;password=s3cr3t
Or, if you prefer to use getConnection(url, "sa", "s3cr3t")
:
jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS
EDIT: Regarding your Connection refused
error, double check that you're running SQL Server on port 1433, that the service is running and that you don't have a firewall blocking incoming connections.
You could just write it out in multiline like this,
$ cat dict.go
package main
import "fmt"
func main() {
items := map[string]interface{}{
"foo": map[string]int{
"strength": 10,
"age": 2000,
},
"bar": map[string]int{
"strength": 20,
"age": 1000,
},
}
for key, value := range items {
fmt.Println("[", key, "] has items:")
for k,v := range value.(map[string]int) {
fmt.Println("\t-->", k, ":", v)
}
}
}
And the output:
$ go run dict.go
[ foo ] has items:
--> strength : 10
--> age : 2000
[ bar ] has items:
--> strength : 20
--> age : 1000
You have an instance method called num_words
, but you also have a variable called num_words
. They have the same name. When you run num_words()
, the function replaces itself with its own output, which probably isn't what you want to do. Consider return
ing your values.
To fix your problem, change def num_words
to something like def get_num_words
and your code should work fine. Also, change print test.sort_word_list
to print test.sorted_word_list
.
If you're on the Apple Silicon (M1) chip, make sure you're using an ARM64-based emulator:
If you're not, create a new Virtual Device and use the arm64-v8a
image from Other images.
Usually the white-box testing is not possible for testers. Thus the only viable answer for testers is to emphasize black-box approach.
However, with aspect-oriented-programming and design-by-contract methodology, when the testing goals are programmed into the target code as contracts (seen from the static view of a program), and/or when the testing temporal logic is programmed into the code as cross-cuts (dynamic view of the test logic), white-box testing would become not only possible but also a preferred take for testers. Given that said, it will need be an expertise-demanding take, the testers need to be not only good testers, but also good programmers or more than good programmers.
While it is not possible to write a switch statement, it is possible to branch out to specific processing for each given type. One way of doing this is to use standard double dispatch mechanism. An example where we want to "switch" based on type is Jersey Exception mapper where we need to map multitude of exceptions to error responses. While for this specific case there is probably a better way (i.e. using a polymorphic method that translates each exception to an error response), using double dispatch mechanism is still useful and practical.
interface Processable {
<R> R process(final Processor<R> processor);
}
interface Processor<R> {
R process(final A a);
R process(final B b);
R process(final C c);
// for each type of Processable
...
}
class A implements Processable {
// other class logic here
<R> R process(final Processor<R> processor){
return processor.process(this);
}
}
class B implements Processable {
// other class logic here
<R> R process(final Processor<R> processor){
return processor.process(this);
}
}
class C implements Processable {
// other class logic here
<R> R process(final Processor<R> processor){
return processor.process(this);
}
}
Then where ever the "switch" is needed, you can do it as follows:
public class LogProcessor implements Processor<String> {
private static final Logger log = Logger.for(LogProcessor.class);
public void logIt(final Processable base) {
log.info("Logging for type {}", process(base));
}
// Processor methods, these are basically the effective "case" statements
String process(final A a) {
return "Stringifying A";
}
String process(final B b) {
return "Stringifying B";
}
String process(final C c) {
return "Stringifying C";
}
}
If you use mysql 5.6 server and have problems with C:\Program Files\MySQL\MySQL Server 5.6\my.ini
:
You should go to C:\ProgramData\MySQL\MySQL Server 5.6\my.ini
.
You should add skip-grant-tables
and then you do not need a password.
# SERVER SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by the MySQL Server. Make sure that
# you have installed the server correctly (see above) so it reads this
# file.
#
# server_type=3
[mysqld]
skip-grant-tables
Note: after you are done with your work on skip-grant-tables
, you should restore your file of C:\ProgramData\MySQL\MySQL Server 5.6\my.ini
.
I had a similar problem recently, and needed to change the permissions of my vendor folder
By running following commands :
php artisan cache:clear
chmod -R 777 storage vendor
composer dump-autoload
I need to give all the permissions required to open and write vendor files to solve this issue
On MacOS if you've installed python via Homebrew, change the line in /usr/local/opt/python/libexec/bin/pip
from
from pip.internal import main
to
from pip._internal import main
Or use this one liner: sed -i '' "s/from pip import main/from pip._internal import main/" /usr/local/opt/python/libexec/bin/pip
The issue is caused by the changes in pip version 10 moving internal namespace under main._internal
and the bin script put in place by homebrew still looking it from the old place (where it used to be in version 9). Issue and some discussion https://github.com/pypa/pip/issues/5240
I found a way to pass a JSON message using only a HTML form.
This example is for GraphQL but it will work for any endpoint that is expecting a JSON message.
GrapqhQL by default expects a parameter called operations where you can add your query or mutation in JSON format. In this specific case I am invoking this query which is requesting to get allUsers and return the userId of each user.
{
allUsers
{
userId
}
}
I am using a text input to demonstrate how to use it, but you can change it for a hidden input to hide the query from the user.
<html>
<body>
<form method="post" action="http://localhost:8080/graphql">
<input type="text" name="operations" value="{"query": "{ allUsers { userId } }", "variables": {}}"/>
<input type="submit" />
</form>
</body>
</html>
In order to make this dynamic you will need JS to transport the values of the text fields to the query string before submitting your form. Anyway I found this approach very interesting. Hope it helps.
The key of this problem is to detect the load-more event, start an async request for data and then update the list. Also an adapter with loading indicator and other decorators is needed. In fact, the problem is very complicated in some corner cases. Just a OnScrollListener
implementation is not enough, because sometimes the items do not fill the screen.
I have written a personal package which support endless list for RecyclerView
, and also provide a async loader implementation AutoPagerFragment
which makes it very easy to get data from a multi-page source. It can load any page you want into a RecyclerView
on a custom event, not only the next page.
Here is the address: https://github.com/SphiaTower/AutoPagerRecyclerManager
You can query the all_tab_columns
view in the database.
SELECT table_name, column_name, data_type, data_length FROM all_tab_columns where table_name = 'CUSTOMER'
Adding my answer, because it elaborates the idea that you can SELECT multiple columns from the table from which you subquery.
Here I needed the the most recently cast cote and it's associated information.
I first tried simply to SELECT the max(votedate) along with vote, itemid, userid etc., but while the query would return the max votedate, it would also return the a random row for the other information. Hard to see among a bunch of 1s and 0s.
This worked well:
$query = "
SELECT t1.itemid, t1.itemtext, t2.vote, t2.votedate, t2.userid
FROM
(
SELECT itemid, itemtext FROM oc_item ) t1
LEFT JOIN
(
SELECT vote, votedate, itemid,userid FROM oc_votes
WHERE votedate IN
(select max(votedate) FROM oc_votes group by itemid)
AND userid=:userid) t2
ON (t1.itemid = t2.itemid)
order by itemid ASC
";
The subquery in the WHERE clause WHERE votedate IN (select max(votedate) FROM oc_votes group by itemid) returns one record - the record with the max vote date.
I know this has been answered but none of these solutions worked for me. I needed to take a different approach. I am using PhoneGap and am compiling my code natively so I had to move the background to the body. I hope this helps someone else. Or if there a cleaner way to do this please feel free to comment...
$(document).on('shown.bs.modal', '.modal', function (e) {
$("#" + e.target.id).find(".modal-backdrop").css("z-index", $("#" + e.target.id).css("z-index")).insertBefore("#" + e.target.id);
});
There is a lot of incompatibility between different versions of cglib and lots of poor advice that can be googled on this subject (use ancient versions of cglib-nodeb, etc). After wrestling with this nonsense for 3 days with an ancient version of Spring (2.5.6)I have discovered:
It is not strictly possible in default db due to the many public executes that each user gains automatically through public.
What you're basically doing here is relying on Date#toString()
which already has a fixed pattern. To convert a Java Date
object into another human readable String pattern, you need SimpleDateFormat#format()
.
private String modifyDateLayout(String inputDate) throws ParseException{
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").parse(inputDate);
return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date);
}
By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse()
. This means that the inputDate
isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z"
. You'll probably need to modify the pattern to match the inputDate
's actual pattern.
Update: Okay, I did a test:
public static void main(String[] args) throws Exception {
String inputDate = "2010-01-04 01:32:27 UTC";
String newDate = new Test().modifyDateLayout(inputDate);
System.out.println(newDate);
}
This correctly prints:
03.01.2010 21:32:27
(I'm on GMT-4)
Update 2: as per your edit, you really got a ParseException
on that. The most suspicious part would then be the timezone of UTC
. Is this actually known at your Java environment? What Java version and what OS version are you using? Check TimeZone.getAvailableIDs()
. There must be a UTC
in between.
Have a look at CASE statements
http://msdn.microsoft.com/en-us/library/ms181765.aspx
You can continue to use getApplicationContext()
, but before use, you should add this flag: dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
, and the error will not show.
And don't forget to add permission:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
date.toLocaleDateString('en-US')
works great. Here's some more information on it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
The thought process here is that you spend most of your time in development
. When in development, you create a feature
branch (off of development
), complete the feature, and then merge back into development
. This can then be added to the final production version by merging into production
.
See A Successful Git Branching Model for more detail on this approach.
Load your "base" environment -- as OP's py34
-- when you load your terminal/shell.
If you use Bash, put the line:
conda activate py34
in your .bash_profile
(or .bashrc
):
$ echo 'conda activate py34' >> ~/.bash_profile
Every time you run a new terminal, conda environment py34
will be loaded.
console.log(` moment('2019-09-01', 'YYYY-MM-DD').isValid()? ` +moment('2019-09-01', 'YYYY-MM-DD').isValid())
console.log(` moment('2019-22-01', 'YYYY-DD-MM').isValid()? ` +moment('2019-22-01', 'YYYY-DD-MM').isValid())
console.log(` moment('2019-22-22', 'YYYY-DD-MM').isValid()? ` +moment('2019-22-22', 'YYYY-DD-MM').isValid())
console.log(` moment('undefined', 'YYYY-DD-MM').isValid()? ` +moment('undefined', 'YYYY-DD-MM').isValid())
moment('2019-09-01', 'YYYY-MM-DD').isValid()? true
moment('2019-22-01', 'YYYY-DD-MM').isValid()? true
moment('2019-22-22', 'YYYY-DD-MM').isValid()? false
moment('undefined', 'YYYY-DD-MM').isValid()? false
A slave isn't a server, it's a client type application. Network clients (almost) never use a specific port. Instead, they ask the OS for a random free port. This works much better since you usually run clients on many machines where the current configuration isn't known in advance. This prevents thousands of "client wouldn't start because port is already in use" bug reports every day.
You need to tell the security department that the slave isn't a server but a client which connects to the server and you absolutely need to have a rule which says client:ANY -> server:FIXED. The client port number should be >= 1024 (ports 1 to 1023 need special permissions) but I'm not sure if you actually gain anything by adding a rule for this - if an attacker can open privileged ports, they basically already own the machine.
If they argue, then ask them why they don't require the same rule for all the web browsers which people use in your company.
The standard option grep -l
(that is a lowercase L) could do this.
From the Unix standard:
-l
(The letter ell.) Write only the names of files containing selected
lines to standard output. Pathnames are written once per file searched.
If the standard input is searched, a pathname of (standard input) will
be written, in the POSIX locale. In other locales, standard input may be
replaced by something more appropriate in those locales.
You also do not need -H
in this case.
you may use template reference variable and send to a method
html
<input #variable type="file" placeholder="File Name" name="filename" (change)="onChange($event, variable);">
component
onChange(event: any, element): void {
// codes
element.value = '';
}
Assuming you want the format "(123) 456-7890
":
function formatPhoneNumber(phoneNumberString) {
var cleaned = ('' + phoneNumberString).replace(/\D/g, '')
var match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/)
if (match) {
return '(' + match[1] + ') ' + match[2] + '-' + match[3]
}
return null
}
Here's a version that allows the optional +1
international code:
function formatPhoneNumber(phoneNumberString) {
var cleaned = ('' + phoneNumberString).replace(/\D/g, '')
var match = cleaned.match(/^(1|)?(\d{3})(\d{3})(\d{4})$/)
if (match) {
var intlCode = (match[1] ? '+1 ' : '')
return [intlCode, '(', match[2], ') ', match[3], '-', match[4]].join('')
}
return null
}
formatPhoneNumber('+12345678900') // => "+1 (234) 567-8900"
formatPhoneNumber('2345678900') // => "(234) 567-8900"
JAVA_OPTS
is not restricted to Tomcat’s Java process, but passed to all JVM processes running on the same machine.
Use CATALINA_OPTS
if you specifically want to pass JVM arguments to Tomcat's servlet engine.
My preference is to convert to and from a std::u32string and work with codepoints internally, then convert to utf8 when writing out to a file using these converting iterators I put on github.
#include <utf/utf.h>
int main()
{
using namespace utf;
u32string u32_text = U"?????";
// do stuff with string
// convert to utf8 string
utf32_to_utf8_iterator<u32string::iterator> pos(u32_text.begin());
utf32_to_utf8_iterator<u32string::iterator> end(u32_text.end());
u8string u8_text(pos, end);
// write out utf8 to file.
// ...
}
MySQL for excel plugin can help you.
http://dev.mysql.com/doc/refman/5.6/en/mysql-for-excel.html
Open your CSV file in excel. You can use this plugin to export excel data into a new table of remote or local mysql server. It will analyze your data (top 100 to 1000 rows) and create a corresponding table schema.
I have created customize function to validate given date is between two dates or not.
var getvalidDate = function(d){ return new Date(d) }
function validateDateBetweenTwoDates(fromDate,toDate,givenDate){
return getvalidDate(givenDate) <= getvalidDate(toDate) && getvalidDate(givenDate) >= getvalidDate(fromDate);
}
Apple states in the latest version of Building Cocoa Apps,
The Swift compiler does not include a preprocessor. Instead, it takes advantage of compile-time attributes, build configurations, and language features to accomplish the same functionality. For this reason, preprocessor directives are not imported in Swift.
The # character appears to still be how you work with various build configurations and things like that, but it looks like they're trying to cut back on your need for most preprocessing in the vein of pragma and forward you to other language features altogether. Perhaps this is to aid in the operation of the Playgrounds and the REPL behaving as close as possible to the fully compiled code.
If your pair of lines will only appear once in your file, you could use
File.ReadLines(pathToTextFile)
.SkipWhile(line => !line.Contains("CustomerEN"))
.Skip(1) // optional
.TakeWhile(line => !line.Contains("CustomerCh"));
If you could have multiple occurrences in one file, you're probably better off using a regular foreach
loop - reading lines, keeping track of whether you're currently inside or outside a customer etc:
List<List<string>> groups = new List<List<string>>();
List<string> current = null;
foreach (var line in File.ReadAllLines(pathToFile))
{
if (line.Contains("CustomerEN") && current == null)
current = new List<string>();
else if (line.Contains("CustomerCh") && current != null)
{
groups.Add(current);
current = null;
}
if (current != null)
current.Add(line);
}
It didn't. Your compiler did, but there's still a debug symbol for the original variable name.
I use #3. Same for long lists, tuples, etc. It doesn't require adding any extra spaces beyond the indentations. As always, be consistent.
mydict = {
"key1": 1,
"key2": 2,
"key3": 3,
}
mylist = [
(1, 'hello'),
(2, 'world'),
]
nested = {
a: [
(1, 'a'),
(2, 'b'),
],
b: [
(3, 'c'),
(4, 'd'),
],
}
Similarly, here's my preferred way of including large strings without introducing any whitespace (like you'd get if you used triple-quoted multi-line strings):
data = (
"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABG"
"l0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAEN"
"xBRpFYmctaKCfwrBSCrRLuL3iEW6+EEUG8XvIVjYWNgJdhFjIX"
"rz6pKtPB5e5rmq7tmxk+hqO34e1or0yXTGrj9sXGs1Ib73efh1"
"AAAABJRU5ErkJggg=="
)
@SafeVarargs
does not prevent it from happening, however it mandates that the compiler is stricter when compiling code that uses it.
http://docs.oracle.com/javase/7/docs/api/java/lang/SafeVarargs.html explains this in futher detail.
Heap pollution is when you get a ClassCastException
when doing an operation on a generic interface and it contains another type than declared.
Try using
FROM [TableX]
ORDER BY [FieldX]
OFFSET 500 ROWS
FETCH NEXT 100 ROWS ONLY
to get the rows from 501 to 600 in the SQL server, without loading them in memory. Note that this syntax has become available with SQL Server 2012 only
To add to those who have mentioned the implicit rules, it's best to see what make has defined implicitly and for your env using:
make -p
For instance:
%.o: %.c
$(COMPILE.c) $(OUTPUT_OPTION) $<
which expands
COMPILE.c = $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c
This will also print # environment
data. Here, you will find GCC's include path among other useful info.
C_INCLUDE_PATH=/usr/include
In make, when it comes to search, the paths are many, the light is one... or something to that effect.
C_INCLUDE_PATH
is system-wide, set it in your shell's *.rc
.$(CPPFLAGS)
is for the preprocessor include path.VPATH = my_dir_to_search
... or even more specific
vpath %.c src
vpath %.h include
make uses VPATH as a general search path so use cautiously. If a file exists in more than one location listed in VPATH, make will take the first occurrence in the list.
You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start()
. The headers will be sent automatically when any HTML is output.
Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.
Move the session_start()
to the top of your document :
<?php session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php'; // more PHP code here.
I've just started using OSX. Free editors of note that I've discovered:
There is no way to skip a check if it exists.
It might mean the application is already installed for another user on your device. Users share applications. I don't know why they do but they do. So if one user updates an application is updated for the other user also. If you uninstall on one, it doesn't remove the app from the system on the other.
I was unable to find name of an error for given code when developing in Swift. For that reason I paste minus codes for NSURLErrorDomain
taken from NSURLError.h
/*!
@enum NSURL-related Error Codes
@abstract Constants used by NSError to indicate errors in the NSURL domain
*/
NS_ENUM(NSInteger)
{
NSURLErrorUnknown = -1,
NSURLErrorCancelled = -999,
NSURLErrorBadURL = -1000,
NSURLErrorTimedOut = -1001,
NSURLErrorUnsupportedURL = -1002,
NSURLErrorCannotFindHost = -1003,
NSURLErrorCannotConnectToHost = -1004,
NSURLErrorNetworkConnectionLost = -1005,
NSURLErrorDNSLookupFailed = -1006,
NSURLErrorHTTPTooManyRedirects = -1007,
NSURLErrorResourceUnavailable = -1008,
NSURLErrorNotConnectedToInternet = -1009,
NSURLErrorRedirectToNonExistentLocation = -1010,
NSURLErrorBadServerResponse = -1011,
NSURLErrorUserCancelledAuthentication = -1012,
NSURLErrorUserAuthenticationRequired = -1013,
NSURLErrorZeroByteResource = -1014,
NSURLErrorCannotDecodeRawData = -1015,
NSURLErrorCannotDecodeContentData = -1016,
NSURLErrorCannotParseResponse = -1017,
NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022,
NSURLErrorFileDoesNotExist = -1100,
NSURLErrorFileIsDirectory = -1101,
NSURLErrorNoPermissionsToReadFile = -1102,
NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) = -1103,
// SSL errors
NSURLErrorSecureConnectionFailed = -1200,
NSURLErrorServerCertificateHasBadDate = -1201,
NSURLErrorServerCertificateUntrusted = -1202,
NSURLErrorServerCertificateHasUnknownRoot = -1203,
NSURLErrorServerCertificateNotYetValid = -1204,
NSURLErrorClientCertificateRejected = -1205,
NSURLErrorClientCertificateRequired = -1206,
NSURLErrorCannotLoadFromNetwork = -2000,
// Download and file I/O errors
NSURLErrorCannotCreateFile = -3000,
NSURLErrorCannotOpenFile = -3001,
NSURLErrorCannotCloseFile = -3002,
NSURLErrorCannotWriteToFile = -3003,
NSURLErrorCannotRemoveFile = -3004,
NSURLErrorCannotMoveFile = -3005,
NSURLErrorDownloadDecodingFailedMidStream = -3006,
NSURLErrorDownloadDecodingFailedToComplete =-3007,
NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) = -1018,
NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) = -1019,
NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) = -1020,
NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) = -1021,
NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995,
NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996,
NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997,
};
Here is another approach, up to the OP to choose which one he prefers.
When including the code below in the __init__
.py file before any other code, messages printed with print
and any errors will no longer be logged to Ableton's Log.txt but to separate files on your disk:
import sys
path = "/Users/#username#"
errorLog = open(path + "/stderr.txt", "w", 1)
errorLog.write("---Starting Error Log---\n")
sys.stderr = errorLog
stdoutLog = open(path + "/stdout.txt", "w", 1)
stdoutLog.write("---Starting Standard Out Log---\n")
sys.stdout = stdoutLog
(for Mac, change #username#
to the name of your user folder. On Windows the path to your user folder will have a different format)
When you open the files in a text editor that refreshes its content when the file on disk is changed (example for Mac: TextEdit does not but TextWrangler does), you will see the logs being updated in real-time.
Credits: this code was copied mostly from the liveAPI control surface scripts by Nathan Ramella
setTimeout( function ( ) { alert( "moo" ); }, 10000 ); //displays msg in 10 seconds
Finally, I solved it. Even though the solution is a bit lengthy, I think its the simplest. The solution is as follows:
- Install Visual Studio 2008
- Install the service Package 1 (SP1)
- Install SQL Server 2008 r2
Highlighting an entity in a query and pressing ALT + F1 will run sp_help for it, giving you a breakdown of any columns, indexes, parameters etc.
You cannot do so - the browser will not allow this because of security concerns.
When a file is selected by using the input type=file object, the value of the value property depends on the value of the "Include local directory path when uploading files to a server" security setting for the security zone used to display the Web page containing the input object.
The fully qualified filename of the selected file is returned only when this setting is enabled. When the setting is disabled, Internet Explorer 8 replaces the local drive and directory path with the string C:\fakepath\ in order to prevent inappropriate information disclosure.
And other
You missed );
this at the end of the change event function.
Also do not create function for change event instead just use it as below,
<script type="text/javascript">
$(function()
{
$('#fileUpload').on('change',function ()
{
var filePath = $(this).val();
console.log(filePath);
});
});
</script>
From Tomcat documentation, For blocking I/O (BIO), the default value of maxConnections
is the value of maxThreads
unless Executor (thread pool) is used in which case, the value of 'maxThreads' from Executor will be used instead. For Non-blocking IO, it doesn't seem to be dependent on maxThreads
.
Save the Excel file to CSV, and read the resulting file with C# using a CSV reader library like FileHelpers.
You can store favourites with no associated menu in a separate table:
CREATE TABLE FavoriteWithoutMenu
(
FavoriteWithoutMenuId uuid NOT NULL, --Primary key
UserId uuid NOT NULL,
RecipeId uuid NOT NULL,
UNIQUE KEY (UserId, RecipeId)
)
What the existing answers do not elaborate on is that it makes a difference whether you use path parameters or query parameters.
/users/9
, the response should be 404
because that resource was not found. /users/9
is the resource, and the result is unary, or an error, it doesn't exist. This is not a monad./users?id=9
, the response should be 204
because the resource /users
was found but it could not return any data. The resource /users
exists and the result is n-ary, it exists even if it is empty. If id
is unique, this is a monad.Whether to use path parameters or query parameters depends on the use case. I prefer path parameters for mandatory, normative, or identifying arguments and query parameters for optional, non-normative, or attributing arguments (like paging, collation locale and stuff). In a REST API, I would use /users/9
not /users?id=9
especially because of the possible nesting to get "child records" like /users/9/ssh-keys/0
to get the first public ssh key or /users/9/address/2
to get the third postal address.
I prefer using 404. Here's why:
204
is like a void
method. I would not use it for GET
, only for POST
, PUT
, and DELETE
. I make an exception in case of GET
where the identifiers are query parameters not path parameters.NoSuchElementException
, ArrayIndexOutOfBoundsException
or something like that, caused by the client using an id that doesn't exist, so, it's a client error.204
means an additional branch in the code that could be avoided. It complicates client code, and in some cases it also complicates server code (depending on whether you use entity/model monads or plain entities/models; and I strongly recommend staying away from entity/model monads, it can lead to nasty bugs where because of the monad you think an operation is successful and return 200 or 204 when you should actually have returned something else).Last but not least: Consistency
GET /users/9
PUT /users/9
and DELETE /users/9
PUT /users/9
and DELETE /users/9
already have to return 204
in case of successful update or deletion. So what should they return in case user 9 didn't exist? It makes no sense having the same situation presented as different status codes depending on the HTTP method used.
Besides, not a normative, but a cultural reason: If 204
is used for GET /users/9
next thing that will happen in the project is that somebody thinks returning 204
is good for n-ary methods. And that complicates client code, because instead of just checking for 2xx
and then decoding the body, the client now has to specifically check for 204
and in that case skip decoding the body. Bud what does the client do instead? Create an empty array? Why not have that on the wire, then? If the client creates the empty array, 204 is a form of stupid compression. If the client uses null
instead, a whole different can of worms is opened.
Include: #include<stdlib.h>
and use System("cls")
instead of clrscr()
As of Chrome 46, a simple onclick=window.close()
does the trick. This only closes the tab, and not the entire browser, if multiple tabs are opened.
My favorite:
https://inloop.github.io/sqlite-viewer/
No installation needed. Just drop the file.
Android Studio Go to File -> Project Structure or press Ctrl+Alt+Shift+S
See The Image
Click Ok
Then the signingConfigs will generate on your build.gradle file.
The below code gets the full path, where the anchor points:
document.getElementById("aaa").href; // http://example.com/sec/IF00.html
while the one below gets the value of the href
attribute:
document.getElementById("aaa").getAttribute("href"); // sec/IF00.html
Unlike languages that employ 'true' lexical scoping, Python opts to have specific 'namespaces' for variables, whether it be global
, nonlocal
, or local. It could be argued that making developers consciously code with such namespaces in mind is more explicit, thus more understandable. I would argue that such complexities make the language more unwieldy, but I guess it's all down to personal preference.
Here are some examples regarding global
:-
>>> global_var = 5
>>> def fn():
... print(global_var)
...
>>> fn()
5
>>> def fn_2():
... global_var += 2
... print(global_var)
...
>>> fn_2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in fn_2
UnboundLocalError: local variable 'global_var' referenced before assignment
>>> def fn_3():
... global global_var
... global_var += 2
... print(global_var)
...
>>> fn_3()
7
The same patterns can be applied to nonlocal
variables too, but this keyword is only available to the latter Python versions.
In case you're wondering, nonlocal
is used where a variable isn't global, but isn't within the function definition it's being used. For example, a def
within a def
, which is a common occurrence partially due to a lack of multi-statement lambdas. There's a hack to bypass the lack of this feature in the earlier Pythons though, I vaguely remember it involving the use of a single-element list...
Note that writing to variables is where these keywords are needed. Just reading from them isn't ambiguous, thus not needed. Unless you have inner def
s using the same variable names as the outer ones, which just should just be avoided to be honest.
This likely doesn't work with start
, as that starts a new window, but to answer your question:
If the command returns a error level you can check the following ways
By Specific Error Level
commandhere
if %errorlevel%==131 echo do something
By If Any Error
commandhere || echo what to do if error level ISN'T 0
By If No Error
commandhere && echo what to do if error level IS 0
If it does not return a error level but does give output, you can catch it in a variable and determine by the output, example (note the tokens and delims are just examples and would likely fail with any special characters)
By Parsing Full Output
for /f "tokens=* delims=" %%a in ('somecommand') do set output=%%a
if %output%==whateveritwouldsayinerror echo error
Or you could just look for a single phrase in the output like the word Error
By Checking For String
commandhere | find "Error" || echo There was no error!
commandhere | find "Error" && echo There was an error!
And you could even mix together (just remember to escape |
with ^|
if in a for
statement)
Hope this helps.
I follow this simple setup with meld. Meld is free and opensource diff tool. You will see nice side by side comparison of files and directory for any code changes.
[diff] tool = meld
git difftool --dir-diff ./
git difftool --cached --dir-diff ./
Just a suggestion, but you might try the Pear Mail_Mime class instead.
http://pear.php.net/package/Mail_Mime/docs
Otherwise you can use a bit of code. Gabi Purcaru method of using rename() won't work the way it's written. See this post http://us3.php.net/manual/en/function.rename.php#97347 . You'll need something like this:
$dir = dirname($_FILES["file"]["tmp_name"]);
$destination = $dir . DIRECTORY_SEPARATOR . $_FILES["file"]["name"];
rename($_FILES["file"]["tmp_name"], $destination);
$geekMail->attach($destination);
Try the solution from Reportlab.
Download it and install it as usual with python setup.py install
You will also need to install the following modules: xhtml2pdf, html5lib, pypdf with easy_install.
Here is an usage example:
First define this function:
import cStringIO as StringIO
from xhtml2pdf import pisa
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
from cgi import escape
def render_to_pdf(template_src, context_dict):
template = get_template(template_src)
context = Context(context_dict)
html = template.render(context)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
Then you can use it like this:
def myview(request):
#Retrieve data or whatever you need
return render_to_pdf(
'mytemplate.html',
{
'pagesize':'A4',
'mylist': results,
}
)
The template:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>My Title</title>
<style type="text/css">
@page {
size: {{ pagesize }};
margin: 1cm;
@frame footer {
-pdf-frame-content: footerContent;
bottom: 0cm;
margin-left: 9cm;
margin-right: 9cm;
height: 1cm;
}
}
</style>
</head>
<body>
<div>
{% for item in mylist %}
RENDER MY CONTENT
{% endfor %}
</div>
<div id="footerContent">
{%block page_foot%}
Page <pdf:pagenumber>
{%endblock%}
</div>
</body>
</html>
Hope it helps.
Here is a shorthand that webpack will use so you don't have to use require.context
.
HTML:
<div class="col-lg-2" v-for="pic in pics">
<img :src="getImgUrl(pic)" v-bind:alt="pic">
</div>
Vue Method:
getImgUrl(pic) {
return require('../assets/'+pic)
}
And I find that the first 2 paragraphs in here explain why this works? well.
Please note that it's a good idea to put your pet pictures inside a subdirectory, instead of lobbing it in with all your other image assets. Like so: ./assets/pets/
The Pair class from Commons Lang might help:
Pair<String, String> keyValue = new ImmutablePair("key", "value");
Of course, you would need to include commons-lang.
I think there may be problem that you haven't added click listener for ok positive button.
dlgAlert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//dismiss the dialog
}
});
You have to add to the source property an object with a property called "uri" where you can specify the path of your image as you can see in the following example:
<Image style={styles.image} source={{uri: "http://www.mysyte.com/myimage.jpg"}} />
remember then to set the width and height via the style property:
var styles = StyleSheet.create({
image:{
width: 360,
height: 40,
}
});
You can always just use antecedent numbers to repeat actions:
Install the Package Control first.
The simplest method of installation is through the Sublime Text console. The console is accessed via the Ctrl+` shortcut or the View > Show Console menu. Once open, paste the appropriate Python code for your version of Sublime Text into the console.
Code for Sublime Text 3
import urllib.request,os; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); open(os.path.join(ipp, pf), 'wb').write(urllib.request.urlopen( 'http://sublime.wbond.net/' + pf.replace(' ','%20')).read())
Code for Sublime Text 2
import urllib2,os; pf='Package Control.sublime-package'; ipp = sublime.installed_packages_path(); os.makedirs( ipp ) if not os.path.exists(ipp) else None; urllib2.install_opener( urllib2.build_opener( urllib2.ProxyHandler( ))); open( os.path.join( ipp, pf), 'wb' ).write( urllib2.urlopen( 'http://sublime.wbond.net/' +pf.replace( ' ','%20' )).read()); print( 'Please restart Sublime Text to finish installation')
For the up-to-date installation code, please check Package Control Installation Guide.
Manual
If for some reason the console installation instructions do not work for you (such as having a proxy on your network), perform the following steps to manually install Package Control:
Package Control is driven by the Command Pallete. To open the pallete, press Ctrl+Shift+p (Win, Linux) or CMD+Shift+p (OSX). All Package Control commands begin with Package Control:, so start by typing Package.
look at overloaded Sort method of the List class. there are some ways to to it. one of them: your custom class has to implement IComparable interface then you cam use Sort method of the List class.
To extend the answer from @mingos above, I wrote the below function to format my time to a specific format ([dd mm yyyy hh:mm:ss]).
// Store the formatted string of time in the output
void format_time(char *output){
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
sprintf(output, "[%d %d %d %d:%d:%d]",timeinfo->tm_mday, timeinfo->tm_mon + 1, timeinfo->tm_year + 1900, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
}
More information about struct tm
can be found here.
Check this link , it is advanced github search https://github.com/search?l=Java&o=desc&q=android&ref=searchresults&s=stars&type=Repositories and this project contain a lot of libraries to Kick-starts you in Android https://github.com/mttkay/ignition
There is an animationend
Event that can be observed see documentation here,
also for css transition
animations you could use the transitionend
event
There is no need for additional libraries these all work with vanilla JS
document.getElementById("myDIV").addEventListener("transitionend", myEndFunction);_x000D_
function myEndFunction() {_x000D_
this.innerHTML = "transition event ended";_x000D_
}
_x000D_
#myDIV {transition: top 2s; position: relative; top: 0;}_x000D_
div {background: #ede;cursor: pointer;padding: 20px;}
_x000D_
<div id="myDIV" onclick="this.style.top = '55px';">Click me to start animation.</div>
_x000D_
If you want to add multiple columns you can do it this way for example:
ALTER TABLE YourTable
ADD Column1 INT NOT NULL DEFAULT 0,
Column2 INT NOT NULL DEFAULT 1,
Column3 VARCHAR(50) DEFAULT 'Hello'
GO
For those who could not get DATEADD to work, try this instead: ( NOW( ) - INTERVAL 1 MONTH )
when you add Domains in Google recaptcha
Add new domain: Localhost not localhost
"L" is capital letter
Good luck
An Alternative is....
Convert both dates into milliseconds as below
Date d = new Date();
long l = d.getTime();
Now compare both long values
Maven does not respect the KISS principle. Try to do anything besides mvn clean install and you are in trouble. With ant you can do whatever you want without any pain.
This is a very simple solution that returns an array of string with the matches
Swift 3.
internal func stringsMatching(regularExpressionPattern: String, options: NSRegularExpression.Options = []) -> [String] {
guard let regex = try? NSRegularExpression(pattern: regularExpressionPattern, options: options) else {
return []
}
let nsString = self as NSString
let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
return results.map {
nsString.substring(with: $0.range)
}
}
Take a look at anchor tags. You can create an anchor with
<div id="anchor-name">Heading Text</div>
and refer to it later with
<a href="http://server/page.html#anchor-name">Link text</a>
While most answers are saying that, e.g.,
def f(**kwargs):
foo = kwargs.pop('foo')
bar = kwargs.pop('bar')
...etc...
is "the same as"
def f(foo=None, bar=None, **kwargs):
...etc...
this is not true. In the latter case, f
can be called as f(23, 42)
, while the former case accepts named arguments only -- no positional calls. Often you want to allow the caller maximum flexibility and therefore the second form, as most answers assert, is preferable: but that is not always the case. When you accept many optional parameters of which typically only a few are passed, it may be an excellent idea (avoiding accidents and unreadable code at your call sites!) to force the use of named arguments -- threading.Thread
is an example. The first form is how you implement that in Python 2.
The idiom is so important that in Python 3 it now has special supporting syntax: every argument after a single *
in the def
signature is keyword-only, that is, cannot be passed as a positional argument, but only as a named one. So in Python 3 you could code the above as:
def f(*, foo=None, bar=None, **kwargs):
...etc...
Indeed, in Python 3 you can even have keyword-only arguments that aren't optional (ones without a default value).
However, Python 2 still has long years of productive life ahead, so it's better to not forget the techniques and idioms that let you implement in Python 2 important design ideas that are directly supported in the language in Python 3!
JSONObject.java
takes whatever map you pass. It may be LinkedHashMap
or TreeMap
and it will take hashmap
only when the map is null .
Here is the constructor of JSONObject.java
class that will do the checking of map.
public JSONObject(Map paramMap)
{
this.map = (paramMap == null ? new HashMap() : paramMap);
}
So before building a json object construct LinkedHashMap
and then pass it to the constructor like this ,
LinkedHashMap<String, String> jsonOrderedMap = new LinkedHashMap<String, String>();
jsonOrderedMap.put("1","red");
jsonOrderedMap.put("2","blue");
jsonOrderedMap.put("3","green");
JSONObject orderedJson = new JSONObject(jsonOrderedMap);
JSONArray jsonArray = new JSONArray(Arrays.asList(orderedJson));
System.out.println("Ordered JSON Fianl CSV :: "+CDL.toString(jsonArray));
So there is no need to change the JSONObject.java
class . Hope it helps somebody .
Let's say this is your dataframe.
You can rename the columns using two methods.
Using dataframe.columns=[#list]
df.columns=['a','b','c','d','e']
The limitation of this method is that if one column has to be changed, full column list has to be passed. Also, this method is not applicable on index labels. For example, if you passed this:
df.columns = ['a','b','c','d']
This will throw an error. Length mismatch: Expected axis has 5 elements, new values have 4 elements.
Another method is the Pandas rename()
method which is used to rename any index, column or row
df = df.rename(columns={'$a':'a'})
Similarly, you can change any rows or columns.
string.Concat(los.ToArray());
If you just want to concatenate the strings then use string.Concat() instead of string.Join().
I wrote ublame
python tool that returns a naive history of a file commits that impacted a given search term, you'll find more information on the þroject page.
For those who enabled HAXM and the emulator still works slow here is what you should do:
as per HAXM Release_Notes.txt (Version 7.5.2):
- On Windows, Avast Antivirus may interfere with HAXM and cause Android Emulator or QEMU to run very slowly. A workaround is to uncheck "Use nested virtualization where available" in Avast Settings > Troubleshooting.
So open your Avast dashboard > Menu > Settings > Troubleshooting and disable "Enable hardware-assisted virtualization"
Give a higher priority to your emulator's process in the Task Manager:
Locate your emulator's process in the Task Manager > Details tab:
Sorry that the screenshot is not in English but you got the point, right? That helped me significantly! I hope it will help you as well.
Also, one thing as per the Release Notes:
- On Windows 8, 8.1 and 10, it is recommended to disable Hyper-V from Windows Features in order for the HAXM driver to properly function.
In my case, I didn't have any "Hyper-V" feature on my Windows 8.1 but you probably should try it, just in case. To locate and disable that feature see this article: https://support.bluestacks.com/hc/en-us/articles/115004254383-How-do-I-disable-Hyper-V-on-Windows-
As of November 2020, in order to show one figure at a time, the following works:
import matplotlib.pyplot as plt
f1, ax1 = plt.subplots()
ax1.plot(range(0,10))
f1.show()
input("Close the figure and press a key to continue")
f2, ax2 = plt.subplots()
ax2.plot(range(10,20))
f2.show()
input("Close the figure and press a key to continue")
The call to input()
prevents the figure from opening and closing immediately.
I had problems with collations as I had most of the tables with Modern_Spanish_CI_AS
, but a few, which I had inherited or copied from another Database, had SQL_Latin1_General_CP1_CI_AS
collation.
In my case, the easiest way to solve the problem has been as follows:
I hope this helps other users.
You could put it in the session:
session_start();
$_SESSION['array_name'] = $array_name;
Or if you want to send it via a form you can serialize it:
<input type='hidden' name='input_name' value="<?php echo htmlentities(serialize($array_name)); ?>" />
$passed_array = unserialize($_POST['input_name']);
Note that to work with serialized arrays, you need to use POST as the form's transmission method, as GET has a size limit somewhere around 1024 characters.
I'd use sessions wherever possible.
Useful to quickly print entries in a HashMap
System.out.println(Arrays.toString(map.entrySet().toArray()));
Couple of points:
git stash
+ git stash drop
could be replaced with git reset --hard
... or, even shorter, add -f
to checkout
command:
git checkout -f -b $branch
That will discard any local changes, just as if git reset --hard
was used prior to checkout.
As for the main question:
instead of pulling in the last step, you could just merge the appropriate branch from the remote into your local branch: git merge $branch origin/$branch
, I believe it does not hit the remote. If that is the case, it removes the need for credensials and hence, addresses your biggest concern.
if (!mytime.before(fromtime) && !mytime.after(totime))
$('body').delegate('.deletelanguage','click',function(){
alert("success");
});
or
$('body').on('click','.deletelanguage',function(){
alert("success");
});
The short answer: no.
The long answer:
Fixed formats work better for HTML emails. In my experience you're best off pretending it's 1999 when it comes to HTML emails. Be explicit and use HTML attributes (width="650") where ever possible in your table definitions, not CSS (style="width:650px"). Use fixed widths, no percentages. A table width of 650 pixels wide is a safe bet. Use inline CSS to set text properties.
It's not a matter of what works in "HTML emails", but rather the plethora of email clients and their limited (and sometimes deliberately so in the case of Gmail, Hotmail etc) ability to render HTML.
Extract characters from a string:
var str = "Hello world!";
var res = str.substring(1,4);
The result of res
will be:
ell
http://www.w3schools.com/jsref/jsref_substring.asp
$('.dep_buttons').mouseover(function(){
$(this).text().substring(0,25);
if($(this).text().length > 30) {
$(this).stop().animate({height:"150px"},150);
}
$(".dep_buttons").mouseout(function(){
$(this).stop().animate({height:"40px"},150);
});
});
Credit should go here: how to detect if a link was clicked when window.onbeforeunload is triggered?
Basically, the solution adds a listener to detect if a link or window caused the unload event to fire.
var link_was_clicked = false;
document.addEventListener("click", function(e) {
if (e.target.nodeName.toLowerCase() === 'a') {
link_was_clicked = true;
}
}, true);
window.onbeforeunload = function(e) {
if(link_was_clicked) {
return;
}
return confirm('Are you sure?');
}
They are parts of the Observer design pattern. Usually one or more obervers get informed about changes in one observable. It's a notifcation that "something" happened, where you as a programmer can define what "something" means.
When using this pattern, you decouple the both entities from each another - the observers become pluggable.
Supervised Learning
In this, every input pattern that is used to train the network is associated with an output pattern, which is the target or the desired pattern. A teacher is assumed to be present during the learning process, when a comparison is made between the network's computed output and the correct expected output, to determine the error. The error can then be used to change network parameters, which result in an improvement in performance.
Unsupervised Learning
In this learning method, the target output is not presented to the network. It is as if there is no teacher to present the desired pattern and hence, the system learns of its own by discovering and adapting to structural features in the input patterns.
Your test cases where you cannot connect with "ServerName\Instance" but ARE able to connect to the server via "ServerName,Port" is what happens when you VPN into a network with Microsoft VPN. (I had this issue). For my VPN Issue I simply use the static port numbers to get around it.
This is appearently due to VPN not forwarding UDP Packets, allowing only TCP Connections.
In your case your firewall or security settings or antivirus or whatever may be blocking UDP.
I would suggest you check your firewall setting to specifically allow for UDP.
On startup, SQL Server Browser starts and claims UDP port 1434. SQL Server Browser reads the registry, identifies all SQL Server instances on the computer, and notes the ports and named pipes that they use. When a server has two or more network cards, SQL Server Browser will return all ports enabled for SQL Server. SQL Server 2005 and SQL Server Browser support ipv6 and ipv4.
When SQL Server 2000 and SQL Server 2005 clients request SQL Server resources, the client network library sends a UDP message to the server using port 1434. SQL Server Browser responds with the TCP/IP port or named pipe of the requested instance. The network library on the client application then completes the connection by sending a request to the server using the port or named pipe of the desired instance.
Using a Firewall
To communicate with the SQL Server Browser service on a server behind a firewall, open UDP port 1434 in addition to the TCP port used by SQL Server (for example, 1433).
this.options[this.selectedIndex].innerHTML
should provide you with the "displayed" text of the selected item. this.value
, like you said, merely provides the value of the value
attribute.
the class attribute contains disabled
when the element is not clickable.
WebElement webElement = driver.findElement(By.id("elementId"));
if(!webElement.getAttribute("class").contains("disabled")){
webElement.click();
}
There's this Explorer Exclude extension that exactly does this. https://marketplace.visualstudio.com/items?itemName=RedVanWorkshop.explorer-exclude-vscode-extension
It adds an option to hide current folder/file to the right click menu. It also adds a vertical tab Hidden Items to explorer menu where you can see currently hidden files & folders and can toggle them easily.
Usually the problem is not closing brackets (}) or missing semicolon (;)
Faced the same issue. Indeed it was wrong SQL at the beginning of the file because when dumping I did:
mysqldump -u username --password=password db_name > dump.sql
Which wrote at the beginning of the file something that was in stdout which was:
mysqldump: [Warning] Using a password on the command line interface can be insecure.
Resulting in the restore raising that error.
So deleting the first line of the SQL dump enables a proper restore.
Looking at the way the restore was done in the original question, there is a high chance the dump was done similarly as mine, causing a stdout warning printing in the SQL file (if ever mysqldump was printing it back then).
There is several escaping options with same result:
body { width: ~"calc(100% - 250px - 1.5em)"; }
body { width: calc(~"100% - 250px - 1.5em"); }
body { width: calc(100% ~"-" 250px ~"-" 1.5em); }
The Python dateutil
library is designed for this (and more). It will automatically convert this to a datetime
object for you and raise a ValueError
if it can't.
As an example:
>>> from dateutil.parser import parse
>>> parse("2003-09-25")
datetime.datetime(2003, 9, 25, 0, 0)
This raises a ValueError
if the date is not formatted correctly:
>>> parse("2003-09-251")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/jacinda/envs/dod-backend-dev/lib/python2.7/site-packages/dateutil/parser.py", line 720, in parse
return DEFAULTPARSER.parse(timestr, **kwargs)
File "/Users/jacinda/envs/dod-backend-dev/lib/python2.7/site-packages/dateutil/parser.py", line 317, in parse
ret = default.replace(**repl)
ValueError: day is out of range for month
dateutil
is also extremely useful if you start needing to parse other formats in the future, as it can handle most known formats intelligently and allows you to modify your specification: dateutil
parsing examples.
It also handles timezones if you need that.
Update based on comments: parse
also accepts the keyword argument dayfirst
which controls whether the day or month is expected to come first if a date is ambiguous. This defaults to False. E.g.
>>> parse('11/12/2001')
>>> datetime.datetime(2001, 11, 12, 0, 0) # Nov 12
>>> parse('11/12/2001', dayfirst=True)
>>> datetime.datetime(2001, 12, 11, 0, 0) # Dec 11
Your application icon shows in the taskbar. The icon on the topleft (window) is the form-icon. Go to your form and fill the property "icon" with the same icon; problem solved. You don't need to put the icon in the outputfolder (that's just for setups).
Well the answer from @sahhhm didn't work for me, what i needed was to trigger the backKey from a custom button so what I did was I simply called,
backAction.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MyRides.super.onBackPressed();
}
});
and it work like charm. Hope it will help others too.
DotNetCoders has a starter article on it: http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50. They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).
There's another article on CodeProject: A Treatise on Using Debug and Trace classes, including Exception Handling, but it's the same age.
CodeGuru has another article on custom TraceListeners: Implementing a Custom TraceListener
If you want to cut out the last or the first do this:
list = ["This", "is", "a", "list"]
listnolast = list[:-1]
listnofirst = list[1:]
If you change 1 to 2 the first 2 characters will be removed not the second. Hope this still helps!
Use the property table-layout:fixed;
on the table to get equally spaced cells. If a column has a width set, then no matter what the content is, it will be the specified width. Columns without a width set will divide whatever room is left over among themselves.
<table style='table-layout:fixed;'>
<tbody>
<tr>
<td>gobble de gook</td>
<td>mibs</td>
</tr>
</tbody>
</table>
Just to throw it out there, you could also use <colgroup><col span='#' style='width:#%;'/></colgroup>
, which doesn't require repetition of style per table data or giving the table an id to use in a style sheet. I think setting the widths on the first row is enough though.
In my case I used the below pom.xml file here
and it worked for me.
[JDK8]
import java.util.Base64;
To string:
String str = Base64.getEncoder().encode(new byte[]{ -47, 1, 16, ... });
To byte array:
byte[] bytes = Base64.getDecoder().decode("JVBERi0xLjQKMyAwIG9iago8P...");
Another option is to use Sort-Object
(whose alias is sort
, but only on Windows) with the -Unique
switch, which combines sorting with removal of duplicates:
$a | sort -unique
Someone edited my answer to add incorrect English, but here was the original, which is inferior to the accepted answer.
. .bashrc
The font-size
won't respond like this when resizing the browser window. Instead they respond to the browser zoom/type size settings, such as if you press Ctrl and + together on the keyboard while in the browser.
Media Queries
You would have to look at using media queries to reduce the font-size at certain intervals where it starts breaking your design and creating scrollbars.
For example, try adding this inside your CSS at the bottom, changing the 320 pixels width for wherever your design starts breaking:
@media only screen and (max-width: 320px) {
body {
font-size: 2em;
}
}
Viewport percentage lengths
You can also use viewport percentage lengths such as vw
, vh
, vmin
and vmax
. The official W3C document for this states:
The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly.
Again, from the same W3C document each individual unit can be defined as below:
vw unit - Equal to 1% of the width of the initial containing block.
vh unit - Equal to 1% of the height of the initial containing block.
vmin unit - Equal to the smaller of vw or vh.
vmax unit - Equal to the larger of vw or vh.
And they are used in exactly the same way as any other CSS value:
.text {
font-size: 3vw;
}
.other-text {
font-size: 5vh;
}
Compatibility is relatively good as can be seen here. However, some versions of Internet Explorer and Edge don’t support vmax. Also, iOS 6 and 7 have an issue with the vh unit, which was fixed in iOS 8.
TRUNCATE TABLE is functionally identical to DELETE statement with no WHERE clause: both remove all rows in the table. But TRUNCATE TABLE is faster and uses fewer system and transaction log resources than DELETE.
The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE removes the data by deallocating the data pages used to store the table's data, and only the page deallocations are recorded in the transaction log.
TRUNCATE TABLE removes all rows from a table, but the table structure and its columns, constraints, indexes and so on remain. The counter used by an identity for new rows is reset to the seed for the column. If you want to retain the identity counter, use DELETE instead. If you want to remove table definition and its data, use the DROP TABLE statement.
You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint; instead, use DELETE statement without a WHERE clause. Because TRUNCATE TABLE is not logged, it cannot activate a trigger.
TRUNCATE TABLE may not be used on tables participating in an indexed view.
From http://msdn.microsoft.com/en-us/library/aa260621(SQL.80).aspx
Based on Cameron's initial answer, here is what I've just added at my enhanced version of SilverFlow library's FloatingWindowHost (copying from FloatingWindowHost.cs at http://clipflair.codeplex.com source code)
public int MaxZIndex
{
get {
return FloatingWindows.Aggregate(-1, (maxZIndex, window) => {
int w = Canvas.GetZIndex(window);
return (w > maxZIndex) ? w : maxZIndex;
});
}
}
private void SetTopmost(UIElement element)
{
if (element == null)
throw new ArgumentNullException("element");
Canvas.SetZIndex(element, MaxZIndex + 1);
}
Worth noting regarding the code above that Canvas.ZIndex is an attached property available for UIElements in various containers, not just used when being hosted in a Canvas (see Controlling rendering order (ZOrder) in Silverlight without using the Canvas control). Guess one could even make a SetTopmost and SetBottomMost static extension method for UIElement easily by adapting this code.
request.getParameter("accountID")
is what you're looking for. This is part of the Java Servlet API. See http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletRequest.html for more information.
This one works better if you don't have the python on path or want to specify the directory :
//for Windows
npm config set python C:\Python27\python.exe
//for Linux
npm config set python /usr/bin/python27
If body contains a io.StringIO, you have to do like below:
object.get()['Body'].getvalue()
You shouldn't be closing the serial port in Python between writing and reading. There is a chance that the port is still closed when the Arduino responds, in which case the data will be lost.
while running:
# Serial write section
setTempCar1 = 63
setTempCar2 = 37
setTemp1 = str(setTempCar1)
setTemp2 = str(setTempCar2)
print ("Python value sent: ")
print (setTemp1)
ard.write(setTemp1)
time.sleep(6) # with the port open, the response will be buffered
# so wait a bit longer for response here
# Serial read section
msg = ard.read(ard.inWaiting()) # read everything in the input buffer
print ("Message from arduino: ")
print (msg)
The Python Serial.read
function only returns a single byte by default, so you need to either call it in a loop or wait for the data to be transmitted and then read the whole buffer.
On the Arduino side, you should consider what happens in your loop
function when no data is available.
void loop()
{
// serial read section
while (Serial.available()) // this will be skipped if no data present, leading to
// the code sitting in the delay function below
{
delay(30); //delay to allow buffer to fill
if (Serial.available() >0)
{
char c = Serial.read(); //gets one byte from serial buffer
readString += c; //makes the string readString
}
}
Instead, wait at the start of the loop
function until data arrives:
void loop()
{
while (!Serial.available()) {} // wait for data to arrive
// serial read section
while (Serial.available())
{
// continue as before
EDIT 2
Here's what I get when interfacing with your Arduino app from Python:
>>> import serial
>>> s = serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=5)
>>> s.write('2')
1
>>> s.readline()
'Arduino received: 2\r\n'
So that seems to be working fine.
In testing your Python script, it seems the problem is that the Arduino resets when you open the serial port (at least my Uno does), so you need to wait a few seconds for it to start up. You are also only reading a single line for the response, so I've fixed that in the code below also:
#!/usr/bin/python
import serial
import syslog
import time
#The following line is for serial over GPIO
port = '/dev/tty.usbmodem1411' # note I'm using Mac OS-X
ard = serial.Serial(port,9600,timeout=5)
time.sleep(2) # wait for Arduino
i = 0
while (i < 4):
# Serial write section
setTempCar1 = 63
setTempCar2 = 37
ard.flush()
setTemp1 = str(setTempCar1)
setTemp2 = str(setTempCar2)
print ("Python value sent: ")
print (setTemp1)
ard.write(setTemp1)
time.sleep(1) # I shortened this to match the new value in your Arduino code
# Serial read section
msg = ard.read(ard.inWaiting()) # read all characters in buffer
print ("Message from arduino: ")
print (msg)
i = i + 1
else:
print "Exiting"
exit()
Here's the output of the above now:
$ python ardser.py
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1
Exiting
If you want this for unit testing I just use the hasNoNullFieldsOrProperties()
method from assertj
assertThat(myObj).hasNoNullFieldsOrProperties();
I have same problem with the most basic situation and my problem was solved with inserting this meta in the head:
<meta charset="UTF-8">
the character encoding (which is actually UTF-8) of the html document was not declared
The answer is Colorama for all cross-platform coloring in Python.
It supports Python 3.5+ as well as Python 2.7.
And as of January 2021 it is maintained.
You can use these solutions :
CSS rules applies to all tags that have following two classes :
.left.ui-class-selector {
/*style here*/
}
CSS rules applies to all tags that have <li>
with following two classes :
li.left.ui-class-selector {
/*style here*/
}
jQuery solution :
$("li.left.ui-class-selector").css("color", "red");
Javascript solution :
document.querySelector("li.left.ui-class-selector").style.color = "red";
As i am using gitkraken and command prompt, i ran into the same issue. And then i run git gc
command it resolved my problem. So i am happy and want share some of the points which might be helpful.
What git gc
will do ?
git gc
removing unreachable objects which may have been created from prior invocations of git add.
When to run git gc
?
From doc, users are encouraged to run this task on a regular basis within each repository to maintain good disk space utilization and good operating performance.
How to make it auto-configurable?
Some git commands may automatically run git gc; see the --auto flag below for details. If you know what you’re doing and all you want is to disable this behavior permanently without further considerations, just do
git config --global gc.auto 0
What browser are you testing in?
What DOCType have you set?
How exactly are you declaring your CSS?
Are you sure you haven't missed a ;
before/after the overflow-y: scroll
?
I've just tested the following in IE7 and Firefox and it works fine
<!-- Scroll bar present but disabled when less content -->_x000D_
<div style="width: 200px; height: 100px; overflow-y: scroll;">_x000D_
test_x000D_
</div>_x000D_
_x000D_
<!-- Scroll bar present and enabled when more contents --> _x000D_
<div style="width: 200px; height: 100px; overflow-y: scroll;">_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
</div>
_x000D_
For the former, convention over configuration. Rails default when you reference another table with
belongs_to :something
is to look for something_id
.
references
, or belongs_to
is actually newer way of writing the former with few quirks.
Important is to remember that it will not create foreign keys for you. In order to do that, you need to set it up explicitly using either:
t.references :something, foreign_key: true
t.belongs_to :something_else, foreign_key: true
or (note the plural):
add_foreign_key :table_name, :somethings
add_foreign_key :table_name, :something_elses`
Yes you can do that by just creating a BroadcastReceiver
that calls your Service
when your Application boots. Here is a complete answer given by me.
Android - Start service on boot
If you don't want any icon/launcher for you Application you can do that also, just don't create any Activity with
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
Just declare your Service
as declared normally.
select Qty, vajan, Rate,Amt,nhamali,ncommission,ntolai from SalesDtl,SalesMSt where SalesDtl.PurEntryNo=1 and SalesMST.SaleDate= (22/03/2014) and SalesMST.SaleNo= SalesDtl.SaleNo;
That should work.
In Swift 2.0, @user478681's answer might look like this:
let HTMLDocumentPath = NSBundle.mainBundle().pathForResource("index", ofType: "html")
let HTMLString: NSString?
do {
HTMLString = try NSString(contentsOfFile: HTMLDocumentPath!, encoding: NSUTF8StringEncoding)
} catch {
HTMLString = nil
}
myWebView.loadHTMLString(HTMLString as! String, baseURL: nil)
If you removed the make all
line from your "fresh" target:
fresh :
rm -f *.o $(EXEC)
clear
You could simply run the command make fresh all
, which will execute as make fresh; make all
.
Some might consider this as a second instance of make, but it's certainly not a sub-instance of make (a make inside of a make), which is what your attempt seemed to result in.
If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:
The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.
Setting cookie in the express is easy
npm install cookie parser
const cookieParser = require('cookie-parser');
app.use(cookieParser());
res.cookie('cookieName', '1', { expires: new Date(Date.now() + 900000), httpOnly: true })
console.dir(req.cookies.cookieName)
I ran into this exact same error message. I tried Aditi's example, and then I realized what the real issue was. (Because I had another apiEndpoint making a similar call that worked fine.) In this case The object in my list had not had an interface extracted from it yet. So because I apparently missed a step, when it went to do the bind to the
List<OfthisModelType>
It failed to deserialize.
If you see this issue, check to see if that could be the issue.
Try this
for(int i = 0; i != 5; ++i, ++j)
do_something(i,j);
You missed underscore in argument document_root. But it's bad idea to use serve
in production. Use something like this instead:
import os
from django.conf import settings
from django.http import HttpResponse, Http404
def download(request, path):
file_path = os.path.join(settings.MEDIA_ROOT, path)
if os.path.exists(file_path):
with open(file_path, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/vnd.ms-excel")
response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)
return response
raise Http404
If the methods above don't work, you can also tell Python to ignore portions of a string that it can't convert to utf-8:
stringnamehere.decode('utf-8', 'ignore')
"""
merge_image takes three parameters first two parameters specify
the two images to be merged and third parameter i.e. vertically
is a boolean type which if True merges images vertically
and finally saves and returns the file_name
"""
def merge_image(img1, img2, vertically):
images = list(map(Image.open, [img1, img2]))
widths, heights = zip(*(i.size for i in images))
if vertically:
max_width = max(widths)
total_height = sum(heights)
new_im = Image.new('RGB', (max_width, total_height))
y_offset = 0
for im in images:
new_im.paste(im, (0, y_offset))
y_offset += im.size[1]
else:
total_width = sum(widths)
max_height = max(heights)
new_im = Image.new('RGB', (total_width, max_height))
x_offset = 0
for im in images:
new_im.paste(im, (x_offset, 0))
x_offset += im.size[0]
new_im.save('test.jpg')
return 'test.jpg'
Note that you can also determine in pure js in what browser you script is beeing executed through : window.navigator.userAgent
However, that's not a recommended way as it's configurable in the browser settings. More info available there: https://developer.mozilla.org/fr/docs/DOM/window.navigator.userAgent
Timsort is "an adaptive, stable, natural mergesort" with "supernatural performance on many
kinds of partially ordered arrays (less than lg(N!) comparisons needed, and
as few as N-1)". Python's built-in sort()
has used this algorithm for some time, apparently with good results. It's specifically designed to detect and take advantage of partially sorted subsequences in the input, which often occur in real datasets. It is often the case in the real world that comparisons are much more expensive than swapping items in a list, since one typically just swaps pointers, which very often makes timsort an excellent choice. However, if you know that your comparisons are always very cheap (writing a toy program to sort 32-bit integers, for instance), other algorithms exist that are likely to perform better. The easiest way to take advantage of timsort is of course to use Python, but since Python is open source you might also be able to borrow the code. Alternately, the description above contains more than enough detail to write your own implementation.
You likely want to use onupdate=datetime.now
so that UPDATEs also change the last_updated
field.
SQLAlchemy has two defaults for python executed functions.
default
sets the value on INSERT, only onceonupdate
sets the value to the callable result on UPDATE as well.there are three ways you can use: the RETURN value, and OUTPUT parameter and a result set
ALSO, watch out if you use the pattern: SELECT @Variable=column FROM table ...
if there are multiple rows returned from the query, your @Variable will only contain the value from the last row returned by the query.
RETURN VALUE
since your query returns an int field, at least based on how you named it. you can use this trick:
CREATE PROCEDURE GetMyInt
( @Param int)
AS
DECLARE @ReturnValue int
SELECT @ReturnValue=MyIntField FROM MyTable WHERE MyPrimaryKeyField = @Param
RETURN @ReturnValue
GO
and now call your procedure like:
DECLARE @SelectedValue int
,@Param int
SET @Param=1
EXEC @SelectedValue = GetMyInt @Param
PRINT @SelectedValue
this will only work for INTs, because RETURN can only return a single int value and nulls are converted to a zero.
OUTPUT PARAMETER
you can use an output parameter:
CREATE PROCEDURE GetMyInt
( @Param int
,@OutValue int OUTPUT)
AS
SELECT @OutValue=MyIntField FROM MyTable WHERE MyPrimaryKeyField = @Param
RETURN 0
GO
and now call your procedure like:
DECLARE @SelectedValue int
,@Param int
SET @Param=1
EXEC GetMyInt @Param, @SelectedValue OUTPUT
PRINT @SelectedValue
Output parameters can only return one value, but can be any data type
RESULT SET for a result set make the procedure like:
CREATE PROCEDURE GetMyInt
( @Param int)
AS
SELECT MyIntField FROM MyTable WHERE MyPrimaryKeyField = @Param
RETURN 0
GO
use it like:
DECLARE @ResultSet table (SelectedValue int)
DECLARE @Param int
SET @Param=1
INSERT INTO @ResultSet (SelectedValue)
EXEC GetMyInt @Param
SELECT * FROM @ResultSet
result sets can have many rows and many columns of any data type
(https://www.youtube.com/watch?v=Vxw1b8f_yts&t=3384s) Avinash Jain
for i in range(2,5003):
j = 2
c = 0
while j < i:
if i % j == 0:
c = 1
j = j + 1
else:
j = j + 1
if c == 0:
print(str(i) + ' is a prime number')
else:
c = 0
Okay, looks like big solutions.
Why not to add width: 100%;
directly in your iframe. ;)
So your code would looks something like <iframe style="width: 100%;" ...></iframe>
Try this it'll work as it worked in my case.
Enjoy! :)
I know this is almost 1.5 years old, but I hope I can help someone with what I found.
I had built both a console app and a UWP app and my console connnected fine, but not my UWP. After hours of banging my head against the desk - if it's a intranet server hosting the SQL database you must enable "Private Networks (Client & Server)". It's under Package.appxmanifest and the Capabilities tab.Screenshot
Just recently found out about this. With apis as:
targetSdkVersion 26
ActivityManager.getCurrentActivity(context)
Hope this is of any use.
For newer Android platforms, one can execute a system utility screencap
in /system/bin
to get the screenshot without root permission.
You can try /system/bin/screencap -h
to see how to use it under adb or any shell.
By the way, I think this method is only good for single snapshot. If we want to capture multiple frames for screen play, it will be too slow. I don't know if there exists any other approach for a faster screen capture.
Compare two numbers. If it equals Yes "Y", it prints No "N" on the screen if it is not equal. I am using emu8086. You can use the SUB or CMP command.
MOV AX,5h
MOV BX,5h
SUB AX,BX
JZ EQUALS
JNZ NOTEQUALS
EQUALS:
MOV CL,'Y'
JMP PRINT
NOTEQUALS:
MOV CL,'N'
PRINT:
MOV AH,2
MOV DL,CL
INT 21H
RET
To print certain lines in a text file. Create a "lines2print" list and then just print when the enumeration is "in" the lines2print list. To get rid of extra '\n' use line.strip() or line.strip('\n'). I just like "list comprehension" and try to use when I can. I like the "with" method to read text files in order to prevent leaving a file open for any reason.
lines2print = [26,30] # can be a big list and order doesn't matter.
with open("filepath", 'r') as fp:
[print(x.strip()) for ei,x in enumerate(fp) if ei in lines2print]
or if list is small just type in list as a list into the comprehension.
with open("filepath", 'r') as fp:
[print(x.strip()) for ei,x in enumerate(fp) if ei in [26,30]]
[Edit]
In the future (mobile) Safari 9 there will be -webkit-backdrop-filter
for exactly this. See this pen I made to showcase it.
I thought about this for the last 4 weeks and came up with this solution.
[Edit] I wrote a more indepth post on CSS-Tricks
This technique is using CSS Regions so the browser support is not the best at this moment. (http://caniuse.com/#feat=css-regions)
The key part of this technique is to split apart content from layout by using CSS Region. First define a .content
element with flow-into:content
and then use the appropriate structure to blur the header.
The layout structure:
<div class="phone">
<div class="phone__display">
<div class="header">
<div class="header__text">Header</div>
<div class="header__background"></div>
</div>
<div class="phone__content">
</div>
</div>
</div>
The two important parts of this layout are .header__background
and .phone__content
- these are the containers where the content should flow though.
Using CSS Regions it is simple as flow-from:content
(.content
is flowing into the named region content
)
Now comes the tricky part. We want to always flow the content through the .header__background
because that is the section where the content will be blured. (using webkit-filter:blur(10px);
)
This is done by transfrom:translateY(-$HeightOfTheHeader)
the .content
to ensure that the content will always flow though the .header__background
. This transform while always hide some content beneath the header. Fixing this is ease adding
.header__background:before{
display:inline-block;
content:'';
height:$HeightOfTheHEader
}
to accommodate for the transform.
This is currently working in:
The generic view of a loop is
for (initialization; condition; increment-decrement){}
The first part initializes the code. The second part is the condition that will continue to run the loop as long as it is true. The last part is what will be run after each iteration of the loop. The last part is typically used to increment or decrement a counter, but it doesn't have to.
JSON is perfectly capable of expressing lists of integers, and the JSON you have posted is valid. You can simply separate the integers by commas:
{
"Id": "610",
"Name": "15",
"Description": "1.99",
"ItemModList": [42, 47, 139]
}
df[sapply(df, function(x) all(is.na(x)))] <- NULL
1.Monolithic Kernel (Pure Monolithic) :all
All Kernel Services From single component
(-) addition/removal is not possible, less/Zero flexible
(+) inter Component Communication is better
e.g. :- Traditional Unix
2.Micro Kernel :few
few services(Memory management ,CPU management,IPC etc) from core kernel, other services(File management,I/O management. etc.) from different layers/component
Split Approach [Some services is in privileged(kernel) mode and some are in Normal(user) mode]
(+)flexible for changes/up-gradations
(-)communication overhead
e.g.:- QNX etc.
3.Modular kernel(Modular Monolithic) :most
Combination of Micro and Monolithic kernel
Collection of Modules -- modules can be --> Static + Dynamic
Drivers come in the form of Modules
e.g. :- Linux Modern OS
What you are looking to do is get the position using the LocationManager.NETWORK_PROVIDER
instead of LocationManager.GPS_PROVIDER
. The NETWORK_PROVIDER
will resolve on the GSM or wifi, which ever available. Obviously with wifi off, GSM will be used. Keep in mind that using the cell network is accurate to basically 500m.
http://developer.android.com/guide/topics/location/obtaining-user-location.html has some really great information and sample code.
After you get done with most of the code in OnCreate()
, add this:
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
You could also have your activity implement the LocationListener
class and thus implement onLocationChanged()
in your activity.
If you are executing a stored procedure from Informix using EntityFrameworkCore you need to include the command EXECUTE PROCEDURE
var spresult = _informixContext.procdata.FromSql("EXECUTE PROCEDURE dummyproc ({0},{1},{2})", parameters: new[] { p0, p1,p2 }).ToList();
What I was looking for is a way to fetch the data
so I used this $data = $this->db->get('table_name')->result_array();
and then fetched my data just as you operate on array objects.
$data[0]['field_name']
No need to worry about type casting or anything just straight to the point.
So it worked for me.
You can also set the test env in your test file as follows:
/* eslint-env jest */
describe(() => {
/* ... */
})
Before we'll begin, let's just remind that origin point is the Upper Left corner CGPoint
of a view.
An important thing to understand about views and parents.
Lets take a look at this simple code, a view controller that adds to it's view a black square:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
createDummyView()
super.view.backgroundColor = UIColor.cyanColor();
}
func createDummyView(){
var subView = UIView(frame: CGRect(x: 15, y: 50, width: 50 , height: 50));
super.view.addSubview(subView);
view.backgroundColor = UIColor.blackColor()
}
}
This will create this view: the black rectangle origin and center does fit the same coordinates as it's parent
Now let's try to add subView another SubSubView, and giving subSubview same origin as subView, but make subSubView a child view of subView
We'll add this code:
var subSubView = UIView();
subSubView.frame.origin = subView.frame.origin;
subSubView.frame.size = CGSizeMake(20, 20);
subSubView.backgroundColor = UIColor.purpleColor()
subView.addSubview(subSubView)
And this is the result:
Because of this line:
subSubView.frame.origin = subView.frame.origin;
You expect for the purple rectangle's origin to be same as it's parent (the black rectangle) but it goes under it, and why is that? Because when you add a view to another view, the subView frame "world" is now it's parent BOUND RECTANGLE, if you have a view that it's origin on the main screen is at coords (15,15) for all it's sub views, the upper left corner will be (0,0)
This is why you need to always refer to a parent by it's bound rectangle, which is the "world" of it's subViews, lets fix this line to:
subSubView.frame.origin = subView.bounds.origin;
And see the magic, the subSubview is now located exactly in it's parent origin:
So, you like "ok I only wanted to center my view by my parents view, what's the big deal?" well, it isn't big deal, you just need to "translate" the parent Center point which is taken from it's frame to parent's bounds center by doing this:
subSubView.center = subView.convertPoint(subView.center, fromView: subSubView);
You're actually telling him "take parents view center, and convert it into subSubView world".
And you'll get this result:
As noted in this newsgroup posting, there are a few reasons why using alloca
can be considered difficult and dangerous:
alloca
.alloca
differently, so portability is not guaranteed even between compilers that support it.If you want to change all columns of a certain type to another type, you can generate queries using a query like this:
select distinct concat('alter table ',
table_name,
' modify ',
column_name,
' <new datatype> ',
if(is_nullable = 'NO', ' NOT ', ''),
' NULL;')
from information_schema.columns
where table_schema = '<your database>'
and column_type = '<old datatype>';
For instance, if you want to change columns from tinyint(4)
to bit(1)
, run it like this:
select distinct concat('alter table ',
table_name,
' modify ',
column_name,
' bit(1) ',
if(is_nullable = 'NO', ' NOT ', ''),
' NULL;')
from information_schema.columns
where table_schema = 'MyDatabase'
and column_type = 'tinyint(4)';
and get an output like this:
alter table table1 modify finished bit(1) NOT NULL;
alter table table2 modify canItBeTrue bit(1) NOT NULL;
alter table table3 modify canBeNull bit(1) NULL;
!! Does not keep unique constraints, but should be easily fixed with another if
-parameter to concat
. I'll leave it up to the reader to implement that if needed..
Stop the IIS service. It should work then
A null key can also be helpful when the map stores data for UI selections where the map key represents a bean field.
A corresponding null field value would for example be represented as "(please select)" in the UI selection.