You should install the graphviz package in your system (not just the python package). On Ubuntu you should try:
sudo apt-get install graphviz
Lattice solution with additional settings which I needed:
library(lattice)
distribution<-function(x) {2^(-x*2)}
X<-seq(0,10,0.00001)
xyplot(distribution(X)~X,type="l", col = rgb(red = 255, green = 90, blue = 0, maxColorValue = 255), cex.lab = 3.5, cex.axis = 3.5, lwd=2 )
X<-seq(0,10,0.00001)
col = rgb(red = 255, green = 90, blue = 0, maxColorValue = 255)
lwd = 2
cex.lab = 3.5, cex.axis = 3.5
@Jan Kuiken's answer is certainly well-thought and thorough, but there are some caveats:
A much simpler approach is to annotate the last point of each plot. The point can also be circled, for emphasis. This can be accomplished with one extra line:
from matplotlib import pyplot as plt
for i, (x, y) in enumerate(samples):
plt.plot(x, y)
plt.text(x[-1], y[-1], 'sample {i}'.format(i=i))
A variant would be to use ax.annotate
.
Remove "SSLv2ClientHello" from the enabled protocols on the client SSLSocket or HttpsURLConnection.
A combination of line styles, markers, and qualitative colors from matplotlib
:
import itertools
import matplotlib as mpl
import matplotlib.pyplot as plt
N = 8*4+10
l_styles = ['-','--','-.',':']
m_styles = ['','.','o','^','*']
colormap = mpl.cm.Dark2.colors # Qualitative colormap
for i,(marker,linestyle,color) in zip(range(N),itertools.product(m_styles,l_styles, colormap)):
plt.plot([0,1,2],[0,2*i,2*i], color=color, linestyle=linestyle,marker=marker,label=i)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,ncol=4);
UPDATE: Supporting not only ListedColormap
, but also LinearSegmentedColormap
import itertools
import matplotlib.pyplot as plt
Ncolors = 8
#colormap = plt.cm.Dark2# ListedColormap
colormap = plt.cm.viridis# LinearSegmentedColormap
Ncolors = min(colormap.N,Ncolors)
mapcolors = [colormap(int(x*colormap.N/Ncolors)) for x in range(Ncolors)]
N = Ncolors*4+10
l_styles = ['-','--','-.',':']
m_styles = ['','.','o','^','*']
fig,ax = plt.subplots(gridspec_kw=dict(right=0.6))
for i,(marker,linestyle,color) in zip(range(N),itertools.product(m_styles,l_styles, mapcolors)):
ax.plot([0,1,2],[0,2*i,2*i], color=color, linestyle=linestyle,marker=marker,label=i)
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,ncol=3,prop={'size': 8})
graphics.h
appears to something once bundled with Borland and/or Turbo C++, in the 90's.
http://www.daniweb.com/software-development/cpp/threads/17709/88149#post88149
It's unlikely that you will find any support for that file with modern compiler. For other graphics libraries check the list of "related" questions (questions related to this one). E.g., "A Simple, 2d cross-platform graphics library for c or c++?".
Your current code:
ggplot(histogram, aes(f0, fill = utt)) + geom_histogram(alpha = 0.2)
is telling ggplot
to construct one histogram using all the values in f0
and then color the bars of this single histogram according to the variable utt
.
What you want instead is to create three separate histograms, with alpha blending so that they are visible through each other. So you probably want to use three separate calls to geom_histogram
, where each one gets it's own data frame and fill:
ggplot(histogram, aes(f0)) +
geom_histogram(data = lowf0, fill = "red", alpha = 0.2) +
geom_histogram(data = mediumf0, fill = "blue", alpha = 0.2) +
geom_histogram(data = highf0, fill = "green", alpha = 0.2) +
Here's a concrete example with some output:
dat <- data.frame(xx = c(runif(100,20,50),runif(100,40,80),runif(100,0,30)),yy = rep(letters[1:3],each = 100))
ggplot(dat,aes(x=xx)) +
geom_histogram(data=subset(dat,yy == 'a'),fill = "red", alpha = 0.2) +
geom_histogram(data=subset(dat,yy == 'b'),fill = "blue", alpha = 0.2) +
geom_histogram(data=subset(dat,yy == 'c'),fill = "green", alpha = 0.2)
which produces something like this:
Edited to fix typos; you wanted fill, not colour.
My solution is to use ggplot2
. It takes care of these types of things automatically. The biggest thing is to arrange the data appropriately.
y1 <- c(100, 200, 300, 400, 500)
y2 <- c(1, 2, 3, 4, 5)
x <- c(1, 2, 3, 4, 5)
df <- data.frame(x=rep(x,2), y=c(y1, y2), class=c(rep("y1", 5), rep("y2", 5)))
Then use ggplot2
to plot it
library(ggplot2)
ggplot(df, aes(x=x, y=y, color=class)) + geom_point()
This is saying plot the data in df
, and separate the points by class
.
The plot generated is
Yes, you can solve it using the ElementName=Something
as suggested by Juve.
BUT!
If a child element (on which you use this kind of binding) is a user control which uses the same element name as you specify in the parent control, then the binding goes to the wrong object!!
I know this post is not a solution but I thought everyone who uses the ElementName in the binding should know this, since it's a possible runtime bug.
<UserControl x:Class="MyNiceControl"
x:Name="TheSameName">
the content ...
</UserControl>
<UserControl x:Class="AnotherUserControl">
<ListView x:Name="TheSameName">
<ListView.ItemTemplate>
<DataTemplate>
<MyNiceControl Width="{Binding DataContext.Width, ElementName=TheSameName}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</UserControl>
PLOTYY allows two different y-axes. Or you might look into LayerPlot from the File Exchange. I guess I should ask if you've considered using HOLD or just rescaling the data and using regular old plot?
OLD, not what the OP was looking for: SUBPLOT allows you to break a figure window into multiple axes. Then if you want to have only one x-axis showing, or some other customization, you can manipulate each axis independently.
To obtain the perspective-corrected co-ordinates, just divide by the z
co-ordinate:
xc = x / z
yc = y / z
The above works assuming that the camera is at (0, 0, 0)
and you are projecting onto the plane at z = 1
-- you need to translate the co-ords relative to the camera otherwise.
There are some complications for curves, insofar as projecting the points of a 3D Bezier curve will not in general give you the same points as drawing a 2D Bezier curve through the projected points.
It's excerpt for the webpage: http://android.programmerguru.com/android-localization-at-runtime/
It's simple to change the language of your app upon user selects it from list of languages. Have a method like below which accepts the locale as String (like 'en' for English, 'hi' for hindi), configure the locale for your App and refresh your current activity to reflect the change in language. The locale you applied will not be changed until you manually change it again.
public void setLocale(String lang) {
Locale myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
Intent refresh = new Intent(this, AndroidLocalize.class);
finish();
startActivity(refresh);
}
Make sure you imported following packages:
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.util.DisplayMetrics;
add in manifest to activity android:configChanges="locale|orientation"
set -x
enables a mode of the shell where all executed commands are printed to the terminal. In your case it's clearly used for debugging, which is a typical use case for set -x
: printing every command as it is executed may help you to visualize the control flow of the script if it is not functioning as expected.
set +x
disables it.
You are absolutely right, supporting completely stateless interactions with the server does put an additional burden on the client. However, if you consider scaling an application, the computation power of the clients is directly proportional to the number of clients. Therefore scaling to high numbers of clients is much more feasible.
As soon as you put a tiny bit of responsibility on the server to manage some information related to a specific client's interactions, that burden can quickly grow to consume the server.
It's a trade off.
This will validate with HTML5.
<form action="#">
Just convert the timestamp in millisec representation. Use getTime() method.
Case 1 : Yes, this works fine.
Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.
Share and enjoy.
You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?
You do not need to call d.keys()
, so
if key not in d:
d[key] = value
is enough. There is no clearer, more readable method.
You could update again with dict.get()
, which would return an existing value if the key is already present:
d[key] = d.get(key, value)
but I strongly recommend against this; this is code golfing, hindering maintenance and readability.
Maybe you should try using react-native-hr something like this:
<Hr lineColor='#b3b3b3'/>
documentation: https://www.npmjs.com/package/react-native-hr
Use an call thru section, it works
<div id="content">
<section id="home">
...
</section>
Call the above the thru
<a href="#home">page1</a>
Scrolling needs jquery paste this.. on above to ending body closing tag..
<script>
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
</script>
Most of what people here suggested works, however you should only place generic code in to the style sheet, and place the specific code in to the html code as shown below. Otherwise you will end up with a bloated style sheet.
Here is how I do it:
Your style sheet code:
<style>
dt {
float:left;
}
dd {
border-left:2px dotted #aaa;
padding-left: 1em;
margin: .5em;
}
</style>
Your html code:
<dl>
<dt>1st Entity</dt>
<dd style="margin-left: 5em;">Consumer</dd>
<dt>2nd Entity</dt>
<dd style="margin-left: 5em;">Merchant</dd>
<dt>3rd Entity</dt>
<dd style="margin-left: 5em;">Provider, or cToken direct to Merchant</dd>
<dt>4th Entity</dt>
<dd style="margin-left: 5em;">cToken to Provider</dd>
</dl>
StringBuilder output = new StringBuilder();
String xmlString =
@"<?xml version='1.0'?>
<!-- This is a sample XML document -->
<Items>
<Item>test with a child element <more/> stuff</Item>
</Items>";
// Create an XmlReader
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
XmlWriterSettings ws = new XmlWriterSettings();
ws.Indent = true;
using (XmlWriter writer = XmlWriter.Create(output, ws))
{
// Parse the file and display each of the nodes.
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
writer.WriteStartElement(reader.Name);
break;
case XmlNodeType.Text:
writer.WriteString(reader.Value);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
writer.WriteProcessingInstruction(reader.Name, reader.Value);
break;
case XmlNodeType.Comment:
writer.WriteComment(reader.Value);
break;
case XmlNodeType.EndElement:
writer.WriteFullEndElement();
break;
}
}
}
}
OutputTextBlock.Text = output.ToString();
StringBuilder output = new StringBuilder();
String xmlString =
@"<bookstore>
<book genre='autobiography' publicationdate='1981-03-22' ISBN='1-861003-11-0'>
<title>The Autobiography of Benjamin Franklin</title>
<author>
<first-name>Benjamin</first-name>
<last-name>Franklin</last-name>
</author>
<price>8.99</price>
</book>
</bookstore>";
// Create an XmlReader
using (XmlReader reader = XmlReader.Create(new StringReader(xmlString)))
{
reader.ReadToFollowing("book");
reader.MoveToFirstAttribute();
string genre = reader.Value;
output.AppendLine("The genre value: " + genre);
reader.ReadToFollowing("title");
output.AppendLine("Content of the title element: " + reader.ReadElementContentAsString());
}
OutputTextBlock.Text = output.ToString();
java -classpath Predit.jar your.package.name.MainClass
I know 3 way to resolve your problem:
First if you have access to both domains you can allow access for all other domain using :
header("Access-Control-Allow-Origin: *");
or just a domain by adding code bellow to .htaccess file:
<FilesMatch "\.(ttf|otf|eot|woff)$">
<IfModule mod_headers.c>
SetEnvIf Origin "http(s)?://(www\.)?(google.com|staging.google.com|development.google.com|otherdomain.net|dev02.otherdomain.net)$" AccessControlAllowOrigin=$0
Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
</IfModule>
</FilesMatch>
you can have ajax request to a php file in your server and handle request to another domain using this php file.
You can use inner divs to set the margin.
<div style="display: table-cell;">
<div style="margin:5px;background-color: red;">1</div>
</div>
<div style="display: table-cell; ">
<div style="margin:5px;background-color: green;">1</div>
</div>
I think your questions will all be answered if you understand how Sets, and in particular HashSets work. A set is a collection of unique objects, with Java defining uniqueness in that it doesn't equal anything else (equals returns false).
The HashSet takes advantage of hashcodes to speed things up. It assumes that two objects that equal eachother will have the same hash code. However it does not assume that two objects with the same hash code mean they are equal. This is why when it detects a colliding hash code, it only compares with other objects (in your case one) in the set with the same hash code.
You did say you had a number-
String.prototype.padZero= function(len, c){
var s= '', c= c || '0', len= (len || 2)-this.length;
while(s.length<len) s+= c;
return s+this;
}
Number.prototype.padZero= function(len, c){
return String(this).padZero(len,c);
}
In situations like this, why not write your own? A simple server app to test connections can be done in a matter of minutes if you know what you're doing, and you can make it respond exactly how you need to, and for specific scenarios.
If week 1 always starts on the first Monday
of the month try this formula for week number
=INT((6+DAY(A1+1-WEEKDAY(A1-1)))/7)
That gets the week number from the date in A1 with no intermediate calculations - if you want to use your "Monday's date" in B1 you can use this version
=INT((DAY(B1)+6)/7)
The oneliner:
open("out1.txt", "w").writelines([l for l in open("in.txt").readlines() if "tests/file/myword" in l])
Recommended with with
:
with open("in.txt") as f:
lines = f.readlines()
lines = [l for l in lines if "ROW" in l]
with open("out.txt", "w") as f1:
f1.writelines(lines)
Using less memory:
with open("in.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
if "ROW" in line:
f1.write(line)
This may be overkill for what you're looking for, but there is an npm package called marky
that you can use to do this. It gives you a couple of extra features beyond just starting and stopping a timer.
You just need to install it via npm
and then import the dependency anywhere you'd like to use it.
Here is a link to the npm
package:
https://www.npmjs.com/package/marky
An example of use after installing via npm would be as follows:
import * as _M from 'marky';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {
Marky = _M;
}
constructor() {}
ngOnInit() {}
startTimer(key: string) {
this.Marky.mark(key);
}
stopTimer(key: string) {
this.Marky.stop(key);
}
key
is simply a string which you are establishing to identify that particular measurement of time. You can have multiple measures which you can go back and reference your timer stats using the keys you create.
It means "a python object", i.e. not one of the builtin scalar types supported by numpy.
np.array([object()]).dtype
=> dtype('O')
A small improvement from the accepted answer is to do the null check and also get full object.
public class DateComparator {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(1, "name1", addDays(new Date(), 1)));
employees.add(new Employee(2, "name2", addDays(new Date(), 3)));
employees.add(new Employee(3, "name3", addDays(new Date(), 6)));
employees.add(new Employee(4, "name4", null));
employees.add(new Employee(5, "name5", addDays(new Date(), 4)));
employees.add(new Employee(6, "name6", addDays(new Date(), 5)));
System.out.println(employees);
Date maxDate = employees.stream().filter(emp -> emp.getJoiningDate() != null).map(Employee::getJoiningDate).max(Date::compareTo).get();
System.out.println(format.format(maxDate));
//Comparator<Employee> comparator = (p1, p2) -> p1.getJoiningDate().compareTo(p2.getJoiningDate());
Comparator<Employee> comparator = Comparator.comparing(Employee::getJoiningDate);
Employee maxDatedEmploye = employees.stream().filter(emp -> emp.getJoiningDate() != null).max(comparator).get();
System.out.println(" maxDatedEmploye : " + maxDatedEmploye);
Employee minDatedEmployee = employees.stream().filter(emp -> emp.getJoiningDate() != null).min(comparator).get();
System.out.println(" minDatedEmployee : " + minDatedEmployee);
}
public static Date addDays(Date date, int days) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, days); // minus number would decrement the days
return cal.getTime();
}
}
You would get below results :
[Employee [empId=1, empName=name1, joiningDate=Wed Mar 21 13:33:09 EDT 2018],
Employee [empId=2, empName=name2, joiningDate=Fri Mar 23 13:33:09 EDT 2018],
Employee [empId=3, empName=name3, joiningDate=Mon Mar 26 13:33:09 EDT 2018],
Employee [empId=4, empName=name4, joiningDate=null],
Employee [empId=5, empName=name5, joiningDate=Sat Mar 24 13:33:09 EDT 2018],
Employee [empId=6, empName=name6, joiningDate=Sun Mar 25 13:33:09 EDT 2018]
]
2018-03-26
maxDatedEmploye : Employee [empId=3, empName=name3, joiningDate=Mon Mar 26 13:33:09 EDT 2018]
minDatedEmployee : Employee [empId=1, empName=name1, joiningDate=Wed Mar 21 13:33:09 EDT 2018]
Update : What if list itself is empty ?
Date maxDate = employees.stream().filter(emp -> emp.getJoiningDate() != null).map(Employee::getJoiningDate).max(Date::compareTo).orElse(new Date());
System.out.println(format.format(maxDate));
Comparator<Employee> comparator = Comparator.comparing(Employee::getJoiningDate);
Employee maxDatedEmploye = employees.stream().filter(emp -> emp.getJoiningDate() != null).max(comparator).orElse(null);
System.out.println(" maxDatedEmploye : " + maxDatedEmploye);
I would always encode in UTF-8. From the Wikipedia page on percent encoding:
The generic URI syntax mandates that new URI schemes that provide for the representation of character data in a URI must, in effect, represent characters from the unreserved set without translation, and should convert all other characters to bytes according to UTF-8, and then percent-encode those values. This requirement was introduced in January 2005 with the publication of RFC 3986. URI schemes introduced before this date are not affected.
It seems like because there were other accepted ways of doing URL encoding in the past, browsers attempt several methods of decoding a URI, but if you're the one doing the encoding you should use UTF-8.
If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
The error message says your DbContext
(LogManagerContext
) needs a constructor which accepts a DbContextOptions
. But i couldn't find such a constructor in your DbContext
. So adding below constructor probably solves your problem.
public LogManagerContext(DbContextOptions options) : base(options)
{
}
Edit for comment
If you don't register IHttpContextAccessor
explicitly, use below code:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
If you are using setup tools or distribute (a setup.py install) then the "right" way to access these packaged resources seem to be using package_resources.
In your case the example would be
import pkg_resources
my_data = pkg_resources.resource_string(__name__, "foo.dat")
Which of course reads the resource and the read binary data would be the value of my_data
If you just need the filename you could also use
resource_filename(package_or_requirement, resource_name)
Example:
resource_filename("MyPackage","foo.dat")
The advantage is that its guaranteed to work even if it is an archive distribution like an egg.
See http://packages.python.org/distribute/pkg_resources.html#resourcemanager-api
For anyone looking for a Kotlin implementation see below.
Note that the OnBackPressedCallback
only seems to work for providing custom back behavior to the built-in software/hardware back button and not the back arrow button/home as up button within the actionbar/toolbar. To also override the behavior for the actionbar/toolbar back button I'm providing the solution that's working for me. If this is a bug or you are aware of a better solution for that case please comment.
build.gradle
...
implementation "androidx.appcompat:appcompat:1.1.0-rc01"
implementation "androidx.navigation:navigation-fragment-ktx:2.0.0"
implementation "androidx.navigation:navigation-ui-ktx:2.0.0"
...
MainActivity.kt
...
import androidx.appcompat.app.AppCompatActivity
...
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
setContentView(R.layout.activity_main)
...
val navController = findNavController(R.id.nav_host_fragment)
val appBarConfiguration = AppBarConfiguration(navController.graph)
// This line is only necessary if using the default action bar.
setupActionBarWithNavController(navController, appBarConfiguration)
// This remaining block is only necessary if using a Toolbar from your layout.
val toolbar = findViewById<Toolbar>(R.id.toolbar)
toolbar.setupWithNavController(navController, appBarConfiguration)
// This will handle back actions initiated by the the back arrow
// at the start of the toolbar.
toolbar.setNavigationOnClickListener {
// Handle the back button event and return to override
// the default behavior the same way as the OnBackPressedCallback.
// TODO(reason: handle custom back behavior here if desired.)
// If no custom behavior was handled perform the default action.
navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
}
/**
* If using the default action bar this must be overridden.
* This will handle back actions initiated by the the back arrow
* at the start of the action bar.
*/
override fun onSupportNavigateUp(): Boolean {
// Handle the back button event and return true to override
// the default behavior the same way as the OnBackPressedCallback.
// TODO(reason: handle custom back behavior here if desired.)
// If no custom behavior was handled perform the default action.
val navController = findNavController(R.id.nav_host_fragment)
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
}
MyFragment.kt
...
import androidx.activity.OnBackPressedCallback
import androidx.fragment.app.Fragment
...
class MyFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val onBackPressedCallback = object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
// Handle the back button event
}
}
requireActivity().getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback)
}
}
The official documentation can be viewed at https://developer.android.com/guide/navigation/navigation-custom-back
IN this answer when i say a file i mean the location in memory
All the data that is saved is stored in memory using a data structure called inodes Every inode has a inodenumber.The inode number is used to access the inode.All the hard links to a file may have different names but share the same inode number.Since all the hard links have the same inodenumber(which inturn access the same inode),all of them point to the same physical memory.
A symbolic link is a special kind of file.Since it is also a file it will have a file name and an inode number.As said above the inode number acceses an inode which points to data.Now what makes a symbolic link special is that the inodenumbers in symbolic links access those inodes which point to "a path" to another file.More specifically the inode number in symbolic link acceses those inodes who point to another hard link.
when we are moving,copying,deleting a file in GUI we are playing with the hardlinks of the file not the physical memory.when we delete a file we are deleting the hardlink of the file. we are not wiping out the physical memory.If all the hardlinks to file are deleted then it will not be possible to access the data stored although it may still be present in memory
You can use the function difftime
. It returns the difference between two given time_t
values, the output value is double
(see difftime documentation).
time_t actual_time;
double actual_time_sec;
actual_time = time(0);
actual_time_sec = difftime(actual_time,0);
printf("%g",actual_time_sec);
$(document).ready ->
$("a[href^='#']").click ->
$(document.body).animate
scrollTop: $($(this).attr("href")).offset().top, 1000
This is because after the nextInt() finished it's execution, when the nextLine() method is called, it scans the newline character of which was present after the nextInt(). You can do this in either of the following ways:
You can use the next method on the scanner object as
scan.next();
Slightly related, I was looking for the unique combinations and I came up with this method:
def unique_columns(df,columns):
result = pd.Series(index = df.index)
groups = meta_data_csv.groupby(by = columns)
for name,group in groups:
is_unique = len(group) == 1
result.loc[group.index] = is_unique
assert not result.isnull().any()
return result
And if you only want to assert that all combinations are unique:
df1.set_index(['A','B']).index.is_unique
You can do this without a JOIN
:
SELECT *
FROM (SELECT *,COUNT(*) OVER(PARTITION BY phone_number) as Phone_CT
FROM YourTable
)sub
WHERE Phone_CT > 1
ORDER BY phone_number, employee_ids
Demo: SQL Fiddle
Here's a way to do it without using groups (Python 3.6 or above):
>>> re.search('2\d\d\d[01]\d[0-3]\d', 'report_20191207.xml')[0]
'20191207'
Below is the code for ImageFullViewActivity
Class
public class ImageFullViewActivity extends AppCompatActivity {
private ScaleGestureDetector mScaleGestureDetector;
private float mScaleFactor = 1.0f;
private ImageView mImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_fullview);
mImageView = (ImageView) findViewById(R.id.imageView);
mScaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());
}
@Override
public boolean onTouchEvent(MotionEvent motionEvent) {
mScaleGestureDetector.onTouchEvent(motionEvent);
return true;
}
private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector scaleGestureDetector) {
mScaleFactor *= scaleGestureDetector.getScaleFactor();
mScaleFactor = Math.max(0.1f,
Math.min(mScaleFactor, 10.0f));
mImageView.setScaleX(mScaleFactor);
mImageView.setScaleY(mScaleFactor);
return true;
}
}
}
CSVReader reader = new CSVReader(new FileReader(
"myfile.csv"));
try {
List<String[]> myEntries = reader.readAll();
for (String[] s : myEntries) {
for(String ss : s) {
System.out.print(", " + ss);
}
}
} catch (IOException e) {
e.printStackTrace();
}
Try Shift + Delete. Did 24.000 files in 2 minutes for me.
Note that if you are using [self class] nibName]
can return different name if you are using swift... might be different than the name you are expecting it to return.
Especially if you have multiple targets for your code.
In that case try to override:
override var nibName: String?{
return "YourXibFileName" // No .xib at the end :)
}
Worked this out, turns out that android.R.color.black is not the same as Color.BLACK. Changed the code to:
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStyle(Style.FILL);
canvas.drawPaint(paint);
paint.setColor(Color.BLACK);
paint.setTextSize(20);
canvas.drawText("Some Text", 10, 25, paint);
and it all works fine now!!
You need to run your script after the element exists. Move the <input type="hidden" name="checkyear" id="checkyear" value="">
to the beginning.
There is also an alternative way to use MarkupExtension
in order to use Binding
for a ConverterParameter
. With this solution you can still use the default IValueConverter
instead of the IMultiValueConverter
because the ConverterParameter
is passed into the IValueConverter
just like you expected in your first sample.
Here is my reusable MarkupExtension
:
/// <summary>
/// <example>
/// <TextBox>
/// <TextBox.Text>
/// <wpfAdditions:ConverterBindableParameter Binding="{Binding FirstName}"
/// Converter="{StaticResource TestValueConverter}"
/// ConverterParameterBinding="{Binding ConcatSign}" />
/// </TextBox.Text>
/// </TextBox>
/// </example>
/// </summary>
[ContentProperty(nameof(Binding))]
public class ConverterBindableParameter : MarkupExtension
{
#region Public Properties
public Binding Binding { get; set; }
public BindingMode Mode { get; set; }
public IValueConverter Converter { get; set; }
public Binding ConverterParameter { get; set; }
#endregion
public ConverterBindableParameter()
{ }
public ConverterBindableParameter(string path)
{
Binding = new Binding(path);
}
public ConverterBindableParameter(Binding binding)
{
Binding = binding;
}
#region Overridden Methods
public override object ProvideValue(IServiceProvider serviceProvider)
{
var multiBinding = new MultiBinding();
Binding.Mode = Mode;
multiBinding.Bindings.Add(Binding);
if (ConverterParameter != null)
{
ConverterParameter.Mode = BindingMode.OneWay;
multiBinding.Bindings.Add(ConverterParameter);
}
var adapter = new MultiValueConverterAdapter
{
Converter = Converter
};
multiBinding.Converter = adapter;
return multiBinding.ProvideValue(serviceProvider);
}
#endregion
[ContentProperty(nameof(Converter))]
private class MultiValueConverterAdapter : IMultiValueConverter
{
public IValueConverter Converter { get; set; }
private object lastParameter;
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (Converter == null) return values[0]; // Required for VS design-time
if (values.Length > 1) lastParameter = values[1];
return Converter.Convert(values[0], targetType, lastParameter, culture);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
if (Converter == null) return new object[] { value }; // Required for VS design-time
return new object[] { Converter.ConvertBack(value, targetTypes[0], lastParameter, culture) };
}
}
}
With this MarkupExtension
in your code base you can simply bind the ConverterParameter
the following way:
<Style TargetType="FrameworkElement">
<Setter Property="Visibility">
<Setter.Value>
<wpfAdditions:ConverterBindableParameter Binding="{Binding Tag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}"
Converter="{StaticResource AccessLevelToVisibilityConverter}"
ConverterParameterBinding="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Tag}" />
</Setter.Value>
</Setter>
Which looks almost like your initial proposal.
For some reason none of the above answers seemed to be addressing the case of the real first and only first child of the parent.
#element_id > .class_name:first-child
All the above answers will fail if you want to apply the style to only the first class child within this code.
<aside id="element_id">
Content
<div class="class_name">First content that need to be styled</div>
<div class="class_name">
Second content that don't need to be styled
<div>
<div>
<div class="class_name">deep content - no style</div>
<div class="class_name">deep content - no style</div>
<div>
<div class="class_name">deep content - no style</div>
</div>
</div>
</div>
</div>
</aside>
Here is the function I use to prevent chrome and opera from showing the invalid input dialog even when using novalidate.
window.submittingForm = false;
$('input[novalidate]').bind('invalid', function(e) {
if(!window.submittingForm){
window.submittingForm = true;
$(e.target.form).submit();
setTimeout(function(){window.submittingForm = false;}, 100);
}
e.preventDefault();
return false;
});
Can be cause by wrong operator, =, when it should be ==
if(mysql_num_rows($result) = 1)
return $result;
else
return false;
This code throws this error
Note that = is assignment operator and not comparison operator. Fix is to change = to ==.
I upgraded from Beta to RC and faced 'Scripts' does not exist issue. Surfed all over the web and the final solution is what N40JPJ said plus another workaroudn:
Copy the following in View\Web.config :
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.Optimization"/>
<add namespace="System.Web.Helpers"/>
</namespaces>
and the following inside View\Shared_Layout.cshtml
@if (IsSectionDefined("scripts"))
{
@RenderSection("scripts", required: false)
}
Hope it helps.
to indent a ul
dropdown menu, use
/* Main Level */
ul{
margin-left:10px;
}
/* Second Level */
ul ul{
margin-left:15px;
}
/* Third Level */
ul ul ul{
margin-left:20px;
}
/* and so on... */
You can indent the li
s and (if applicable) the a
s (or whatever content elements you have) as well , each with differing effects.
You could also use padding-left
instead of margin-left
, again depending on the effect you want.
Update
By default, many browsers use padding-left
to set the initial indentation. If you want to get rid of that, set padding-left: 0px;
Still, both margin-left
and padding-left
settings impact the indentation of lists in different ways. Specifically: margin-left
impacts the indentation on the outside of the element's border, whereas padding-left
affects the spacing on the inside of the element's border. (Learn more about the CSS box model here)
Setting padding-left: 0;
leaves the li's bullet icons hanging over the edge of the element's border (at least in Chrome), which may or may not be what you want.
Examples of padding-left vs margin-left and how they can work together on ul: https://jsfiddle.net/daCrosby/bb7kj8cr/1/
First of all do not use list
as a variable name- that is a builtin function.
I'm not super clear of what you're asking (a little more context would help), but maybe this is helpful-
my_list = []
my_list.append(np.genfromtxt('temp.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))
my_list.append(np.genfromtxt('temp2.txt', usecols=3, dtype=[('floatname','float')], skip_header=1))
That will create a list (a type of mutable array in python) called my_list
with the output of the np.getfromtext()
method in the first 2 indexes.
The first can be referenced with my_list[0]
and the second with my_list[1]
On your backEnd, you should add:
@RequestMapping(value="/blabla", produces="text/plain" , method = RequestMethod.GET)
On the frontEnd (Service):
methodBlabla()
{
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
return this.http.get(this.url,{ headers, responseType: 'text'});
}
I had the very same issue. The answer is that you are doing it right already. It is the problem of MS Excel. Try opening the file with another editor and you will notice that your encoding was successful already. To make MS Excel happy, move from UTF-8 to UTF-16. This should work:
class UnicodeWriter:
def __init__(self, f, dialect=csv.excel_tab, encoding="utf-16", **kwds):
# Redirect output to a queue
self.queue = StringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
# Force BOM
if encoding=="utf-16":
import codecs
f.write(codecs.BOM_UTF16)
self.encoding = encoding
def writerow(self, row):
# Modified from original: now using unicode(s) to deal with e.g. ints
self.writer.writerow([unicode(s).encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = data.encode(self.encoding)
# strip BOM
if self.encoding == "utf-16":
data = data[2:]
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
The C++ concept of a lambda function originates in the lambda calculus and functional programming. A lambda is an unnamed function that is useful (in actual programming, not theory) for short snippets of code that are impossible to reuse and are not worth naming.
In C++ a lambda function is defined like this
[]() { } // barebone lambda
or in all its glory
[]() mutable -> T { } // T is the return type, still lacking throw()
[]
is the capture list, ()
the argument list and {}
the function body.
The capture list defines what from the outside of the lambda should be available inside the function body and how. It can be either:
You can mix any of the above in a comma separated list [x, &y]
.
The argument list is the same as in any other C++ function.
The code that will be executed when the lambda is actually called.
If a lambda has only one return statement, the return type can be omitted and has the implicit type of decltype(return_statement)
.
If a lambda is marked mutable (e.g. []() mutable { }
) it is allowed to mutate the values that have been captured by value.
The library defined by the ISO standard benefits heavily from lambdas and raises the usability several bars as now users don't have to clutter their code with small functors in some accessible scope.
In C++14 lambdas have been extended by various proposals.
An element of the capture list can now be initialized with =
. This allows renaming of variables and to capture by moving. An example taken from the standard:
int x = 4;
auto y = [&r = x, x = x+1]()->int {
r += 2;
return x+2;
}(); // Updates ::x to 6, and initializes y to 7.
and one taken from Wikipedia showing how to capture with std::move
:
auto ptr = std::make_unique<int>(10); // See below for std::make_unique
auto lambda = [ptr = std::move(ptr)] {return *ptr;};
Lambdas can now be generic (auto
would be equivalent to T
here if
T
were a type template argument somewhere in the surrounding scope):
auto lambda = [](auto x, auto y) {return x + y;};
C++14 allows deduced return types for every function and does not restrict it to functions of the form return expression;
. This is also extended to lambdas.
The following should work:
public static void main(String[] args)
{
final String title = "Test Window";
final int width = 1200;
final int height = width / 16 * 9;
//Creating the frame.
JFrame frame = new JFrame(title);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
//Creating the canvas.
Canvas canvas = new Canvas();
canvas.setSize(width, height);
canvas.setBackground(Color.BLACK);
canvas.setVisible(true);
canvas.setFocusable(false);
//Putting it all together.
frame.add(canvas);
canvas.createBufferStrategy(3);
boolean running = true;
BufferStrategy bufferStrategy;
Graphics graphics;
while (running) {
bufferStrategy = canvas.getBufferStrategy();
graphics = bufferStrategy.getDrawGraphics();
graphics.clearRect(0, 0, width, height);
graphics.setColor(Color.GREEN);
graphics.drawString("This is some text placed in the top left corner.", 5, 15);
bufferStrategy.show();
graphics.dispose();
}
}
Use itext libray:
Here is the sample code. It is working perfectly fine:
String htmlFilePath = filePath + ".html";
String pdfFilePath = filePath + ".pdf";
// create an html file on given file path
Writer unicodeFileWriter = new OutputStreamWriter(new FileOutputStream(htmlFilePath), "UTF-8");
unicodeFileWriter.write(document.toString());
unicodeFileWriter.close();
ConverterProperties properties = new ConverterProperties();
properties.setCharset("UTF-8");
if (url.contains(".kr") || url.contains(".tw") || url.contains(".cn") || url.contains(".jp")) {
properties.setFontProvider(new DefaultFontProvider(false, false, true));
}
// convert the html file to pdf file.
HtmlConverter.convertToPdf(new File(htmlFilePath), new File(pdfFilePath), properties);
Maven dependencies
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext7-core</artifactId>
<version>7.1.6</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>2.1.3</version>
</dependency>
Simple, use array_intersect()
instead:
$result = array_intersect($array1, $array2);
A CLASSPATH entry is either a directory at the head of a package hierarchy of .class files, or a .jar file. If you're expecting ./lib
to include all the .jar files in that directory, it won't. You have to name them explicitly.
The best way to handle this (with ease and no additional software) is with Excel - but using Powerpivot (which has MSFT Power Query embedded). Simply create a new Power Pivot data model that attaches to your large csv or text file. You will then be able to import multi-million rows into memory using the embedded X-Velocity (in-memory compression) engine. The Excel sheet limit is not applicable - as the X-Velocity engine puts everything up in RAM in compressed form. I have loaded 15 million rows and filtered at will using this technique. Hope this helps someone... - Jaycee
Yet another alternative if you have a controller just specific to that page:
(function(){
//code to run
}());
A simple code to list all the Items from DynamoDB Table by specifying the region of AWS Service.
import boto3
dynamodb = boto3.resource('dynamodb', region_name='ap-south-1')
table = dynamodb.Table('puppy_store')
response = table.scan()
items = response['Items']
# Prints All the Items at once
print(items)
# Prints Items line by line
for i, j in enumerate(items):
print(f"Num: {i} --> {j}")
You need to use document.write()
<div>foo</div>
<script>
document.write('<div>Print this after the script tag</div>');
</script>
<div>bar</div>
Note that this will only work if you are in the process of writing the document. Once the document has been rendered, calling document.write()
will clear the document and start writing a new one. Please refer to other answers provided to this question if this is your use case.
Put the database password in a file, make it read-only to the user serving the files.
Unless you have some means of only allowing the php server process to access the database, this is pretty much all you can do.
Why do you use Restrictions.like(...
)?
You should use Restrictions.eq(...)
.
Note you can also use .le
, .lt
, .ge
, .gt
on date objects as comparison operators. LIKE
operator is not appropriate for this case since LIKE
is useful when you want to match results according to partial content of a column.
Please see http://www.sql-tutorial.net/SQL-LIKE.asp for the reference.
For example if you have a name column with some people's full name, you can do where name like 'robert %'
so that you will return all entries with name starting with 'robert '
(%
can replace any character).
In your case you know the full content of the date you're trying to match so you shouldn't use LIKE
but equality. I guess Hibernate doesn't give you any exception in this case, but anyway you will probably have the same problem with the Restrictions.eq(...)
.
Your date object you got with the code:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
String myDate = "17-04-2011";
Date date = formatter.parse(myDate);
This date object is equals to the 17-04-2011 at 0h, 0 minutes, 0 seconds and 0 nanoseconds.
This means that your entries in database must have exactly that date. What i mean is that if your database entry has a date "17-April-2011 19:20:23.707000000", then it won't be retrieved because you just ask for that date: "17-April-2011 00:00:00.0000000000".
If you want to retrieve all entries of your database from a given day, you will have to use the following code:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
String myDate = "17-04-2011";
// Create date 17-04-2011 - 00h00
Date minDate = formatter.parse(myDate);
// Create date 18-04-2011 - 00h00
// -> We take the 1st date and add it 1 day in millisecond thanks to a useful and not so known class
Date maxDate = new Date(minDate.getTime() + TimeUnit.DAYS.toMillis(1));
Conjunction and = Restrictions.conjunction();
// The order date must be >= 17-04-2011 - 00h00
and.add( Restrictions.ge("orderDate", minDate) );
// And the order date must be < 18-04-2011 - 00h00
and.add( Restrictions.lt("orderDate", maxDate) );
Your data is problematic in that you have inner wrapper objects in your array. Presumably your Vendor
object is designed to handle id
, name
, company_id
, but each of those multiple objects are also wrapped in an object with a single property vendor
.
I'm assuming that you're using the Jackson Data Binding model.
If so then there are two things to consider:
The first is using a special Jackson config property. Jackson - since 1.9 I believe, this may not be available if you're using an old version of Jackson - provides UNWRAP_ROOT_VALUE
. It's designed for cases where your results are wrapped in a top-level single-property object that you want to discard.
So, play around with:
objectMapper.configure(SerializationConfig.Feature.UNWRAP_ROOT_VALUE, true);
The second is using wrapper objects. Even after discarding the outer wrapper object you still have the problem of your Vendor
objects being wrapped in a single-property object. Use a wrapper to get around this:
class VendorWrapper
{
Vendor vendor;
// gettors, settors for vendor if you need them
}
Similarly, instead of using UNWRAP_ROOT_VALUES
, you could also define a wrapper class to handle the outer object. Assuming that you have correct Vendor
, VendorWrapper
object, you can define:
class VendorsWrapper
{
List<VendorWrapper> vendors = new ArrayList<VendorWrapper>();
// gettors, settors for vendors if you need them
}
// in your deserialization code:
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readValue(jsonInput, VendorsWrapper.class);
The object tree for VendorsWrapper is analogous to your JSON:
VendorsWrapper:
vendors:
[
VendorWrapper
vendor: Vendor,
VendorWrapper:
vendor: Vendor,
...
]
Finally, you might use the Jackson Tree Model to parse this into JsonNodes
, discarding the outer node, and for each JsonNode
in the ArrayNode
, calling:
mapper.readValue(node.get("vendor").getTextValue(), Vendor.class);
That might result in less code, but it seems no less clumsy than using two wrappers.
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
#include <cstdlib>
...
/*wherever you want it to end, e.g. in an if-statement:*/
if (T == 0)
{
exit(0);
}
success
only fires if the AJAX call is successful, i.e. ultimately returns a HTTP 200 status. error
fires if it fails and complete
when the request finishes, regardless of success.
In jQuery 1.8 on the jqXHR
object (returned by $.ajax
) success
was replaced with done
, error
with fail
and complete
with always
.
However you should still be able to initialise the AJAX request with the old syntax. So these do similar things:
// set success action before making the request
$.ajax({
url: '...',
success: function(){
alert('AJAX successful');
}
});
// set success action just after starting the request
var jqxhr = $.ajax( "..." )
.done(function() { alert("success"); });
This change is for compatibility with jQuery 1.5's deferred object. Deferred (and now Promise
, which has full native browser support in Chrome and FX) allow you to chain asynchronous actions:
$.ajax("parent").
done(function(p) { return $.ajax("child/" + p.id); }).
done(someOtherDeferredFunction).
done(function(c) { alert("success: " + c.name); });
This chain of functions is easier to maintain than a nested pyramid of callbacks you get with success
.
However, please note that done
is now deprecated in favour of the Promise
syntax that uses then
instead:
$.ajax("parent").
then(function(p) { return $.ajax("child/" + p.id); }).
then(someOtherDeferredFunction).
then(function(c) { alert("success: " + c.name); }).
catch(function(err) { alert("error: " + err.message); });
This is worth adopting because async
and await
extend promises improved syntax (and error handling):
try {
var p = await $.ajax("parent");
var x = await $.ajax("child/" + p.id);
var c = await someOtherDeferredFunction(x);
alert("success: " + c.name);
}
catch(err) {
alert("error: " + err.message);
}
list(your_iterator)
./gradlew
Your directory with gradlew is not included in the PATH, so you must specify path to the gradlew. .
means "current directory".
To overcome this problem you can write an ActionMethodSelectorAttribute
that examines the MethodInfo
for each action and compares it to the posted Form values and then rejects any method for which the form values don't match (excluding the button name, of course).
Here's an example:- http://blog.abodit.com/2010/02/asp-net-mvc-ambiguous-match/
BUT, this isn't a good idea.
Well, local storage speed greatly depends on the browser the client is using, as well as the operating system. Chrome or Safari on a mac could be much faster than Firefox on a PC, especially with newer APIs. As always though, testing is your friend (I could not find any benchmarks).
I really don't see a huge difference in cookie vs local storage. Also, you should be more worried about compatibility issues: not all browsers have even begun to support the new HTML5 APIs, so cookies would be your best bet for speed and compatibility.
When you create a database in Microsoft SQL Server you can have multiple file groups, where storage is created in multiple places, directories or disks. Each file group can be named. The PRIMARY file group is the default one, which is always created, and so the SQL you've given creates your table ON the PRIMARY file group.
See MSDN for the full syntax.
setInterval(function()
{
$.ajax({
type:"post",
url:"myurl.html",
datatype:"html",
success:function(data)
{
//do something with response data
}
});
}, 10000);//time in milliseconds
There are several options. You can use the WebMethod attribute, for your purpose.
Git 2.7 (Q4 2015) will introduce -local
as an instruction.
It means that, in addition to:
--date=(relative|local|default|iso|iso-strict|rfc|short|raw)
you will also have:
--date=(default-local|iso-local|iso-strict-local|rfc-local|short-local)
The -local
suffix cannot be used with raw
or relative
. Reference.
You now can ask for any date format using the local timezone. See
johnkeeping
). See commit add00ba, commit 547ed71 (03 Sep 2015) by Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit 7b09c45, 05 Oct 2015)
In particular, the last from above (commit add00ba) mentions:
date
: make "local
" orthogonal to date format:Most of our "
--date
" modes are about the format of the date: which items we show and in what order.
But "--date=local
" is a bit of an oddball. It means "show the date in the normal format, but using the local timezone".
The timezone we use is orthogonal to the actual format, and there is no reason we could not have "localized iso8601", etc.This patch adds a "
local
" boolean field to "struct date_mode
", and drops theDATE_LOCAL
element from thedate_mode_type
enum (it's now justDATE_NORMAL
pluslocal=1
).
The new feature is accessible to users by adding "-local
" to any date mode (e.g., "iso-local
"), and we retain "local
" as an alias for "default-local
" for backwards compatibility.
It was due to WWWRoot directory security issue.
Simple solution is, Just copy applicatio folder to some other drive, Instead of "C:\Inetpub\wwwroot" and then create a virtual directory for this new path. That's it.
I had this error because I registered the wrong class in this line of code:
JAXBContext context = JAXBContext.newInstance(MyRootXmlClass.class);
(Angular 2 - Angular 7)
Component can be declared in a single module only. In order to use a component from another module, you need to do two simple tasks:
1st Module:
Have a component (lets call it: "ImportantCopmonent"), we want to re-use in the 2nd Module's page.
@NgModule({
declarations: [
FirstPage,
ImportantCopmonent // <-- Enable using the component html tag in current module
],
imports: [
IonicPageModule.forChild(NotImportantPage),
TranslateModule.forChild(),
],
exports: [
FirstPage,
ImportantCopmonent // <--- Enable using the component in other modules
]
})
export class FirstPageModule { }
2nd Module:
Reuses the "ImportantCopmonent", by importing the FirstPageModule
@NgModule({
declarations: [
SecondPage,
Example2ndComponent,
Example3rdComponent
],
imports: [
IonicPageModule.forChild(SecondPage),
TranslateModule.forChild(),
FirstPageModule // <--- this Imports the source module, with its exports
],
exports: [
SecondPage,
]
})
export class SecondPageModule { }
I'll edit my previous answer based on further info supplied. You can clearely ping the remote computer as you can use terminal services.
I've a feeling that port 1433 is being blocked by a firewall, hence your trouble. See TCP Ports Needed for Communication to SQL Server Through a Firewall by Microsoft.
Try using this application to ping your servers ip address and port 1433.
tcping your.server.ip.address 1433
And see if you get a "Port is open" response from tcping.
Ok, next to try is to check SQL Server. RDP onto the SQL Server computer. Start SSMS. Connect to the database. In object explorer (usually docked on the left) right click on the server and click properties.
alt text http://www.hicrest.net/server_prop_menu.jpg
Goto the Connections settings and make sure "Allow remote connections to this server" is ticket.
An IEnumerator
is a thing that can enumerate: it has the Current
property and the MoveNext
and Reset
methods (which in .NET code you probably won't call explicitly, though you could).
An IEnumerable
is a thing that can be enumerated...which simply means that it has a GetEnumerator method that returns an IEnumerator
.
Which do you use? The only reason to use IEnumerator
is if you have something that has a nonstandard way of enumerating (that is, of returning its various elements one-by-one), and you need to define how that works. You'd create a new class implementing IEnumerator
. But you'd still need to return that IEnumerator
in an IEnumerable
class.
For a look at what an enumerator (implementing IEnumerator<T>
) looks like, see any Enumerator<T>
class, such as the ones contained in List<T>
, Queue<T>,
or Stack<T>
. For a look at a class implementing IEnumerable
, see any standard collection class.
String
values are not implementation dependent, according the ECMA-262 3rd Edition Specification, each character represents a single 16-bit unit of UTF-16 text:
4.3.16 String Value
A string value is a member of the type String and is a finite ordered sequence of zero or more 16-bit unsigned integer values.
NOTE Although each value usually represents a single 16-bit unit of UTF-16 text, the language does not place any restrictions or requirements on the values except that they be 16-bit unsigned integers.
A little risky, but you could run a curl POST command with the values from the form from the JMX console, its URL and http authentication (if required):
curl -s -X POST --user 'myuser:mypass'
--data "action=invokeOp&name=App:service=ThisServiceOp&methodIndex=3&arg0=value1&arg1=value1&submit=Invoke"
http://yourhost.domain.com/jmx-console/HtmlAdaptor
Beware: the method index may change with changes to the software. And the implementation of the web form could change.
The above is based on source of the JMX service page for the operation you want to perform:
http://yourhost.domain.com/jmx-console/HtmlAdaptor?action=inspectMBean&name=YourJMXServiceName
Source of the form:
form method="post" action="HtmlAdaptor">
<input type="hidden" name="action" value="invokeOp">
<input type="hidden" name="name" value="App:service=ThisServiceOp">
<input type="hidden" name="methodIndex" value="3">
<hr align='left' width='80'>
<h4>void ThisOperation()</h4>
<p>Operation exposed for management</p>
<table cellspacing="2" cellpadding="2" border="1">
<tr class="OperationHeader">
<th>Param</th>
<th>ParamType</th>
<th>ParamValue</th>
<th>ParamDescription</th>
</tr>
<tr>
<td>p1</td>
<td>java.lang.String</td>
<td>
<input type="text" name="arg0">
</td>
<td>(no description)</td>
</tr>
<tr>
<td>p2</td>
<td>arg1Type</td>
<td>
<input type="text" name="arg1">
</td>
<td>(no description)</td>
</tr>
</table>
<input type="submit" value="Invoke">
</form>
Use break, as such:
while(choice!=99)
{
cin>>choice;
if (choice==99)
break; //exit here and don't get additional input
cin>>gNum;
}
This works for for loops also, and is the keyword for ending a switch clause. More info here.
try this one http://code.google.com/p/geckofx/ hope it ain't dupe or this one i think is better http://webkitdotnet.sourceforge.net/
Running the command prompt or Powershell ISE as an administrator fixed this for me.
If i am understanding your question, would this work? (you will have to replace with your actual column and table names)
SELECT time_col, COUNT(time_col) As Count
FROM time_table
GROUP BY time_col
WHERE activity_col = 3
Although there are many acceptable answers in response to this question, I don't see any examples of the sub
method using the \Datetime
object: https://www.php.net/manual/en/datetime.sub.php
So, for reference, you can also use a \DateInterval
to modify a \Datetime
object:
$date = new \DateTime('2009-01-01');
$date->sub(new \DateInterval('P1Y'));
echo $date->format('Y-m-d');
Which returns:
2008-01-01
For more information about \DateInterval
, refer to the documentation: https://www.php.net/manual/en/class.dateinterval.php
File protocol URIs are like this
file://[HOST]/[PATH]
that's why you often see file URLs like this (3 slashes) file:///c:\path...
So if the host is server01, you want
file://server01/folder/path....
This is according to the wikipedia page on file:// protocols and checks out with .NET's Uri.IsWellFormedUriString method.
public OnClickListener moreListener = new OnClickListener() {
@Override
public void onClick(View v) {
adapter.add("aaaa")
}
}
Ahh, found the answer myself:
if (/[a-zA-Z]/.test(num)) {
alert('Letter Found')
}
So that its value can easily contain quotes and <> characters and respect whitespace and newlines.
The following HTML code successfully pass the w3c validator and displays <,> and & without the need to encode them. It also respects the white spaces.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Yes I can</title>
</head>
<body>
<textarea name="test">
I can put < and > and & signs in
my textarea without any problems.
</textarea>
</body>
</html>
There is an .Offset property on a Range class which allows you to do just what you need
ActiveCell.Offset(numRows, numCols)
follow up on a comment:
Dim newRange as Range
Set newRange = Range(ActiveCell, ActiveCell.Offset(numRows, numCols))
and you can verify by MsgBox newRange.Address
sudo service mongod stop
sudo apt-get purge mongodb-org*
sudo rm -r /var/log/mongodb
sudo rm -r /var/lib/mongodb
this worked for me
For a simple stored procedure that using IN/OUT parameters like this
CREATE OR REPLACE PROCEDURE count_comments (
postId IN NUMBER,
commentCount OUT NUMBER )
AS
BEGIN
SELECT COUNT(*) INTO commentCount
FROM post_comment
WHERE post_id = postId;
END;
You can call it from JPA as follows:
StoredProcedureQuery query = entityManager
.createStoredProcedureQuery("count_comments")
.registerStoredProcedureParameter(1, Long.class,
ParameterMode.IN)
.registerStoredProcedureParameter(2, Long.class,
ParameterMode.OUT)
.setParameter(1, 1L);
query.execute();
Long commentCount = (Long) query.getOutputParameterValue(2);
For a stored procedure which uses a SYS_REFCURSOR
OUT parameter:
CREATE OR REPLACE PROCEDURE post_comments (
postId IN NUMBER,
postComments OUT SYS_REFCURSOR )
AS
BEGIN
OPEN postComments FOR
SELECT *
FROM post_comment
WHERE post_id = postId;
END;
You can call it as follows:
StoredProcedureQuery query = entityManager
.createStoredProcedureQuery("post_comments")
.registerStoredProcedureParameter(1, Long.class,
ParameterMode.IN)
.registerStoredProcedureParameter(2, Class.class,
ParameterMode.REF_CURSOR)
.setParameter(1, 1L);
query.execute();
List<Object[]> postComments = query.getResultList();
For a SQL function that looks as follows:
CREATE OR REPLACE FUNCTION fn_count_comments (
postId IN NUMBER )
RETURN NUMBER
IS
commentCount NUMBER;
BEGIN
SELECT COUNT(*) INTO commentCount
FROM post_comment
WHERE post_id = postId;
RETURN( commentCount );
END;
You can call it like this:
BigDecimal commentCount = (BigDecimal) entityManager
.createNativeQuery(
"SELECT fn_count_comments(:postId) FROM DUAL"
)
.setParameter("postId", 1L)
.getSingleResult();
At least when using Hibernate 4.x and 5.x because the JPA StoredProcedureQuery
does not work for SQL FUNCTIONS.
For more details about how to call stored procedures and functions when using JPA and Hibernate, check out the following articles
Unfortunately the only thing that worked for me was completely deleting and recreating the class library project, after having temporarily copied the class files in it elsewhere. Only then would the ASP.Net web project recognise the using
statements that referred to the class library project. This was with Visual Studio 2010, not using ReSharper.
I was looking a lot to find a solution for sticy menue with old school JS (without JQuery). So I build small test to play with it. I think it can be helpfull to those looking for solution in js. It needs improvments of unsticking the menue back, and making it more smooth. Also I find a nice solution with JQuery that clones the original div instead of position fixed, its better since the rest of page element dont need to be replaced after fixing. Anyone know how to that with JS ? Please remark, correct and improve.
<!DOCTYPE html>
<html>
<head>
<script>
// addEvent function by John Resig:
// http://ejohn.org/projects/flexible-javascript-events/
function addEvent( obj, type, fn ) {
if ( obj.attachEvent ) {
obj['e'+type+fn] = fn;
obj[type+fn] = function(){obj['e'+type+fn]( window.event );};
obj.attachEvent( 'on'+type, obj[type+fn] );
} else {
obj.addEventListener( type, fn, false );
}
}
function getScrollY() {
var scrOfY = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
//Netscape compliant
scrOfY = window.pageYOffset;
} else if( document.body && document.body.scrollTop ) {
//DOM compliant
scrOfY = document.body.scrollTop;
}
return scrOfY;
}
</script>
<style>
#mydiv {
height:100px;
width:100%;
}
#fdiv {
height:100px;
width:100%;
}
</style>
</head>
<body>
<!-- HTML for example event goes here -->
<div id="fdiv" style="background-color:red;position:fix">
</div>
<div id="mydiv" style="background-color:yellow">
</div>
<div id="fdiv" style="background-color:green">
</div>
<script>
// Script for example event goes here
addEvent(window, 'scroll', function(event) {
var x = document.getElementById("mydiv");
var y = getScrollY();
if (y >= 100) {
x.style.position = "fixed";
x.style.top= "0";
}
});
</script>
</body>
</html>
You can use a property setter to raise an event whenever the value of a field is going to change.
You can have your own EventHandler delegate or you can use the famous System.EventHandler delegate.
Usually there's a pattern for this:
Here's an example
private int _age;
//#1
public event System.EventHandler AgeChanged;
//#2
protected virtual void OnAgeChanged()
{
if (AgeChanged != null) AgeChanged(this,EventArgs.Empty);
}
public int Age
{
get
{
return _age;
}
set
{
//#3
_age=value;
OnAgeChanged();
}
}
The advantage of this approach is that you let any other classes that want to inherit from your class to change the behavior if necessary.
If you want to catch an event in a different thread that it's being raised you must be careful not to change the state of objects that are defined in another thread which will cause a cross thread exception to be thrown. To avoid this you can either use an Invoke method on the object that you want to change its state to make sure that the change is happening in the same thread that the event has been raised or in case that you are dealing with a Windows Form you can use a BackgourndWorker to do things in a parallel thread nice and easy.
This gets you X and X' as variant arrays you can pass to another function.
Dim X() As Variant
Dim XT() As Variant
X = ActiveSheet.Range("InRng").Value2
XT = Application.Transpose(X)
To have the transposed values as a range, you have to pass it via a worksheet as in this answer. Without seeing how your covariance function works it's hard to see what you need.
The easiest way to do it is to link the CSV-file into the Access database as a table. Then you can work on this table as if it was an ordinary access table, for instance by creating an appropriate query based on this table that returns exactly what you want.
You can link the table either manually or with VBA like this
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
FileName:="C:\MyData.csv", HasFieldNames:=true
Dim db As DAO.Database
' Re-link the CSV Table
Set db = CurrentDb
On Error Resume Next: db.TableDefs.Delete "tblImport": On Error GoTo 0
db.TableDefs.Refresh
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
FileName:="C:\MyData.csv", HasFieldNames:=true
db.TableDefs.Refresh
' Perform the import
db.Execute "INSERT INTO someTable SELECT col1, col2, ... FROM tblImport " _
& "WHERE NOT F1 IN ('A1', 'A2', 'A3')"
db.Close: Set db = Nothing
I tried a few ones above but they seem to reset @ 1000
This one definately works, and should also take year into consideration
long millisStart = Calendar.getInstance().getTimeInMillis();
and then do the same for end time if needed.
This is what you wanna do:
var oldSrc = 'http://example.com/smith.gif';
var newSrc = 'http://example.com/johnson.gif';
$('img[src="' + oldSrc + '"]').attr('src', newSrc);
This answer was so obvious and it took me forever to figure out:
echo "foo
bar";
I know that looks like it's wrapping. It's not. What I did is I literally hit return halfway through the string, between foo
and bar
. It creates a new line in the HTML source and makes your PHP look horrible. This was in Linux/Apache.
A hack the I've used on Solaris 9 and Linux and which works fine for both of them:
ps -o user= -p $$ | awk '{print $1}'
This snippet prints the name of the user with the current EUID.
NOTE: you need Bash as the interpreter here.
On Solaris you have problems with methods, described above:
id
does not accept the -u
and -n
parameters (so you will have to parse the output)whoami
does not exist (by default)who am I
prints owner of current terminal (ignores EUID)$USER
variable is set correctly only after reading profile files (for example, /etc/profile
)To clarify some of the logical equivalence solutions.
An if statement
if (a) then b
is logically equivalent to
(!a || b)
It's the first line on the Logical equivalences involving conditional statements section of the Logical equivalence wikipedia article.
To include the else, all you would do is add another conditional
if(a) then b;
if(!a) then c;
which is logically equivalent to (!a || b) && (a || c)
So using the OP as an example:
IF IsNumeric(@OrderNumber) = 1
OrderNumber = @OrderNumber
ELSE
OrderNumber LIKE '%' + @OrderNumber + '%'
the logical equivalent would be:
(IsNumeric(@OrderNumber) <> 1 OR OrderNumber = @OrderNumber)
AND (IsNumeric(@OrderNumber) = 1 OR OrderNumber LIKE '%' + @OrderNumber + '%' )
When throw specifications were added to the language it was with the best intentions, but practice has borne out a more practical approach.
With C++, my general rule of thumb is to only use throw specifications to indicate that a method can't throw. This is a strong guarantee. Otherwise, assume it could throw anything.
The document has moved here it seems: https://help.apple.com/xcode/mac/8.0/#/dev564169bb1
Can't copy the icons here, but here are the descriptions:
Show: Present the content in the detail or master area depending on the content of the screen.
If the app is displaying a master and detail view, the content is pushed onto the detail area. If the app is only displaying the master or the detail, the content is pushed on top of the current view controller stack.
Show Detail: Present the content in the detail area.
If the app is displaying a master and detail view, the new content replaces the current detail. If the app is only displaying the master or the detail, the content replaces the top of the current view controller stack.
Present Modally: Present the content modally.
Present as Popover: Present the content as a popover anchored to an existing view.
Custom: Create your own behaviors by using a custom segue.
I have used a script but to make a join, maybe I can help you
string Email = String.Join(", ", Emails.Where(i => i.Email != "").Select(i => i.Email).Distinct());
Use inline styles:
<div class="button" style="width:60px;height:100px;">This is a button</div>
$("html, body").scrollTop($(element).offset().top); // <-- Also integer can be used
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
Given annotation worked for me. Can have a try
For Example :-
public class Parent{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="cct_id")
private Integer cct_id;
@OneToMany(cascade=CascadeType.REMOVE, fetch=FetchType.EAGER,mappedBy="clinicalCareTeam", orphanRemoval=true)
@Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
private List<Child> childs;
}
public class Child{
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="cct_id")
private Parent parent;
}
I use something similar, but with opposite logic, in a lot of my functions.
DWORD dwError = ERROR_SUCCESS;
do
{
if ( (dwError = SomeFunction()) != ERROR_SUCCESS )
{
/* handle error */
continue;
}
if ( (dwError = SomeOtherFunction()) != ERROR_SUCCESS )
{
/* handle error */
continue;
}
}
while ( 0 );
if ( dwError != ERROR_SUCCESS )
{
/* resource cleanup */
}
If you are more visual like myself, you can use the Visual Studio Code configurations in menu File ? Preferences ? Settings (Ctrl + ,). Go to Extensions ? Python.
In the section Analysis: Disabled, add the suppression of the following message: unresolved-import
:
Move pod members to a base class to shorten your initializer list:
struct foo_pod
{
int x;
int y;
int z;
};
struct foo : foo_pod
{
std::string name;
foo(std::string name)
: foo_pod()
, name(name)
{
}
};
int main()
{
foo f("bar");
printf("%d %d %d %s\n", f.x, f.y, f.z, f.name.c_str());
}
Java 10 introduced List#copyOf
which returns unmodifiable List while preserving the order:
List<Integer> list = List.copyOf(coll);
Try this:
<style>
#wrapper { position: relative; }
#over_map { position: absolute; top: 10px; left: 10px; z-index: 99; }
</style>
<div id="wrapper">
<div id="google_map">
</div>
<div id="over_map">
</div>
</div>
It is globally method for rounded border of UIButton
class func setRoundedBorderButton(btn:UIButton)
{
btn.layer.cornerRadius = btn.frame.size.height/2
btn.layer.borderWidth = 0.5
btn.layer.borderColor = UIColor.darkGray.cgColor
}
It's very easy:
numb = raw_input('Input Line: ')
fiIn = open('file.txt').readlines()
for lines in fiIn:
if numb == lines[0]:
print lines
If you are certain that the script runs in the first hours of the day, you can simply do
date -d "12 hours ago" '+%Y-%m-%d'
BTW, if the script runs daily at 00:35 (via crontab?) you should ask yourself what will happen if a DST change falls in that hour; the script could not run, or run twice in some cases. Modern implementations of cron
are quite clever in this regard, though.
In MSDN, Assembly.GetExecutingAssembly Method, is remark about method "getexecutingassembly", that for performance reasons, you should call this method only when you do not know at design time what assembly is currently executing.
The recommended way to retrieve an Assembly object that represents the current assembly is to use the Type.Assembly
property of a type found in the assembly.
The following example illustrates:
using System;
using System.Reflection;
public class Example
{
public static void Main()
{
Console.WriteLine("The version of the currently executing assembly is: {0}",
typeof(Example).Assembly.GetName().Version);
}
}
/* This example produces output similar to the following:
The version of the currently executing assembly is: 1.1.0.0
Of course this is very similar to the answer with helper class "public static class CoreAssembly", but, if you know at least one type of executing assembly, it isn't mandatory to create a helper class, and it saves your time.
This piece of code may help..
#include <bits/stdc++.h>
using namespace std;
class node{
public:
int age;
string name;
node(int a, string b){
age = a;
name = b;
}
};
bool operator<(const node& a, const node& b) {
node temp1=a,temp2=b;
if(a.age != b.age)
return a.age > b.age;
else{
return temp1.name.append(temp2.name) > temp2.name.append(temp1.name);
}
}
int main(){
priority_queue<node> pq;
node b(23,"prashantandsoon..");
node a(22,"prashant");
node c(22,"prashantonly");
pq.push(b);
pq.push(a);
pq.push(c);
int size = pq.size();
for (int i = 0; i < size; ++i)
{
cout<<pq.top().age<<" "<<pq.top().name<<"\n";
pq.pop();
}
}
Output:
22 prashantonly
22 prashant
23 prashantandsoon..
If you have android, you can install free app on phone (Wifi file Transfer) and enable ssl, port and other options for access and send data in both directions just start application and write in pc browser phone ip and port. enjoy!
Use the Native JavaScript Methods: String.trimLeft()
, String.trimRight()
, and String.trim()
.
String.trim()
is supported in IE9+ and all other major browsers:
' Hello '.trim() //-> 'Hello'
String.trimLeft()
and String.trimRight()
are non-standard, but are supported in all major browsers except IE
' Hello '.trimLeft() //-> 'Hello '
' Hello '.trimRight() //-> ' Hello'
IE support is easy with a polyfill however:
if (!''.trimLeft) {
String.prototype.trimLeft = function() {
return this.replace(/^\s+/,'');
};
String.prototype.trimRight = function() {
return this.replace(/\s+$/,'');
};
if (!''.trim) {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
};
}
}
To use window.open() in safari you must put it in an element's onclick event attribute.
For example:
<button class='btn' onclick='window.open("https://www.google.com", "_blank");'>Open Google search</button>
try
yum install php-pdo
yum install php-pdo_mysql
service httpd restart
I use this command for scripts which extracts data for dimensional tables (DW). So, I use the following syntax:
set colsep '|'
set echo off
set feedback off
set linesize 1000
set pagesize 0
set sqlprompt ''
set trimspool on
set headsep off
spool output.dat
select '|', <table>.*, '|'
from <table>
where <conditions>
spool off
And works. I don't use sed for format the output file.
To increase the heap size you can use the -Xmx argument when starting Java; e.g.
-Xmx256M
I know this might be a little late but here is a very good article on how to manually add Android ADB USB Driver. Manually adding Android ADB USB driver in Ubuntu 14.04 LTS
Edited to Add Link Content
Note: Make sure that you have connected your Android device in USB Debugging mode
Open terminal (CTRL + ALT + T
) and enter command:
lsusb
Now you might get a similar reply to this:
Bus 002 Device 013: ID 283b:1024
Note:
With reference to this Bus 002 Device 008: ID 283b:1024
{idVendor}==”283b”
{idProduct}==”1024"
Now enter the following command:
sudo gedit /etc/udev/rules.d/51-android.rules
This creates the android rules file (51-android.rules
) or open the existing one in the specified location (/etc/udev/rules.d
)
Add a new line to this file:
SUBSYSTEM==”usb”, ATTRS{idVendor}==”283b”, ATTRS{idProduct}==”1024", MODE=”0666"
Note Edit idVendor
& idProduct
values with your device values.
Save and close.
Now enter the following command:
sudo chmod a+rx /etc/udev/rules.d/51-android.rules
- grant read/execution permission
sudo service udev restart
- Restart the udev
service
Now we have to add the idVendor
to adb_usb.ini
. Enter the following commands:
cd ~/.android
gedit adb_usb.ini
Add the following value
0x283b
This is nothing but 0x(idVendor
value). So replace the value with. respect to your device value
Save and close the file.
Now enter the following command:
sudo service udev restart
Plug out the Android device and reconnect it again.
Now enter the following command:
adb kill-server
adb devices
There you go! Your device must be listed.
Copied From Manually adding Android ADB USB driver in Ubuntu 14.04 LTS
Worked for me.
If you only want to change the route for picture.php
then adding rewrite rule in .htaccess
will serve your needs, but, if you want the URL rewriting as in Wordpress then PHP is the way. Here is simple example to begin with.
Folder structure
There are two files that are needed in the root folder, .htaccess
and index.php
, and it would be good to place the rest of the .php
files in separate folder, like inc/
.
root/
inc/
.htaccess
index.php
.htaccess
RewriteEngine On
RewriteRule ^inc/.*$ index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]
This file has four directives:
RewriteEngine
- enable the rewriting engineRewriteRule
- deny access to all files in inc/
folder, redirect any call to that folder to index.php
RewriteCond
- allow direct access to all other files ( like images, css or scripts )RewriteRule
- redirect anything else to index.php
index.php
Because everything is now redirected to index.php, there will be determined if the url is correct, all parameters are present, and if the type of parameters are correct.
To test the url we need to have a set of rules, and the best tool for that is a regular expression. By using regular expressions we will kill two flies with one blow. Url, to pass this test must have all the required parameters that are tested on allowed characters. Here are some examples of rules.
$rules = array(
'picture' => "/picture/(?'text'[^/]+)/(?'id'\d+)", // '/picture/some-text/51'
'album' => "/album/(?'album'[\w\-]+)", // '/album/album-slug'
'category' => "/category/(?'category'[\w\-]+)", // '/category/category-slug'
'page' => "/page/(?'page'about|contact)", // '/page/about', '/page/contact'
'post' => "/(?'post'[\w\-]+)", // '/post-slug'
'home' => "/" // '/'
);
Next is to prepare the request uri.
$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );
Now that we have the request uri, the final step is to test uri on regular expression rules.
foreach ( $rules as $action => $rule ) {
if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
/* now you know the action and parameters so you can
* include appropriate template file ( or proceed in some other way )
*/
}
}
Successful match will, since we use named subpatterns in regex, fill the $params
array almost the same as PHP fills the $_GET
array. However, when using a dynamic url, $_GET
array is populated without any checks of the parameters.
/picture/some+text/51 Array ( [0] => /picture/some text/51 [text] => some text [1] => some text [id] => 51 [2] => 51 ) picture.php?text=some+text&id=51 Array ( [text] => some text [id] => 51 )
These few lines of code and a basic knowing of regular expressions is enough to start building a solid routing system.
Complete source
define( 'INCLUDE_DIR', dirname( __FILE__ ) . '/inc/' );
$rules = array(
'picture' => "/picture/(?'text'[^/]+)/(?'id'\d+)", // '/picture/some-text/51'
'album' => "/album/(?'album'[\w\-]+)", // '/album/album-slug'
'category' => "/category/(?'category'[\w\-]+)", // '/category/category-slug'
'page' => "/page/(?'page'about|contact)", // '/page/about', '/page/contact'
'post' => "/(?'post'[\w\-]+)", // '/post-slug'
'home' => "/" // '/'
);
$uri = rtrim( dirname($_SERVER["SCRIPT_NAME"]), '/' );
$uri = '/' . trim( str_replace( $uri, '', $_SERVER['REQUEST_URI'] ), '/' );
$uri = urldecode( $uri );
foreach ( $rules as $action => $rule ) {
if ( preg_match( '~^'.$rule.'$~i', $uri, $params ) ) {
/* now you know the action and parameters so you can
* include appropriate template file ( or proceed in some other way )
*/
include( INCLUDE_DIR . $action . '.php' );
// exit to avoid the 404 message
exit();
}
}
// nothing is found so handle the 404 error
include( INCLUDE_DIR . '404.php' );
An extension to Joachim Isaksson's answer: Quite often I need something from the middle of a long file, e.g. lines 5001 to 5020, in which case you can combine head
with tail
:
head -5020 file.txt | tail -20 | grep x
This gets the first 5020 lines, then shows only the last 20 of those, then pipes everything to grep.
(Edited: fencepost error in my example numbers, added pipe to grep)
Simple and fully equiped truncate() method:
function truncate($string, $width, $etc = ' ..')
{
$wrapped = explode('$trun$', wordwrap($string, $width, '$trun$', false), 2);
return $wrapped[0] . (isset($wrapped[1]) ? $etc : '');
}
If you just want to see the files a generator will create you can pass the generator --pretend or -p option.
Because of your initialization wrong.
Don't do like this,
MethodName _methodName;
Do like this,
MethodName _methodName = MethodName();
Try
location ~ ^/(first/location|second/location)/ {
...
}
The ~
means to use a regular expression for the url. The ^
means to check from the first character. This will look for a /
followed by either of the locations and then another /
.
Simple Example below:
Sub openPath()
Dim path As String
path = Application.ActivePresentation.path
Shell Environ("windir") & "\explorer.exe """ & path & "", vbNormalFocus
End Sub
We can't use "PHP in between JavaScript", because PHP runs on the server and JavaScript - on the client.
However we can generate JavaScript code as well as HTML, using all PHP features, including the escaping from HTML one.
Just to be complete, C++
#include <iostream>
#include <algorithm>
#include <string>
std::string theSeq = "abc";
do
{
std::cout << theSeq << endl;
}
while (std::next_permutation(theSeq.begin(), theSeq.end()));
...
abc
acb
bac
bca
cab
cba
IMO this link from Yochai Timmer was very good and relevant but painful to read. I wrote a summary.
Yochai, if you ever read this, please see the note at the end.
For the original post read : warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs
LINK : warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs; use /NODEFAULTLIB:library
one part of the system was compiled to use a single threaded standard (libc) library with debug information (libcd) which is statically linked
while another part of the system was compiled to use a multi-threaded standard library without debug information which resides in a DLL and uses dynamic linking
Ignore the warning, after all it is only a warning. However, your program now contains multiple instances of the same functions.
Use the linker option /NODEFAULTLIB:lib. This is not a complete solution, even if you can get your program to link this way you are ignoring a warning sign: the code has been compiled for different environments, some of your code may be compiled for a single threaded model while other code is multi-threaded.
[...] trawl through all your libraries and ensure they have the correct link settings
In the latter, as it in mentioned in the original post, two common problems can arise :
You have a third party library which is linked differently to your application.
You have other directives embedded in your code: normally this is the MFC. If any modules in your system link against MFC all your modules must nominally link against the same version of MFC.
For those cases, ensure you understand the problem and decide among the solutions.
Note : I wanted to include that summary of Yochai Timmer's link into his own answer but since some people have trouble to review edits properly I had to write it in a separate answer. Sorry
If you are early into the development cycle you can try this -
Remove/comment that model and all its usages. Apply migrations. That would delete that model and then add the model again, run migrations and you have a clean model with the new field added.
Solution #1
My solution here is to create an iframe
<iframe src="audio/source.mp3" allow="autoplay" style="display:none" id="iframeAudio">
</iframe>
and audio
tag aswell for non-chrome browsers
<audio autoplay loop id="playAudio">
<source src="audio/source.mp3">
</audio>
and in my script
var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
if (!isChrome){
$('#iframeAudio').remove()
}
else {
$('#playAudio').remove() // just to make sure that it will not have 2x audio in the background
}
Solution #2:
There is also another workaround for this according to @Leonard
Create an iframe
that doesn't play anything just to trigger the autoplay in the first load.
<iframe src="silence.mp3" allow="autoplay" id="audio" style="display: none"></iframe>
good source for the mp3 file silence.mp3
Then play your real audio file at ease.
<audio id="player" autoplay loop>
<source src="audio/source.mp3" type="audio/mp3">
</audio>
Personally I prefer solution #2 because it is cleaner approach for not relying so much in JavaScript.
Update August 2019
Solution #3
As an alternative we can use <embed>
For Firefox
It seems that audio auto-play is working so we don't need the <embed>
element because it will create double audio running.
// index.js
let audioPlaying = true,
backgroundAudio, browser;
browser = navigator.userAgent.toLowerCase();
$('<audio class="audio1" src="audio.mp3" loop></audio>').prependTo('body');
if (!browser.indexOf('firefox') > -1) {
$('<embed id="background-audio" src="audio.mp3" autostart="1"></embed>').prependTo('body');
backgroundAudio = setInterval(function() {
$("#background-audio").remove();
$('<embed id="background-audio" src="audio.mp3"></embed>').prependTo('body');
}, 120000); // 120000 is the duration of your audio which in this case 2 mins.
}
Also if you have a toggle event for your audio make sure to remove the created <embed>
element for audio.
Note: After your toggle, it will restart from the beginning because the <embed>
is already deleted and the <audio>
element will play as normal now.
$(".toggle-audio").on('click', function(event) {
audioPlaying = !audioPlaying;
$("#background-audio").remove();
clearInterval(backgroundAudio);
if (audioPlaying){
$(".audio1").play();
// play audio
}
else {
$(".audio1").pause();
}
And now make sure to hide these <audio>
and <embed>
elements
audio, embed {
position: absolute;
z-index: -9999;
}
Note: diplay: none
and visibility: hidden
will make the <embed>
element not work.
A SELECT INTO
statement creates the table for you. There is no need for the CREATE TABLE
statement before hand.
What is happening is that you create #ivmy_cash_temp1
in your CREATE
statement, then the DB tries to create it for you when you do a SELECT INTO
. This causes an error as it is trying to create a table that you have already created.
Either eliminate the CREATE TABLE
statement or alter your query that fills it to use INSERT INTO SELECT
format.
If you need a unique ID added to your new row then it's best to use SELECT INTO
... since IDENTITY()
only works with this syntax.
In case you want to get the row count in the middle of a chained operation, you can use:
df.pipe(len)
Example:
row_count = (
pd.DataFrame(np.random.rand(3,4))
.reset_index()
.pipe(len)
)
This can be useful if you don't want to put a long statement inside a len()
function.
You could use __len__()
instead but __len__()
looks a bit weird.
For other people trying to make a table (or something) look focused on one row using opacity. Like @Blowski said use color not opacity. Check out this fiddle: http://jsfiddle.net/2en6o43d/
.table:hover > .row:not(:hover)
You just have to put it under separate folders with different names depending on orientation and resolution, the device will automatically select the right one for its screen settings
More info here:
http://developer.android.com/guide/practices/screens_support.html
under "Resource directory qualifiers for screen size and density"
If you know the maxValue (can be easily done if another iteration of the elements is not an issue) of the matrix, I find the following code more effective and generic.
int numDigits = (int) Math.log10(maxValue) + 1;
if (numDigits <= 1) {
numDigits = 2;
}
StringBuffer buf = new StringBuffer();
for (int i = 0; i < matrix.length; i++) {
int[] row = matrix[i];
for (int j = 0; j < row.length; j++) {
int block = row[j];
buf.append(String.format("%" + numDigits + "d", block));
if (j >= row.length - 1) {
buf.append("\n");
}
}
}
return buf.toString();
Assuming your question was referring to an int, the following works for negative/positive and zero as well:
Math.Floor((decimal) Math.Abs(n)).ToString().Length
type Config struct {
AWSRegion string `default:"us-west-2"`
}
do this on a new thread (seperate it from main thread)
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
}
}).run();
Your test requires a ServletContext: add @WebIntegrationTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT
...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html
UPDATE
In Spring Boot 1.4.x and above @WebIntegrationTest
is no longer preferred. @SpringBootTest
or @WebMvcTest
You could add a compact method to Hash like this
class Hash
def compact
delete_if { |k, v| v.nil? }
end
end
or for a version that supports recursion
class Hash
def compact(opts={})
inject({}) do |new_hash, (k,v)|
if !v.nil?
new_hash[k] = opts[:recurse] && v.class == Hash ? v.compact(opts) : v
end
new_hash
end
end
end
convert timestamp to unix timestamp.
const date = 1513787412;
const unixDate = new Date(date * 1000);// Dec 20 2020 (object)
to get the timeStamp after conversion
const TimeStamp = new Date(date*1000).getTime(); //1513787412000
import copy
a = ["a", "b", "c", "d", "e"]
b = copy.copy(a)
for item in a:
print item
b.remove(item)
a = copy.copy(b)
Works: to avoid changing the list you are iterating on, you make a copy of a
, iterate over it and remove the items from b
. Then you copy b
(the altered copy) back to a
.
There is one more option to follow. In your gradle tasks available in Eclipse, you can set your desired jdk path. (I know this is a while since the question was posted. This answer can help someone.)
Right click on the deploy or any other task and select "Open Gradle Run Configuration..."
Then navigate to "Java Home" and paste your desired java path.
Please note that, bin will be added by the gradle task itself. So don't add the "bin" to the path.
VB Version:
Class:
Protected divControl As System.Web.UI.HtmlControls.HtmlGenericControl
OnLoad/Other function:
divControl.Style("height") = "200px"
I've never tried the Add method with the styles. What if the height already exists on the DIV?
public static void copyFile(File oldLocation, File newLocation) throws IOException {
if ( oldLocation.exists( )) {
BufferedInputStream reader = new BufferedInputStream( new FileInputStream(oldLocation) );
BufferedOutputStream writer = new BufferedOutputStream( new FileOutputStream(newLocation, false));
try {
byte[] buff = new byte[8192];
int numChars;
while ( (numChars = reader.read( buff, 0, buff.length ) ) != -1) {
writer.write( buff, 0, numChars );
}
} catch( IOException ex ) {
throw new IOException("IOException when transferring " + oldLocation.getPath() + " to " + newLocation.getPath());
} finally {
try {
if ( reader != null ){
writer.close();
reader.close();
}
} catch( IOException ex ){
Log.e(TAG, "Error closing files when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
} else {
throw new IOException("Old location does not exist when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
I know it's been quite some time since the question was asked. However, if it helps anyone this worked for me.
$(function() {
$('.datetimepicker').datetimepicker({
format: 'MM-DD-YYYY HH:mm '
});
});
This need is exactly why createInsecureRfcommSocketToServiceRecord()
was added to BluetoothDevice
starting in Android 2.3.3 (API Level 10) (SDK Docs)...before that there was no SDK support for this. It was designed to allow Android to connect to devices without user interfaces for entering a PIN code (like an embedded device), but it just as usable for setting up a connection between two devices without user PIN entry.
The corollary method listenUsingInsecureRfcommWithServiceRecord()
in BluetoothAdapter
is used to accept these types of connections. It's not a security breach because the methods must be used as a pair. You cannot use this to simply attempt to pair with any old Bluetooth device.
You can also do short range communications over NFC, but that hardware is less prominent on Android devices. Definitely pick one, and don't try to create a solution that uses both.
Hope that Helps!
P.S. There are also ways to do this on many devices prior to 2.3 using reflection, because the code did exist...but I wouldn't necessarily recommend this for mass-distributed production applications. See this StackOverflow.
TL;DR Just add
-- $(git diff --staged --name-only)
for your git<pathspec>
parameter
git stash -- $(git diff --staged --name-only)
And to add a message simply:
git stash push -m "My work in progress" -- $(git diff --staged --name-only)
Tested on v2.17.1 and v2.21.0.windows.1
Limitations:
- Please be aware that this will stash every single thing, if you have no files staged.
- Also if you have a file that is only partially staged ( i.e. only some changed lines, are staged while some other changed lines are not), then the whole file will get stashed (including unstaged lines).
You could use grep
as well:
grep('2', strsplit(string, '')[[1]])
#4 24
You could create a wrapper application that you run instead of directly running your real app. The wrapper application can listen to stdout and redirect everything to Trace. Then change the run settings to launch your wrapper and pass in the path to the real app to run.
You could also have the wrapper auto-attach the debugger to the new process if a debugger is attached to the wrapper.
you can do this in different ways:
see here for more details on the second case:
http://msdn.microsoft.com/en-us/library/ff647786.aspx#scalenetchapt10_topic14
and here for details on the last case:
Style the td
and th
instead
td, th {
border: 1px solid black;
}
And also to make it so there is no spacing between cells use:
table {
border-collapse: collapse;
}
(also note, you have border-style: none;
which should be border-style: solid;
)
See an example here: http://jsfiddle.net/KbjNr/
In pyspark,SparkSql syntax:
where column_n like 'xyz%'
might not work.
Use:
where column_n RLIKE '^xyz'
This works perfectly fine.
Here's another example of using filter
in an Angular controller:
$scope.ListOfPeople = [
{ PersonID: 10, FirstName: "John", LastName: "Smith", Sex: "Male" },
{ PersonID: 11, FirstName: "James", LastName: "Last", Sex: "Male" },
{ PersonID: 12, FirstName: "Mary", LastName: "Heart", Sex: "Female" },
{ PersonID: 13, FirstName: "Sandra", LastName: "Goldsmith", Sex: "Female" },
{ PersonID: 14, FirstName: "Shaun", LastName: "Sheep", Sex: "Male" },
{ PersonID: 15, FirstName: "Nicola", LastName: "Smith", Sex: "Male" }
];
$scope.ListOfWomen = $scope.ListOfPeople.filter(function (person) {
return (person.Sex == "Female");
});
// This will display "There are 2 women in our list."
prompt("", "There are " + $scope.ListOfWomen.length + " women in our list.");
Simple, hey ?
For those looking for an example of how to pass the OAuth2 authorization (access token) in the header (as opposed to using a request or body parameter), here is how it's done:
Authorization: Bearer 0b79bab50daca910b000d4f1a2b675d604257e42
You are looking for the __getitem__
method. See http://docs.python.org/reference/datamodel.html, section 3.4.6
This version does not rely on hard-coded, fixed values but sizes relative to the font-size
of the div
.
CSS:
.numberCircle {
font: 32px Arial, sans-serif;
width: 2em;
height: 2em;
box-sizing: initial;
background: #fff;
border: 0.1em solid #666;
color: #666;
text-align: center;
border-radius: 50%;
line-height: 2em;
box-sizing: content-box;
}
HTML:
<div class="numberCircle">30</div>
<div class="numberCircle" style="font-size: 60px">1</div>
<div class="numberCircle" style="font-size: 12px">2</div>
According to an article on Medium, this will work:
install --upgrade pandas==1.0.0rc0
There is a library for this BarCode PHP. You just need to include a few files:
require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');
You can generate many types of barcodes, namely 1D or 2D. Add the required library:
require_once('class/BCGcode39.barcode.php');
Generate the colours:
// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);
After you have added all the codes, you will get this way:
Example
Since several have asked for an example here is what I was able to do to get it done
require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');
require_once('class/BCGcode128.barcode.php');
header('Content-Type: image/png');
$color_white = new BCGColor(255, 255, 255);
$code = new BCGcode128();
$code->parse('HELLO');
$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);
$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);
If you want to actually create the image file so you can save it then change
$drawing = new BCGDrawing('', $color_white);
to
$drawing = new BCGDrawing('image.png', $color_white);
The power in dBm is the 10 times the logarithm of the ratio of actual Power/1 milliWatt.
dBm stands for "decibel milliwatts". It is a convenient way to measure power. The exact formula is
P(dBm) = 10 · log10( P(W) / 1mW )
where
P(dBm) = Power expressed in dBm P(W) = the absolute power measured in Watts mW = milliWatts log10 = log to base 10
From this formula, the power in dBm of 1 Watt is 30 dBm. Because the calculation is logarithmic, every increase of 3dBm is approximately equivalent to doubling the actual power of a signal.
There is a conversion calculator and a comparison table here. There is also a comparison table on the Wikipedia english page, but the value it gives for mobile networks is a bit off.
Your actual question was "does the - sign count?"
The answer is yes, it does.
-85 dBm is less powerful (smaller) than -60 dBm. To understand this, you need to look at negative numbers. Alternatively, think about your bank account. If you owe the bank 85 dollars/rands/euros/rupees (-85), you're poorer than if you only owe them 65 (-65), i.e. -85 is smaller than -65. Also, in temperature measurements, -85 is colder than -65 degrees.
Signal strengths for mobile networks are always negative dBm values, because the transmitted network is not strong enough to give positive dBm values.
How will this affect your location finding? I have no idea, because I don't know what technology you are using to estimate the location. The values you quoted correspond roughly to a 5 bar network in GSM, UMTS or LTE, so you shouldn't have be having any problems due to network strength.
C++11 N3337 standard draft
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf
19.3 Assertions
1 The header <cassert>, described in (Table 42), provides a macro for documenting C ++ program assertions and a mechanism for disabling the assertion checks.
2 The contents are the same as the Standard C library header <assert.h>.
C99 N1256 standard draft
http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf
7.2 Diagnostics <assert.h>
1 The header
<assert.h>
defines the assert macro and refers to another macro,NDEBUG
which is not defined by<assert.h>
. IfNDEBUG
is defined as a macro name at the point in the source file where <assert.h> is included, the assert macro is defined simply as#define assert(ignore) ((void)0)
The assert macro is redefined according to the current state of NDEBUG each time that
<assert.h>
is included.2. The assert macro shall be implemented as a macro, not as an actual function. If the macro definition is suppressed in order to access an actual function, the behavior is undefined.
7.2.1 Program diagnostics
7.2.1.1 The assert macro
Synopsis
1.
#include <assert.h> void assert(scalar expression);
Description
2 The assert macro puts diagnostic tests into programs; it expands to a void expression. When it is executed, if expression (which shall have a scalar type) is false (that is, compares equal to 0), the assert macro writes information about the particular call that failed (including the text of the argument, the name of the source file, the source line number, and the name of the enclosing function — the latter are respectively the values of the preprocessing macros
__FILE__
and__LINE__
and of the identifier__func__
) on the standard error stream in an implementation-defined format. 165) It then calls the abort function.Returns
3 The assert macro returns no value.
Prefix you literal with 0b
like in
int i = 0b11111111;
See here.
Method 1 : Using jQuery Ajax Get call (partial page update).
Suitable for when you need to retrieve jSon data from database.
Controller's Action Method
[HttpGet]
public ActionResult Foo(string id)
{
var person = Something.GetPersonByID(id);
return Json(person, JsonRequestBehavior.AllowGet);
}
Jquery GET
function getPerson(id) {
$.ajax({
url: '@Url.Action("Foo", "SomeController")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: { id: id },
success: function(person) {
$('#FirstName').val(person.FirstName);
$('#LastName').val(person.LastName);
}
});
}
Person class
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Method 2 : Using jQuery Ajax Post call (partial page update).
Suitable for when you need to do partial page post data into database.
Post method is also same like above just replace [HttpPost]
on Action method and type as post
for jquery method.
For more information check Posting JSON Data to MVC Controllers Here
Method 3 : As a Form post scenario (full page update).
Suitable for when you need to save or update data into database.
View
@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{
@Html.TextBoxFor(model => m.Text)
<input type="submit" value="Save" />
}
Action Method
[HttpPost]
public ActionResult SaveData(FormCollection form)
{
// Get movie to update
return View();
}
Method 4 : As a Form Get scenario (full page update).
Suitable for when you need to Get data from database
Get method also same like above just replace [HttpGet]
on Action method and FormMethod.Get
for View's form method.
I hope this will help to you.
ES6 version:
const angleInRadians = angleInDegrees => (angleInDegrees - 90) * (Math.PI / 180.0);
const polarToCartesian = (centerX, centerY, radius, angleInDegrees) => {
const a = angleInRadians(angleInDegrees);
return {
x: centerX + (radius * Math.cos(a)),
y: centerY + (radius * Math.sin(a)),
};
};
const arc = (x, y, radius, startAngle, endAngle) => {
const fullCircle = endAngle - startAngle === 360;
const start = polarToCartesian(x, y, radius, endAngle - 0.01);
const end = polarToCartesian(x, y, radius, startAngle);
const arcSweep = endAngle - startAngle <= 180 ? '0' : '1';
const d = [
'M', start.x, start.y,
'A', radius, radius, 0, arcSweep, 0, end.x, end.y,
].join(' ');
if (fullCircle) d.push('z');
return d;
};
Yes, when you import classes with the same simple names, you must refer to them by their fully qualified class names. I would leave the import statements in, as it gives other developers a sense of what is in the file when they are working with it.
java.util.Data date1 = new java.util.Date();
my.own.Date date2 = new my.own.Date();
Be careful while using
num % 1
empty string ('') or boolean (true or false) will return as integer. You might not want to do that
false % 1 // true
'' % 1 //true
Number.isInteger(22); //true
Number.isInteger(22.2); //false
Number.isInteger('22'); //false
build in function in the browser. Dosnt support older browsers
Alternatives:
Math.round(num)=== num
However, Math.round() also will fail for empty string and boolean
This also happens if you forget self
declaration inside class methods.
Example:
class Example():
def is_overlapping(x1, x2, y1, y2):
# Thanks to https://stackoverflow.com/a/12888920/940592
return max(x1, y1) <= min(x2, y2)
Fails calling it like self.is_overlapping(x1=2, x2=4, y1=3, y2=5)
with:
{TypeError} is_overlapping() got multiple values for argument 'x1'
WORKS:
class Example():
def is_overlapping(self, x1, x2, y1, y2):
# Thanks to https://stackoverflow.com/a/12888920/940592
return max(x1, y1) <= min(x2, y2)
Change your getTaskCount Method to this:
public int getTaskCount(long tasklist_id){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor= db.rawQuery("SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?", new String[] { String.valueOf(tasklist_id) });
cursor.moveToFirst();
int count= cursor.getInt(0);
cursor.close();
return count;
}
Then, update the click handler accordingly:
public void onItemClick(AdapterView<?> arg0, android.view.View v, int position, long id) {
db = new TodoTask_Database(getApplicationContext());
// Get task list id
int tasklistid = adapter.getItem(position).getTaskListId();
if(db.getTaskCount(tasklistid) > 0) {
System.out.println(c);
Intent taskListID = new Intent(getApplicationContext(), AddTask_List.class);
taskListID.putExtra("TaskList_ID", tasklistid);
startActivity(taskListID);
} else {
Intent addTask = new Intent(getApplicationContext(), Add_Task.class);
startActivity(addTask);
}
}
from a table?
You can use this if you have no foreign keys to other tables
truncate table TableName
or
delete TableName
if you want all tables
sp_msforeachtable 'delete ?'
I had the same issue and concern over duplicate code in two or more sprocs. I ended up adding an additional attribute for "mode". This allowed common code to exist inside one sproc and the mode directed flow and result set of the sproc.
Maybe this could be a little older article. but must of the above answers don´t help me as I need. Then I wrote a little snippet for that.
This accepts any XML that hast at least 3 levels (Like this sample):
<XmlData>
<XmlRow>
<XmlField1>Data 1</XmlField1>
<XmlField2>Data 2</XmlField2>
<XmlField3>Data 3</XmlField3>
.......
</XmlRow>
</XmlData>
public static class XmlParser
{
/// <summary>
/// Converts XML string to DataTable
/// </summary>
/// <param name="Name">DataTable name</param>
/// <param name="XMLString">XML string</param>
/// <returns></returns>
public static DataTable BuildDataTableFromXml(string Name, string XMLString)
{
XmlDocument doc = new XmlDocument();
doc.Load(new StringReader(XMLString));
DataTable Dt = new DataTable(Name);
try
{
XmlNode NodoEstructura = doc.FirstChild.FirstChild;
// Table structure (columns definition)
foreach (XmlNode columna in NodoEstructura.ChildNodes)
{
Dt.Columns.Add(columna.Name, typeof(String));
}
XmlNode Filas = doc.FirstChild;
// Data Rows
foreach (XmlNode Fila in Filas.ChildNodes)
{
List<string> Valores = new List<string>();
foreach (XmlNode Columna in Fila.ChildNodes)
{
Valores.Add(Columna.InnerText);
}
Dt.Rows.Add(Valores.ToArray());
}
} catch(Exception)
{
}
return Dt;
}
}
This solve my problem
Sebastian comment on Adrien's answer needs more attention it helped me but it being a comment might be ignore sometime so here's a solution:
var options = { useMongoClient: true, keepAlive: 1, connectTimeoutMS: 30000, reconnectTries: 30, reconnectInterval: 5000 }
mongoose.connect(config.mongoConnectionString, options, (err) => {
if(err) {
console.error("Error while connecting", err);
}
});
Instant
corresponds to time on the prime meridian (Greenwich).
Whereas LocalDateTime
relative to OS time zone settings, and
cannot represent an instant without additional information such as an offset or time-zone.
In your product.service.ts you are using stringify method in a wrong way..
Just use
JSON.stringify(product)
instead of
JSON.stringify({product})
i have checked your problem and after this it's working absolutely fine.
For passing both a function, and any arguments to the function:
from typing import Callable
def looper(fn: Callable, n:int, *args, **kwargs):
"""
Call a function `n` times
Parameters
----------
fn: Callable
Function to be called.
n: int
Number of times to call `func`.
*args
Positional arguments to be passed to `func`.
**kwargs
Keyword arguments to be passed to `func`.
Example
-------
>>> def foo(a:Union[float, int], b:Union[float, int]):
... '''The function to pass'''
... print(a+b)
>>> looper(foo, 3, 2, b=4)
6
6
6
"""
for i in range(n):
fn(*args, **kwargs)
Depending on what you are doing, it could make sense to define a decorator
, or perhaps use functools.partial
.
One possible answer will be given when you run this snippet.
document.write('<table>')_x000D_
for (var i = 0; i < 250; i++) {_x000D_
document.write('<tr><td>' + i + '</td><td>' + String.fromCharCode(i) + '</td></tr>')_x000D_
}_x000D_
document.write('</table>')
_x000D_
td {_x000D_
border: solid 1px;_x000D_
padding: 1px 12px;_x000D_
text-align: right;_x000D_
}_x000D_
table {_x000D_
border-collapse: collapse;_x000D_
}_x000D_
* {_x000D_
font-family: monospace;_x000D_
font-size: 1.1em;_x000D_
}
_x000D_
Using a custom spinner layout like this:
<?xml version="1.0" encoding="utf-8"?>
<Spinner xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/spinnerTarget"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="14dp"
android:textColor="#000000"/>
In the activity:
// populate the list
ArrayList<String> dataList = new ArrayList<String>();
for (int i = 0; i < 4; i++) {
dataList.add("Item");
}
// set custom layout spinner_layout.xml and adapter
Spinner spinnerObject = (Spinner) findViewById(R.id.spinnerObject);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.drawable.spinner_layout, dataList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerObject.setAdapter(dataAdapter);
spinnerObject.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// to set value of first selection, because setOnItemSelectedListener will not dispatch if the user selects first element
TextView spinnerTarget = (TextView)v.findViewById(R.id.spinnerTarget);
spinnerTarget.setText(spinnerObject.getSelectedItem().toString());
return false;
}
});
spinnerObject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
private boolean selectionControl = true;
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// just the first time
if(selectionControl){
// find TextView in layout
TextView spinnerTarget = (TextView)parent.findViewById(R.id.spinnerTarget);
// set spinner text empty
spinnerTarget.setText("");
selectionControl = false;
}
else{
// select object
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
Try the distfit
library.
pip install distfit
# Create 1000 random integers, value between [0-50]
X = np.random.randint(0, 50,1000)
# Retrieve P-value for y
y = [0,10,45,55,100]
# From the distfit library import the class distfit
from distfit import distfit
# Initialize.
# Set any properties here, such as alpha.
# The smoothing can be of use when working with integers. Otherwise your histogram
# may be jumping up-and-down, and getting the correct fit may be harder.
dist = distfit(alpha=0.05, smooth=10)
# Search for best theoretical fit on your empirical data
dist.fit_transform(X)
> [distfit] >fit..
> [distfit] >transform..
> [distfit] >[norm ] [RSS: 0.0037894] [loc=23.535 scale=14.450]
> [distfit] >[expon ] [RSS: 0.0055534] [loc=0.000 scale=23.535]
> [distfit] >[pareto ] [RSS: 0.0056828] [loc=-384473077.778 scale=384473077.778]
> [distfit] >[dweibull ] [RSS: 0.0038202] [loc=24.535 scale=13.936]
> [distfit] >[t ] [RSS: 0.0037896] [loc=23.535 scale=14.450]
> [distfit] >[genextreme] [RSS: 0.0036185] [loc=18.890 scale=14.506]
> [distfit] >[gamma ] [RSS: 0.0037600] [loc=-175.505 scale=1.044]
> [distfit] >[lognorm ] [RSS: 0.0642364] [loc=-0.000 scale=1.802]
> [distfit] >[beta ] [RSS: 0.0021885] [loc=-3.981 scale=52.981]
> [distfit] >[uniform ] [RSS: 0.0012349] [loc=0.000 scale=49.000]
# Best fitted model
best_distr = dist.model
print(best_distr)
# Uniform shows best fit, with 95% CII (confidence intervals), and all other parameters
> {'distr': <scipy.stats._continuous_distns.uniform_gen at 0x16de3a53160>,
> 'params': (0.0, 49.0),
> 'name': 'uniform',
> 'RSS': 0.0012349021241149533,
> 'loc': 0.0,
> 'scale': 49.0,
> 'arg': (),
> 'CII_min_alpha': 2.45,
> 'CII_max_alpha': 46.55}
# Ranking distributions
dist.summary
# Plot the summary of fitted distributions
dist.plot_summary()
# Make prediction on new datapoints based on the fit
dist.predict(y)
# Retrieve your pvalues with
dist.y_pred
# array(['down', 'none', 'none', 'up', 'up'], dtype='<U4')
dist.y_proba
array([0.02040816, 0.02040816, 0.02040816, 0. , 0. ])
# Or in one dataframe
dist.df
# The plot function will now also include the predictions of y
dist.plot()
Note that in this case, all points will be significant because of the uniform distribution. You can filter with the dist.y_pred if required.
I've been struggling with this for awhile too. It actually occurred due to some Microsoft Office updates via Windows Update starting in December. It has caused quite a bit of a headache, not to mention hours of lost productivity due to this issue.
One of the updates breaks the forms, and you need to clear the Office cache as stated by UHsoccer
Additionally, another answer thread here: Suddenly several VBA macro errors, mostly 32809 has a link to the MS blog with details.
Another of the updates causes another error where if you create or modify one of these forms (even as simple as saving the form data) it will update the internals of the spreadsheet, which, when given to another person without the updates, will cause the error above.
The solution (if you are working with others on the same spreadsheet)? Sadly, either have everyone you deal with use the office updates, then have them clear the office cache, or revert back to pre Dec '14 updates via a system restore (or by manually removing them).
I know, not much of a solution, right? I'm not happy either.
Just as a back-story, I updated my machine, keeping up with updates, and one of the companies I dealt with did not. I was pulling out my hair just before Christmas trying to figure out the issue, and without any restore points, I finally relented and reformatted.
Now, a month later, the company's IT department updated their workstations. And, without surprise, they began having issues similar to this as well (not to mention when I received their spreadsheets, I had the same issue).
Now, we are all up on the same updates, and everything is well as can be.
You can now (C++14) return a locally-defined (i.e. defined inside the function) as follows:
auto f()
{
struct S
{
int a;
double b;
} s;
s.a = 42;
s.b = 42.0;
return s;
}
auto x = f();
a = x.a;
b = x.b;
PrincipalContext for browsing the AD is ridiculously slow (only use it for .ValidateCredentials, see below), use DirectoryEntry instead and .PropertiesToLoad() so you only pay for what you need.
Filters and syntax here: https://social.technet.microsoft.com/wiki/contents/articles/5392.active-directory-ldap-syntax-filters.aspx
Attributes here: https://docs.microsoft.com/en-us/windows/win32/adschema/attributes-all
using (var root = new DirectoryEntry($"LDAP://{Domain}"))
{
using (var searcher = new DirectorySearcher(root))
{
// looking for a specific user
searcher.Filter = $"(&(objectCategory=person)(objectClass=user)(sAMAccountName={username}))";
// I only care about what groups the user is a memberOf
searcher.PropertiesToLoad.Add("memberOf");
// FYI, non-null results means the user was found
var results = searcher.FindOne();
var properties = results?.Properties;
if (properties?.Contains("memberOf") == true)
{
// ... iterate over all the groups the user is a member of
}
}
}
Clean, simple, fast. No magic, no half-documented calls to .RefreshCache to grab the tokenGroups or to .Bind or .NativeObject in a try/catch to validate credentials.
For authenticating the user:
using (var context = new PrincipalContext(ContextType.Domain))
{
return context.ValidateCredentials(username, password);
}
You asked for Modernizr example, so here you go. This code uses Modernizr to detect whether the 'date' input type is supported. If it isn't supported, then it fails back to JQueryUI datepicker.
Note: You will need to download JQueryUI and possibly change the paths to the CSS and JS files in your own code.
<!DOCTYPE html>
<html>
<head>
<title>Modernizer Detect 'date' input type</title>
<link rel="stylesheet" type="text/css" href="jquery-ui-1.10.3/themes/base/jquery.ui.all.css"/>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/modernizr/modernizr-1.7-development-only.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.10.3/ui/jquery.ui.core.js"></script>
<script type="text/javascript" src="jquery-ui-1.10.3/ui/jquery.ui.widget.js"></script>
<script type="text/javascript" src="jquery-ui-1.10.3/ui/jquery.ui.datepicker.js"></script>
<script type="text/javascript">
$(function(){
if(!Modernizr.inputtypes.date) {
console.log("The 'date' input type is not supported, so using JQueryUI datepicker instead.");
$("#theDate").datepicker();
}
});
</script>
</head>
<body>
<form>
<input id="theDate" type="date"/>
</form>
</body>
</html>
I hope this works for you.
You also need to include the Log4J JAR file in the classpath.
Note that slf4j-log4j12-1.6.4.jar
is only an adapter to make it possible to use Log4J via the SLF4J API. It does not contain the actual implementation of Log4J.
I created this simple function to help me. This makes my calls a lot easier to read that having inline an Get-WmiObject, Where-Object statements, etc.
function GetDiskSizeInfo($drive) {
$diskReport = Get-WmiObject Win32_logicaldisk
$drive = $diskReport | Where-Object { $_.DeviceID -eq $drive}
$result = @{
Size = $drive.Size
FreeSpace = $drive.Freespace
}
return $result
}
$diskspace = GetDiskSizeInfo "C:"
write-host $diskspace.FreeSpace " " $diskspace.Size
CodeXL has now superseded the End Of Line'd AMD Code Analyst and both are free, but not as advanced as VTune.
There's also Sleepy, which is very simple, but does the job in many cases.
Note: All three of the tools above are unmaintained since several years.
How about emulating a const array via an accessor function? It's non-static (as you requested), and it doesn't require stl or any other library:
class a {
int privateB[2];
public:
a(int b0,b1) { privateB[0]=b0; privateB[1]=b1; }
int b(const int idx) { return privateB[idx]; }
}
Because a::privateB is private, it is effectively constant outside a::, and you can access it similar to an array, e.g.
a aobj(2,3); // initialize "constant array" b[]
n = aobj.b(1); // read b[1] (write impossible from here)
If you are willing to use a pair of classes, you could additionally protect privateB from member functions. This could be done by inheriting a; but I think I prefer John Harrison's comp.lang.c++ post using a const class.
I generally prefer to add these codes in a function to get the Android version:
int whichAndroidVersion;
whichAndroidVersion= Build.VERSION.SDK_INT;
textView.setText("" + whichAndroidVersion); //If you don't use "" then app crashes.
For example, that code above will set the text into my textView as "29" now.
On the side note, here is how the various plyr
functions correspond to the base *apply
functions (from the intro to plyr document from the plyr webpage http://had.co.nz/plyr/)
Base function Input Output plyr function
---------------------------------------
aggregate d d ddply + colwise
apply a a/l aaply / alply
by d l dlply
lapply l l llply
mapply a a/l maply / mlply
replicate r a/l raply / rlply
sapply l a laply
One of the goals of plyr
is to provide consistent naming conventions for each of the functions, encoding the input and output data types in the function name. It also provides consistency in output, in that output from dlply()
is easily passable to ldply()
to produce useful output, etc.
Conceptually, learning plyr
is no more difficult than understanding the base *apply
functions.
plyr
and reshape
functions have replaced almost all of these functions in my every day use. But, also from the Intro to Plyr document:
Related functions
tapply
andsweep
have no corresponding function inplyr
, and remain useful.merge
is useful for combining summaries with the original data.
Like any HTML input field, the browser will leave it empty unless a default value is specified with the value
attribute.
Unfortunately HTML5 doesn't provide a way of specifying 'today' in the value
attribute (that I can see), only a RFC3339 valid date like 2011-09-29
.
TL;DR Use YYYY-MM-DD
date format or it won't display
add to link
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular-route.min.js"></script>
var app = angular.module('apps', [ 'ngRoute' ]);
Radio buttons are ideal. You just need a third "neither" option that is select by default.
In the hexadecimal it can't get a negative value. So it shows it like ffffffff.
The advantage to using the unsigned version (when you know the values contained will be non-negative) is that sometimes the computer will spot errors for you (the program will "crash" when a negative value is assigned to the variable).