I can't comment yet, but make sure you made all the checks in this quide: How to enable remote connections in SQL Server 2008? It should work fine if all steps are made.
\
is used for escape sequences in programming languages.
\n
prints a newline
\\
prints a backslash
\"
prints "
\t
prints a tabulator
\b
moves the cursor one back
For normal DateTimes, if you don't initialize them at all then they will match DateTime.MinValue
, because it is a value type rather than a reference type.
You can also use a nullable DateTime, like this:
DateTime? MyNullableDate;
Or the longer form:
Nullable<DateTime> MyNullableDate;
And, finally, there's a built in way to reference the default of any type. This returns null
for reference types, but for our DateTime example it will return the same as DateTime.MinValue
:
default(DateTime)
or, in more recent versions of C#,
default
If you are doing this for virtualenv
, the kernels in inactive environments might not be shown with jupyter kernelspec list
, as suggested above. You can delete it from directory:
~/.local/share/jupyter/kernels/
Okay, so this is probably even uglier that what you did, but anyway...
but I do the same so...
What you can do to do it in pure TypeScript, is to use the eval
function like so :
declare var something: string;
eval("something = 'testing';")
And later you'll be able to do
if (something === 'testing')
This is nothing more than a hack to force executing the instruction without TypeScript refusing to compile, and we declare var
for TypeScript to compile the rest of the code.
ecatmur's solution will work fine. This will be better performance on large datasets, though:
data.groupby(data['date'].map(lambda x: x.year))
Try this method.
public static Type GetType(string typeName)
{
var type = Type.GetType(typeName);
if (type != null) return type;
foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
{
type = a.GetType(typeName);
if (type != null)
return type;
}
return null;
}
I can not use the "int length" constructor for
StringBuilder
since the length of my CLOB is longer than aint
and needs along
value.
If the CLOB length is greater than fits in an int, the CLOB data won't fit in a String either. You'll have to use a streaming approach to deal with this much XML data.
If the actual length of the CLOB is smaller than Integer.MAX_VALUE
, just force the long
to int
by putting (int)
in front of it.
If I understand you correctly you want to close the application even if the user did not click on the close button. You will need to register WindowEvents maybe with addWindowListener() or enableEvents() whichever suits your needs better.
You can then invoke the event with a call to processWindowEvent(). Here is a sample code that will create a JFrame, wait 5 seconds and close the JFrame without user interaction.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ClosingFrame extends JFrame implements WindowListener{
public ClosingFrame(){
super("A Frame");
setSize(400, 400);
//in case the user closes the window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
//enables Window Events on this Component
this.addWindowListener(this);
//start a timer
Thread t = new Timer();
t.start();
}
public void windowOpened(WindowEvent e){}
public void windowClosing(WindowEvent e){}
//the event that we are interested in
public void windowClosed(WindowEvent e){
System.exit(0);
}
public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
//a simple timer
class Timer extends Thread{
int time = 10;
public void run(){
while(time-- > 0){
System.out.println("Still Waiting:" + time);
try{
sleep(500);
}catch(InterruptedException e){}
}
System.out.println("About to close");
//close the frame
ClosingFrame.this.processWindowEvent(
new WindowEvent(
ClosingFrame.this, WindowEvent.WINDOW_CLOSED));
}
}
//instantiate the Frame
public static void main(String args[]){
new ClosingFrame();
}
}
As you can see, the processWindowEvent() method causes the WindowClosed event to be fired where you have an oportunity to do some clean up code if you require before closing the application.
The difference can be demonstrated by this example:
generate a matrix
>>> A = numpy.matrix(numpy.ones((3,3)))
>>> A
matrix([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
use numpy.array
to modify A
. Doesn't work because you are modifying a copy
>>> numpy.array(A)[2]=2
>>> A
matrix([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 1., 1., 1.]])
use numpy.asarray
to modify A
. It worked because you are modifying A
itself
>>> numpy.asarray(A)[2]=2
>>> A
matrix([[ 1., 1., 1.],
[ 1., 1., 1.],
[ 2., 2., 2.]])
Hope this helps!
You can open a command prompt and run as administrator. Then type
../bin>psql -f c:/...-h localhost -p 5432 -d databasename -U "postgres"
Password for user postgres:
will show up.
Type your password and enter. I couldn't see the password what I was typing, but this time when I press enter it worked. Actually I was loading data into the database.
Another way to (kinda) test threaded code, and very complex systems in general is through Fuzz Testing. It's not great, and it won't find everything, but its likely to be useful and its simple to do.
Quote:
Fuzz testing or fuzzing is a software testing technique that provides random data("fuzz") to the inputs of a program. If the program fails (for example, by crashing, or by failing built-in code assertions), the defects can be noted. The great advantage of fuzz testing is that the test design is extremely simple, and free of preconceptions about system behavior.
...
Fuzz testing is often used in large software development projects that employ black box testing. These projects usually have a budget to develop test tools, and fuzz testing is one of the techniques which offers a high benefit to cost ratio.
...
However, fuzz testing is not a substitute for exhaustive testing or formal methods: it can only provide a random sample of the system's behavior, and in many cases passing a fuzz test may only demonstrate that a piece of software handles exceptions without crashing, rather than behaving correctly. Thus, fuzz testing can only be regarded as a bug-finding tool rather than an assurance of quality.
As @oportocala mentions, an empty string will not result in the expected empty array.
So to counter, do:
str
.split(',')
.map(entry => entry.trim())
.filter(entry => entry)
For an array of expected integers, do:
str
.split(',')
.map(entry => parseInt(entry))
.filter(entry => typeof entry ==='number')
#nav ul {
display: inline-block;
list-style-type: none;
}
It should work, I tested it in your site.
It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.
In Web API, it's very simple to remember how parameter binding is happening.
POST
simple types, Web API tries to bind it from the URL if you POST
complex type, Web API tries to bind it from the body of
the request (this uses a media-type
formatter).
If you want to bind a complex type from the URL, you'll use [FromUri]
in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.
public IHttpActionResult Put([FromUri] ViewModel data) { ... }
If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.
public IHttpActionResult Put([FromBody] string name) { ... }
as a side note, say you are making a PUT
request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data
parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.
var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});
and your web api action will look something like below.
public IHttpActionResult Put([FromBody] string name){ ... }
This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
You've nearly got it:
DECLARE @myVariable nvarchar(max) = 'hello world';
See here for the docs
For the quotes, SQL Server uses apostrophes, not quotes:
DECLARE @myVariable nvarchar(max) = 'John said to Emily "Hey there Emily"';
Use double apostrophes if you need them in a string:
DECLARE @myVariable nvarchar(max) = 'John said to Emily ''Hey there Emily''';
I think this link demonstrates the best way to get application context anywhere, even in the non-bean class. I find it very useful. Hope its the same for you. The below is the abstract code of it
Create a new class ApplicationContextProvider.java
package com.java2novice.spring;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class ApplicationContextProvider implements ApplicationContextAware{
private static ApplicationContext context;
public static ApplicationContext getApplicationContext() {
return context;
}
@Override
public void setApplicationContext(ApplicationContext ac)
throws BeansException {
context = ac;
}
}
Add an entry in application-context.xml
<bean id="applicationContextProvider"
class="com.java2novice.spring.ApplicationContextProvider"/>
In annotations case (instead of application-context.xml)
@Component
public class ApplicationContextProvider implements ApplicationContextAware{
...
}
Get the context like this
TestBean tb = ApplicationContextProvider.getApplicationContext().getBean("testBean", TestBean.class);
Cheers!!
The unix 'date' command is surprisingly versatile.
date -j -f "%a %b %d %T %Z %Y" "`date`" "+%s"
Takes the output of date
, which will be in the format defined by -f, and then prints it out (-j says don't attempt to set the date) in the form +%s, seconds since epoch.
If you are using Pipenv
, you may need to add this to your Pipfile
:
[packages]
python-dateutil = "*"
You're missing a FROM and you need to give the subquery an alias.
SELECT COUNT(*) FROM
(
SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
FROM dbo.Table_A AS a
INNER JOIN dbo.Table_B AS b
ON a.a_id = b.a_id
) AS subquery;
You have a JSON string, not an object. Tell jQuery that you expect a JSON response and it will parse it for you. Either use $.getJSON instead of $.get, or pass the dataType argument to $.get
:
$.get(
'index.php?r=admin/post/ajax',
{"parentCatId":parentCatId},
function(data){
$.each(data, function(key, value){
console.log(key + ":" + value)
})
},
'json'
);
Yes there is one and it is inside the SQLServer management studio. Unlike the previous versions I think. Follow these simple steps.
1)Right click on a database in the Object explorer 2)Selected New Query from the popup menu 3)Query Analyzer will be opened.
Enjoy work.
I use SimpleJpaRepository as the base class of repository implementation and add custom method in the interface,eg:
public interface UserRepository {
User FindOrInsert(int userId);
}
@Repository
public class UserRepositoryImpl extends SimpleJpaRepository implements UserRepository {
private RedisClient redisClient;
public UserRepositoryImpl(RedisClient redisClient, EntityManager em) {
super(User.class, em);
this.redisClient = redisClient;
}
@Override
public User FindOrInsert(int userId) {
User u = redisClient.getOrSet("test key.. User.class, () -> {
Optional<User> ou = this.findById(Integer.valueOf(userId));
return ou.get();
});
…………
return u;
}
Two things: the extension and the header flag stored in the file.
Both files are PE files. Both contain the exact same layout. A DLL is a library and therefore can not be executed. If you try to run it you'll get an error about a missing entry point. An EXE is a program that can be executed. It has an entry point. A flag inside the PE header indicates which file type it is (irrelevant of file extension). The PE header has a field where the entry point for the program resides. In DLLs it isn't used (or at least not as an entry point).
One minor difference is that in most cases DLLs have an export section where symbols are exported. EXEs should never have an export section since they aren't libraries but nothing prevents that from happening. The Win32 loader doesn't care either way.
Other than that they are identical. So, in summary, EXEs are executable programs while DLLs are libraries loaded into a process and contain some sort of useful functionality like security, database access or something.
Be sure that the tag "php" is stick in the code like this:
?php phpinfo(); ?>
Not like this:
? php phpinfo(); ?>
OR the server will treat it as a (normal word), so the server will not understand the language you are writing to deal with it so it will be blank.
I know it's a silly error ...but it happened ^_^
Now, back to your questions:
Q1. Does this sequence generator make use of the database's increasing numeric value generating capability or generates the number on its own?
By using the GenerationType.SEQUENCE
strategy on the @GeneratedValue
annotation, the JPA provider will try to use a database sequence object of the underlying database that supports this feature (e.g., Oracle, SQL Server, PostgreSQL, MariaDB).
If you are using MySQL, which doesn't support database sequence objects, then Hibernate is going to fall back to using the GenerationType.TABLE
instead, which is undesirable since the TABLE generation performs badly.
So, don't use the GenerationType.SEQUENCE
strategy with MySQL.
Q2. If JPA uses a database auto-increment feature, then will it work with datastores that don't have auto-increment feature?
I assume you are talking about the GenerationType.IDENTITY
when you say database auto-increment feature
.
To use an AUTO_INCREMENT
or IDENTITY
column, you need to use the GenerationType.IDENTITY
strategy on the @GeneratedValue
annotation.
Q3. If JPA generates numeric value on its own, then how does the JPA implementation know which value to generate next? Does it consult with the database first to see what value was stored last in order to generate the value (last + 1)?
The only time when the JPA provider generates values on its own is when you are using the sequence-based optimizers, like:
These optimizers are meat to reduce the number of database sequence calls, so they multiply the number of identifier values that can be generated using a single database sequence call.
To avoid conflicts between Hibernate identifier optimizers and other 3rd-party clients, you should use pooled
or pooled-lo
instead of hi/lo
. Even if you are using a legacy application that was designed to use hi/lo, you can migrate to the pooled
or pooled-lo
optimizers.
Q4. Please also shed some light on
sequenceName
andallocationSize
properties of@SequenceGenerator
annotation.
The sequenceName
attribute defines the database sequence object to be used to generate the identifier values. IT's the object you created using the CREATE SEQUENCE
DDL statement.
So, if you provide this mapping:
@Id
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "seq_post"
)
@SequenceGenerator(
name = "seq_post"
)
private Long id;
Hibernate is going to use the seq_post
database object to generate the identifier values:
SELECT nextval('hibernate_sequence')
The allocationSize
defines the identifier value multiplier, and if you provide a value that's greater than 1, then Hibernate is going to use the pooled
optimizer, to reduce the number of database sequence calls.
So, if you provide this mapping:
@Id
@GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "seq_post"
)
@SequenceGenerator(
name = "seq_post",
allocationSize = 5
)
private Long id;
Then, when you persist 5 entities:
for (int i = 1; i <= 5; i++) {
entityManager.persist(
new Post().setTitle(
String.format(
"High-Performance Java Persistence, Part %d",
i
)
)
);
}
Only 2 database sequence calls will be executed, instead of 5:
SELECT nextval('hibernate_sequence')
SELECT nextval('hibernate_sequence')
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 1', 1)
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 2', 2)
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 3', 3)
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 4', 4)
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 5', 5)
"Have you tried turning it off and on again?" (Roy of The IT crowd)
This happened to me today, which is why I ended up to this page. Seeing that error was weird since, recently, I have not made any changes in my Python environment. Interestingly, I observed that if I open a new notebook and import pandas
I would not get the same error message. So, I did shutdown
the troublesome notebook and started it again and voila it is working again!
Even though this solved the problem (at least for me), I cannot readily come up with an explanation as to why it happened in the first place!
Google Hosted jQuery
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
Backup/Fallback Plan!
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>if (!window.jQuery) { document.write('<script src="/path/to/your/jquery"><\/script>'); }
</script>
Reference: http://websitespeedoptimizations.com/ContentDeliveryNetworkPost.aspx
For symfony 4 users:
$query = $request->query->get('query');
Your question can be conveniently divided into several parts:
Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.
How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.
You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):
Download and install a trusted VPN.
Install the VPN on your Android device.
Open the application and connect to a server in a different country.
Your Android location will now be successfully changed!
Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.
Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.
This function works perfectly with no repeats and desired number of digits.
$digits = '';
function randomDigits($length){
$numbers = range(0,9);
shuffle($numbers);
for($i = 0; $i < $length; $i++){
global $digits;
$digits .= $numbers[$i];
}
return $digits;
}
You can call the function and pass the number of digits for example:
randomDigits(4);
sample results:
4957 8710 6730 6082 2987 2041 6721
Original script got from this gist
If you are using GNU time instead of the bash built-in, try
time -o outfile command
(Note: GNU time formats a little differently than the bash built-in).
As long as you fix the width of the table itself and set the table-layout property, this is pretty simple :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
td { width: 30px; overflow: hidden; }
table { width : 90px; table-layout: fixed; }
</style>
</head>
<body>
<table border="2">
<tr>
<td>word</td>
<td>two words</td>
<td>onereallylongword</td>
</tr>
</table>
</body>
</html>
I've tested this in IE6 and 7 and it seems to work fine.
Actually you need to wait till the push animation ends. So you can delegate UINavigationController and prevent pushing till the animation ends.
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
waitNavigation = NO;
}
-(void)showGScreen:(id)gvc{
if (!waitNavigation) {
waitNavigation = YES;
[_nav popToRootViewControllerAnimated:NO];
[_nav pushViewController:gvc animated:YES];
}
}
In my particular case the function was actually missing. The error message is the same. I am using the Postgresql plugin PostGIS and I had to reinstall that for whatever reason.
Method that will work. The way it is used above will not work.
declare @str varchar(50)='79136'
select
case
when @str LIKE replicate('[0-9]',LEN(@str)) then 1
else 0
end
declare @str2 varchar(50)='79D136'
select
case
when @str2 LIKE replicate('[0-9]',LEN(@str)) then 1
else 0
end
In the Table Designer on SQL Server Management Studio you can set the where the auto increment will start. Right-click on the table in Object Explorer and choose Design, then go to the Column Properties for the relevant column:
You can create a class based on a Button with specific images for MouseHover and MouseDown like this:
public class AdvancedImageButton : Button {
public Image HoverImage { get; set; }
public Image PlainImage { get; set; }
public Image PressedImage { get; set; }
protected override void OnMouseEnter(System.EventArgs e)
{
base.OnMouseEnter(e);
if (HoverImage == null) return;
if (PlainImage == null) PlainImage = base.Image;
base.Image = HoverImage;
}
protected override void OnMouseLeave(System.EventArgs e)
{
base.OnMouseLeave(e);
if (HoverImage == null) return;
base.Image = PlainImage;
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (PressedImage == null) return;
if (PlainImage == null) PlainImage = base.Image;
base.Image = PressedImage;
}
}
This solution has a small drawback that I am sure can be fixed: when you need for some reason change the Image property, you will also have to change the PlainImage property also.
Checking if array has all assoc-keys. With using stdClass
& get_object_vars ^):
$assocArray = array('fruit1' => 'apple',
'fruit2' => 'orange',
'veg1' => 'tomato',
'veg2' => 'carrot');
$assoc_object = (object) $assocArray;
$isAssoc = (count($assocArray) === count (get_object_vars($assoc_object)));
var_dump($isAssoc); // true
Why? Function get_object_vars
returns only accessible properties (see more about what is occuring during converting array
to object
here). Then, just logically: if count of basic array's elements equals count of object's accessible properties - all keys are assoc.
Few tests:
$assocArray = array('apple', 'orange', 'tomato', 'carrot');
$assoc_object = (object) $assocArray;
$isAssoc = (count($assocArray) === count (get_object_vars($assoc_object)));
var_dump($isAssoc); // false
//...
$assocArray = array( 0 => 'apple', 'orange', 'tomato', '4' => 'carrot');
$assoc_object = (object) $assocArray;
$isAssoc = (count($assocArray) === count (get_object_vars($assoc_object)));
var_dump($isAssoc); // false
//...
$assocArray = array('fruit1' => 'apple',
NULL => 'orange',
'veg1' => 'tomato',
'veg2' => 'carrot');
$assoc_object = (object) $assocArray;
$isAssoc = (count($assocArray) === count (get_object_vars($assoc_object)));
var_dump($isAssoc); //false
Etc.
or you can write
import.R.layout // at the top
It will work for sure
Callback can be very helpful in Java.
Using Callback you can notify another Class of an asynchronous action that has completed with success or error.
You are trying to copy a string into an address that is statically allocated. You need to cat into a buffer.
Specifically:
...snip...
destination
Pointer to the destination array, which should contain a C string, and be large enough to contain the concatenated resulting string.
...snip...
http://www.cplusplus.com/reference/clibrary/cstring/strcat.html
There's an example here as well.
An alternative would be to use Font-Awesome for icons:
Open Font-Awesome on CDNJS and copy the CSS url of the latest version:
<link rel="stylesheet" href="<url>">
Or in CSS
@import url("<url>");
For example (note, the version will change):
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
<i class="fa fa-bed"></i>
It contains a lot of icons!
I haven't found a better solution. You can use explode()
, preg_match_all()
, etc.
I have a static helper function like this
class Date {
public static function ausStrToTime($str) {
$dateTokens = explode('/', $str);
return strtotime($dateTokens[1] . '/' . $dateTokens[0] . '/' . $dateTokens[2]);
}
}
There is probably a better name for that, but I use ausStrToTime()
because it works with Australian dates (which I often deal with, being an Australian). A better name would probably be the standardised name, but I'm not sure what that is.
You can open the file using the ios::ate
flag (and ios::binary
flag), so the tellg()
function will give you directly the file size:
ifstream file( "example.txt", ios::binary | ios::ate);
return file.tellg();
I use this
var e = document.getElementById('ticket_category_clone').value;
Notice that you don't need the '#' character in javascript.
function check () {
var str = document.getElementById('ticket_category_clone').value;
if (str==="Hardware")
{
SPICEWORKS.utils.addStyle('#ticket_c_hardware_clone{display: none !important;}');
}
}
SPICEWORKS.app.helpdesk.ready(check);?
I had this error, too. I thought everything was setup correctly, but I found out that one thing was missing: The host name I used for my project was not (yet) resolvable.
Since my app determines the current client's name from the host name I used a host name like clientname.mysuperapp.local
for development. When I added the development host name to my hosts
file, the project was loadable again. Obviously, I had to this anyway, but I haven't thought that VS checks the host name before loading the project.
Java is giving you the choice to restrict exceptions in the parent class, because it's assuming the client will restrict what is caught. IMHO you should essentially never use this "feature", because your clients may need flexibility down the road.
Java is an old language that is poorly designed. Modern languages don't have such restrictions.
The easiest way around this flaw is make your base class throw Exception
always. Clients can throw more specific Exceptions but make your base classes really broad.
You shouldn't use ${varName}
when you're outside of strings, you should just use varName
. Inside strings you use it like this; echo "this is a string ${someVariable}";
. Infact you can place an general java expression inside of ${...}
; echo "this is a string ${func(arg1, arg2)}
.
echo -n Aa | hexdump -e '/1 "%02x"'; echo
First give the link of logout.php
page in that logout button.In that page make the code which is given below:
Here is the code:
<?php
session_start();
session_destroy();
?>
When the session has started, the session for the last/current user has been started, so don't need to declare the username. It will be deleted automatically by the session_destroy method.
A much simpler way is to just generate your SVG into a string, create a wrapper HTML element and insert the svg string into the HTML element using $("#wrapperElement").html(svgString)
. This works just fine in Chrome and Firefox.
subprocess.call
Automatically waits , you can also use:
p1.wait()
TV Sony Bravia KLV-32T550A Below mention config works greatly You should add the following into the /boot/config.txt to force the output to HDMI and set the
resolution 82 1920x1080 60Hz 1080p
hdmi_ignore_edid=0xa5000080
hdmi_force_hotplug=1
hdmi_boost=7
hdmi_group=2
hdmi_mode=82
hdmi_drive=1
For WAMP server, comment given by "Enrique" solved my problem.
wamp is using this php.ini:
c:\wamp\bin\apache\Apache2.4.4\bin\php.ini
But composer is using PHP from CLI, and hence it's reading this file:
c:\wamp\bin\php\php5.4.12\php.ini (so you need to enable openssl there)
For composer you will have to enable extension in
c:\wamp\bin\php\php5.4.12\php.ini
Change:
;extension=php_openssl.dll
to
extension=php_openssl.dll
That's JSON, or JavaScript Object Notation. It's a quick way of describing an object, or a hash map. The thing before the colon is the property name, and the thing after the colon is its value. So in this example, there's a property "r", whose value is whatever's in the variable r. Same for t.
Old question but appears to have a lot of traffic, here is a simple solution:
IntPtr GetMainWindowHandle(IntPtr aHandle) {
return System.Diagnostics.Process.GetProcessById(aHandle.ToInt32()).MainWindowHandle;
}
It for example happens in this case here:
void initializeJSP(unknownType Experiment);
Try using std::string
instead of just string
(and include the <string>
header). C++ Standard library classes are within the namespace std::
.
I implemented translucent Toolbar by creating two Theme.AppCompat.Light.NoActionBar
themes and setting colorPrimary
attribute to transparent color.
1) Create one theme for opaque Toolbar:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Toolbar background color -->
<item name="colorPrimary">#ff212cff</item>
</style>
Second theme for transparent/overlay Toolbar:
<style name="AppTheme.Overlay" parent="AppTheme">
<item name="colorPrimary">@color/transparent</item>
</style>
2) In your activity layout, put Toolbar behind content so it can be displayed in front of it:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment
android:id="@+id/container"
android:name="com.test.CustomFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
</RelativeLayout>
3) Apply the transparent theme to your acivity in AndroidManifest.xml
<activity
android:name="com.test.TransparentActivity"
android:parentActivityName="com.test.HomeActivity"
android:theme="@style/AppTheme.Overlay" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.test.HomeActivity" />
</activity>
TextBoxFor: It will render like text input html element corresponding to specified expression. In simple word it will always render like an input textbox irrespective datatype of the property which is getting bind with the control.
EditorFor: This control is bit smart. It renders HTML markup based on the datatype of the property. E.g. suppose there is a boolean property in model. To render this property in the view as a checkbox either we can use CheckBoxFor or EditorFor. Both will be generate the same markup.
What is the advantage of using EditorFor?
As we know, depending on the datatype of the property it generates the html markup. So suppose tomorrow if we change the datatype of property in the model, no need to change anything in the view. EditorFor control will change the html markup automatically.
if nothing worked, try this
public struct Platform {
public static var isSimulator: Bool {
return TARGET_OS_SIMULATOR != 0 // Use this line in Xcode 7 or newer
}
}
The position :fixed
is differ from the other layout.
Once you fixed
the position
for your header
, keep in mind that you have to set the margin-top
for the content
div.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
final RelativeLayout relativeLayout = new RelativeLayout(this);
final TextView tv1 = new TextView(this);
tv1.setText("tv1 is here");
// Setting an ID is mandatory.
tv1.setId(View.generateViewId());
relativeLayout.addView(tv1);
final TextView tv2 = new TextView(this);
tv2.setText("tv2 is here");
// We are defining layout params for tv2 which will be added to its parent relativelayout.
// The type of the LayoutParams depends on the parent type.
RelativeLayout.LayoutParams tv2LayoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
//Also, we want tv2 to appear below tv1, so we are adding rule to tv2LayoutParams.
tv2LayoutParams.addRule(RelativeLayout.BELOW, tv1.getId());
//Now, adding the child view tv2 to relativelayout, and setting tv2LayoutParams to be set on view tv2.
relativeLayout.addView(tv2);
tv2.setLayoutParams(tv2LayoutParams);
//Or we can combined the above two steps in one line of code
//relativeLayout.addView(tv2, tv2LayoutParams);
this.setContentView(relativeLayout);
}
}
Foreground needs a Brush, so you can use
textBlock.Foreground = Brushes.Navy;
If you want to use the color from RGB or ARGB then
textBlock.Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 255, 125, 35));
or
textBlock.Foreground = new System.Windows.Media.SolidColorBrush(Colors.Navy);
To get the Color from Hex
textBlock.Foreground = new System.Windows.Media.SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFDFD991"));
I like to use GSON because it's often already a dependency of the type of projects I'm working on:
public static String getDump(Object o) {
return new GsonBuilder().setPrettyPrinting().create().toJson(o);
}
Or substitute GSON for any other JSON library you use.
This Is Work For Me.
You Can Check It.
var script_tag = document.createElement('script');_x000D_
script_tag.setAttribute('src','https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js');_x000D_
document.head.appendChild(script_tag);_x000D_
window.onload = function() {_x000D_
if (window.jQuery) { _x000D_
// jQuery is loaded _x000D_
alert("ADD SCRIPT TAG ON HEAD!");_x000D_
} else {_x000D_
// jQuery is not loaded_x000D_
alert("DOESN'T ADD SCRIPT TAG ON HEAD");_x000D_
}_x000D_
}
_x000D_
This is a more tolerate way to handle this with user input. This regex will match both "100" or "100.1" but doesn't allow for negative numbers.
/^(\d+)(\.\d+)?$/
You should use the Android AccountManager. It's purpose-built for this scenario. It's a little bit cumbersome but one of the things it does is invalidate the local credentials if the SIM card changes, so if somebody swipes your phone and throws a new SIM in it, your credentials won't be compromised.
This also gives the user a quick and easy way to access (and potentially delete) the stored credentials for any account they have on the device, all from one place.
SampleSyncAdapter (like @Miguel mentioned) is an example that makes use of stored account credentials.
Try using varchar2 instead of varchar and use this :
INSERT INTO LOCATION VALUES('PQ95VM','HAPPY_STREET','FRANCE');
Here is a sample:
<?php
// Snippet from PHP Share: http://www.phpshare.org
function formatSizeUnits($bytes)
{
if ($bytes >= 1073741824)
{
$bytes = number_format($bytes / 1073741824, 2) . ' GB';
}
elseif ($bytes >= 1048576)
{
$bytes = number_format($bytes / 1048576, 2) . ' MB';
}
elseif ($bytes >= 1024)
{
$bytes = number_format($bytes / 1024, 2) . ' KB';
}
elseif ($bytes > 1)
{
$bytes = $bytes . ' bytes';
}
elseif ($bytes == 1)
{
$bytes = $bytes . ' byte';
}
else
{
$bytes = '0 bytes';
}
return $bytes;
}
?>
pickling is recursive, not sequential. Thus, to pickle a list, pickle
will start to pickle the containing list, then pickle the first element… diving into the first element and pickling dependencies and sub-elements until the first element is serialized. Then moves on to the next element of the list, and so on, until it finally finishes the list and finishes serializing the enclosing list. In short, it's hard to treat a recursive pickle as sequential, except for some special cases. It's better to use a smarter pattern on your dump
, if you want to load
in a special way.
The most common pickle, it to pickle everything with a single dump
to a file -- but then you have to load
everything at once with a single load
. However, if you open a file handle and do multiple dump
calls (e.g. one for each element of the list, or a tuple of selected elements), then your load
will mirror that… you open the file handle and do multiple load
calls until you have all the list elements and can reconstruct the list. It's still not easy to selectively load
only certain list elements, however. To do that, you'd probably have to store your list elements as a dict
(with the index of the element or chunk as the key) using a package like klepto
, which can break up a pickled dict
into several files transparently, and enables easy loading of specific elements.
The obvious subtext of this question is:
why can't you just use
==
to check if two strings are the same?
Perl doesn't have distinct data types for text vs. numbers. They are both represented by the type "scalar". Put another way, strings are numbers if you use them as such.
if ( 4 == "4" ) { print "true"; } else { print "false"; }
true
if ( "4" == "4.0" ) { print "true"; } else { print "false"; }
true
print "3"+4
7
Since text and numbers aren't differentiated by the language, we can't simply overload the ==
operator to do the right thing for both cases. Therefore, Perl provides eq
to compare values as text:
if ( "4" eq "4.0" ) { print "true"; } else { print "false"; }
false
if ( "4.0" eq "4.0" ) { print "true"; } else { print "false"; }
true
In short:
==
or !=
, to compare two operands as numberseq
or ne
, to compare two operands as textThere are many other functions and operators that can be used to compare scalar values, but knowing the distinction between these two forms is an important first step.
Solutions until now only deal with lists, and most are copying the list. In my experience a lot of times that isn't possible.
Also, they don't deal with the fact that you can have repeated elements in the list.
The title of your question says "Previous and next values inside a loop", but if you run most answers here inside a loop, you'll end up iterating over the entire list again on each element to find it.
So I've just created a function that. using the itertools
module, splits and slices the iterable, and generates tuples with the previous and next elements together. Not exactly what your code does, but it is worth taking a look, because it can probably solve your problem.
from itertools import tee, islice, chain, izip
def previous_and_next(some_iterable):
prevs, items, nexts = tee(some_iterable, 3)
prevs = chain([None], prevs)
nexts = chain(islice(nexts, 1, None), [None])
return izip(prevs, items, nexts)
Then use it in a loop, and you'll have previous and next items in it:
mylist = ['banana', 'orange', 'apple', 'kiwi', 'tomato']
for previous, item, nxt in previous_and_next(mylist):
print "Item is now", item, "next is", nxt, "previous is", previous
The results:
Item is now banana next is orange previous is None
Item is now orange next is apple previous is banana
Item is now apple next is kiwi previous is orange
Item is now kiwi next is tomato previous is apple
Item is now tomato next is None previous is kiwi
It'll work with any size list (because it doesn't copy the list), and with any iterable (files, sets, etc). This way you can just iterate over the sequence, and have the previous and next items available inside the loop. No need to search again for the item in the sequence.
A short explanation of the code:
tee
is used to efficiently create 3 independent iterators over the input sequencechain
links two sequences into one; it's used here to append a single-element sequence [None]
to prevs
islice
is used to make a sequence of all elements except the first, then chain
is used to append a None
to its endsome_iterable
that look like:
prevs
: None, A, B, C, D, E
items
: A, B, C, D, E
nexts
: B, C, D, E, None
izip
is used to change 3 sequences into one sequence of triplets.Note that izip
stops when any input sequence gets exhausted, so the last element of prevs
will be ignored, which is correct - there's no such element that the last element would be its prev
. We could try to strip off the last elements from prevs
but izip
's behaviour makes that redundant
Also note that tee
, izip
, islice
and chain
come from the itertools
module; they operate on their input sequences on-the-fly (lazily), which makes them efficient and doesn't introduce the need of having the whole sequence in memory at once at any time.
In python 3
, it will show an error while importing izip
,you can use zip
instead of izip
. No need to import zip
, it is predefined in python 3
- source
If you have pandas
installed you can turn it into a series with the keys as the index. So something like
import pandas as pd
s = pd.Series(my_dict)
s[['key1', 'key3', 'key2']]
How about something like this: http://jsfiddle.net/EgLKV/3/
Its done by using position:absolute
and z-index
to place the text over the image.
#container {_x000D_
height: 400px;_x000D_
width: 400px;_x000D_
position: relative;_x000D_
}_x000D_
#image {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
}_x000D_
#text {_x000D_
z-index: 100;_x000D_
position: absolute;_x000D_
color: white;_x000D_
font-size: 24px;_x000D_
font-weight: bold;_x000D_
left: 150px;_x000D_
top: 350px;_x000D_
}
_x000D_
<div id="container">_x000D_
<img id="image" src="http://www.noao.edu/image_gallery/images/d4/androa.jpg" />_x000D_
<p id="text">_x000D_
Hello World!_x000D_
</p>_x000D_
</div>
_x000D_
I received same error despite jar being in lib directory & added to deployment assembly in Eclipse.
So I doubted two things ,
1.Some Weblogic cache issue - as this app was deployed before & I was trying to redeploy after some changes
2.Jar itself is corrupt due to partial download etc
So I re downloaded the jar & deleted everything in directory - ..\Oracle_Home\user_projects\domains\base_domain\lib and redeployed again & all went well.
It depends on the jQuery selector that you use. Since id
should be unique within the DOM, the first one would be simple:
$('#Comanda').hide();
The second one might require something more, depending on the other elements and how to uniquely identify it. If the name
of that particular input
is unique, then this would work:
$('input[name="Vizualizeaza"]').hide();
Go to the "Database" option you mentioned.
Copied from here.
To run an executable in mac
1). Move to the path of the file:
cd/PATH_OF_THE_FILE
2). Run the following command to set the file's executable bit using the chmod command:
chmod +x ./NAME_OF_THE_FILE
3). Run the following command to execute the file:
./NAME_OF_THE_FILE
Once you have run these commands, going ahead you just have to run command 3, while in the files path.
I ended up getting the answer from AngularJS forum. See this thread for details
The link is to a Google Groups thread, which is difficult to read and doesn't provide a clear answer. To remove URL parameters use
$location.url($location.path());
https://services.gradle.org/distributions/gradle-2.1-all.zip
open this link in the browser and download the zip file and extract it to folder
Before extraction please delete the old folder whose name ends gradle-2.1-all and then you can start extracting
if you are window user extract it to this folder
C:\Users{Your-Name}.gradle\wrapper\dists
after that just restart your android studio. I hope it works it works for me .
:nth-last-child(-n+2)
should do the trick
if you like to use for URLRequest httpBody
extension Dictionary {
func toString() -> String? {
return (self.compactMap({ (key, value) -> String in
return "\(key)=\(value)"
}) as Array).joined(separator: "&")
}
}
// print: Fields=sdad&ServiceId=1222
Some IDEs highlight the code in heredoc strings automatically - which makes using heredoc for XML or HTML visually appealing.
I personally like it for longer parts of i.e. XML since I don't have to care about quoting quote characters and can simply paste the XML.
Spring source code to explain how ApplicationContextAware work
when you use ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
In AbstractApplicationContext
class,the refresh()
method have the following code:
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
enter this method,beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
will add ApplicationContextAwareProcessor to AbstractrBeanFactory.
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
beanFactory.setBeanClassLoader(getClassLoader());
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
...........
When spring initialize bean in AbstractAutowireCapableBeanFactory
,
in method initializeBean
,call applyBeanPostProcessorsBeforeInitialization
to implement the bean post process. the process include inject the applicationContext.
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessBeforeInitialization(result, beanName);
if (result == null) {
return result;
}
}
return result;
}
when BeanPostProcessor implement Objectto execute the postProcessBeforeInitialization method,for example ApplicationContextAwareProcessor
that added before.
private void invokeAwareInterfaces(Object bean) {
if (bean instanceof Aware) {
if (bean instanceof EnvironmentAware) {
((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
}
if (bean instanceof EmbeddedValueResolverAware) {
((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(
new EmbeddedValueResolver(this.applicationContext.getBeanFactory()));
}
if (bean instanceof ResourceLoaderAware) {
((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
}
if (bean instanceof ApplicationEventPublisherAware) {
((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
}
if (bean instanceof MessageSourceAware) {
((MessageSourceAware) bean).setMessageSource(this.applicationContext);
}
if (bean instanceof ApplicationContextAware) {
((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
}
}
}
I only have half the answer, but I hope that it is useful as it adds unicode (utf-8) support
//decimal to unicode character
function unichr($dec) {
if ($dec < 128) {
$utf = chr($dec);
} else if ($dec < 2048) {
$utf = chr(192 + (($dec - ($dec % 64)) / 64));
$utf .= chr(128 + ($dec % 64));
} else {
$utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
$utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
$utf .= chr(128 + ($dec % 64));
}
return $utf;
}
To string
var_dump(unichr(hexdec('e641')));
Source: http://www.php.net/manual/en/function.chr.php#Hcom55978
Had the same issue today. I added the user to:
Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Log on as a batch job
But was still getting the error. I found this post, and it turns out there's also this setting that I had to remove the user from (not sure how it got in there):
Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Deny log on as a batch job
So just be aware that you may need to check both policies for the user.
For ANSI character encoding:
translate(//variable, 'ABCDEFGHIJKLMNOPQRSTUVWXYZÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞŸŽŠŒ', 'abcdefghijklmnopqrstuvwxyzàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿžšœ')
Sources that helped me get to work with my self signed certificate on my AWS Apache server and connect with HttpsURLConnection from android device:
SSL on aws instance - amazon tutorial on ssl
Android Security with HTTPS and SSL - creating your own trust manager on client for accepting your certificate
Creating self signed certificate - easy script for creating your certificates
Then I did the following:
create_my_certs.sh
:#!/bin/bash FQDN=$1 # make directories to work from mkdir -p server/ client/ all/ # Create your very own Root Certificate Authority openssl genrsa \ -out all/my-private-root-ca.privkey.pem \ 2048 # Self-sign your Root Certificate Authority # Since this is private, the details can be as bogus as you like openssl req \ -x509 \ -new \ -nodes \ -key all/my-private-root-ca.privkey.pem \ -days 1024 \ -out all/my-private-root-ca.cert.pem \ -subj "/C=US/ST=Utah/L=Provo/O=ACME Signing Authority Inc/CN=example.com" # Create a Device Certificate for each domain, # such as example.com, *.example.com, awesome.example.com # NOTE: You MUST match CN to the domain name or ip address you want to use openssl genrsa \ -out all/privkey.pem \ 2048 # Create a request from your Device, which your Root CA will sign openssl req -new \ -key all/privkey.pem \ -out all/csr.pem \ -subj "/C=US/ST=Utah/L=Provo/O=ACME Tech Inc/CN=${FQDN}" # Sign the request from Device with your Root CA openssl x509 \ -req -in all/csr.pem \ -CA all/my-private-root-ca.cert.pem \ -CAkey all/my-private-root-ca.privkey.pem \ -CAcreateserial \ -out all/cert.pem \ -days 500 # Put things in their proper place rsync -a all/{privkey,cert}.pem server/ cat all/cert.pem > server/fullchain.pem # we have no intermediates in this case rsync -a all/my-private-root-ca.cert.pem server/ rsync -a all/my-private-root-ca.cert.pem client/
bash create_my_certs.sh yourdomain.com
Place the certificates in their proper place on the server (you can find configuration in /etc/httpd/conf.d/ssl.conf). All these should be set:
SSLCertificateFile
SSLCertificateKeyFile
SSLCertificateChainFile
SSLCACertificateFile
Restart httpd using sudo service httpd restart
and make sure httpd started:
Stopping httpd: [ OK ]
Starting httpd: [ OK ]
Copy my-private-root-ca.cert
to your android project assets folder
Create your trust manager:
SSLContext SSLContext;
CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream caInput = context.getAssets().open("my-private-root-ca.cert.pem"); Certificate ca; try { ca = cf.generateCertificate(caInput); } finally { caInput.close(); }
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext = SSLContext.getInstance("TLS");
SSSLContext.init(null, tmf.getTrustManagers(), null);
And make the connection using HttpsURLConnection:
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setSSLSocketFactory(SSLContext.getSocketFactory());
Thats it, try your https connection.
Version 7 of Angular has been released Official Angular blog link. Visit official angular update guide https://update.angular.io for detailed information. These steps will work for basic angular 6 apps using Angular Material.
ng update @angular/cli
ng update @angular/core
ng update @angular/material
Version 6 of Angular has been released Official Angular blog link. I have mentioned general upgrade steps below, but before and after the update you need to make changes in your code to make it workable in v6, for that detailed information visit official website https://update.angular.io .
Upgrade Steps (largely taken from the official Angular Update Guide for a basic Angular app using Angular Material):
Make sure NodeJS version is 8.9+ if not update it.
Update Angular cli globally and locally, and migrate the old configuration .angular-cli.json to the new angular.json format by running the following:
npm install -g @angular/cli
npm install @angular/cli
ng update @angular/cli
Update all of your Angular framework packages to v6,and the correct version of RxJS and TypeScript by running the following:
ng update @angular/core
Update Angular Material to the latest version by running the following:
ng update @angular/material
RxJS v6 has major changes from v5, v6 brings backwards compatibility package rxjs-compat that will keep your applications working, but you should refactor TypeScript code so that it doesn't depend on rxjs-compat. To refactor TypeScript code run following:
npm install -g rxjs-tslint
rxjs-5-to-6-migrate -p src/tsconfig.app.json
Note: Once all of your dependencies have updated to RxJS 6, remove rxjs- compat as it increases bundle size. please see this RxJS Upgrade Guide for more info.
npm uninstall rxjs-compat
Done run ng serve
to check it.
If you get errors in build refer https://update.angular.io for detailed info.
Upgrade rxjs to 6.0.0-beta.0, please see this RxJS Upgrade Guide for more info. RxJS v6 has breaking change hence first make your code compatible to latest RxJS version.
Update NodeJS version to 8.9+ (this is required by angular cli 6 version)
Update Angular cli global package to next version.
npm uninstall -g @angular/cli
npm cache verify
if npm version is < 5 then use npm cache clean
npm install -g @angular/cli@next
Change angular packages versions in package.json file to ^6.0.0-rc.5
"dependencies": {
"@angular/animations": "^6.0.0-rc.5",
"@angular/cdk": "^6.0.0-rc.12",
"@angular/common": "^6.0.0-rc.5",
"@angular/compiler": "^6.0.0-rc.5",
"@angular/core": "^6.0.0-rc.5",
"@angular/forms": "^6.0.0-rc.5",
"@angular/http": "^6.0.0-rc.5",
"@angular/material": "^6.0.0-rc.12",
"@angular/platform-browser": "^6.0.0-rc.5",
"@angular/platform-browser-dynamic": "^6.0.0-rc.5",
"@angular/router": "^6.0.0-rc.5",
"core-js": "^2.5.5",
"karma-jasmine": "^1.1.1",
"rxjs": "^6.0.0-uncanny-rc.7",
"rxjs-compat": "^6.0.0-uncanny-rc.7",
"zone.js": "^0.8.26"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.5.0",
"@angular/cli": "^6.0.0-rc.5",
"@angular/compiler-cli": "^6.0.0-rc.5",
"@types/jasmine": "2.5.38",
"@types/node": "~8.9.4",
"codelyzer": "~4.1.0",
"jasmine-core": "~2.5.2",
"jasmine-spec-reporter": "~3.2.0",
"karma": "~1.4.1",
"karma-chrome-launcher": "~2.0.0",
"karma-cli": "~1.0.1",
"karma-coverage-istanbul-reporter": "^0.2.0",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"postcss-loader": "^2.1.4",
"protractor": "~5.1.0",
"ts-node": "~5.0.0",
"tslint": "~5.9.1",
"typescript": "^2.7.2"
}
Next update Angular cli local package to next version and install above mentioned packages.
rm -rf node_modules dist # use rmdir /S/Q node_modules dist in Windows
Command Prompt; use rm -r -fo node_modules,dist in Windows PowerShell
npm install --save-dev @angular/cli@next
npm install
The Angular CLI configuration format has been changed from angular cli 6.0.0-rc.2 version, and your existing configuration can be updated automatically by running the following command. It will remove old config file .angular-cli.json and will write new angular.json file.
ng update @angular/cli --migrate-only --from=1.7.4
Note :- If you get following error "The Angular Compiler requires TypeScript >=2.7.2 and <2.8.0 but 2.8.3 was found instead". run following command :
npm install [email protected]
Here I present an alias based on Richard Hansen's answer (and Ben C's suggestion), but that I adapted to exclude tags. The alias should be fairly robust.
# For Git 1.22+
git config --global alias.only '!b=${1:-$(git branch --show-current)}; git log --oneline --graph "heads/$b" --not --exclude="$b" --branches --remotes #'
# For older Git:
git config --global alias.only '!b=${1:-$(git symbolic-ref -q --short HEAD)}; b=${b##heads/}; git log --oneline --graph "heads/$b" --not --exclude="$b" --branches --remotes #'
Example of use:
git only mybranch # Show commits that are in mybranch ONLY
git only # Show commits that are ONLY in current branch
Note that ONLY means commits that would be LOST (after garbage collection) if the given branch was deleted (excluding the effect of tags). The alias should work even if there is unfortunately a tag named mybranch
(thanks to prefix heads/
). Note also that no commits are shown if they are part of any remote branch (including upstream if any), in compliance with the definition of ONLY.
The alias shows the one-line history as a graph of the selected commits.
a --- b --- c --- master
\ \
\ d
\ \
e --- f --- g --- mybranch (HEAD)
\
h --- origin/other
With example above, git only
would show:
* (mybranch,HEAD)
* g
|\
| * d
* f
In order to include tags (but still excluding HEAD
), the alias becomes (adapt as above for older Git):
git config --global alias.only '!b=${1:-$(git branch --show-current)}; git log --oneline --graph --all --not --exclude="refs/heads/$b" --exclude=HEAD --all #'
Or the variant that includes all the tags including HEAD (and removing current branch as default since it won't output anything):
git config --global alias.only '!git log --oneline --graph --all --not --exclude=\"refs/heads/$1\" --all #'
This last version is the only one that really satisfies the criteria commits-that-are-lost-if-given-branch-is-deleted, since a branch cannot be deleted if it is checked out, and no commit pointed by HEAD or any other tag will be lost. However the first two variants are more useful.
Finally, the alias does not work with remote branches (eg. git only origin/master
). The alias must be modified, for instance:
git config --global alias.remote-only '!git log --oneline --graph "$1" --not --exclude="$1" --remotes --branches #'
With your ANDs you shouldn't have a FALSE value -2, until right at the end, e.g. with just 2 ANDs
=IF(AND(E2="In Play",F2="Closed"),3,IF(AND(E2="In Play",F2=" Suspended"),3,-2))
although it might be better with a combination of nested IFs and ANDs - try like this for the full formula:[Edited - thanks David]
=IF(E2="In Play",IF(F2="Closed",3,IF(F2="Suspended",2,IF(F2="Null",1))),IF(AND(E2="Pre-play",F2="Null"),-1,IF(AND(E2="Completed",F2="Closed"),2,IF(AND(E2="Pre-play",F2="Null"),3,-2))))
To avoid a long formula like the above you could create a table with all E2 possibilities in a column like K2:K5 and all F2 possibilities in a row like L1:N1 then fill in the required results in L2:N5 and use this formula
=INDEX($L$2:$N$5,MATCH(E2,$K$2:$K$5,0),MATCH(F2,$L$1:$N$1,0))
C# / Xamarin:
segment.SetTitleTextAttributes(new UITextAttributes {
Font = UIFont.SystemFontOfSize(font_size) }, UIControlState.Normal);
Adding the data-toggle="collapse" data-target=".navbar-collapse.in" to the tag <a>
worked for me.
<div>
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li class="nav-item"><a
href="#" data-toggle="collapse" data-target=".navbar-collapse.in" class="nav-link" >Home
</a></li>
</ul>
</div>
mysql version 5.5 set datetime default value as CURRENT_TIMESTAMP will be report error you can update to version 5.6 , it set datetime default value as CURRENT_TIMESTAMP
echo "<a href='#' style = \"font-color: #ff0000;\"> Movie List for {$key} 2013 </a>";
I answered a similar question here
As @Syden said, the mixins will work. Another option is using SASS map-get
like this..
@media (min-width: map-get($grid-breakpoints, sm)){
.something {
padding: 10px;
}
}
@media (min-width: map-get($grid-breakpoints, md)){
.something {
padding: 20px;
}
}
http://www.codeply.com/go/0TU586QNlV
I did the following:
<Create a backup of the entire folder>
Rename the project from within Visual Studio 2013 (optional/not needed).
Export the project as a template.
Close the solution.
Reopen the solution
Create a project from the saved template and use the name you like.
Delete from the solution explorer the previous project.
At this point I tried to compile the new solution, and to do so, I had to manually copy some resources and headers to the new project folder from the old project folder. Do this until it compiles without errors. Now this new project saved the ".exe" file to the previous folder.*
So ->
Go to Windows Explorer and manually copy the solution file from the old project folder to the new project folder.
Close the solution, and open the solution from within the new project.
Changed the configuration back to (x64) if needed.
Delete the folder of the project with the old name from the folder of the solution.
I like the a.push.apply(a, b)
method described above, and if you want you can always create a library function like this:
Array.prototype.append = function(array)
{
this.push.apply(this, array)
}
and use it like this
a = [1,2]
b = [3,4]
a.append(b)
Try running task manager to determine if your program is still running.
If it is running then stop it and run it again. the [Error] ld returned 1 exit status will not come back
svn revert -R .
svn up
This will recursively revert the current directory and everything under it and then update to the latest version.
Going back to the Kalman Filters ... I found a C implementation for a Kalman filter for GPS data here: http://github.com/lacker/ikalman I haven't tried it out yet, but it seems promising.
In my case MySQL sever was not running. I restarted the MySQL server and issue was resolved.
//on ubuntu server
sudo /etc/init.d/mysql start
To avoid MySQL stop problem, you can use the "initctl" utility in Ubuntu 14.04 LTS Linux to make sure the service restarts in case of a failure or reboot. Please consider talking a snapshot of root volume (with mysql stopped) before performing this operations for data retention purpose[8]. You can use the following commands to manage the mysql service with "initctl" utility with stop and start operations.
$ sudo initctl stop mysql
$ sudo initctl start mysql
To verify the working, you can check the status of the service and get the process id (pid), simulate a failure by killing the "mysql" process and verify its status as running with new process id after sometime (typically within 1 minute) using the following commands.
$ sudo initctl status mysql # get pid
$ sudo kill -9 <pid> # kill mysql process
$ sudo initctl status mysql # verify status as running after sometime
Note : In latest Ubuntu version now initctl is replaced by systemctl
hr {
height:0;
border:0;
border-top:1px solid #083972;
}
This will keep the Horizontal Rule 1px thick while also changing the color of it
With Java8, non heap region no more contains PermGen but Metaspace, which is a major change in Java8, supposed to get rid of out of memory errors with java as metaspace size can be increased depending on the space required by jvm for class data.
there's a library called DropKick.js that replaces the normal select dropdowns with HTML/CSS so you can fully style and control them with javascript. http://dropkickjs.com/
Give name and values to those submit buttons like:
<td>
<input type="submit" name='mybutton' class="noborder" id="save" value="save" alt="Save" tabindex="4" />
</td>
<td>
<input type="submit" name='mybutton' class="noborder" id="publish" value="publish" alt="Publish" tabindex="5" />
</td>
and then in your php script you could check
if($_POST['mybutton'] == 'save')
{
///do save processing
}
elseif($_POST['mybutton'] == 'publish')
{
///do publish processing here
}
With one group in the pattern, you can only get one exact result in that group. If your capture group gets repeated by the pattern (you used the +
quantifier on the surrounding non-capturing group), only the last value that matches it gets stored.
You have to use your language's regex implementation functions to find all matches of a pattern, then you would have to remove the anchors and the quantifier of the non-capturing group (and you could omit the non-capturing group itself as well).
Alternatively, expand your regex and let the pattern contain one capturing group per group you want to get in the result:
^([A-Z]+),([A-Z]+),([A-Z]+)$
The password_hash() function in PHP is an inbuilt function , used to create a new password hash with different algorithms and options. the function uses a strong hashing algorithm.
the function take 2 mandetory parametres ($password and $algorithm,) and 1 optional parameter ($options).
$strongPassword = password_hash( $password, $algorithm, $options )
Algoristrong textthms allowed right now for password_hash() are :
PASSWORD_DEFAULT
PASSWORD_BCRYPT
ASSWORD_ARGON2I
PASSWORD_ARGON2ID
example : echo password_hash("abcDEF", PASSWORD_DEFAULT);
answer : $2y$10$KwKceUaG84WInAif5ehdZOkE4kHPWTLp0ZK5a5OU2EbtdwQ9YIcGy
answer :$2y$10$SNly5bFzB/R6OVbBMq1bj.yiOZdsk6Mwgqi4BLR2sqdCvMyv/AyL2
to use the BCRYPT as password, use option cost =12 in an array , also change 1st parameter $password to some strong password like "wgt167yuWBGY@#1987__"
Example: echo password_hash("wgt167yuWBGY@#1987__", PASSWORD_BCRYPT ,['cost' => 12]);
Answer : $2y$12$TjSggXiFSidD63E.QP8PJOds2texJfsk/82VaNU8XRZ/niZhzkJ6S
Sample: Number of requests sent.
The Throughput: is the number of requests per unit of time (seconds, minutes, hours) that are sent to your server during the test.
The Response time: is the elapsed time from the moment when a given request is sent to the server until the moment when the last bit of information has returned to the client.
The throughput is the real load processed by your server during a run but it does not tell you anything about the performance of your server during this same run. This is the reason why you need both measures in order to get a real idea about your server’s performance during a run. The response time tells you how fast your server is handling a given load.
Average: This is the Average (Arithmetic mean µ = 1/n * Si=1…n xi) Response time of your total samples.
Min and Max are the minimum and maximum response time.
An important thing to understand is that the mean value can be very misleading as it does not show you how close (or far) your values are from the average.For this purpose, we need the Deviation value since Average value can be the Same for different response time of the samples!!
Deviation: The standard deviation (s) measures the mean distance of the values to their average (µ).It gives you a good idea of the dispersion or variability of the measures to their mean value.
The following equation show how the standard deviation (s) is calculated:
s = 1/n * v Si=1…n (xi-µ)2
For Details, see here!!
So, if the deviation value is low compared to the mean value, it will indicate you that your measures are not dispersed (or mostly close to the mean value) and that the mean value is significant.
Kb/sec: The throughput measured in Kilobytes per second.
Error % : Percent of requests with errors.
An example is always better to understand!!! I think, this article will help you.
You can define a Multi-module project structure, then you can set the configuration for sonar in one properties file in the root folder of your project, (Way #1
)
Use transform: scale(...);
and add matching margin: -...px
to compensate free space from scaling. (you can use * {outline: 1px solid}
to see element boundaries).
Using header file stdio.h
you can easily do it as usual like c. before using %.2lf(set a specific number after % specifier.) using printf().
It simply printf specific digits after decimal point.
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
double total=100;
printf("%.2lf",total);//this prints 100.00 like as C
}
I think @Evert has the right answer:
plt.scatter(dates,values)
plt.plot(dates, values)
plt.show()
Which is pretty much the same as
plt.plot(dates, values, '-o')
plt.show()
or whatever linestyle you prefer.
As an even easier solution, you could just use:
$results = $objects.Name
Which should fill $results
with an array of all the 'Name' property values of the elements in $objects
.
When it is on server side, use web services - maybe RESTful with JSON.
When Java code is in applet you can use JavaScript bridge. The bridge between the Java and JavaScript programming languages, known informally as LiveConnect, is implemented in Java plugin. Formerly Mozilla-specific LiveConnect functionality, such as the ability to call static Java methods, instantiate new Java objects and reference third-party packages from JavaScript, is now available in all browsers.
Below is example from documentation. Look at methodReturningString
.
Java code:
public class MethodInvocation extends Applet {
public void noArgMethod() { ... }
public void someMethod(String arg) { ... }
public void someMethod(int arg) { ... }
public int methodReturningInt() { return 5; }
public String methodReturningString() { return "Hello"; }
public OtherClass methodReturningObject() { return new OtherClass(); }
}
public class OtherClass {
public void anotherMethod();
}
Web page and JavaScript code:
<applet id="app"
archive="examples.jar"
code="MethodInvocation" ...>
</applet>
<script language="javascript">
app.noArgMethod();
app.someMethod("Hello");
app.someMethod(5);
var five = app.methodReturningInt();
var hello = app.methodReturningString();
app.methodReturningObject().anotherMethod();
</script>
Might help someone else : I encountered the same kind of issues while I had done some "copy-paste" from a side Microsoft Word document, where I took notes, to my shell script(s).
Re-writing, manually, the exact same code in the script just solved this.
It was quite un-understandable at first, I think Word's hidden characters and/or formatting were the issue. Obvious but not see-able ... I lost about one hour on this (I'm no shell expert, as you might guess ...)
Assuming that this is about OAuth 2.0 since it is about JWTs and refresh tokens...:
just like an access token, in principle a refresh token can be anything including all of the options you describe; a JWT could be used when the Authorization Server wants to be stateless or wants to enforce some sort of "proof-of-possession" semantics on to the client presenting it; note that a refresh token differs from an access token in that it is not presented to a Resource Server but only to the Authorization Server that issued it in the first place, so the self-contained validation optimization for JWTs-as-access-tokens does not hold for refresh tokens
that depends on the security/access of the database; if the database can be accessed by other parties/servers/applications/users, then yes (but your mileage may vary with where and how you store the encryption key...)
an Authorization Server may issue both access tokens and refresh tokens at the same time, depending on the grant that is used by the client to obtain them; the spec contains the details and options on each of the standardized grants
Clone is broken, so dont use it.
THE CLONE METHOD of the Object class is a somewhat magical method that does what no pure Java method could ever do: It produces an identical copy of its object. It has been present in the primordial Object superclass since the Beta-release days of the Java compiler*; and it, like all ancient magic, requires the appropriate incantation to prevent the spell from unexpectedly backfiring
Prefer a method that copies the object
Foo copyFoo (Foo foo){
Foo f = new Foo();
//for all properties in FOo
f.set(foo.get());
return f;
}
Read more http://adtmag.com/articles/2000/01/18/effective-javaeffective-cloning.aspx
Microsoft hired one fo the kids from A List Apart to whip some out. The .Net projects are free of charge for download.
I encountered EXC_BAD_ACCESS on the iPhone only while trying to execute a C method that included a big array. The simulator was able to give me enough memory to run the code, but not the device (the array was a million characters, so it was a tad excessive!).
The EXC_BAD_ACCESS occurred just after entry point of the method, and had me confused for quite a while because it was nowhere near the array declaration.
Perhaps someone else might benefit from my couple of hours of hair-pulling.
int add(int a, int b)
{
return (a+b);
}
int minus(int a, int b)
{
return (a-b);
}
typedef int (*math_func)(int, int); //declaration of function pointer
int main()
{
math_func addition = add; //typedef assigns a new variable i.e. "addition" to original function "add"
math_func substract = minus; //typedef assigns a new variable i.e. "substract" to original function "minus"
int c = addition(11, 11); //calling function via new variable
printf("%d\n",c);
c = substract(11, 5); //calling function via new variable
printf("%d",c);
return 0;
}
Output of this is :
22
6
Note that, same math_func definer has been used for the declaring both the function.
Same approach of typedef may be used for extern struct.(using sturuct in other file.)
All the above answers directly answer the question. But here's a less direct solution but a potentially more important idea, to provoke thought.
Since line lengths are arbitrary, all the bytes of the file before the nth line need to be read. If you have a huge file or need to repeat this task many times, and this process is time-consuming, then you should seriously think about whether you should be storing your data in a different way in the first place.
The real solution is to have an index, e.g. at the start of the file, indicating the positions where the lines begin. You could use a database format, or just add a table at the start of the file. Alternatively create a separate index file to accompany your large text file.
e.g. you might create a list of character positions for newlines:
awk 'BEGIN{c=0;print(c)}{c+=length()+1;print(c+1)}' file.txt > file.idx
then read with tail
, which actually seek
s directly to the appropriate point in the file!
e.g. to get line 1000:
tail -c +$(awk 'NR=1000' file.idx) file.txt | head -1
I'd consider passing your IDs as an XML string, and then you could shred the XML into a temp table to join against, or you could also query against the XML directly using SP_XML_PREPAREDOCUMENT and OPENXML.
If you are using NetBeans, you just press f11 and your project will be build. The default path is projectfolder\dist
in Short, There are 3 parameters in AsyncTask
parameters for Input use in DoInBackground(String... params)
parameters for show status of progress use in OnProgressUpdate(String... status)
parameters for result use in OnPostExcute(String... result)
Note : - [Type of parameters can vary depending on your requirement]
After logging in, on the home page of the Server Console you should see 3 sections:
Under Services Configurations there is subsection Other Services. Click the JTA Configuration link under Other Services. The transaction timeout should be the top setting on the page displayed, labelled Timeout Seconds.
Not in VB.NET, you have to select all lines at then Edit, Advanced, Comment Selection menu, or a keyboard shortcut for that menu.
http://bytes.com/topic/visual-basic-net/answers/376760-how-block-comment
Example found on: http://www.orafaq.com/usenet/comp.databases.oracle.server/2006/12/20/0646.htm
SELECT REGEXP_REPLACE(SYS_GUID(), '(.{8})(.{4})(.{4})(.{4})(.{12})', '\1-\2-\3-\4-\5') MSSQL_GUID FROM DUAL
Result:
6C7C9A50-3514-4E77-E053-B30210AC1082
To stick with the Maven terms:
http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html#Lifecycle_Reference
If you want to get an array of ints, with values from 1 to 10, from a Stream<Integer>
, there is IntStream
at your disposal.
Here we create a Stream
with a Stream.of
method and convert a Stream<Integer>
to an IntStream
using a mapToInt
. Then we can call IntStream
's toArray
method.
Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9,10);
//or use this to create our stream
//Stream<Integer> stream = IntStream.rangeClosed(1, 10).boxed();
int[] array = stream.mapToInt(x -> x).toArray();
Here is the same thing, without the Stream<Integer>
, using only the IntStream
:
int[]array2 = IntStream.rangeClosed(1, 10).toArray();
You can call the function created in another js file from the file you are working in. So for this firstly you need to add the external js file into the html document as-
<html>
<head>
<script type="text/javascript" src='path/to/external/js'></script>
</head>
<body>
........
The function defined in the external javascript file -
$.fn.yourFunctionName = function(){
alert('function called succesfully for - ' + $(this).html() );
}
To call this function in your current file, just call the function as -
......
<script type="text/javascript">
$(function(){
$('#element').yourFunctionName();
});
</script>
If you want to pass the parameters to the function, then define the function as-
$.fn.functionWithParameters = function(parameter1, parameter2){
alert('Parameters passed are - ' + parameter1 + ' , ' + parameter2);
}
And call this function in your current file as -
$('#element').functionWithParameters('some parameter', 'another parameter');
There's an article over on MSDN that has a sample application for zipping and unzipping files and folders purely in C#. I've been using some of the classes in that successfully for a long time. The code is released under the Microsoft Permissive License, if you need to know that sort of thing.
EDIT: Thanks to Cheeso for pointing out that I'm a bit behind the times. The MSDN example I pointed to is in fact using DotNetZip and is really very fully-featured these days. Based on my experience of a previous version of this I'd happily recommend it.
SharpZipLib is also quite a mature library and is highly rated by people, and is available under the GPL license. It really depends on your zipping needs and how you view the license terms for each of them.
Rich
- Create a Class
with public static final
fields.
- And then you can access these fields from any class using the Class_Name.Field_Name
.
- You can declare the class
as final
, so that the class
can't be extended(Inherited) and modify....
You are defining the color: #C1C1C1;
for all the a
elements with #sub-nav-container a
.
Doing it again in li.sub-navigation-home-news
won't do anything, as it is a parent of the a
element.
There was a change from 1.3.x to 1.4.x.
In Angular 1.3.x this worked:
var dir: ng.IDirective = {
restrict: "A",
require: ["select", "ngModel"],
compile: compile,
};
function compile(tElement: ng.IAugmentedJQuery, tAttrs, transclude) {
tElement.append("<option value=''>--- Kein ---</option>");
return function postLink(scope: DirectiveScope, element: ng.IAugmentedJQuery, attributes: ng.IAttributes) {
attributes["ngOptions"] = "a.ID as a.Bezeichnung for a in akademischetitel";
scope.akademischetitel = AkademischerTitel.query();
}
}
Now in Angular 1.4.x we have to do this:
var dir: ng.IDirective = {
restrict: "A",
compile: compile,
terminal: true,
priority: 10,
};
function compile(tElement: ng.IAugmentedJQuery, tAttrs, transclude) {
tElement.append("<option value=''>--- Kein ---</option>");
tElement.removeAttr("tq-akademischer-titel-select");
tElement.attr("ng-options", "a.ID as a.Bezeichnung for a in akademischetitel");
return function postLink(scope: DirectiveScope, element: ng.IAugmentedJQuery, attributes: ng.IAttributes) {
$compile(element)(scope);
scope.akademischetitel = AkademischerTitel.query();
}
}
(From the accepted answer: https://stackoverflow.com/a/19228302/605586 from Khanh TO).
There are several ways, like:
where some_column is null or some_column = ''
or
where ifnull(some_column, '') = ''
or
where coalesce(some_column, '') = ''
of
where ifnull(length(some_column), 0) = 0
Add the jar in your classpath.
For example, if you have NoClassDefFoundError
for class XXXXXX
, get the jar containing the class and add it to your classpath manually.
It works for me. Hopefully it will work for you as well.
You can use JsonBuilder for that.
Example Code:
import groovy.json.JsonBuilder
class Person {
String name
String address
}
def o = new Person( name: 'John Doe', address: 'Texas' )
println new JsonBuilder( o ).toPrettyString()
Another and short way to get value of selected value,
$('#selectElement').on('change',function(){
var selectedVal = $(this).val();
^^^^ ^^^^ -> presents #selectElement selected value
|
v
presents #selectElement,
});
If you want to run the script directly, you can:
PYTHONPATH
).sys.path
in the your script.Then:
import module_you_wanted
You can use IntArrays.quickSort(array, comparator)
from fastutil library.
$sum = 0;
foreach($group as $key=>$value)
{
$sum+= $value;
}
echo $sum;
Try this:
List<Double> list = Arrays.asList(1.38, 2.56, 4.3);
which returns a fixed size list.
If you need an expandable list, pass this result to the ArrayList
constructor:
List<Double> list = new ArrayList<>(Arrays.asList(1.38, 2.56, 4.3));
We need to cover at least these aspects to provide a comprehensive answer/comparison (in no particular order of importance): Speed
, Memory usage
, Syntax
and Features
.
My intent is to cover each one of these as clearly as possible from data.table perspective.
Note: unless explicitly mentioned otherwise, by referring to dplyr, we refer to dplyr's data.frame interface whose internals are in C++ using Rcpp.
The data.table syntax is consistent in its form - DT[i, j, by]
. To keep i
, j
and by
together is by design. By keeping related operations together, it allows to easily optimise operations for speed and more importantly memory usage, and also provide some powerful features, all while maintaining the consistency in syntax.
Quite a few benchmarks (though mostly on grouping operations) have been added to the question already showing data.table gets faster than dplyr as the number of groups and/or rows to group by increase, including benchmarks by Matt on grouping from 10 million to 2 billion rows (100GB in RAM) on 100 - 10 million groups and varying grouping columns, which also compares pandas
. See also updated benchmarks, which include Spark
and pydatatable
as well.
On benchmarks, it would be great to cover these remaining aspects as well:
Grouping operations involving a subset of rows - i.e., DT[x > val, sum(y), by = z]
type operations.
Benchmark other operations such as update and joins.
Also benchmark memory footprint for each operation in addition to runtime.
Operations involving filter()
or slice()
in dplyr can be memory inefficient (on both data.frames and data.tables). See this post.
Note that Hadley's comment talks about speed (that dplyr is plentiful fast for him), whereas the major concern here is memory.
data.table interface at the moment allows one to modify/update columns by reference (note that we don't need to re-assign the result back to a variable).
# sub-assign by reference, updates 'y' in-place
DT[x >= 1L, y := NA]
But dplyr will never update by reference. The dplyr equivalent would be (note that the result needs to be re-assigned):
# copies the entire 'y' column
ans <- DF %>% mutate(y = replace(y, which(x >= 1L), NA))
A concern for this is referential transparency. Updating a data.table object by reference, especially within a function may not be always desirable. But this is an incredibly useful feature: see this and this posts for interesting cases. And we want to keep it.
Therefore we are working towards exporting shallow()
function in data.table that will provide the user with both possibilities. For example, if it is desirable to not modify the input data.table within a function, one can then do:
foo <- function(DT) {
DT = shallow(DT) ## shallow copy DT
DT[, newcol := 1L] ## does not affect the original DT
DT[x > 2L, newcol := 2L] ## no need to copy (internally), as this column exists only in shallow copied DT
DT[x > 2L, x := 3L] ## have to copy (like base R / dplyr does always); otherwise original DT will
## also get modified.
}
By not using shallow()
, the old functionality is retained:
bar <- function(DT) {
DT[, newcol := 1L] ## old behaviour, original DT gets updated by reference
DT[x > 2L, x := 3L] ## old behaviour, update column x in original DT.
}
By creating a shallow copy using shallow()
, we understand that you don't want to modify the original object. We take care of everything internally to ensure that while also ensuring to copy columns you modify only when it is absolutely necessary. When implemented, this should settle the referential transparency issue altogether while providing the user with both possibilties.
Also, once
shallow()
is exported dplyr's data.table interface should avoid almost all copies. So those who prefer dplyr's syntax can use it with data.tables.But it will still lack many features that data.table provides, including (sub)-assignment by reference.
Aggregate while joining:
Suppose you have two data.tables as follows:
DT1 = data.table(x=c(1,1,1,1,2,2,2,2), y=c("a", "a", "b", "b"), z=1:8, key=c("x", "y"))
# x y z
# 1: 1 a 1
# 2: 1 a 2
# 3: 1 b 3
# 4: 1 b 4
# 5: 2 a 5
# 6: 2 a 6
# 7: 2 b 7
# 8: 2 b 8
DT2 = data.table(x=1:2, y=c("a", "b"), mul=4:3, key=c("x", "y"))
# x y mul
# 1: 1 a 4
# 2: 2 b 3
And you would like to get sum(z) * mul
for each row in DT2
while joining by columns x,y
. We can either:
1) aggregate DT1
to get sum(z)
, 2) perform a join and 3) multiply (or)
# data.table way
DT1[, .(z = sum(z)), keyby = .(x,y)][DT2][, z := z*mul][]
# dplyr equivalent
DF1 %>% group_by(x, y) %>% summarise(z = sum(z)) %>%
right_join(DF2) %>% mutate(z = z * mul)
2) do it all in one go (using by = .EACHI
feature):
DT1[DT2, list(z=sum(z) * mul), by = .EACHI]
What is the advantage?
We don't have to allocate memory for the intermediate result.
We don't have to group/hash twice (one for aggregation and other for joining).
And more importantly, the operation what we wanted to perform is clear by looking at j
in (2).
Check this post for a detailed explanation of by = .EACHI
. No intermediate results are materialised, and the join+aggregate is performed all in one go.
Have a look at this, this and this posts for real usage scenarios.
In dplyr
you would have to join and aggregate or aggregate first and then join, neither of which are as efficient, in terms of memory (which in turn translates to speed).
Update and joins:
Consider the data.table code shown below:
DT1[DT2, col := i.mul]
adds/updates DT1
's column col
with mul
from DT2
on those rows where DT2
's key column matches DT1
. I don't think there is an exact equivalent of this operation in dplyr
, i.e., without avoiding a *_join
operation, which would have to copy the entire DT1
just to add a new column to it, which is unnecessary.
Check this post for a real usage scenario.
To summarise, it is important to realise that every bit of optimisation matters. As Grace Hopper would say, Mind your nanoseconds!
Let's now look at syntax. Hadley commented here:
Data tables are extremely fast but I think their concision makes it harder to learn and code that uses it is harder to read after you have written it ...
I find this remark pointless because it is very subjective. What we can perhaps try is to contrast consistency in syntax. We will compare data.table and dplyr syntax side-by-side.
We will work with the dummy data shown below:
DT = data.table(x=1:10, y=11:20, z=rep(1:2, each=5))
DF = as.data.frame(DT)
Basic aggregation/update operations.
# case (a)
DT[, sum(y), by = z] ## data.table syntax
DF %>% group_by(z) %>% summarise(sum(y)) ## dplyr syntax
DT[, y := cumsum(y), by = z]
ans <- DF %>% group_by(z) %>% mutate(y = cumsum(y))
# case (b)
DT[x > 2, sum(y), by = z]
DF %>% filter(x>2) %>% group_by(z) %>% summarise(sum(y))
DT[x > 2, y := cumsum(y), by = z]
ans <- DF %>% group_by(z) %>% mutate(y = replace(y, which(x > 2), cumsum(y)))
# case (c)
DT[, if(any(x > 5L)) y[1L]-y[2L] else y[2L], by = z]
DF %>% group_by(z) %>% summarise(if (any(x > 5L)) y[1L] - y[2L] else y[2L])
DT[, if(any(x > 5L)) y[1L] - y[2L], by = z]
DF %>% group_by(z) %>% filter(any(x > 5L)) %>% summarise(y[1L] - y[2L])
data.table syntax is compact and dplyr's quite verbose. Things are more or less equivalent in case (a).
In case (b), we had to use filter()
in dplyr while summarising. But while updating, we had to move the logic inside mutate()
. In data.table however, we express both operations with the same logic - operate on rows where x > 2
, but in first case, get sum(y)
, whereas in the second case update those rows for y
with its cumulative sum.
This is what we mean when we say the DT[i, j, by]
form is consistent.
Similarly in case (c), when we have if-else
condition, we are able to express the logic "as-is" in both data.table and dplyr. However, if we would like to return just those rows where the if
condition satisfies and skip otherwise, we cannot use summarise()
directly (AFAICT). We have to filter()
first and then summarise because summarise()
always expects a single value.
While it returns the same result, using filter()
here makes the actual operation less obvious.
It might very well be possible to use filter()
in the first case as well (does not seem obvious to me), but my point is that we should not have to.
Aggregation / update on multiple columns
# case (a)
DT[, lapply(.SD, sum), by = z] ## data.table syntax
DF %>% group_by(z) %>% summarise_each(funs(sum)) ## dplyr syntax
DT[, (cols) := lapply(.SD, sum), by = z]
ans <- DF %>% group_by(z) %>% mutate_each(funs(sum))
# case (b)
DT[, c(lapply(.SD, sum), lapply(.SD, mean)), by = z]
DF %>% group_by(z) %>% summarise_each(funs(sum, mean))
# case (c)
DT[, c(.N, lapply(.SD, sum)), by = z]
DF %>% group_by(z) %>% summarise_each(funs(n(), mean))
In case (a), the codes are more or less equivalent. data.table uses familiar base function lapply()
, whereas dplyr
introduces *_each()
along with a bunch of functions to funs()
.
data.table's :=
requires column names to be provided, whereas dplyr generates it automatically.
In case (b), dplyr's syntax is relatively straightforward. Improving aggregations/updates on multiple functions is on data.table's list.
In case (c) though, dplyr would return n()
as many times as many columns, instead of just once. In data.table, all we need to do is to return a list in j
. Each element of the list will become a column in the result. So, we can use, once again, the familiar base function c()
to concatenate .N
to a list
which returns a list
.
Note: Once again, in data.table, all we need to do is return a list in
j
. Each element of the list will become a column in result. You can usec()
,as.list()
,lapply()
,list()
etc... base functions to accomplish this, without having to learn any new functions.You will need to learn just the special variables -
.N
and.SD
at least. The equivalent in dplyr aren()
and.
Joins
dplyr provides separate functions for each type of join where as data.table allows joins using the same syntax DT[i, j, by]
(and with reason). It also provides an equivalent merge.data.table()
function as an alternative.
setkey(DT1, x, y)
# 1. normal join
DT1[DT2] ## data.table syntax
left_join(DT2, DT1) ## dplyr syntax
# 2. select columns while join
DT1[DT2, .(z, i.mul)]
left_join(select(DT2, x, y, mul), select(DT1, x, y, z))
# 3. aggregate while join
DT1[DT2, .(sum(z) * i.mul), by = .EACHI]
DF1 %>% group_by(x, y) %>% summarise(z = sum(z)) %>%
inner_join(DF2) %>% mutate(z = z*mul) %>% select(-mul)
# 4. update while join
DT1[DT2, z := cumsum(z) * i.mul, by = .EACHI]
??
# 5. rolling join
DT1[DT2, roll = -Inf]
??
# 6. other arguments to control output
DT1[DT2, mult = "first"]
??
Some might find a separate function for each joins much nicer (left, right, inner, anti, semi etc), whereas as others might like data.table's DT[i, j, by]
, or merge()
which is similar to base R.
However dplyr joins do just that. Nothing more. Nothing less.
data.tables can select columns while joining (2), and in dplyr you will need to select()
first on both data.frames before to join as shown above. Otherwise you would materialiase the join with unnecessary columns only to remove them later and that is inefficient.
data.tables can aggregate while joining (3) and also update while joining (4), using by = .EACHI
feature. Why materialse the entire join result to add/update just a few columns?
data.table is capable of rolling joins (5) - roll forward, LOCF, roll backward, NOCB, nearest.
data.table also has mult =
argument which selects first, last or all matches (6).
data.table has allow.cartesian = TRUE
argument to protect from accidental invalid joins.
Once again, the syntax is consistent with
DT[i, j, by]
with additional arguments allowing for controlling the output further.
do()
...
dplyr's summarise is specially designed for functions that return a single value. If your function returns multiple/unequal values, you will have to resort to do()
. You have to know beforehand about all your functions return value.
DT[, list(x[1], y[1]), by = z] ## data.table syntax
DF %>% group_by(z) %>% summarise(x[1], y[1]) ## dplyr syntax
DT[, list(x[1:2], y[1]), by = z]
DF %>% group_by(z) %>% do(data.frame(.$x[1:2], .$y[1]))
DT[, quantile(x, 0.25), by = z]
DF %>% group_by(z) %>% summarise(quantile(x, 0.25))
DT[, quantile(x, c(0.25, 0.75)), by = z]
DF %>% group_by(z) %>% do(data.frame(quantile(.$x, c(0.25, 0.75))))
DT[, as.list(summary(x)), by = z]
DF %>% group_by(z) %>% do(data.frame(as.list(summary(.$x))))
.SD
's equivalent is .
In data.table, you can throw pretty much anything in j
- the only thing to remember is for it to return a list so that each element of the list gets converted to a column.
In dplyr, cannot do that. Have to resort to do()
depending on how sure you are as to whether your function would always return a single value. And it is quite slow.
Once again, data.table's syntax is consistent with
DT[i, j, by]
. We can just keep throwing expressions inj
without having to worry about these things.
Have a look at this SO question and this one. I wonder if it would be possible to express the answer as straightforward using dplyr's syntax...
To summarise, I have particularly highlighted several instances where dplyr's syntax is either inefficient, limited or fails to make operations straightforward. This is particularly because data.table gets quite a bit of backlash about "harder to read/learn" syntax (like the one pasted/linked above). Most posts that cover dplyr talk about most straightforward operations. And that is great. But it is important to realise its syntax and feature limitations as well, and I am yet to see a post on it.
data.table has its quirks as well (some of which I have pointed out that we are attempting to fix). We are also attempting to improve data.table's joins as I have highlighted here.
But one should also consider the number of features that dplyr lacks in comparison to data.table.
I have pointed out most of the features here and also in this post. In addition:
fread - fast file reader has been available for a long time now.
fwrite - a parallelised fast file writer is now available. See this post for a detailed explanation on the implementation and #1664 for keeping track of further developments.
Automatic indexing - another handy feature to optimise base R syntax as is, internally.
Ad-hoc grouping: dplyr
automatically sorts the results by grouping variables during summarise()
, which may not be always desirable.
Numerous advantages in data.table joins (for speed / memory efficiency and syntax) mentioned above.
Non-equi joins: Allows joins using other operators <=, <, >, >=
along with all other advantages of data.table joins.
Overlapping range joins was implemented in data.table recently. Check this post for an overview with benchmarks.
setorder()
function in data.table that allows really fast reordering of data.tables by reference.
dplyr provides interface to databases using the same syntax, which data.table does not at the moment.
data.table
provides faster equivalents of set operations (written by Jan Gorecki) - fsetdiff
, fintersect
, funion
and fsetequal
with additional all
argument (as in SQL).
data.table loads cleanly with no masking warnings and has a mechanism described here for [.data.frame
compatibility when passed to any R package. dplyr changes base functions filter
, lag
and [
which can cause problems; e.g. here and here.
Finally:
On databases - there is no reason why data.table cannot provide similar interface, but this is not a priority now. It might get bumped up if users would very much like that feature.. not sure.
On parallelism - Everything is difficult, until someone goes ahead and does it. Of course it will take effort (being thread safe).
OpenMP
.1
is a literal. name = value
is an assignment. 1 = value
is an assignment to a literal, which makes no sense. Why would you want 1
to mean something other than 1
?
In your class AutoMapper
profile, you need to create a map for your entity and viewmodel.
This is usually in AutoMapper/DomainToViewModelMappingProfile
In Configure()
, add a line like
Mapper.CreateMap<YourEntityViewModel, YourEntity>();
In ViewModelToDomainMappingProfile
, add:
Mapper.CreateMap<YourEntity, YourEntityViewModel>();
None of these answers did what I needed: Login to a remote server using a different domain account than I was logged into on my local machine, and it's a client's domain across a vpn. I don't want to be on their domain!
Instead, on the connect to server dialog, select "Windows Authentication", click the Options button, and then on the Additional Connection Parameters tab, enter
user id=domain\user;password=password
SSMS won't remember, but it will connect with that account.
If array item and list item are same
List<object> list=myArray.ToList();
I am using: Apache Commons Lang: StringUtils.ordinalIndexOf()
StringUtils.ordinalIndexOf("Java Language", "a", 2)
SHA doesn't require anything but an input to be applied, while AES requires at least 3 things - what you're encrypting/decrypting, an encryption key, and the initialization vector.
If $AccountNumber
or $Balance
is a node-set, then this behavior could easily happen. It's not because and
is being treated as or
.
For example, if $AccountNumber
referred to nodes with the values 12345
and 66
and $Balance
referred to nodes with the values 55
and 0
, then
$AccountNumber != '12345'
would be true (because 66
is not equal to 12345
) and $Balance != '0'
would be true (because 55
is not equal to 0
).
I'd suggest trying this instead:
<xsl:when test="not($AccountNumber = '12345' or $Balance = '0')">
$AccountNumber = '12345' or $Balance = '0'
will be true any time there is an $AccountNumber
with the value 12345
or there is a $Balance
with the value 0
, and if you apply not()
to that, you will get a false result.
At last, here I found the solution.
I added jdk path org.gradle.java.home=C:\\Program Files\\Java\\jdk1.8.0_144
to gradle.properties
file and did a rebuild. It works now.
"datetime" expects the date to be formated like this: YYYY-MM-DD HH:MM:SS
so format your date like that when you are inserting.
Python 2.6 and 3 specifically say to avoid using PIPE for stdout and stderr.
The correct way is
import subprocess
# must create a file object to store the output. Here we are getting
# the ssid we are connected to
outfile = open('/tmp/ssid', 'w');
status = subprocess.Popen(["iwgetid"], bufsize=0, stdout=outfile)
outfile.close()
# now operate on the file
Clickatell is a popular SMS gateway. It works in 200+ countries.
Their API offers a choice of connection options via: HTTP/S, SMPP, SMTP, FTP, XML, SOAP. Any of these options can be used from php.
The HTTP/S method is as simple as this:
http://api.clickatell.com/http/sendmsg?to=NUMBER&msg=Message+Body+Here
The SMTP method consists of sending a plain-text e-mail to: [email protected]
, with the following body:
user: xxxxx
password: xxxxx
api_id: xxxxx
to: 448311234567
text: Meet me at home
You can also test the gateway (incoming and outgoing) for free from your browser
You have to do write
in the same loop as read
.
Use the same compiler options for linking also.
Example:
gcc -mfloat-abi=hard fpu=neon -c -o test.cpp test.o
gcc -mfloat-abi=hard fpu=neon -c test1.cpp test1.o
gcc test.o test1.o mfloat-abi=hard fpu=neon HardTest
The answers here have pointed out that because after incrementing count it doesn't equal exactly 100, then it keeps going as the criteria isn't met (it's likely you want <
to say less than 100).
I'll just add that you should really be looking at Python's builtin range
function which generates a sequence of integers from a starting value, up to (but not including) another value, and an optional step - so you can adjust from adding 1 or 3 or 9 at a time...
0-100 (but not including 100, defaults starting from 0 and stepping by 1):
for number in range(100):
print(number)
0-100 (but not including and makes sure number doesn't go above 100) in steps of 3:
for number in range(0, 100, 3):
print(number)
I wrote a function which take into account eclipse debugger and unittest. It return the folder of the first script you launch. You can optionally specify the __file__ var, but the main thing is that you don't have to share this variable across all your calling hierarchy.
Maybe you can handle others stack particular cases I didn't see, but for me it's ok.
import inspect, os
def getRootDirectory(_file_=None):
"""
Get the directory of the root execution file
Can help: http://stackoverflow.com/questions/50499/how-do-i-get-the-path-and-name-of-the-file-that-is-currently-executing
For eclipse user with unittest or debugger, the function search for the correct folder in the stack
You can pass __file__ (with 4 underscores) if you want the caller directory
"""
# If we don't have the __file__ :
if _file_ is None:
# We get the last :
rootFile = inspect.stack()[-1][1]
folder = os.path.abspath(rootFile)
# If we use unittest :
if ("/pysrc" in folder) & ("org.python.pydev" in folder):
previous = None
# We search from left to right the case.py :
for el in inspect.stack():
currentFile = os.path.abspath(el[1])
if ("unittest/case.py" in currentFile) | ("org.python.pydev" in currentFile):
break
previous = currentFile
folder = previous
# We return the folder :
return os.path.dirname(folder)
else:
# We return the folder according to specified __file__ :
return os.path.dirname(os.path.realpath(_file_))
Taking a point from both Boycs Answer and mtmurdock's subsequent answer I have the following stored proc on all of my development or staging databases. I've added some switches to fit my own requirement if I need to add in statements to reseed the data for certain columns.
(Note: I would have added this as a comment to Boycs brilliant answer but I haven't got enough reputation to do that yet. So please accept my apologies for adding this as an entirely new answer.)
ALTER PROCEDURE up_ResetEntireDatabase
@IncludeIdentReseed BIT,
@IncludeDataReseed BIT
AS
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'DELETE FROM ?'
IF @IncludeIdentReseed = 1
BEGIN
EXEC sp_MSForEachTable 'DBCC CHECKIDENT (''?'' , RESEED, 1)'
END
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
IF @IncludeDataReseed = 1
BEGIN
-- Populate Core Data Table Here
END
GO
And then once ready the execution is really simple:
EXEC up_ResetEntireDatabase 1, 1
How to design table like this in mongodb?
First, to clarify some naming conventions. MongoDB uses collections
instead of tables
.
I think there are no foreign keys!
Take the following model:
student
{
_id: ObjectId(...),
name: 'Jane',
courses: [
{ course: 'bio101', mark: 85 },
{ course: 'chem101', mark: 89 }
]
}
course
{
_id: 'bio101',
name: 'Biology 101',
description: 'Introduction to biology'
}
Clearly Jane's course list points to some specific courses. The database does not apply any constraints to the system (i.e.: foreign key constraints), so there are no "cascading deletes" or "cascading updates". However, the database does contain the correct information.
In addition, MongoDB has a DBRef standard that helps standardize the creation of these references. In fact, if you take a look at that link, it has a similar example.
How can I solve this task?
To be clear, MongoDB is not relational. There is no standard "normal form". You should model your database appropriate to the data you store and the queries you intend to run.
Simply. You can go to 'File -> Preferences -> Color Theme' option in visual studio and change the color of you choice.
Up to C#5 (-VS2013) you have to call a function/method for it. Either a "normal" function such as String.Format
or an overload of the + operator.
string str = "Hello " + name; // This calls an overload of operator +.
In C#6 (VS2015) string interpolation has been introduced (as described by other answers).
For Windows/WSL/Cygwin etc users:
Make sure that your line endings are standard Unix line feeds, i.e. \n
(LF) only.
Using Windows line endings \r\n
(CRLF) line endings will break the command line break.
This is because having \
at the end of a line with Windows line ending translates to
\
\r
\n
.
As Mark correctly explains above:
The line-continuation will fail if you have whitespace after the backslash and before the newline.
This includes not just space () or tabs (
\t
) but also the carriage return (\r
).
In Virtual Box
Now the tricky bit is your localhost, if you are running from Node.js set the IP address to 0.0.0.0, then lookup your own IP address, for example cmd:ipconfig --> 10.0.1.3
Type that address in with the port number. And it will work.
In short, they are equivalent. Let's have a history view:
(1) at first, the function looks like this.
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
(2) to make code more abstract (and more portable). A common method to get Super-Class is invented like:
super(<class>, <instance>)
And init function can be:
class MySubClassBetter(MySuperClass):
def __init__(self):
super(MySubClassBetter, self).__init__()
However requiring an explicit passing of both the class and instance break the DRY (Don't Repeat Yourself) rule a bit.
(3) in V3. It is more smart,
super()
is enough in most case. You can refer to http://www.python.org/dev/peps/pep-3135/
$num += (6-$num%6)%6;
no need for a while loop! Modulo (%) returns the remainder of a division. IE 20%6 = 2. 6-2 = 4. 20+4 = 24. 24 is divisible by 6.
Simply putting - this.setState({data: value}) is asynchronous in nature that means it moves out of the Call Stack and only comes back to the Call Stack unless it is resolved.
Please read about Event Loop to have a clear picture about Asynchronous nature in JS and why it takes time to update -
https://medium.com/front-end-weekly/javascript-event-loop-explained-4cd26af121d4
Hence -
this.setState({data:value});
console.log(this.state.data); // will give undefined or unupdated value
as it takes time to update. To achieve the above process -
this.setState({data:value},function () {
console.log(this.state.data);
});
A cleaner Python3 version that use standard numpy, matplotlib and PIL. Merging the answer for opening from URL.
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
pil_im = Image.open('image.png') #Take jpg + png
## Uncomment to open from URL
#import requests
#r = requests.get('https://www.vegvesen.no/public/webkamera/kamera?id=131206')
#pil_im = Image.open(BytesIO(r.content))
im_array = np.asarray(pil_im)
plt.imshow(im_array)
plt.show()
kieron's answer contains w3schools ref. to which nobody rely , bobince's answer gives link , which actually tells native implementation of IE ,
so here is the original documentation quoted to rightly understand what readystate represents :
The XMLHttpRequest object can be in several states. The readyState attribute must return the current state, which must be one of the following values:
UNSENT (numeric value 0)
The object has been constructed.OPENED (numeric value 1)
The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.HEADERS_RECEIVED (numeric value 2)
All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.LOADING (numeric value 3)
The response entity body is being received.DONE (numeric value 4)
The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects).
Please Read here : W3C Explaination Of ReadyState
In such cases, you are better off re-adding the whitespace which makes the syntax error immediate apparent:
function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
document.getElementById("content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","data/"+id+".html",true);xmlhttp.send();
}
There's a } too many. Also, after the closing } of the function, you should add a ; before the xmlhttp.open()
And finally, I don't see what that anonymous function does up there. It's never executed or referenced. Are you sure you pasted the correct code?
Xcode 8.1
Product -> Archive Then export on the right hand side to somewhere on your drive.
Here is the same solution than Rukshan but in sass (in order to keep your grid configuration) for special case that don't work with Ross Allen solution (when you can't have a parent div.row)
@mixin make-grid-offset-right($class) {
@for $index from 0 through $grid-columns {
.col-#{$class}-offset-right-#{$index} {
margin-right: percentage(($index / $grid-columns));
}
}
}
@include make-grid-offset-right(xs);
@media (min-width: $screen-sm-min) {
@include make-grid-offset-right(sm);
}
@media (min-width: $screen-md-min) {
@include make-grid-offset-right(md);
}
@media (min-width: $screen-lg-min) {
@include make-grid-offset-right(lg);
}
OpenGL should be present already - it will probably be Freeglut / GLUT that is missing.
GLUT is very dated now and not actively supported - so you should certainly be using Freeglut instead. You won't have to change your code at all, and a few additional features become available.
You'll find pre-packaged sets of files from here: http://freeglut.sourceforge.net/index.php#download If you don't see the "lib" folder, it's because you didn't download the pre-packaged set. "Martin Payne's Windows binaries" is posted at above link and works on Windows 8.1 with Visual Studio 2013 at the time of this writing.
When you download these you'll find that the Freeglut folder has three subfolders: - bin folder: this contains the dll files for runtime - include: the header files for compilation - lib: contains library files for compilation/linking
Installation instructions usually suggest moving these files into the visual studio folder and the Windows system folder: It is best to avoid doing this as it makes your project less portable, and makes it much more difficult if you ever need to change which version of the library you are using (old projects might suddenly stop working, etc.)
Instead (apologies for any inconsistencies, I'm basing these instructions on VS2010)... - put the freeglut folder somewhere else, e.g. C:\dev - Open your project in Visual Studio - Open project properties - There should be a tab for VC++ Directories, here you should add the appropriate include and lib folders, e.g.: C:\dev\freeglut\include and C:\dev\freeglut\lib - (Almost) Final step is to ensure that the opengl lib file is actually linked during compilation. Still in project properties, expand the linker menu, and open the input tab. For Additional Dependencies add opengl32.lib (you would assume that this would be linked automatically just by adding the include GL/gl.h to your project, but for some reason this doesn't seem to be the case)
At this stage your project should compile OK. To actually run it, you also need to copy the freeglut.dll files into your project folder
I changed the line
.ui-helper-hidden-accessible { position: absolute !important; clip: rect(1px 1px 1px 1px); clip: rect(1px,1px,1px,1px); }
to
.ui-helper-hidden-accessible { position: absolute !important; }
and everything works now. Otherwise try upping the z-index as Soldierflup suggested.
This program is doing almost everything with Public and private keys. The der format can be obtained but saving raw data ( without encoding base64). I hope this helps programmers.
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import sun.security.pkcs.PKCS8Key;
import sun.security.pkcs10.PKCS10;
import sun.security.x509.X500Name;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* @author Desphilboy
* DorOd bar shomA barobach
*
*/
public class csrgenerator {
private static PublicKey publickey= null;
private static PrivateKey privateKey=null;
//private static PKCS8Key privateKey=null;
private static KeyPairGenerator kpg= null;
private static ByteArrayOutputStream bs =null;
private static csrgenerator thisinstance;
private KeyPair keypair;
private static PKCS10 pkcs10;
private String signaturealgorithm= "MD5WithRSA";
public String getSignaturealgorithm() {
return signaturealgorithm;
}
public void setSignaturealgorithm(String signaturealgorithm) {
this.signaturealgorithm = signaturealgorithm;
}
private csrgenerator() {
try {
kpg = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
System.out.print("No such algorithm RSA in constructor csrgenerator\n");
}
kpg.initialize(2048);
keypair = kpg.generateKeyPair();
publickey = keypair.getPublic();
privateKey = keypair.getPrivate();
}
/** Generates a new key pair
*
* @param int bits
* this is the number of bits in modulus must be 512, 1024, 2048 or so on
*/
public KeyPair generateRSAkys(int bits)
{
kpg.initialize(bits);
keypair = kpg.generateKeyPair();
publickey = keypair.getPublic();
privateKey = keypair.getPrivate();
KeyPair dup= keypair;
return dup;
}
public static csrgenerator getInstance() {
if (thisinstance == null)
thisinstance = new csrgenerator();
return thisinstance;
}
/**
* Returns a CSR as string
* @param cn Common Name
* @param OU Organizational Unit
* @param Org Organization
* @param LocName Location name
* @param Statename State/Territory/Province/Region
* @param Country Country
* @return returns csr as string.
* @throws Exception
*/
public String getCSR(String commonname, String organizationunit, String organization,String localname, String statename, String country ) throws Exception {
byte[] csr = generatePKCS10(commonname, organizationunit, organization, localname, statename, country,signaturealgorithm);
return new String(csr);
}
/** This function generates a new Certificate
* Signing Request.
*
* @param CN
* Common Name, is X.509 speak for the name that distinguishes
* the Certificate best, and ties it to your Organization
* @param OU
* Organizational unit
* @param O
* Organization NAME
* @param L
* Location
* @param S
* State
* @param C
* Country
* @return byte stream of generated request
* @throws Exception
*/
private static byte[] generatePKCS10(String CN, String OU, String O,String L, String S, String C,String sigAlg) throws Exception {
// generate PKCS10 certificate request
pkcs10 = new PKCS10(publickey);
Signature signature = Signature.getInstance(sigAlg);
signature.initSign(privateKey);
// common, orgUnit, org, locality, state, country
//X500Name(String commonName, String organizationUnit,String organizationName,Local,State, String country)
X500Name x500Name = new X500Name(CN, OU, O, L, S, C);
pkcs10.encodeAndSign(x500Name,signature);
bs = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bs);
pkcs10.print(ps);
byte[] c = bs.toByteArray();
try {
if (ps != null)
ps.close();
if (bs != null)
bs.close();
} catch (Throwable th) {
}
return c;
}
public PublicKey getPublicKey() {
return publickey;
}
/**
* @return
*/
public PrivateKey getPrivateKey() {
return privateKey;
}
/**
* saves private key to a file
* @param filename
*/
public void SavePrivateKey(String filename)
{
PKCS8EncodedKeySpec pemcontents=null;
pemcontents= new PKCS8EncodedKeySpec( privateKey.getEncoded());
PKCS8Key pemprivatekey= new PKCS8Key( );
try {
pemprivatekey.decode(pemcontents.getEncoded());
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File file=new File(filename);
try {
file.createNewFile();
FileOutputStream fos=new FileOutputStream(file);
fos.write(pemprivatekey.getEncoded());
fos.flush();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Saves Certificate Signing Request to a file;
* @param filename is a String containing full path to the file which will be created containing the CSR.
*/
public void SaveCSR(String filename)
{
FileOutputStream fos=null;
PrintStream ps=null;
File file;
try {
file = new File(filename);
file.createNewFile();
fos = new FileOutputStream(file);
ps= new PrintStream(fos);
}catch (IOException e)
{
System.out.print("\n could not open the file "+ filename);
}
try {
try {
pkcs10.print(ps);
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ps.flush();
ps.close();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.print("\n cannot write to the file "+ filename);
e.printStackTrace();
}
}
/**
* Saves both public key and private key to file names specified
* @param fnpub file name of public key
* @param fnpri file name of private key
* @throws IOException
*/
public static void SaveKeyPair(String fnpub,String fnpri) throws IOException {
// Store Public Key.
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
publickey.getEncoded());
FileOutputStream fos = new FileOutputStream(fnpub);
fos.write(x509EncodedKeySpec.getEncoded());
fos.close();
// Store Private Key.
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
fos = new FileOutputStream(fnpri);
fos.write(pkcs8EncodedKeySpec.getEncoded());
fos.close();
}
/**
* Reads a Private Key from a pem base64 encoded file.
* @param filename name of the file to read.
* @param algorithm Algorithm is usually "RSA"
* @return returns the privatekey which is read from the file;
* @throws Exception
*/
public PrivateKey getPemPrivateKey(String filename, String algorithm) throws Exception {
File f = new File(filename);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) f.length()];
dis.readFully(keyBytes);
dis.close();
String temp = new String(keyBytes);
String privKeyPEM = temp.replace("-----BEGIN PRIVATE KEY-----", "");
privKeyPEM = privKeyPEM.replace("-----END PRIVATE KEY-----", "");
//System.out.println("Private key\n"+privKeyPEM);
BASE64Decoder b64=new BASE64Decoder();
byte[] decoded = b64.decodeBuffer(privKeyPEM);
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
KeyFactory kf = KeyFactory.getInstance(algorithm);
return kf.generatePrivate(spec);
}
/**
* Saves the private key to a pem file.
* @param filename name of the file to write the key into
* @param key the Private key to save.
* @return String representation of the pkcs8 object.
* @throws Exception
*/
public String SavePemPrivateKey(String filename) throws Exception {
PrivateKey key=this.privateKey;
File f = new File(filename);
FileOutputStream fos = new FileOutputStream(f);
DataOutputStream dos = new DataOutputStream(fos);
byte[] keyBytes = key.getEncoded();
PKCS8Key pkcs8= new PKCS8Key();
pkcs8.decode(keyBytes);
byte[] b=pkcs8.encode();
BASE64Encoder b64=new BASE64Encoder();
String encoded = b64.encodeBuffer(b);
encoded= "-----BEGIN PRIVATE KEY-----\r\n" + encoded + "-----END PRIVATE KEY-----";
dos.writeBytes(encoded);
dos.flush();
dos.close();
//System.out.println("Private key\n"+privKeyPEM);
return pkcs8.toString();
}
/**
* Saves a public key to a base64 encoded pem file
* @param filename name of the file
* @param key public key to be saved
* @return string representation of the pkcs8 object.
* @throws Exception
*/
public String SavePemPublicKey(String filename) throws Exception {
PublicKey key=this.publickey;
File f = new File(filename);
FileOutputStream fos = new FileOutputStream(f);
DataOutputStream dos = new DataOutputStream(fos);
byte[] keyBytes = key.getEncoded();
BASE64Encoder b64=new BASE64Encoder();
String encoded = b64.encodeBuffer(keyBytes);
encoded= "-----BEGIN PUBLIC KEY-----\r\n" + encoded + "-----END PUBLIC KEY-----";
dos.writeBytes(encoded);
dos.flush();
dos.close();
//System.out.println("Private key\n"+privKeyPEM);
return encoded.toString();
}
/**
* reads a public key from a file
* @param filename name of the file to read
* @param algorithm is usually RSA
* @return the read public key
* @throws Exception
*/
public PublicKey getPemPublicKey(String filename, String algorithm) throws Exception {
File f = new File(filename);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) f.length()];
dis.readFully(keyBytes);
dis.close();
String temp = new String(keyBytes);
String publicKeyPEM = temp.replace("-----BEGIN PUBLIC KEY-----\n", "");
publicKeyPEM = publicKeyPEM.replace("-----END PUBLIC KEY-----", "");
BASE64Decoder b64=new BASE64Decoder();
byte[] decoded = b64.decodeBuffer(publicKeyPEM);
X509EncodedKeySpec spec =
new X509EncodedKeySpec(decoded);
KeyFactory kf = KeyFactory.getInstance(algorithm);
return kf.generatePublic(spec);
}
public static void main(String[] args) throws Exception {
csrgenerator gcsr = csrgenerator.getInstance();
gcsr.setSignaturealgorithm("SHA512WithRSA");
System.out.println("Public Key:\n"+gcsr.getPublicKey().toString());
System.out.println("Private Key:\nAlgorithm: "+gcsr.getPrivateKey().getAlgorithm().toString());
System.out.println("Format:"+gcsr.getPrivateKey().getFormat().toString());
System.out.println("To String :"+gcsr.getPrivateKey().toString());
System.out.println("GetEncoded :"+gcsr.getPrivateKey().getEncoded().toString());
BASE64Encoder encoder= new BASE64Encoder();
String s=encoder.encodeBuffer(gcsr.getPrivateKey().getEncoded());
System.out.println("Base64:"+s+"\n");
String csr = gcsr.getCSR( "[email protected]","baxshi az xodam", "Xodam","PointCook","VIC" ,"AU");
System.out.println("CSR Request Generated!!");
System.out.println(csr);
gcsr.SaveCSR("c:\\testdir\\javacsr.csr");
String p=gcsr.SavePemPrivateKey("c:\\testdir\\java_private.pem");
System.out.print(p);
p=gcsr.SavePemPublicKey("c:\\testdir\\java_public.pem");
privateKey= gcsr.getPemPrivateKey("c:\\testdir\\java_private.pem", "RSA");
BASE64Encoder encoder1= new BASE64Encoder();
String s1=encoder1.encodeBuffer(gcsr.getPrivateKey().getEncoded());
System.out.println("Private Key in Base64:"+s1+"\n");
System.out.print(p);
}
}
You never refer to a specific style sheet. All CSS rules in a document are internally fused into one.
In the case of rules in both style sheets that apply to the same element with the same specificity, the style sheet embedded later will override the earlier one.
You can use an element inspector like Firebug to see which rules apply, and which ones are overridden by others.
I'm getting the same solution as @camino's comment on https://stackoverflow.com/a/19365454/10593190 and XavierStuvw's reply.
I got it to work (for installing ffmpeg) by simply reinstalling the whole thing from the beginning with all instances of $ ./configure
replaced by $ ./configure --enable-shared
(first make sure to delete all the folders and files including the .so files from the previous attempt).
Apparently this works because https://stackoverflow.com/a/13812368/10593190.
Multiple instances of the same project
WORKAROUND
You cannot open multiple instances of the same folder but a workaround I have found is to open different folders.
lib
-components
-models
-helpers
tests
So, here I might open components, models and tests in different windows and then I can view them on my three monitors.
It sounds a bit simple but this has helped me a lot.
it should work perfectly fine if you would download it from --http://curl.haxx.se/dlwiz/?type=bin&os=Win64&flav=MinGW64 -- FOR 64BIT Win7/XP OR from http://curl.haxx.se/dlwiz/?type=bin&os=Win32&flav=-&ver=2000%2FXP --- FOR 32BIT Win7/XP just extract the files to c:/Windows and run it from cmd
C:\Users\WaQas>curl -v google.com
* About to connect() to google.com port 80 (#0)
* Trying 173.194.35.105...
* connected
* Connected to google.com (173.194.35.105) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.28.1
> Host: google.com
> Accept: */*
>
* HTTP 1.0, assume close after body
< HTTP/1.0 301 Moved Permanently
< Location: http://www.google.com/
< Content-Type: text/html; charset=UTF-8
< Date: Tue, 05 Feb 2013 00:50:57 GMT
< Expires: Thu, 07 Mar 2013 00:50:57 GMT
< Cache-Control: public, max-age=2592000
< Server: gws
< Content-Length: 219
< X-XSS-Protection: 1; mode=block
< X-Frame-Options: SAMEORIGIN
< X-Cache: MISS from LHR-CacheMARA3
< X-Cache-Lookup: HIT from LHR-CacheMARA3:64003
< Connection: close
<
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>
* Closing connection #0
Here's a Linq
version:
string s = "123iuow45ss";
var getNumbers = (from t in s
where char.IsDigit(t)
select t).ToArray();
Console.WriteLine(new string(getNumbers));
You need to install the Visual C++ libraries: http://www.microsoft.com/en-us/download/details.aspx?id=30679
@mani's response is now slightly outdated as using catch-all '*'
routes is no longer supported when using Vue 3 onward. If this is no longer working for you, try replacing the old catch-all path with
{ path: '/:pathMatch(.*)*', component: PathNotFound },
Essentially, you should be able to replace the '*'
path with '/:pathMatch(.*)*'
and be good to go!
Reason: Vue Router doesn't use path-to-regexp
anymore, instead it implements its own parsing system that allows route ranking and enables dynamic routing. Since we usually add one single catch-all route per project, there is no big benefit in supporting a special syntax for *.
(from https://next.router.vuejs.org/guide/migration/#removed-star-or-catch-all-routes)
This might sound stupid, but, in the first problem presented to you, you would have to see all the remaining numbers in the bag to actually add them up to find the missing number using that equation.
So, since you get to see all the numbers, just look for the number that's missing. The same goes for when two numbers are missing. Pretty simple I think. No point in using an equation when you get to see the numbers remaining in the bag.
You miss the from
clause
SELECT * from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP
Using .attr
method
.attr(attribute,value); // syntax
.attr("required", true);
// required="required"
.attr("required", false);
//
Using .prop
.prop(property,value) // syntax
.prop("required", true);
// required=""
.prop("required", false);
//
Read more from here
For starters
rake db:rollback
will get you back one step
then
rake db:rollback STEP=n
Will roll you back n
migrations where n
is the number of recent migrations you want to rollback.
More references here.
Quite old post, but it might help somebody new into git.
I will go with
git rebase master
long millisecond = beginupd.getTime();
Date.getTime()
JavaDoc states:
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
If you want to know on which platform you are on out of "Linux", "Windows", or "Darwin" (Mac), without more precision, you should use:
>>> import platform
>>> platform.system()
'Linux' # or 'Windows'/'Darwin'
The platform.system
function uses uname
internally.
I believe that phrase should have been worded as follows:
bcrypt has salts built into the generated hashes to prevent rainbow table attacks.
The bcrypt
utility itself does not appear to maintain a list of salts. Rather, salts are generated randomly and appended to the output of the function so that they are remembered later on (according to the Java implementation of bcrypt
). Put another way, the "hash" generated by bcrypt
is not just the hash. Rather, it is the hash and the salt concatenated.
In your AndroidManifest.xml file
<application
android:name="ApplicationClass"
android:icon="@drawable/ic_launcher" <--------
android:label="@string/app_name"
android:theme="@style/AppTheme" >
Pipe to gawk:
cat files.txt | xargs ls -l | cut -c 23-30 | gawk 'BEGIN { sum = 0 } // { sum = sum + $0 } END { print sum }'
in Swift 3.0 or Later
passwordTextField.isSecureTextEntry = true
[ $b == 5 ] && { a=$c; true; } || a=$d
This will avoid executing the part after || by accident when the code between && and || fails.
I think @Zack properly answered the question but just to cover all the bases:
Update myTable set MyColumn = NULL
This would set the entire column to null as the Question Title asks.
To set a specific row on a specific column to null use:
Update myTable set MyColumn = NULL where Field = Condition.
This would set a specific cell to null as the inner question asks.