You can set default width and height for all Columns and Rows as below only with one loop.
// DataGridView Name= dgvMachineStatus
foreach (DataGridViewColumn column in dgvMachineStatus.Columns)
{
column.Width = 155;
}
foreach (DataGridViewRow row in dgvMachineStatus.Rows)
{
row.Height = 45;
}
var pass = new SecureString();
pass.AppendChar('s');
pass.AppendChar('e');
pass.AppendChar('c');
pass.AppendChar('r');
pass.AppendChar('e');
pass.AppendChar('t');
Process.Start("notepad", "admin", pass, "");
Works also with ProcessStartInfo:
var psi = new ProcessStartInfo
{
FileName = "notepad",
UserName = "admin",
Domain = "",
Password = pass,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
Process.Start(psi);
As of October 2016, Google has added a file upload question type in native Google Forms, no Google Apps Script needed. See documentation.
Collations affect how data is sorted and how strings are compared to each other. That means you should use the collation that most of your users expect.
Example from the documentation for charset unicode:
utf8_general_ci
also is satisfactory for both German and French, except that ‘ß’ is equal to ‘s’, and not to ‘ss’. If this is acceptable for your application, then you should useutf8_general_ci
because it is faster. Otherwise, useutf8_unicode_ci
because it is more accurate.
So - it depends on your expected user base and on how much you need correct sorting. For an English user base, utf8_general_ci
should suffice, for other languages, like Swedish, special collations have been created.
To convert XML File in to JSON include the following dependency
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
and you can Download Jar from Maven Repository here. Then implement as:
String soapmessageString = "<xml>yourStringURLorFILE</xml>";
JSONObject soapDatainJsonObject = XML.toJSONObject(soapmessageString);
System.out.println(soapDatainJsonObject);
This should do what you want:
sed 's/two.*/BLAH/'
$ echo " one two three five
> four two five five six
> six one two seven four" | sed 's/two.*/BLAH/'
one BLAH
four BLAH
six one BLAH
The $
is unnecessary because the .*
will finish at the end of the line anyways, and the g
at the end is unnecessary because your first match will be the first two
to the end of the line.
I couldn't find a single answer or a section in the official Django docs that had all the information I needed to override/extend the default admin templates, so I'm writing this answer as a complete guide, hoping that it would be helpful for others in the future.
Assuming the standard Django project structure:
mysite-container/ # project container directory
manage.py
mysite/ # project package
__init__.py
admin.py
apps.py
settings.py
urls.py
wsgi.py
app1/
app2/
...
static/
templates/
Here's what you need to do:
In mysite/admin.py
, create a sub-class of AdminSite
:
from django.contrib.admin import AdminSite
class CustomAdminSite(AdminSite):
# set values for `site_header`, `site_title`, `index_title` etc.
site_header = 'Custom Admin Site'
...
# extend / override admin views, such as `index()`
def index(self, request, extra_context=None):
extra_context = extra_context or {}
# do whatever you want to do and save the values in `extra_context`
extra_context['world'] = 'Earth'
return super(CustomAdminSite, self).index(request, extra_context)
custom_admin_site = CustomAdminSite()
Make sure to import custom_admin_site
in the admin.py
of your apps and register your models on it to display them on your customized admin site (if you want to).
In mysite/apps.py
, create a sub-class of AdminConfig
and set default_site
to admin.CustomAdminSite
from the previous step:
from django.contrib.admin.apps import AdminConfig
class CustomAdminConfig(AdminConfig):
default_site = 'admin.CustomAdminSite'
In mysite/settings.py
, replace django.admin.site
in INSTALLED_APPS
with apps.CustomAdminConfig
(your custom admin app config from the previous step).
In mysite/urls.py
, replace admin.site.urls
from the admin URL to custom_admin_site.urls
from .admin import custom_admin_site
urlpatterns = [
...
path('admin/', custom_admin_site.urls),
# for Django 1.x versions: url(r'^admin/', include(custom_admin_site.urls)),
...
]
Create the template you want to modify in your templates
directory, maintaining the default Django admin templates directory structure as specified in the docs. For example, if you were modifying admin/index.html
, create the file templates/admin/index.html
.
All of the existing templates can be modified this way, and their names and structures can be found in Django's source code.
Now you can either override the template by writing it from scratch or extend it and then override/extend specific blocks.
For example, if you wanted to keep everything as-is but wanted to override the content
block (which on the index page lists the apps and their models that you registered), add the following to templates/admin/index.html
:
{% extends 'admin/index.html' %}
{% block content %}
<h1>
Hello, {{ world }}!
</h1>
{% endblock %}
To preserve the original contents of a block, add {{ block.super }}
wherever you want the original contents to be displayed:
{% extends 'admin/index.html' %}
{% block content %}
<h1>
Hello, {{ world }}!
</h1>
{{ block.super }}
{% endblock %}
You can also add custom styles and scripts by modifying the extrastyle
and extrahead
blocks.
You can use html5 tag to download the image directly
<?php
$file = "Bang.png"; //Let say If I put the file name Bang.png
echo "<a href='download.php?nama=".$file."' download>donload</a> ";
?>
For more information, check this link http://www.w3schools.com/tags/att_a_download.asp
echo "<table><tr><th>Title</th><th>Price</th><th>Number</th></tr>";
foreach($shop as $v){
echo "<tr>";
foreach($v as $vv){
echo "<td>{$vv}</td>";
}
echo "<tr>";
}
echo "</table>";
This method does the trick.
boolean contains(char c, char[] array) {
for (char x : array) {
if (x == c) {
return true;
}
}
return false;
}
Example of usage:
class Main {
static boolean contains(char c, char[] array) {
for (char x : array) {
if (x == c) {
return true;
}
}
return false;
}
public static void main(String[] a) {
char[] charArray = new char[] {'h','e','l','l','o'};
if (!contains('q', charArray)) {
// Do something...
System.out.println("Hello world!");
}
}
}
Alternative way:
if (!String.valueOf(charArray).contains("q")) {
// do something...
}
DTO
is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.
DTO
should only contain private fields for your data, getters, setters, and constructors.DTO
is not recommended to add business logic methods to such classes, but it is OK to add some util methods.DAO
is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).
Here is an example of how the DAO and DTO interfaces would look like:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}
interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
The MVC
is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.
As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.
content
doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.
Another problem with your code is "
inside a "
block. You should mix '
and "
(class='headingDetail'
).
If content
did support HTML you could end up in an infinite loop where content
is added inside content
.
I faced this issue once and was able to resolve it by fixing of my /etc/hosts. It just was unable to resolve localhost name... Details are here: http://itvictories.com/node/6
In fact, there is 99% that error related to /etc/hosts file
X server just unable to resolve localhost and all consequent actions just fails.
Please be sure that you have a record like
127.0.0.1 localhost
in your /etc/hosts file.
$("ul[data-group='Companies'] li[data-company='Microsoft']") //Get all elements with data-company="Microsoft" below "Companies"
$("ul[data-group='Companies'] li:not([data-company='Microsoft'])") //get all elements with data-company!="Microsoft" below "Companies"
Look in to jQuery Selectors :contains is a selector
here is info on the :contains selector
<> means not equal. however, in some versions of SQL, you can write !=
Here's how to do it inside ViewModel
and FusedLocationProviderClient
, code in Kotlin
locationClient.lastLocation.addOnSuccessListener { location: Location? ->
location?.let {
val position = CameraPosition.Builder()
.target(LatLng(it.latitude, it.longitude))
.zoom(15.0f)
.build()
map.animateCamera(CameraUpdateFactory.newCameraPosition(position))
}
}
Use "placeholder" instead of "value" in your input field.
You have to consider the Turkish I problem when comparing characters/ lowercasing / uppercasing:
I suggest to convert to String and use toLowerCase with invariant culture (in most cases at least).
public final static Locale InvariantLocale = new Locale(Empty, Empty, Empty); str.toLowerCase(InvariantLocale)
See similar C# string.ToLower() and string.ToLowerInvariant()
Note: Don't use String.equalsIgnoreCase http://nikolajlindberg.blogspot.co.il/2008/03/beware-of-java-comparing-turkish.html
Whenever you have heavyweight initialization that should be done once for many
RDD
elements rather than once perRDD
element, and if this initialization, such as creation of objects from a third-party library, cannot be serialized (so that Spark can transmit it across the cluster to the worker nodes), usemapPartitions()
instead ofmap()
.mapPartitions()
provides for the initialization to be done once per worker task/thread/partition instead of once perRDD
data element for example : see below.
val newRd = myRdd.mapPartitions(partition => {
val connection = new DbConnection /*creates a db connection per partition*/
val newPartition = partition.map(record => {
readMatchingFromDB(record, connection)
}).toList // consumes the iterator, thus calls readMatchingFromDB
connection.close() // close dbconnection here
newPartition.iterator // create a new iterator
})
Q2. does
flatMap
behave like map or likemapPartitions
?
Yes. please see example 2 of flatmap
.. its self explanatory.
Q1. What's the difference between an RDD's
map
andmapPartitions
map
works the function being utilized at a per element level whilemapPartitions
exercises the function at the partition level.
Example Scenario : if we have 100K elements in a particular RDD
partition then we will fire off the function being used by the mapping transformation 100K times when we use map
.
Conversely, if we use mapPartitions
then we will only call the particular function one time, but we will pass in all 100K records and get back all responses in one function call.
There will be performance gain since map
works on a particular function so many times, especially if the function is doing something expensive each time that it wouldn't need to do if we passed in all the elements at once(in case of mappartitions
).
Applies a transformation function on each item of the RDD and returns the result as a new RDD.
Listing Variants
def map[U: ClassTag](f: T => U): RDD[U]
Example :
val a = sc.parallelize(List("dog", "salmon", "salmon", "rat", "elephant"), 3)
val b = a.map(_.length)
val c = a.zip(b)
c.collect
res0: Array[(String, Int)] = Array((dog,3), (salmon,6), (salmon,6), (rat,3), (elephant,8))
This is a specialized map that is called only once for each partition. The entire content of the respective partitions is available as a sequential stream of values via the input argument (Iterarator[T]). The custom function must return yet another Iterator[U]. The combined result iterators are automatically converted into a new RDD. Please note, that the tuples (3,4) and (6,7) are missing from the following result due to the partitioning we chose.
preservesPartitioning
indicates whether the input function preserves the partitioner, which should befalse
unless this is a pair RDD and the input function doesn't modify the keys.Listing Variants
def mapPartitions[U: ClassTag](f: Iterator[T] => Iterator[U], preservesPartitioning: Boolean = false): RDD[U]
Example 1
val a = sc.parallelize(1 to 9, 3)
def myfunc[T](iter: Iterator[T]) : Iterator[(T, T)] = {
var res = List[(T, T)]()
var pre = iter.next
while (iter.hasNext)
{
val cur = iter.next;
res .::= (pre, cur)
pre = cur;
}
res.iterator
}
a.mapPartitions(myfunc).collect
res0: Array[(Int, Int)] = Array((2,3), (1,2), (5,6), (4,5), (8,9), (7,8))
Example 2
val x = sc.parallelize(List(1, 2, 3, 4, 5, 6, 7, 8, 9,10), 3)
def myfunc(iter: Iterator[Int]) : Iterator[Int] = {
var res = List[Int]()
while (iter.hasNext) {
val cur = iter.next;
res = res ::: List.fill(scala.util.Random.nextInt(10))(cur)
}
res.iterator
}
x.mapPartitions(myfunc).collect
// some of the number are not outputted at all. This is because the random number generated for it is zero.
res8: Array[Int] = Array(1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 5, 7, 7, 7, 9, 9, 10)
The above program can also be written using flatMap as follows.
Example 2 using flatmap
val x = sc.parallelize(1 to 10, 3)
x.flatMap(List.fill(scala.util.Random.nextInt(10))(_)).collect
res1: Array[Int] = Array(1, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10)
mapPartitions
transformation is faster than map
since it calls your function once/partition, not once/element..
Further reading : foreach Vs foreachPartitions When to use What?
Try the following statement:
select distinct A.[Tag],
count(A.[Tag]) as TAG_COUNT,
(SELECT count(*) FROM [TagTbl] AS B WHERE A.[Tag]=B.[Tag] AND B.[ID]>0)
from [TagTbl] AS A GROUP BY A.[Tag]
The first field will be the tag the second will be the whole count the third will be the positive ones count.
You can use a sprite which has both version—the colored and the monochrome—stored into it.
Use 'utf8mb4' as encoding to cover all unicode (including emojis)
default: &default
adapter: mysql2
encoding: utf8mb4
collation: utf8mb4_bin
username: <%= ENV.fetch("MYSQL_USERNAME") %>
password: <%= ENV.fetch("MYSQL_PASSWORD") %>
host: <%= ENV.fetch("MYSQL_HOST") %>
(Reference1) (Reference2)
What about using the following:
int number = input.nextInt();
if (number < 0) {
// negative
} else {
// it's a positive
}
this worked like magic for me
RewriteCond %{HTTP_HOST} ^sitename.com [NC] RewriteRule ^(.*)$ https://www.sitename.com/$1 [L,R=301,NC]
i used this code to convert array to collection and back to array to remove duplicates, assembled from various posts here (sorry for not giving properly credit).
Function ArrayRemoveDups(MyArray As Variant) As Variant
Dim nFirst As Long, nLast As Long, i As Long
Dim item As Variant, outputArray() As Variant
Dim Coll As New Collection
'Get First and Last Array Positions
nFirst = LBound(MyArray)
nLast = UBound(MyArray)
ReDim arrTemp(nFirst To nLast)
i = nFirst
'convert to collection
For Each item In MyArray
skipitem = False
For Each key In Coll
If key = item Then skipitem = True
Next
If skipitem = False Then Coll.Add (item)
Next item
'convert back to array
ReDim outputArray(0 To Coll.Count - 1)
For i = 1 To Coll.Count
outputArray(i - 1) = Coll.item(i)
Next
ArrayRemoveDups = outputArray
End Function
Not sure if Access supports it, but in most engines (including SQL Server
) this is called a correlated subquery and works fine:
SELECT TypesAndBread.Type, TypesAndBread.TBName,
(
SELECT Count(Sandwiches.[SandwichID]) As SandwichCount
FROM Sandwiches
WHERE (Type = 'Sandwich Type' AND Sandwiches.Type = TypesAndBread.TBName)
OR (Type = 'Bread' AND Sandwiches.Bread = TypesAndBread.TBName)
) As SandwichCount
FROM TypesAndBread
This can be made more efficient by indexing Type
and Bread
and distributing the subqueries over the UNION
:
SELECT [Sandwiches Types].[Sandwich Type] As TBName, "Sandwich Type" As Type,
(
SELECT COUNT(*) As SandwichCount
FROM Sandwiches
WHERE Sandwiches.Type = [Sandwiches Types].[Sandwich Type]
)
FROM [Sandwiches Types]
UNION ALL
SELECT [Breads].[Bread] As TBName, "Bread" As Type,
(
SELECT COUNT(*) As SandwichCount
FROM Sandwiches
WHERE Sandwiches.Bread = [Breads].[Bread]
)
FROM [Breads]
To know the list of java running on the linux machine. ps -e | grep java
Your regex says the following:
/^ - if the line starts with
( - start a capture group
Clinton| - "Clinton"
| - or
[^Bush] - Any single character except "B", "u", "s" or "h"
| - or
Reagan) - "Reagan". End capture group.
/i - Make matches case-insensitive
So, in other words, your middle part of the regex is screwing you up. As it is a "catch-all" kind of group, it will allow any line that does not begin with any of the upper or lower case letters in "Bush". For example, these lines would match your regex:
Our president, George Bush
In the news today, pigs can fly
012-3123 33
You either make a negative look-ahead, as suggested earlier, or you simply make two regexes:
if( ($string =~ m/^(Clinton|Reagan)/i) and
($string !~ m/^Bush/i) ) {
print "$string\n";
}
As mirod has pointed out in the comments, the second check is quite unnecessary when using the caret (^
) to match only beginning of lines, as lines that begin with "Clinton" or "Reagan" could never begin with "Bush".
However, it would be valid without the carets.
if you want to flip image you can use it.
.image{
width: 100%;
-webkit-animation:spin 3s linear infinite;
-moz-animation:spin 3s linear infinite;
animation:spin 3s linear infinite;
}
@-moz-keyframes spin { 50% { -moz-transform: rotateY(90deg); } }
@-webkit-keyframes spin { 50% { -webkit-transform: rotateY(90deg); } }
@keyframes spin { 50% { -webkit-transform: rotateY(90deg); transform:rotateY(90deg); } }
This should be quite fast
function splitOnFirst (str, sep) {
const index = str.indexOf(sep);
return index < 0 ? [str] : [str.slice(0, index), str.slice(index + sep.length)];
}
Instant.now()
The troublesome old date-time classes bundled with the earliest versions of Java have been supplanted by the java.time classes built into Java 8 and later. See Oracle Tutorial. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
Instant
An Instant
represents a moment on the timeline in UTC with a resolution of up to nanoseconds.
Instant instant = Instant.now();
The toString
method generates a String object with text representing the date-time value using one of the standard ISO 8601 formats.
String output = instant.toString();
2016-06-27T19:15:25.864Z
The Instant
class is a basic building-block class in java.time. This should be your go-to class when handling date-time as generally the best practice is to track, store, and exchange date-time values in UTC.
OffsetDateTime
But Instant
has limitations such as no formatting options for generating strings in alternate formats. For more flexibility, convert from Instant
to OffsetDateTime
. Specify an offset-from-UTC. In java.time that means a ZoneOffset
object. Here we want to stick with UTC (+00) so we can use the convenient constant ZoneOffset.UTC
.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
2016-06-27T19:15:25.864Z
Or skip the Instant
class.
OffsetDateTime.now( ZoneOffset.UTC )
Now with an OffsetDateTime
object in hand, you can use DateTimeFormatter
to create String objects with text in alternate formats. Search Stack Overflow for many examples of using DateTimeFormatter
.
ZonedDateTime
When you want to display wall-clock time for some particular time zone, apply a ZoneId
to get a ZonedDateTime
.
In this example we apply Montréal time zone. In the summer, under Daylight Saving Time (DST) nonsense, the zone has an offset of -04:00
. So note how the time-of-day is four hours earlier in the output, 15
instead of 19
hours. Instant
and the ZonedDateTime
both represent the very same simultaneous moment, just viewed through two different lenses.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
2016-06-27T15:15:25.864-04:00[America/Montreal]
While you should avoid the old date-time classes, if you must you can convert using new methods added to the old classes. Here we use java.util.Date.from( Instant )
and java.util.Date::toInstant
.
java.util.Date utilDate = java.util.Date.from( instant );
And going the other direction.
Instant instant= utilDate.toInstant();
Similarly, look for new methods added to GregorianCalendar
(subclass of Calendar
) to convert to and from java.time.ZonedDateTime
.
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Here is another quick approach without using additional panel.
JFrame f = new JFrame("stackoverflow") {
private Image backgroundImage = ImageIO.read(new File("background.jpg"));
public void paint( Graphics g ) {
super.paint(g);
g.drawImage(backgroundImage, 0, 0, null);
}
};
You can use java.util.Calendar class to get time in milliseconds. Example:
Calendar cal = Calendar.getInstance();
int milliSec = cal.get(Calendar.MILLISECOND);
// print milliSec
java.util.Date date = cal.getTime();
System.out.println("Output: " + new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss:SSS").format(date));
The main alternative is:
Another alternative worth checking out:
I think you want to specify
-H "Content-Type:text/xml"
with a colon, not an equals.
I have a file "cost.ini" on the root of my class path. My JAR file is named "cost.jar".
The following code:
try {
//JDK11: replace "UTF-8" with UTF_8 and remove try-catch
String rootPath = decode(getSystemResource("cost.ini").getPath()
.replaceAll("(cost\\.jar!/)?cost\\.ini$|^(file\\:)?/", ""), "UTF-8");
showMessageDialog(null, rootPath, "rootpath", WARNING_MESSAGE);
} catch(UnsupportedEncodingException e) {}
Path returned from .getPath()
has the format:
file:/C:/folder1/folder2/cost.jar!/cost.ini
/C:/folder1/folder2/cost.ini
Every use of File
, leads on exception, if the application provided in JAR format.
How about list.Find(x => x.Name == "height").Value = 20;
This works fine. I know its an old post, but just wondered why hasn't anyone suggested this? Is there a drawback in this code?
I wanted to run my server online and not under localhost / 127.0.0.1 and had the forbidden message. I am running the WAMP 2.2 server (Apache 2.4.2 / PHP 5.4.3 / MySQL 5.5.24) on Windows 7 64 bit. What worked for me is the following:
httpd.conf
Again, it worked for me and from this thread I understand that there are many cases in which you may get the above error message so if mine does not work, try other solutions.
Good luck.
(I hope it helps someone like it helped me. I did not find any one of the solutions above working for me.)
it's 2021 and here's a fantastically easy plugin to upload anything:
https://pqina.nl/filepond/?ref=pqina
add your element:
<input type="file"
class="filepond"
name="filepond"
multiple
data-allow-reorder="true"
data-max-file-size="3MB"
data-max-files="3">
Register any additional plugins:
FilePond.registerPlugin(
FilePondPluginImagePreview,
FilePondPluginImageExifOrientation,
FilePondPluginFileValidateSize,
FilePondPluginImageEdit);
Then wire in the element:
// Select the file input and use
// create() to turn it into a pond
FilePond.create(
document.querySelector('input'),
// Use Doka.js as image editor
imageEditEditor: Doka.create({
utils: ['crop', 'filter', 'color']
})
);
I use this with the additional Doka image editor to upload and transform images at https://www.yoodu.co.uk
crazy simple to setup and the guys who run it are great at support.
As you can tell I'm a fanboy.
To elevate what jocull mentioned in a comment, I was doing everything mention in this thread and striking out... because mine was in a loop to be run over and over; after the first time through the loop, it would sometimes fail. Always worked the first time through the loop.
To be clear: the loop includes the creation of SmtpClient, and then doing .Send with the right data. The SmtpClient was created inside a try/catch block, to catch errors and to be sure the object got destroyed before the bottom of the loop.
In my case, the solution was to make sure that SmtpClient was disposed after each time in the loop (either via using() statement or by doing a manual dispose). Even if the SmtpClient object is being implicitly destroyed in the loop, .NET appears to be leaving stuff lying around to conflict with the next attempt.
If you know that the dropdownlist contains the value you're looking to select, use:
ddl.SelectedValue = "2";
If you're not sure if the value exists, use (or you'll get a null reference exception):
ListItem selectedListItem = ddl.Items.FindByValue("2");
if (selectedListItem != null)
{
selectedListItem.Selected = true;
}
just add static keyword at the starting of the function return type.. and then you can access the member function of the class without object:) for ex:
static void Name_pairs::read_names()
{
cout << "Enter name: ";
cin >> name;
names.push_back(name);
cout << endl;
}
Try as follows the return must be d, not d.data
ajax: {
"url": "xx/xxx/xxx",
"type": "GET",
"error": function (e) {
},
"dataSrc": function (d) {
return d
}
},
e.printStackTrace equivalent in python
In Java, this does the following (docs):
public void printStackTrace()
Prints this throwable and its backtrace to the standard error stream...
This is used like this:
try
{
// code that may raise an error
}
catch (IOException e)
{
// exception handling
e.printStackTrace();
}
In Java, the Standard Error stream is unbuffered so that output arrives immediately.
import traceback
import sys
try: # code that may raise an error
pass
except IOError as e: # exception handling
# in Python 2, stderr is also unbuffered
print >> sys.stderr, traceback.format_exc()
# in Python 2, you can also from __future__ import print_function
print(traceback.format_exc(), file=sys.stderr)
# or as the top answer here demonstrates, use:
traceback.print_exc()
# which also uses stderr.
In Python 3, we can get the traceback directly from the exception object (which likely behaves better for threaded code). Also, stderr is line-buffered, but the print function gets a flush argument, so this would be immediately printed to stderr:
print(traceback.format_exception(None, # <- type(e) by docs, but ignored
e, e.__traceback__),
file=sys.stderr, flush=True)
Conclusion:
In Python 3, therefore, traceback.print_exc()
, although it uses sys.stderr
by default, would buffer the output, and you may possibly lose it. So to get as equivalent semantics as possible, in Python 3, use print
with flush=True
.
So, when you are doing some JavaScript things with an <a />
tag and if you put href="#"
as well, you can add return false at the end of the event (in case of inline event binding) like:
<a href="#" onclick="myJsFunc(); return false;">Run JavaScript Code</a>
Or you can change the href attribute with JavaScript like:
<a href="javascript://" onclick="myJsFunc();">Run JavaScript Code</a>
or
<a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a>
But semantically, all the above ways to achieve this are wrong (it works fine though). If any element is not created to navigate the page and that have some JavaScript things associated with it, then it should not be a <a>
tag.
You can simply use a <button />
instead to do things or any other element like b, span or whatever fits there as per your need, because you are allowed to add events on all the elements.
So, there is one benefit to use <a href="#">
. You get the cursor pointer by default on that element when you do a href="#"
. For that, I think you can use CSS for this like cursor:pointer;
which solves this problem also.
And at the end, if you are binding the event from the JavaScript code itself, there you can do event.preventDefault()
to achieve this if you are using <a>
tag, but if you are not using a <a>
tag for this, there you get an advantage, you don't need to do this.
So, if you see, it's better not to use a tag for this kind of stuff.
Beside using loop and for comprehension, you could also use map
lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
mylst = map(lambda each:each.strip("8"), lst)
print mylst
Going with Marcel's solution above to secure Forms Authentication cookie you should also update "authentication" config element to use SSL
<authentication mode="Forms">
<forms ... requireSSL="true" />
</authentication>
Other wise authentication cookie will not be https
See: http://msdn.microsoft.com/en-us/library/vstudio/1d3t3c61(v=vs.100).aspx
To update other branches like (backup) with your master branch copy. You can do follow either way (rebase or merge)...
Merge branches (there will be an extra commit automatically to the backup branch).
Note : Rebase is nothing but establishing a new base (a new copy)
git checkout backup git merge master git push
(Repeat for other branches if any like backup2 & etc..,)
git checkout backup git rebase master git push
(Repeat for other branches if any like backup2 & etc..,)
The answer was posted above but wasn't complete. here is the completed version:
XAML
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="MapTest.Window1"
x:Name="Window"
Title="Window1"
Width="1950" Height="1546" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:Controls="clr-namespace:WPFExtensions.Controls;assembly=WPFExtensions" mc:Ignorable="d" Background="#FF000000">
<Grid x:Name="LayoutRoot">
<Grid.RowDefinitions>
<RowDefinition Height="52.92"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Border Grid.Row="1" Name="border">
<Image Name="image" Source="map3-2.png" Opacity="1" RenderTransformOrigin="0.5,0.5" />
</Border>
</Grid>
Code Behind
using System.Linq;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
namespace MapTest
{
public partial class Window1 : Window
{
private Point origin;
private Point start;
public Window1()
{
InitializeComponent();
TransformGroup group = new TransformGroup();
ScaleTransform xform = new ScaleTransform();
group.Children.Add(xform);
TranslateTransform tt = new TranslateTransform();
group.Children.Add(tt);
image.RenderTransform = group;
image.MouseWheel += image_MouseWheel;
image.MouseLeftButtonDown += image_MouseLeftButtonDown;
image.MouseLeftButtonUp += image_MouseLeftButtonUp;
image.MouseMove += image_MouseMove;
}
private void image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
image.ReleaseMouseCapture();
}
private void image_MouseMove(object sender, MouseEventArgs e)
{
if (!image.IsMouseCaptured) return;
var tt = (TranslateTransform) ((TransformGroup) image.RenderTransform).Children.First(tr => tr is TranslateTransform);
Vector v = start - e.GetPosition(border);
tt.X = origin.X - v.X;
tt.Y = origin.Y - v.Y;
}
private void image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
image.CaptureMouse();
var tt = (TranslateTransform) ((TransformGroup) image.RenderTransform).Children.First(tr => tr is TranslateTransform);
start = e.GetPosition(border);
origin = new Point(tt.X, tt.Y);
}
private void image_MouseWheel(object sender, MouseWheelEventArgs e)
{
TransformGroup transformGroup = (TransformGroup) image.RenderTransform;
ScaleTransform transform = (ScaleTransform) transformGroup.Children[0];
double zoom = e.Delta > 0 ? .2 : -.2;
transform.ScaleX += zoom;
transform.ScaleY += zoom;
}
}
}
I have an example of a full wpf project using this code on my website: Jot the sticky note app.
Personally I don't use final on method parameters, because it adds too much clutter to parameter lists. I prefer to enforce that method parameters are not changed through something like Checkstyle.
For local variables I use final whenever possible, I even let Eclipse do that automatically in my setup for personal projects.
I would certainly like something stronger like C/C++ const.
If the performance is an issue, you can use this command in MS_DOS:
dir /OD >d:\dir.txt
This command generate a dir.txt file in **d:** root the have all files sorted by date. And then read the file from your code. Also, you add other filters by * and ?.
List<Person> roster = ...;
Map<String, Person> map =
roster
.stream()
.collect(
Collectors.toMap(p -> p.getLast(), p -> p)
);
that would be the translation, but i havent run this or used the API. most likely you can substitute p -> p, for Function.identity(). and statically import toMap(...)
Are you using platform.system
?
system() Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'. An empty string is returned if the value cannot be determined.
If that isn't working, maybe try platform.win32_ver
and if it doesn't raise an exception, you're on Windows; but I don't know if that's forward compatible to 64-bit, since it has 32 in the name.
win32_ver(release='', version='', csd='', ptype='') Get additional version information from the Windows Registry and return a tuple (version,csd,ptype) referring to version number, CSD level and OS type (multi/single processor).
But os.name
is probably the way to go, as others have mentioned.
if sys.platform == 'win32':
#---------
if os.environ.get('OS','') == 'Windows_NT':
#---------
try: import win32api
#---------
# Emulation using _winreg (added in Python 2.0) and
# sys.getwindowsversion() (added in Python 2.3)
import _winreg
GetVersionEx = sys.getwindowsversion
#----------
def system():
""" Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.
An empty string is returned if the value cannot be determined.
"""
return uname()[0]
string result = arr.Aggregate("", (s, i) => s + i.ToString());
(Disclaimer: If you have a lot of digits (hundreds, at least) and you care about performance, I suggest eschewing this method and using a StringBuilder
, as in JaredPar's answer.)
Using a modern browser, which supports EcmaScript 2015 (ES6), you can enjoy Template Strings. Instead of formatting, you can directly inject the variable value into it:
var name = "Waleed";
var message = `Hello ${name}!`;
Note the template string has to be written using back-ticks (`).
On Windows there is an experimental build that does this, as described on the mailing list, Filter by local process name
Go to [Tools, Options], section "Web Forms Designer" and enable the option "Enable Web Forms Designer". That should give you the Design and Split option again.
<Switch android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:thumb="@drawable/custom_switch_inner_holo_light"
android:track="@drawable/custom_switch_track_holo_light"
android:textOn="@string/yes"
android:textOff="@string/no"/>
drawable/custom_switch_inner_holo_light.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@drawable/custom_switch_thumb_disabled_holo_light" />
<item android:state_pressed="true" android:drawable="@drawable/custom_switch_thumb_pressed_holo_light" />
<item android:state_checked="true" android:drawable="@drawable/custom_switch_thumb_activated_holo_light" />
<item android:drawable="@drawable/custom_switch_thumb_holo_light" />
</selector>
drawable/custom_switch_track_holo_light.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:drawable="@drawable/custom_switch_bg_focused_holo_light" />
<item android:drawable="@drawable/custom_switch_bg_holo_light" />
</selector>
Next images are 9.paths drawables and they must be in different density (mdpi, hdpi, xhdpi, xxhdpi). As example I give xxhdpi (you can resize they if u needed):
drawable/custom_switch_thumb_disabled_holo_light
drawable/custom_switch_thumb_pressed_holo_light
drawable/custom_switch_thumb_activated_holo_light
drawable/custom_switch_thumb_holo_light
drawable/custom_switch_bg_focused_holo_light
drawable/custom_switch_bg_holo_light
Just created my own "plugin" for solving this and it works really well:
adBuddy + jsBuddy:
I added mobile compatibility and jsBlocking detection among other things... (Like an overlay that is shown to the users asking them to disable the adBlocking/jsBlocking software); Also made it responsive friendly.
It's opensourced under the Coffeeware License.
This is an example to read and write binary jjpg or wmv video file. FILE *fout; FILE *fin;
Int ch;
char *s;
fin=fopen("D:\\pic.jpg","rb");
if(fin==NULL)
{ printf("\n Unable to open the file ");
exit(1);
}
fout=fopen("D:\\ newpic.jpg","wb");
ch=fgetc(fin);
while (ch!=EOF)
{
s=(char *)ch;
printf("%c",s);
ch=fgetc (fin):
fputc(s,fout);
s++;
}
printf("data read and copied");
fclose(fin);
fclose(fout);
Visual Studio Extension
Right Click Solution - Select "Delete bin and obj folders"
If you use the Geolocation API, it would be as simple as using the following code.
navigator.geolocation.getCurrentPosition(function(location) {
console.log(location.coords.latitude);
console.log(location.coords.longitude);
console.log(location.coords.accuracy);
});
You may also be able to use Google's Client Location API.
This issue has been discussed in Is it possible to detect a mobile browser's GPS location? and Get position data from mobile browser. You can find more information there.
I'm using simple alias to create pull request,
alias pr='open -n -a "Google Chrome" --args "https://github.com/user/repo/compare/pre-master...nawarkhede:$(git_current_branch)\?expand\=1"'
Sometimes Get specific version
even checking both checkboxes won't get you the latest file. You've probably made a change to a file, and want to undo those changes by re-getting the latest version. Well... that's what Undo pending changes
is for and not the purpose of Get specific version
.
If in doubt:
And this one's my favorite that I just discovered :
keep an eye out in the the Output
window for messages such as this :
Warning - Unable to refresh R:\TFS-PROJECTS\www.example.com\ExampleMVC\Example MVC\Example MVC.csproj because you have a pending edit.
This critical message appears in the output window. No other notifications!
Nothing in pending changes and no other dialog message telling you that the file you just requested explicitly was not retrieved! And yes - you resolve this by just running Undo pending changes
and getting the file.
Server Objects---> linked server ---> new linked server
In linked server write server name or IP address for other server and choose SQL Server In Security select (be made using this security context ) Write login and password for other server
Now connected then use
Select * from [server name or ip addresses ].databasename.dbo.tblname
try your task using IN condition or OR condition and also this query is working on spark-1.6.x
SELECT patient, patient_id FROM `patient` WHERE patient IN ('User4', 'User3');
or
SELECT patient, patient_id FROM `patient` WHERE patient = 'User1' OR patient = 'User2';
You should try using maven failsafe plugin. You can tell it to include a certain set of tests.
The header <math.h>
is a C std lib header. It defines a lot of stuff in the global namespace. The header <cmath>
is the C++ version of that header. It defines essentially the same stuff in namespace std
. (There are some differences, like that the C++ version comes with overloads of some functions, but that doesn't matter.) The header <cmath.h>
doesn't exist.
Since vendors don't want to maintain two versions of what is essentially the same header, they came up with different possibilities to have only one of them behind the scenes. Often, that's the C header (since a C++ compiler is able to parse that, while the opposite won't work), and the C++ header just includes that and pulls everything into namespace std
. Or there's some macro magic for parsing the same header with or without namespace std
wrapped around it or not. To this add that in some environments it's awkward if headers don't have a file extension (like editors failing to highlight the code etc.). So some vendors would have <cmath>
be a one-liner including some other header with a .h
extension. Or some would map all includes matching <cblah>
to <blah.h>
(which, through macro magic, becomes the C++ header when __cplusplus
is defined, and otherwise becomes the C header) or <cblah.h>
or whatever.
That's the reason why on some platforms including things like <cmath.h>
, which ought not to exist, will initially succeed, although it might make the compiler fail spectacularly later on.
I have no idea which std lib implementation you use. I suppose it's the one that comes with GCC, but this I don't know, so I cannot explain exactly what happened in your case. But it's certainly a mix of one of the above vendor-specific hacks and you including a header you ought not to have included yourself. Maybe it's the one where <cmath>
maps to <cmath.h>
with a specific (set of) macro(s) which you hadn't defined, so that you ended up with both definitions.
Note, however, that this code still ought not to compile:
#include <cmath>
double f(double d)
{
return abs(d);
}
There shouldn't be an abs()
in the global namespace (it's std::abs()
). However, as per the above described implementation tricks, there might well be. Porting such code later (or just trying to compile it with your vendor's next version which doesn't allow this) can be very tedious, so you should keep an eye on this.
But the thing is that the .chapter class is not dynamic you're declaring a height:1200px
so it's better to use background:cover and set with media queries specific height's for popular resolutions.
First install express and http-proxy-middleware
npm install express http-proxy-middleware --save
Then in your server.js
const express = require('express');
const proxy = require('http-proxy-middleware');
const app = express();
app.use(express.static('client'));
// Add middleware for http proxying
const apiProxy = proxy('/api', { target: 'http://localhost:8080' });
app.use('/api', apiProxy);
// Render your site
const renderIndex = (req, res) => {
res.sendFile(path.resolve(__dirname, 'client/index.html'));
}
app.get('/*', renderIndex);
app.listen(3000, () => {
console.log('Listening on: http://localhost:3000');
});
In this example we serve the site on port 3000, but when a request end with /api we redirect it to localhost:8080.
http://localhost:3000/api/login redirect to http://localhost:8080/api/login
#!/bin/bash
echo "The number of arguments is: $#"
a=${@}
echo "The total length of all arguments is: ${#a}: "
count=0
for var in "$@"
do
echo "The length of argument '$var' is: ${#var}"
(( count++ ))
(( accum += ${#var} ))
done
echo "The counted number of arguments is: $count"
echo "The accumulated length of all arguments is: $accum"
You can either use the answer from the duplicate link pointed by nvm.
Or you can resolve conflicts by using their changes (but some of your changes might be kept if they don't conflict with remote version):
git pull -s recursive -X theirs
I did some test to see how the theory actually works: kennethxu.blogspot.com/2009/05/interlocked-vs-monitor-performance.html. My test was more focused on CompareExchnage but the result for Increment is similar. Interlocked is not necessary faster in multi-cpu environment. Here is the test result for Increment on a 2 years old 16 CPU server. Bare in mind that the test also involves the safe read after increase, which is typical in real world.
D:\>InterlockVsMonitor.exe 16
Using 16 threads:
InterlockAtomic.RunIncrement (ns): 8355 Average, 8302 Minimal, 8409 Maxmial
MonitorVolatileAtomic.RunIncrement (ns): 7077 Average, 6843 Minimal, 7243 Maxmial
D:\>InterlockVsMonitor.exe 4
Using 4 threads:
InterlockAtomic.RunIncrement (ns): 4319 Average, 4319 Minimal, 4321 Maxmial
MonitorVolatileAtomic.RunIncrement (ns): 933 Average, 802 Minimal, 1018 Maxmial
I did this:
$('#myModal').on 'shown.bs.modal', (e) ->
$(e.target).find('.modal-body').load('http://yourserver.com/content')
Also look up ArrayAdapter interface:
ArrayAdapter(Context context, int textViewResourceId, List<T> objects)
Modules are by no means deprecated and are used heavily in the VB language. It's the only way for instance to implement an extension method in VB.Net.
There is one huge difference between Modules and Classes with Static Members. Any method defined on a Module is globally accessible as long as the Module is available in the current namespace. In effect a Module allows you to define global methods. This is something that a class with only shared members cannot do.
Here's a quick example that I use a lot when writing VB code that interops with raw COM interfaces.
Module Interop
Public Function Succeeded(ByVal hr as Integer) As Boolean
...
End Function
Public Function Failed(ByVal hr As Integer) As Boolean
...
End Function
End Module
Class SomeClass
Sub Foo()
Dim hr = CallSomeHrMethod()
if Succeeded(hr) then
..
End If
End Sub
End Class
In case you were looking to transform your column number into a letter:
Function ConvertToLetter(iCol As Integer) As String
Dim iAlpha As Integer
Dim iRemainder As Integer
iAlpha = Int(iCol / 27)
iRemainder = iCol - (iAlpha * 26)
If iAlpha > 0 Then
ConvertToLetter = Chr(iAlpha + 64)
End If
If iRemainder > 0 Then
ConvertToLetter = ConvertToLetter & Chr(iRemainder + 64)
End If
End Function
This way you could do something like this:
Function selectColumnRange(colNum As Integer, targetWorksheet As Worksheet)
Dim colLetter As String
Dim testRange As Range
colLetter = ConvertToLetter(colNum)
testRange = targetWorksheet.Range(colLetter & ":" & colLetter).Select
End Function
That example function would select the entire column ( i.e. Range("A:A").Select)
I had the same issues but nothing worked. What I did was I added this to the selector:
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
If you have the correct headers defined & are using a non GlibC
library (such as Musl C) gcc
will also throw error: implicit declaration of function
when GNU extensions such as malloc_trim
are encountered.
The solution is to wrap the extension & the header:
#if defined (__GLIBC__)
malloc_trim(0);
#endif
How about something like this?
<input name="myvalue" type="text" onfocus="if(this.value=='enter value')this.value='';" onblur="if(this.value=='')this.value='enter value';">
This will clear upon focusing the first time, but then won't clear on subsequent focuses after the user enters their value, when left blank it restores the given value.
Xcode 11.4 does not support the new iOS 13.5. Updating to Xcode 11.5 fixed the issue for me
https://developer.apple.com/documentation/xcode_release_notes/xcode_11_4_release_notes
Known Issues Xcode 11.4 doesn’t work with devices running iOS 13.4 beta 1 and beta 2. (60055806)
Inspired by answers of Lance Rushing and Simon_Weaver, this is my favourite solution.
$('#myForm').submit( function( event ) {
var values = $(this).serializeArray();
// In my case, I need to fetch these data before custom actions
event.preventDefault();
});
The output is an array of objects, e.g.
[{name: "start-time", value: "11:01"}, {name: "end-time", value: "11:11"}]
With the code below,
var inputs = {};
$.each(values, function(k, v){
inputs[v.name]= v.value;
});
its final output would be
{"start-time":"11:01", "end-time":"11:01"}
Git accepts kdiff3, tkdiff, meld, xxdiff, emerge, vimdiff, gvimdiff, ecmerge,
and opendiff as valid diff tools. You can also set up a custom tool.
git config --global diff.tool vimdiff
git config --global diff.tool kdiff3
git config --global diff.tool meld
git config --global diff.tool xxdiff
git config --global diff.tool emerge
git config --global diff.tool gvimdiff
git config --global diff.tool ecmerge
Nice you gave me something to play around with
Run
class Sample extends Creator {
}
$a = new Sample ();
$a->role->rolename = 'test';
echo $a->role->rolename , PHP_EOL;
$a->role->rolename->am->love->php = 'w00';
echo $a->role->rolename , PHP_EOL;
echo $a->role->rolename->am->love->php , PHP_EOL;
Output
test
test
w00
Class Used
abstract class Creator {
public function __get($name) {
if (! isset ( $this->{$name} )) {
$this->{$name} = new Value ( $name, null );
}
return $this->{$name};
}
public function __set($name, $value) {
$this->{$name} = new Value ( $name, $value );
}
}
class Value extends Creator {
private $name;
private $value;
function __construct($name, $value) {
$this->name = $name;
$this->value = $value;
}
function __toString()
{
return (string) $this->value ;
}
}
class Sample extends Creator {
}
$a = new Sample ();
$a->role = array (
"A",
"B",
"C"
);
$a->role[0]->nice = "OK" ;
print ($a->role[0]->nice . PHP_EOL);
$a->role[1]->nice->ok = array("foo","bar","die");
print ($a->role[1]->nice->ok[2] . PHP_EOL);
$a->role[2]->nice->raw = new stdClass();
$a->role[2]->nice->raw->name = "baba" ;
print ($a->role[2]->nice->raw->name. PHP_EOL);
Output
Ok die baba
Modified Class
abstract class Creator {
public function __get($name) {
if (! isset ( $this->{$name} )) {
$this->{$name} = new Value ( $name, null );
}
return $this->{$name};
}
public function __set($name, $value) {
if (is_array ( $value )) {
array_walk ( $value, function (&$item, $key) {
$item = new Value ( $key, $item );
} );
}
$this->{$name} = $value;
}
}
class Value {
private $name ;
function __construct($name, $value) {
$this->{$name} = $value;
$this->name = $value ;
}
public function __get($name) {
if (! isset ( $this->{$name} )) {
$this->{$name} = new Value ( $name, null );
}
if ($name == $this->name) {
return $this->value;
}
return $this->{$name};
}
public function __set($name, $value) {
if (is_array ( $value )) {
array_walk ( $value, function (&$item, $key) {
$item = new Value ( $key, $item );
} );
}
$this->{$name} = $value;
}
public function __toString() {
return (string) $this->name ;
}
}
RoboSpice Vs. Volley
From https://groups.google.com/forum/#!topic/robospice/QwVCfY_glOQ
I see this being possible using either some regex, or a few substr calls (assuming the input is always of that format, and doesn't change length etc.)
something like
$in = "+11234567890"; $output = substr($in,2,3)."-".substr($in,6,3)."-".substr($in,10,4);
should do it.
Note and update:
Since Git1.7.4 (January 2011), you have git merge --abort
, synonymous to "git reset --merge
" when a merge is in progress.
But if you want to complete the merge, while somehow nothing remains to be added, then a crude rm -rf .git/MERGE*
can be enough for Git to forget about the current merge.
just use this as a middleware
<?php
namespace App\Http\Middleware;
use Closure;
class CorsMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$response->header('Access-Control-Allow-Origin', '*');
$response->header('Access-Control-Allow-Methods', '*');
return $response;
}
}
and register the middleware in your kernel file on this path app/Http/Kernel.php
in which group that you prefer and everything will be fine
input.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n")
This will work if the input contains only one type of line breaks - either CR, or LF, or CR+LF.
This answer was written in 2010. The API it uses has since been retired. It is kept for historical interest only.
Search for it.
Make sure include_entities
is set to true to get hashtag results. See Tweet Entities
Returns 5 mixed results with Twitter.com user IDs plus entities for the term "blue angels":
GET http://search.twitter.com/search.json?q=blue%20angels&rpp=5&include_entities=true&with_twitter_user_id=true&result_type=mixed
You have to replace string line
QString line = in.readLine();
into while:
QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
QMessageBox::information(0, "error", file.errorString());
}
QTextStream in(&file);
while(!in.atEnd()) {
QString line = in.readLine();
QStringList fields = line.split(",");
model->appendRow(fields);
}
file.close();
First off, your trigger as you already see is going to update every record in the table. There is no filtering done to accomplish jus the rows changed.
Secondly, you're assuming that only one row changes in the batch which is incorrect as multiple rows could change.
The way to do this properly is to use the virtual inserted and deleted tables: http://msdn.microsoft.com/en-us/library/ms191300.aspx
In case of gray image, I am using this function and it works fine! however you must take care about the function features ;)
CvMat * src= cvCreateMat(300,300,CV_32FC1);
IplImage *dist= cvCreateImage(cvGetSize(dist),IPL_DEPTH_32F,3);
cvConvertScale(src, dist, 1, 0);
You might look into jwht-scrapper!
This is a complete scrapping framework that has all the features a developper could expect from a web scrapper:
It works with (jwht-htmltopojo)[https://github.com/whimtrip/jwht-htmltopojo) lib which itsef uses Jsoup mentionned by several other people here.
Together they will help you built awesome scrappers mapping directly HTML to POJOs and bypassing any classical scrapping problems in only a matter of minutes!
Hope this might help some people here!
Disclaimer, I am the one who developed it, feel free to let me know your remarks!
try out with this fastest JSON framework JSONKit. it's faster than normal JSON framework.
This works for Python 2 & 3:
from itertools import islice
with open('/tmp/filename.txt') as inf:
for line in islice(inf, N, N+M):
print(line)
This is how I do it using Google Gson. I am not sure, if there are a simpler way to do this.( with or without an external library).
Type collectionType = new TypeToken<List<Class>>() {
} // end new
.getType();
String gsonString =
new Gson().toJson(objList, collectionType);
the bottom cell will grow as you enter more text ... setting the table width will help too
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<table id="content" style="min-height:525px; height:525px; width:100%; border:0px; margin:0; padding:0; border-collapse:collapse;">
<tr><td style="height:10px; background-color:#900;">Upper</td></tr>
<tr><td style="min-height:515px; height:515px; background-color:#909;">lower<br/>
</td></tr>
</table>
</body>
</html>
It is not possible to redirect a POST somewhere else. When you have POSTED the request, the browser will get a response from the server and then the POST is done. Everything after that is a new request. When you specify a location header in there the browser will always use the GET method to fetch the next page.
You could use some Ajax to submit the form in background. That way your form values stay intact. If the server accepts, you can still redirect to some other page. If the server does not accept, then you can display an error message, let the user correct the input and send it again.
You can try one even more simple:
<option value="1" ${item.quantity == 1 ? "selected" : ""}>1</option>
Selected answer works for one drop down menu only. For multiple solution would be:
$('body').click(function(event){
$dropdowns.not($dropdowns.has(event.target)).hide();
});
SELECT
GROUP_CONCAT(DISTINCT (category))
FROM (
SELECT
SUBSTRING_INDEX(SUBSTRING_INDEX(tableName.categories, ' ', numbers.n), ' ', -1) category
FROM
numbers INNER JOIN tableName
ON LENGTH(tableName.categories)>=LENGTH(REPLACE(tableName.categories, ' ', ''))+numbers.n-1
) s;
This will return distinct values like: test1,test2,test4,test3
CTRL + H is actually the right answer, but the scope in which it was pressed is actually pretty important. When you have last clicked on file you're working on, you'll get a different search window - Java Search:
Whereas when you select directory on Package Explorer and then press Ctrl + H (or choose Search -> File..
from main menu), you get the desired window - File Search:
With a small change of the markup, here's my approach (I've just inserted a span
inside the paragraph):
.marquee {
width: 450px;
margin: 0 auto;
overflow: hidden;
box-sizing: border-box;
}
.marquee span {
display: inline-block;
width: max-content;
padding-left: 100%;
/* show the marquee just outside the paragraph */
will-change: transform;
animation: marquee 15s linear infinite;
}
.marquee span:hover {
animation-play-state: paused
}
@keyframes marquee {
0% { transform: translate(0, 0); }
100% { transform: translate(-100%, 0); }
}
/* Respect user preferences about animations */
@media (prefers-reduced-motion: reduce) {
.marquee span {
animation-iteration-count: 1;
animation-duration: 0.01;
/* instead of animation: none, so an animationend event is
* still available, if previously attached.
*/
width: auto;
padding-left: 0;
}
}
_x000D_
<p class="marquee">
<span>
When I had journeyed half of our life's way, I found myself
within a shadowed forest, for I had lost the path that
does not stray. – (Dante Alighieri, <i>Divine Comedy</i>.
1265-1321)
</span>
</p>
_x000D_
No hardcoded values — dependent on paragraph width — have been inserted.
The animation applies the CSS3 transform
property (use prefixes where needed) so it performs well.
If you need to insert a delay just once at the beginning then also set an animation-delay
. If you need instead to insert a small delay at every loop then try to play with an higher padding-left
(e.g. 150%
)
Not Found Exceptions
Sometimes you may wish to throw an exception if a model is not found. This is particularly useful in routes or controllers. The findOrFail
and firstOrFail
methods will retrieve the first result of the query. However, if no result is found, a Illuminate\Database\Eloquent\ModelNotFoundException
will be thrown:
$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
If the exception is not caught, a 404 HTTP response is automatically sent back to the user. It is not necessary to write explicit checks to return 404 responses when using these methods:
Route::get('/api/flights/{id}', function ($id) {
return App\Flight::findOrFail($id);
});
To load your data in WebView. Call loadData() method of WebView
wv.loadData(yourData, "text/html", "UTF-8");
You can check this example
http://developer.android.com/reference/android/webkit/WebView.html
[Edit 1]
You should add -- \ -- before -- " -- for example --> name=\"spanish press\"
below string worked for me
String webData = "<!DOCTYPE html><head> <meta http-equiv=\"Content-Type\" " +
"content=\"text/html; charset=utf-8\"> <html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=windows-1250\">"+
"<meta name=\"spanish press\" content=\"spain, spanish newspaper, news,economy,politics,sports\"><title></title></head><body id=\"body\">"+
"<script src=\"http://www.myscript.com/a\"></script>slkassldkassdksasdkasskdsk</body></html>";
I tried the solutions here, and as? [String:AnyObject] worked for me:
do{
if let json = stringToParse.data(using: String.Encoding.utf8){
if let jsonData = try JSONSerialization.jsonObject(with: json, options: .allowFragments) as? [String:AnyObject]{
let id = jsonData["id"] as! String
...
}
}
}catch {
print(error.localizedDescription)
}
JBoss has an MBean called Server. That reports the build and version of JBoss itself. Once you know the version, you can see what components are involved. It is not that well cataloged, but you can see it in the release notes.
make your app force close once this will start LogCat again ...
use this for force close :D
setContentView(BIND_AUTO_CREATE);
right click you project name then open the properties windows. downgrade your Target framework version, build Solution then upgrade your Target framework version to the latest, build Solution .
You could simplify the above equations using the following:
boolean flag = sqlInt != 0;
If the int representation (sqlInt) of the boolean is 0 (false), the boolean (flag) will be false, otherwise it will be true.
Concise code is always nicer to work with :)
Other answers mention site.USER_SITE
as where Python packages get placed. If you're looking for binaries, these go in {site.USER_BASE}/bin
.
If you want to add this directory to your shell's search path, use:
export PATH="${PATH}:$(python3 -c 'import site; print(site.USER_BASE)')/bin"
some times it's happens buttons also then use below to remove the outerline
input:hover
input:active,
input:focus,
textarea:active,
textarea:hover,
textarea:focus,
button:focus,
button:active,
button:hover
{
outline:0px !important;
}
Type check also works :
if(typeof Obj.property == "undefined"){
// Assign value to the property here
Obj.property = someValue;
}
You can use this implementation that ExecutorService provides
invokeAll(Collection<? extends Callable<T>> tasks,long timeout, TimeUnit unit)
as
executor.invokeAll(Arrays.asList(task), 2 , TimeUnit.SECONDS);
However, in my case, I could not as Arrays.asList took extra 20ms.
You can also use a classic for loop:
import pandas as pd
df = pd.read_csv('your_file.csv')
count = 0
for i in df['a_column']:
count = count + 1
print(count)
Once you're logged in as postgres
, you should be able to write:
psql -t -d database_name -c $'SELECT c_defaults FROM user_info WHERE c_uid = \'testuser\';'
to print out just the value of that field, which means that you can capture it to (for example) save in a Bash variable:
testuser_defaults="$(psql -t -d database_name -c $'SELECT c_defaults FROM user_info WHERE c_uid = \'testuser\';')"
To handle the logging in as postgres
, I recommend using sudo
. You can give a specific user the permission to run
sudo -u postgres /path/to/this/script.sh
so that they can run just the one script as postgres
.
Status bar coloring is not supported in AppCompat v7:21.0.0.
From the Android developers blog post
On older platforms, AppCompat emulates the color theming where possible. At the moment this is limited to coloring the action bar and some widgets.
This means the AppCompat lib will only color status bars on Lollipop and above.
If you want to support more browsers than the CSS3 fancy, you can look at the open source library cufon javascript library
And here is the API, if you want to do more funky stuff.
Major Pro: Allows you to do what you want / need.
Major Con: Disallows text selection in some browsers, so use is appropiate on header texts (but you can use it in all your site if you want)
Just to add my two cents' worth :-) I recently learned a way of handling anonymous objects. It can only be used when targeting the .NET 4 framework and that only when adding a reference to System.Web.dll but then it's quite simple:
...
using System.Web.Routing;
...
class Program
{
static void Main(string[] args)
{
object anonymous = CallMethodThatReturnsObjectOfAnonymousType();
//WHAT DO I DO WITH THIS?
//I know! I'll use a RouteValueDictionary from System.Web.dll
RouteValueDictionary rvd = new RouteValueDictionary(anonymous);
Console.WriteLine("Hello, my name is {0} and I am a {1}", rvd["Name"], rvd["Occupation"]);
}
private static object CallMethodThatReturnsObjectOfAnonymousType()
{
return new { Id = 1, Name = "Peter Perhac", Occupation = "Software Developer" };
}
}
In order to be able to add a reference to System.Web.dll you'll have to follow rushonerok's advice : Make sure your [project's] target framework is ".NET Framework 4" not ".NET Framework 4 Client Profile".
According to git push
documentation:
git push origin HEAD
A handy way to push the current branch to the same name on the remote.
So I think what you need is git push origin HEAD
. Also it can be useful git push -u origin HEAD
to set upstream tracking information in the local branch, if you haven't already pushed to the origin.
The primary use of AtomicInteger
is when you are in a multithreaded context and you need to perform thread safe operations on an integer without using synchronized
. The assignation and retrieval on the primitive type int
are already atomic but AtomicInteger
comes with many operations which are not atomic on int
.
The simplest are the getAndXXX
or xXXAndGet
. For instance getAndIncrement()
is an atomic equivalent to i++
which is not atomic because it is actually a short cut for three operations: retrieval, addition and assignation. compareAndSet
is very useful to implements semaphores, locks, latches, etc.
Using the AtomicInteger
is faster and more readable than performing the same using synchronization.
A simple test:
public synchronized int incrementNotAtomic() {
return notAtomic++;
}
public void performTestNotAtomic() {
final long start = System.currentTimeMillis();
for (int i = 0 ; i < NUM ; i++) {
incrementNotAtomic();
}
System.out.println("Not atomic: "+(System.currentTimeMillis() - start));
}
public void performTestAtomic() {
final long start = System.currentTimeMillis();
for (int i = 0 ; i < NUM ; i++) {
atomic.getAndIncrement();
}
System.out.println("Atomic: "+(System.currentTimeMillis() - start));
}
On my PC with Java 1.6 the atomic test runs in 3 seconds while the synchronized one runs in about 5.5 seconds. The problem here is that the operation to synchronize (notAtomic++
) is really short. So the cost of the synchronization is really important compared to the operation.
Beside atomicity AtomicInteger can be use as a mutable version of Integer
for instance in Map
s as values.
Another way to use gson:
String json_String_to_print = ...
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
return gson.toJson(jp.parse(json_String_to_print));
It can be used when you don't have the bean as in susemi99's post.
Trim your String value by creating a trim function
var text = " ";
if($.trim(text.length == 0){
console.log("Text is empty");
}
else
{
console.log("Text is not empty");
}
Unless you're in a specific speed optimization process, I would say use whichever method produces the easiest to read and maintain code.
If an iterator is already setup, like with one of the collection classes, then the foreach is a good easy option. And if it's an integer range you're iterating, then for is probably cleaner.
matcher.find()
does what you needed. Example:
Pattern.compile("stores.*store.*product").matcher(someString).find();
You should probably re-write the script to return a value rather than output it. Instead of:
a=$( script.sh ) # Now a is a string, either "success" or "Failed"
case "$a" in
success) echo script succeeded;;
Failed) echo script failed;;
esac
you would be able to do:
if script.sh > /dev/null; then
echo script succeeded
else
echo script failed
fi
It is much simpler for other programs to work with you script if they do not have to parse the output. This is a simple change to make. Just exit 0
instead of printing success
, and exit 1
instead of printing Failed
. Of course, you can also print those values as well as exiting with a reasonable return value, so that wrapper scripts have flexibility in how they work with the script.
You could use this line to write to Output Window of the Visual Studio:
System.Diagnostics.Debug.WriteLine("Matrix has you...");
Must run in Debug mode.
I got the same error, when I was trying to import matplotlib.pyplot
In [1]: import matplotlib.pyplot as plt
...
...
ImportError: No module named PyQt4.QtCore
But in my case the problem was due to a missing linux library libGL.so.1
OS : Cent OS 64 bit
Python version : 3.5.2
$> locate libGL.so.1
If this command returns a value, your problem could be different, so please ignore my answer. If it does not return any value and your environment is same as mine, below steps would fix your problem.
$> yum install mesa-libGL.x86_64
This installs the necessary OpenGL libraries for 64 bit Cent OS.
$> locate libGL.so.1
/usr/lib/libGL.so.1
Now go back to iPython and try to import
In [1]: import matplotlib.pyplot as plt
This time it imported successfully.
Found a good explanation with solutions: https://vcfvct.wordpress.com/2016/12/15/spring-nested-transactional-rollback-only/
1) remove the @Transacional from the nested method if it does not really require transaction control. So even it has exception, it just bubbles up and does not affect transactional stuff.
OR:
2) if nested method does need transaction control, make it as REQUIRE_NEW for the propagation policy that way even if throws exception and marked as rollback only, the caller will not be affected.
Modify the background image of the <td> itself.
Or apply some css to the div:
.thatSetsABackgroundWithAnIcon{
height:100%;
}
Well by studying the code above a bit (specifically using TextTestRunner
and defaultTestLoader
), I was able to get pretty close. Eventually I fixed my code by also just passing all test suites to a single suites constructor, rather than adding them "manually", which fixed my other problems. So here is my solution.
import glob
import unittest
test_files = glob.glob('test_*.py')
module_strings = [test_file[0:len(test_file)-3] for test_file in test_files]
suites = [unittest.defaultTestLoader.loadTestsFromName(test_file) for test_file in module_strings]
test_suite = unittest.TestSuite(suites)
test_runner = unittest.TextTestRunner().run(test_suite)
Yeah, it is probably easier to just use nose than to do this, but that is besides the point.
The basic difference between UNION and UNION ALL is union operation eliminates the duplicated rows from the result set but union all returns all rows after joining.
from http://zengin.wordpress.com/2007/07/31/union-vs-union-all/
request.META.get('HTTP_AUTHORIZATION')
/python3.6/site-packages/rest_framework/authentication.py
you can get that from this file though...
As the shortcut Ctrl + Shift + P has been cited, I just wanted to add a really interesting feature: just double-click to the immediate right of the {
, and Eclipse will select the whole code block between the opening {
and corresponding closing }
. Similarly, double-click to the immediate left of the closing '}' and eclipse will select the block.
You are using MapToStoredProcedures()
which indicates that you are mapping your entities to stored procedures, when doing this you need to let go of the fact that there is a stored procedure and use the context
as normal.
Something like this (written into the browser so not tested)
using(MyContext context = new MyContext())
{
Department department = new Department()
{
Name = txtDepartment.text.trim()
};
context.Set<Department>().Add(department);
}
If all you really trying to do is call a stored procedure directly then use SqlQuery
You can also use the below code
$("input:checkbox:checked").map(function()
{
return $(this).val();
}).get();
If your project's source code has import statements that reference classes that are in widget.jar, you should add the jar to your projects Compile-time Libraries. (The jar widget.jar will automatically be added to your project's Run-time Libraries). That corresponds to (1).
If your source code has imports for classes in some other jar and the source code for those classes has import statements that reference classes in widget.jar, you should add widget.jar to the Run-time libraries list. That corresponds to (2).
You can add the jars directly to the Libraries list in the project properties. You can also create a Library that contains the jar file and then include that Library in the Compile-time or Run-time Libraries list.
If you create a NetBeans Library for widget.jar, you can also associate source code for the jar's content and Javadoc for the APIs defined in widget.jar. This additional information about widget.jar will be used by NetBeans as you debug code. It will also be used to provide addition information when you use code completion in the editor.
You should avoid using Tools >> Java Platform to add a jar to a project. That dialog allows you to modify the classpath that is used to compile and run all projects that use the Java Platform that you create. That may be useful at times but hides your project's dependency on widget.jar almost completely.
Django = 2.2
urlpatterns = [
re_path(r'^project_config/(?:(?P<product>\w+)/(?:(?P<project_id>\w+)/)/)?$', tool.views.ProjectConfig, name='project_config')
]
foo(*ob);
You don't need to cast it because it's the same Object type, you just need to dereference it.
find()
- Limited to lookups by tag name
you can see more information
https://docs.angularjs.org/api/ng/function/angular.element
Also you can access by name or id or call please following example:
angular.element(document.querySelector('#txtName')).attr('class', 'error');
Check project configuration. Linker->System->SubSystem should be Windows.
Use XmlTextWriter
...
public static string PrintXML(string xml)
{
string result = "";
MemoryStream mStream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(mStream, Encoding.Unicode);
XmlDocument document = new XmlDocument();
try
{
// Load the XmlDocument with the XML.
document.LoadXml(xml);
writer.Formatting = Formatting.Indented;
// Write the XML into a formatting XmlTextWriter
document.WriteContentTo(writer);
writer.Flush();
mStream.Flush();
// Have to rewind the MemoryStream in order to read
// its contents.
mStream.Position = 0;
// Read MemoryStream contents into a StreamReader.
StreamReader sReader = new StreamReader(mStream);
// Extract the text from the StreamReader.
string formattedXml = sReader.ReadToEnd();
result = formattedXml;
}
catch (XmlException)
{
// Handle the exception
}
mStream.Close();
writer.Close();
return result;
}
Set the Delegate of the UITextField to your ViewController, add a referencing outlet between the File's Owner and the UITextField, then implement this method:
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
if (textField == yourTextField)
{
[textField resignFirstResponder];
}
return NO;
}
Warning by @Geoff: see my note below, only one of the suggestions in this answer works (though on both columns).
I would use sed
:
sed 's/, /,/' input.txt
This will remove on leading space after the ,
.
Output:
Name,Order
Trim,working
cat,cat1
More general might be the following, it will remove possibly multiple spaces and/or tabs after the ,
:
sed 's/,[ \t]\?/,/g' input.txt
It will also work with more than two columns because of the global modifier /g
@Floris asked in discussion for a solution that removes trailing and and ending whitespaces in each colum (even the first and last) while not removing white spaces in the middle of a column:
sed 's/[ \t]\?,[ \t]\?/,/g; s/^[ \t]\+//g; s/[ \t]\+$//g' input.txt
*EDIT by @Geoff, I've appended the input file name to this one, and now it only removes all leading & trailing spaces (though from both columns). The other suggestions within this answer don't work. But try: " Multiple spaces , and 2 spaces before here " *
IMO sed
is the optimal tool for this job. However, here comes a solution with awk
because you've asked for that:
awk -F', ' '{printf "%s,%s\n", $1, $2}' input.txt
Another simple solution that comes in mind to remove all whitespaces is tr -d
:
cat input.txt | tr -d ' '
Since you are in a controller, the action method is given a Request
parameter.
You can access all POST data with $request->request->all();
.
This returns a key-value pair array.
When using GET requests you access data using $request->query->all();
When I do this, I get a very small square screen instead of a maxed screen. Yet, when I only use the FormWindowState.Maximized, it does give me a full screen. Why is that?
public partial class Testscherm : Form
{
public Testscherm()
{
this.WindowState = FormWindowState.Maximized;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = this.Size;
this.MaximumSize = this.Size;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
InitializeComponent();
}
In the MySQL interactive client you can type:
source yourfile.sql
Alternatively you can pipe the data into mysql from the command line:
mysql < yourfile.sql
If the file doesn't specify a database then you will also need to add that:
mysql db_name < yourfile.sql
See the documentation for more details:
var values = {};
$('td input').each(function(){
values[$(this).attr('name')] = $(this).val();
}
Haven't tested, but that should do it...
The question of speed is irrelevant without a specific speed problem.
If you are writing SQL code to make a change to an existing row, you UPDATE it. Anything else is incorrect.
If you're going to break the rules of how code should work, then you'd better have a damn good, quantified reason for it, and not a vague idea of "This way is faster", when you don't have any idea what "faster" is.
class C
defines a class, just as in Java or C++.object O
creates a singleton object O
as instance of some anonymous class; it can be used to hold static members that are not associated with instances of some class.object O extends T
makes the object O
an instance of trait T
; you can then pass O
anywhere, a T
is expected.class C
, then object C
is the companion object of class C
; note that the companion object is not automatically an instance of C
.Also see Scala documentation for object and class.
object
as host of static membersMost often, you need an object
to hold methods and values/variables that shall be available without having to first instantiate an instance of some class.
This use is closely related to static
members in Java.
object A {
def twice(i: Int): Int = 2*i
}
You can then call above method using A.twice(2)
.
If twice
were a member of some class A
, then you would need to make an instance first:
class A() {
def twice(i: Int): Int = 2 * i
}
val a = new A()
a.twice(2)
You can see how redundant this is, as twice
does not require any instance-specific data.
object
as a special named instanceYou can also use the object
itself as some special instance of a class or trait.
When you do this, your object needs to extend some trait
in order to become an instance of a subclass of it.
Consider the following code:
object A extends B with C {
...
}
This declaration first declares an anonymous (inaccessible) class that extends both B
and C
, and instantiates a single instance of this class named A
.
This means A
can be passed to functions expecting objects of type B
or C
, or B with C
.
object
There also exist some special features of objects in Scala. I recommend to read the official documentation.
def apply(...)
enables the usual method name-less syntax of A(...)
def unapply(...)
allows to create custom pattern matching extractorsYou could hide controls using CSS Pseudo Selectors like Demo: https://jsfiddle.net/g1rsasa3
//For Firefox we have to handle it in JavaScript _x000D_
var vids = $("video"); _x000D_
$.each(vids, function(){_x000D_
this.controls = false; _x000D_
}); _x000D_
//Loop though all Video tags and set Controls as false_x000D_
_x000D_
$("video").click(function() {_x000D_
//console.log(this); _x000D_
if (this.paused) {_x000D_
this.play();_x000D_
} else {_x000D_
this.pause();_x000D_
}_x000D_
});
_x000D_
video::-webkit-media-controls {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
/* Could Use thise as well for Individual Controls */_x000D_
video::-webkit-media-controls-play-button {}_x000D_
_x000D_
video::-webkit-media-controls-volume-slider {}_x000D_
_x000D_
video::-webkit-media-controls-mute-button {}_x000D_
_x000D_
video::-webkit-media-controls-timeline {}_x000D_
_x000D_
video::-webkit-media-controls-current-time-display {}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>_x000D_
<!-- Hiding HTML5 Video Controls using CSS Pseudo selectors -->_x000D_
_x000D_
<video width="800" autoplay controls="false">_x000D_
<source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/mp4">_x000D_
</video>
_x000D_
JSONObject class has a method named "has". Returns true if this object has a mapping for name. The mapping may be NULL. http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.popover-1.1.2.js"></script>
<script type="text/javascript">
$(function(){
$("#example").popover({
placement: 'bottom',
html: 'true',
title : '<span class="text-info"><strong>title</strong></span> <button type="button" id="close" class="close">×</button></span>',
content : 'test'
})
$("#close").click(function(event) {
$("#example").popover('hide');
});
});
</script>
<button type="button" id="example" class="btn btn-primary" >click</button>
This will work on SQL SERVER...
SELECT COL_LENGTH('Table', 'Column')
pwd
: to check where you are (If necessary)
cd
: change directory
In your case if I understand you, you need:
cd c/project
A possible solution is to think about it backwards: Accept a float as input and reject the input if the float is not an integer:
int n;
float f;
printf("Please enter an integer: ");
while(scanf("%f",&f)!=1 || (int)f != f)
{
...
}
n = f;
Though this does allow the user to enter something like 12.0, or 12e0, etc.
You've got to do some extra massaging if you want the ticks (not labels) to show up on the top and bottom (not just the top). The only way I could do this is with a minor change to unutbu's code:
import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)
# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()
ax.xaxis.set_ticks_position('both') # THIS IS THE ONLY CHANGE
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)
plt.show()
Output:
Sometimes you have what appears to be a tuple with a leading underscore as in
def foo(bar):
return _('my_' + bar)
In this case, what's going on is that _() is an alias for a localization function that operates on text to put it into the proper language, etc. based on the locale. For example, Sphinx does this, and you'll find among the imports
from sphinx.locale import l_, _
and in sphinx.locale, _() is assigned as an alias of some localization function.
This algorithm is not optimal for winning the game, but it is fairly optimal in terms of performance and amount of code needed:
if(can move neither right, up or down)
direction = left
else
{
do
{
direction = random from (right, down, up)
}
while(can not move in "direction")
}
Use in Swift 3
perform(<Selector>, with: <object>, afterDelay: <Time in Seconds>)
A generic way to get random element(s):
let some_array = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];_x000D_
let months = random_elems(some_array, 3);_x000D_
_x000D_
console.log(months);_x000D_
_x000D_
function random_elems(arr, count) {_x000D_
let len = arr.length;_x000D_
let lookup = {};_x000D_
let tmp = [];_x000D_
_x000D_
if (count > len)_x000D_
count = len;_x000D_
_x000D_
for (let i = 0; i < count; i++) {_x000D_
let index;_x000D_
do {_x000D_
index = ~~(Math.random() * len);_x000D_
} while (index in lookup);_x000D_
lookup[index] = null;_x000D_
tmp.push(arr[index]);_x000D_
}_x000D_
_x000D_
return tmp;_x000D_
}
_x000D_
In a python console, one can try the following 2 ways.
under the same work directory,
1. >> import helloworld
# if you have a variable x, you can print it in the IDLE.
>> helloworld.x
# if you have a function func, you can also call it like this.
>> helloworld.func()
2. >> runfile("./helloworld.py")
Instead of using onload, use Angular's ng-init
.
<article id="showSelector" ng-controller="CinemaCtrl" ng-init="myFunction()">
Note: This requires that myFunction is a property of the CinemaCtrl
scope.
It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:
Access-Control-Allow-Origin:*
or
Access-Control-Allow-Origin:your domain
In Apache config files, the code is like this:
Header set Access-Control-Allow-Origin "*"
In nodejs,the code is like this:
res.setHeader('Access-Control-Allow-Origin','*');
with itertools.product:
import itertools
result = list(itertools.product(*somelists))
Thanks to Dart's factory constructors, it's easy to build a singleton:
class Singleton {
static final Singleton _singleton = Singleton._internal();
factory Singleton() {
return _singleton;
}
Singleton._internal();
}
You can construct it like this
main() {
var s1 = Singleton();
var s2 = Singleton();
print(identical(s1, s2)); // true
print(s1 == s2); // true
}
If you need non-sequential guids you can send the sys_guid()
results through a hashing function (see https://stackoverflow.com/a/22534843/1462295 ). The idea is to keep whatever uniqueness is used from the original creation, and get something with more shuffled bits.
For instance:
LOWER(SUBSTR(STANDARD_HASH(SYS_GUID(), 'SHA1'), 0, 32))
Example showing default sequential guid vs sending it through a hash:
SELECT LOWER(SYS_GUID()) AS OGUID FROM DUAL
UNION ALL
SELECT LOWER(SYS_GUID()) AS OGUID FROM DUAL
UNION ALL
SELECT LOWER(SYS_GUID()) AS OGUID FROM DUAL
UNION ALL
SELECT LOWER(SYS_GUID()) AS OGUID FROM DUAL
UNION ALL
SELECT LOWER(SUBSTR(STANDARD_HASH(SYS_GUID(), 'SHA1'), 0, 32)) AS OGUID FROM DUAL
UNION ALL
SELECT LOWER(SUBSTR(STANDARD_HASH(SYS_GUID(), 'SHA1'), 0, 32)) AS OGUID FROM DUAL
UNION ALL
SELECT LOWER(SUBSTR(STANDARD_HASH(SYS_GUID(), 'SHA1'), 0, 32)) AS OGUID FROM DUAL
UNION ALL
SELECT LOWER(SUBSTR(STANDARD_HASH(SYS_GUID(), 'SHA1'), 0, 32)) AS OGUID FROM DUAL
output
80c32a4fbe405707e0531e18980a1bbb
80c32a4fbe415707e0531e18980a1bbb
80c32a4fbe425707e0531e18980a1bbb
80c32a4fbe435707e0531e18980a1bbb
c0f2ff2d3ef7b422c302bd87a4588490
d1886a8f3b4c547c28b0805d70b384f3
a0c565f3008622dde3148cfce9353ba7
1c375f3311faab15dc6a7503ce08182c
You code is ok only except that you can't add same class test1
.
$('.page-address-edit').addClass('test1').addClass('test2'); //this will add test1 and test2
And you could also do
$('.page-address-edit').addClass('test1 test2');
If you don't mind mutating x
,
x.update(y) or x
Simple, readable, performant. You know update()
always returns None
, which is a false value. So the above expression will always evaluate to x
, after updating it.
Most mutating methods in the standard library (like .update()
) return None
by convention, so this kind of pattern will work on those too. However, if you're using a dict subclass or some other method that doesn't follow this convention, then or
may return its left operand, which may not be what you want. Instead, you can use a tuple display and index, which works regardless of what the first element evaluates to (although it's not quite as pretty):
(x.update(y), x)[-1]
If you don't have x
in a variable yet, you can use lambda
to make a local without using an assignment statement. This amounts to using lambda
as a let expression, which is a common technique in functional languages, but maybe unpythonic.
(lambda x: x.update(y) or x)({'a': 1, 'b': 2})
Although it's not that different from the following use of the new walrus operator (Python 3.8+ only):
(x := {'a': 1, 'b': 2}).update(y) or x
If you do want a copy, PEP 584 style x | y
is the most Pythonic on 3.9+. If you must support older versions, PEP 448 style {**x, **y}
is easiest for 3.5+. But if that's not available in your (even older) Python version, the let pattern works here too.
(lambda z: z.update(y) or z)(x.copy())
(That is, of course, nearly equivalent to (z := x.copy()).update(y) or z
, but if your Python version is new enough for that, then the PEP 448 style will be available.)
BigDecimal(19.0001).setScale(2, BigDecimal.RoundingMode.DOWN)
To display the query string:
print_r($this->db->last_query());
To display the query result:
print_r($query);
The Profiler Class will display benchmark results, queries you have run, and $_POST data at the bottom of your pages. To enable the profiler place the following line anywhere within your Controller methods:
$this->output->enable_profiler(TRUE);
Profiling user guide: https://www.codeigniter.com/user_guide/general/profiling.html
Do NOT do that! setNum(num);//fix- until someone fixes your setter. Your getter should not call your setter with the uninitialized value of
num(e.g.
0`).
I suggest making a few small changes -
public static class Vars { private int num = 5; // Default to 5. public void setNum(int x) { this.num = x; // actually "set" the value. } public int getNum() { return num; } }
For Excel 2013:
http://blogmines.com/blog/how-to-import-text-file-in-excel-2013/
You need to enclose the date time value in quotes:
DECLARE @Test AS DATETIME
SET @Test = '2011-02-15'
PRINT @Test
Set in your .htaccess file
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
JNDI in layman's terms is basically an Interface for being able to get instances of internal/External resources such as
javax.sql.DataSource,
javax.jms.Connection-Factory,
javax.jms.QueueConnectionFactory,
javax.jms.TopicConnectionFactory,
javax.mail.Session, java.net.URL,
javax.resource.cci.ConnectionFactory,
or any other type defined by a JCA resource adapter. It provides a syntax in being able to create access whether they are internal or external. i.e (comp/env in this instance means where component/environment, there are lots of other syntax):
jndiContext.lookup("java:comp/env/persistence/customerDB");
What happens with bittorrent and a DHT is that at the beginning bittorrent uses information embedded in the torrent file to go to either a tracker or one of a set of nodes from the DHT. Then once it finds one node, it can continue to find others and persist using the DHT without needing a centralized tracker to maintain it.
The original information bootstraps the later use of the DHT.
Alternatively, you may also use the CSS3 Flexible Box Model. It's a great way to create flexible layouts that can also be applied to center content like so:
#parent {
-webkit-box-align:center;
-webkit-box-pack:center;
display:-webkit-box;
}
If you've ever been saved by an Emacs backup file, you
probably want more of them, not less of them. It is annoying
that they go in the same directory as the file you're editing,
but that is easy to change. You can make all backup files go
into a directory by putting something like the following in your
.emacs
.
(setq backup-directory-alist `(("." . "~/.saves")))
There are a number of arcane details associated with how Emacs might create your backup files. Should it rename the original and write out the edited buffer? What if the original is linked? In general, the safest but slowest bet is to always make backups by copying.
(setq backup-by-copying t)
If that's too slow for some reason you might also have a look at
backup-by-copying-when-linked
.
Since your backups are all in their own place now, you might want
more of them, rather than less of them. Have a look at the Emacs
documentation for these variables (with C-h v
).
(setq delete-old-versions t
kept-new-versions 6
kept-old-versions 2
version-control t)
Finally, if you absolutely must have no backup files:
(setq make-backup-files nil)
It makes me sick to think of it though.
LCASE or UCASE respectively.
Example:
SELECT UCASE(MyColumn) AS Upper, LCASE(MyColumn) AS Lower
FROM MyTable
if you know pass the pid of the parent process, here's a shell script that should work:
for child in $(ps -o pid,ppid -ax | \
awk "{ if ( \$2 == $pid ) { print \$1 }}")
do
echo "Killing child process $child because ppid = $pid"
kill $child
done
Well, the fastest way to do it is to not do it at all.
Sounds odd I know, here's some pseudocode:
int array [][];
bool array_is_empty;
void ClearArray ()
{
array_is_empty = true;
}
int ReadValue (int x, int y)
{
return array_is_empty ? 0 : array [x][y];
}
void SetValue (int x, int y, int value)
{
if (array_is_empty)
{
memset (array, 0, number of byte the array uses);
array_is_empty = false;
}
array [x][y] = value;
}
Actually, it's still clearing the array, but only when something is being written to the array. This isn't a big advantage here. However, if the 2D array was implemented using, say, a quad tree (not a dynamic one mind), or a collection of rows of data, then you can localise the effect of the boolean flag, but you'd need more flags. In the quad tree just set the empty flag for the root node, in the array of rows just set the flag for each row.
Which leads to the question "why do you want to repeatedly zero a large 2d array"? What is the array used for? Is there a way to change the code so that the array doesn't need zeroing?
For example, if you had:
clear array
for each set of data
for each element in data set
array += element
that is, use it for an accumulation buffer, then changing it like this would improve the performance no end:
for set 0 and set 1
for each element in each set
array = element1 + element2
for remaining data sets
for each element in data set
array += element
This doesn't require the array to be cleared but still works. And that will be far faster than clearing the array. Like I said, the fastest way is to not do it in the first place.
If you have Ruby for Windows,
C:\>more file
bath Abath Bbath XYZbathABC
C:\>ruby -pne "$_.gsub!(/bath/,\"hello\")" file
hello Ahello Bhello XYZhelloABC
Upload sql file
Make sure to select your database in this award winning GUI:
final File open = new File("PicDic.exe");
if (open.exists() == true) {
if (Desktop.isDesktopSupported()) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
Desktop.getDesktop().open(open);
} catch (IOException ex) {
return;
}
}
});
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
//DocumentEditorView.this.getFrame().dispose();
System.exit(0);
}
});
} else {
JOptionPane.showMessageDialog(this.getFrame(), "Desktop is not support to open editor\n You should try manualy");
}
} else {
JOptionPane.showMessageDialog(this.getFrame(), "PicDic.exe is not found");
}
//you can start another apps by using it and can slit your whole project in many apps. it will work lot
A quick way to do the thing now (previous ones haven't worked for me):
sudo wget https://github.com/mikefarah/yq/releases/download/v4.4.1/yq_linux_amd64 -O /usr/bin/yq &&\
sudo chmod +x /usr/bin/yq
Example asd.yaml:
a_list:
- key1: value1
key2: value2
key3: value3
parsing root:
user@vm:~$ yq e '.' asd.yaml
a_list:
- key1: value1
key2: value2
key3: value3
parsing key3:
user@vm:~$ yq e '.a_list[0].key3' asd.yaml
value3
The dataset in ss.csv
contains some columns I am interested in:
ss_ = spark.read.csv("ss.csv", header= True,
inferSchema = True)
ss_.columns
['Reporting Area', 'MMWR Year', 'MMWR Week', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Current week', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Current week, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Med', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Med, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Max', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Previous 52 weeks Max, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2018', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2018, flag', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2017', 'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Cum 2017, flag', 'Shiga toxin-producing Escherichia coli, Current week', 'Shiga toxin-producing Escherichia coli, Current week, flag', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Med', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Med, flag', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Max', 'Shiga toxin-producing Escherichia coli, Previous 52 weeks Max, flag', 'Shiga toxin-producing Escherichia coli, Cum 2018', 'Shiga toxin-producing Escherichia coli, Cum 2018, flag', 'Shiga toxin-producing Escherichia coli, Cum 2017', 'Shiga toxin-producing Escherichia coli, Cum 2017, flag', 'Shigellosis, Current week', 'Shigellosis, Current week, flag', 'Shigellosis, Previous 52 weeks Med', 'Shigellosis, Previous 52 weeks Med, flag', 'Shigellosis, Previous 52 weeks Max', 'Shigellosis, Previous 52 weeks Max, flag', 'Shigellosis, Cum 2018', 'Shigellosis, Cum 2018, flag', 'Shigellosis, Cum 2017', 'Shigellosis, Cum 2017, flag']
but I only need a few:
columns_lambda = lambda k: k.endswith(', Current week') or k == 'Reporting Area' or k == 'MMWR Year' or k == 'MMWR Week'
The filter returns the list of desired columns, list is evaluated:
sss = filter(columns_lambda, ss_.columns)
to_keep = list(sss)
the list of desired columns is unpacked as arguments to dataframe select function that return dataset containing only columns in the list:
dfss = ss_.select(*to_keep)
dfss.columns
The result:
['Reporting Area',
'MMWR Year',
'MMWR Week',
'Salmonellosis (excluding Paratyphoid fever andTyphoid fever)†, Current week',
'Shiga toxin-producing Escherichia coli, Current week',
'Shigellosis, Current week']
The df.select()
has a complementary pair: http://spark.apache.org/docs/2.4.1/api/python/pyspark.sql.html#pyspark.sql.DataFrame.drop
to drop the list of columns.
Here:
$file = 'http://www.example.com/somefile.jpg';
$file_headers = @get_headers($file);
if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
From here and right below the above post, there's a curl solution:
function url_exists($url) {
return curl_init($url) !== false;
}
You can execute this in 2 simple statements:
row.names(samp) <- samp$names
samp[1] <- NULL
For 'Bad' red:
For 'Good' green:
For 'Neutral' yellow:
As you've indicated, you can't output NULL in an excel formula. I think this has to do with the fact that the formula itself causes the cell to not be able to be NULL. "" is the next best thing, but sometimes it's useful to use 0.
--EDIT--
Based on your comment, you might want to check out this link. http://peltiertech.com/WordPress/mind-the-gap-charting-empty-cells/
It goes in depth on the graphing issues and what the various values represent, and how to manipulate their output on a chart.
I'm not familiar with VSTO I'm afraid. So I won't be much help there. But if you are really placing formulas in the cell, then there really is no way. ISBLANK() only tests to see if a cell is blank or not, it doesn't have a way to make it blank. It's possible to write code in VBA (and VSTO I imagine) that would run on a worksheet_change event and update the various values instead of using formulas. But that would be cumbersome and performance would take a hit.
It's just really simple if you use pipe. The following is the server.js code snippet.
var http = require('http');_x000D_
var fs = require('fs');_x000D_
_x000D_
function onRequest(req, res){_x000D_
_x000D_
console.log("USER MADE A REQUEST. " +req.url);_x000D_
res.writeHead(200, {'Content-Type': 'text/html'});_x000D_
var readStream = fs.createReadStream(__dirname + '/index.html','utf8'); _x000D_
_x000D_
/*include your html file and directory name instead of <<__dirname + '/index.html'>>*/_x000D_
_x000D_
readStream.pipe(res);_x000D_
_x000D_
}_x000D_
_x000D_
http.createServer(onRequest).listen(7000);_x000D_
console.log('Web Server is running...');
_x000D_
You could make a method:
public byte[] toBytes(char[] data) {
byte[] toRet = new byte[data.length];
for(int i = 0; i < toRet.length; i++) {
toRet[i] = (byte) data[i];
}
return toRet;
}
Hope this helps
I can see what @Þaw mentioned :
$ENROLLEES = $this->load->database('ENROLLEES', TRUE);
$ACCOUNTS = $this->load->database('ACCOUNTS', TRUE);
CodeIgniter supports multiple databases. You need to keep both database reference in separate variable as you did above. So far you are right/correct.
Next you need to use them as below:
$ENROLLEES->query();
$ENROLLEES->result();
and
$ACCOUNTS->query();
$ACCOUNTS->result();
Instead of using
$this->db->query();
$this->db->result();
See this for reference: http://ellislab.com/codeigniter/user-guide/database/connecting.html
You would use an MvcHtmlString
if you want to pass raw HTML to an MVC helper method and you don't want the helper method to encode the HTML.