It is maybe worth mentioning ave
. ave
is tapply
's friendly cousin. It returns results in a form that you can plug straight back into your data frame.
dfr <- data.frame(a=1:20, f=rep(LETTERS[1:5], each=4))
means <- tapply(dfr$a, dfr$f, mean)
## A B C D E
## 2.5 6.5 10.5 14.5 18.5
## great, but putting it back in the data frame is another line:
dfr$m <- means[dfr$f]
dfr$m2 <- ave(dfr$a, dfr$f, FUN=mean) # NB argument name FUN is needed!
dfr
## a f m m2
## 1 A 2.5 2.5
## 2 A 2.5 2.5
## 3 A 2.5 2.5
## 4 A 2.5 2.5
## 5 B 6.5 6.5
## 6 B 6.5 6.5
## 7 B 6.5 6.5
## ...
There is nothing in the base package that works like ave
for whole data frames (as by
is like tapply
for data frames). But you can fudge it:
dfr$foo <- ave(1:nrow(dfr), dfr$f, FUN=function(x) {
x <- dfr[x,]
sum(x$m*x$m2)
})
dfr
## a f m m2 foo
## 1 1 A 2.5 2.5 25
## 2 2 A 2.5 2.5 25
## 3 3 A 2.5 2.5 25
## ...
Another approach if you want to use a varying portion of the dataset instead of a single value is to use rollapply(data, width, FUN, ...)
. Using a vector of widths allows you to apply a function on a varying window of the dataset. I've used this to build an adaptive filtering routine, though it isn't very efficient.
If you want to learn your data summary (df)
provides the min, 1st quantile, median and mean, 3rd quantile and max of numerical columns and the frequency of the top levels of the factor columns.
I had success using .on() like so:
$('.leadtoscore').on('click', {event_type: 'shot'}, add_event);
Then inside the add_event
function you get access to 'shot' like this:
event.data.event_type
See the .on() documentation for more info, where they provide the following example:
function myHandler( event ) {
alert( event.data.foo );
}
$( "p" ).on( "click", { foo: "bar" }, myHandler );
Edit your Run/Debug Configuration so that Build option is selected before launching
After Build option is selected
The above solution worked for me while working on my JBehave test suite
Xcode -> File -> Workspace Setting -> change Build System to Legacy Build System.
Thats it. Have Fun
There are a few ways this can be completed.
Elements know which form they belong to, so you don't need to wrap this
in jquery, you can just call this.form
which returns the form element. Then you can call submit()
on a form element to submit it.
$('select').on('change', function(e){
this.form.submit()
});
documentation: https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement
Dim regDate As Date = Date.Now.date
This should fix your problem, though it's 2 years old!
Try something like
SELECT
CASE var
WHEN xyz THEN col1
WHEN zyx THEN col2
ELSE col7
END AS col1,
...
In other words, use a conditional expression to select the value, then rename the column.
Alternately, you could build up some sort of dynamic SQL hack to share the query tail; I've done this with iBatis before.
You can pass arbitrary parameters through the query string, but you can also set up custom routes to handle it in a RESTful way:
http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist=cher&
api_key=b25b959554ed76058ac220b7b2e0a026
That could be:
routes.MapRoute(
"ArtistsImages",
"{ws}/artists/{artist}/{action}/{*apikey}",
new { ws = "2.0", controller="artists" artist = "", action="", apikey="" }
);
So if someone used the following route:
ws.audioscrobbler.com/2.0/artists/cher/images/b25b959554ed76058ac220b7b2e0a026/
It would take them to the same place your example querystring did.
The above is just an example, and doesn't apply the business rules and constraints you'd have to set up to make sure people didn't 'hack' the URL.
I assume that you're writing to the file, then close it (so the user can open it in Excel), and then, before re-opening it for append/write operations, you want to check that the file isn't still open in Excel?
This is how you could do that:
while True: # repeat until the try statement succeeds
try:
myfile = open("myfile.csv", "r+") # or "a+", whatever you need
break # exit the loop
except IOError:
input("Could not open file! Please close Excel. Press Enter to retry.")
# restart the loop
with myfile:
do_stuff()
Try this:
Select u.[username]
,u.[ip]
,q.[time_stamp]
From [users] As u
Inner Join (
Select [username]
,max(time_stamp) as [time_stamp]
From [users]
Group By [username]) As [q]
On u.username = q.username
And u.time_stamp = q.time_stamp
Just treat the ES6 class name the same as you would have treated the constructor name in the ES5 way. They are one and the same.
The ES6 syntax is just syntactic sugar and creates exactly the same underlying prototype, constructor function and objects.
So, in your ES6 example with:
// animal.js
class Animal {
...
}
var a = new Animal();
module.exports = {Animal: Animal};
You can just treat Animal
like the constructor of your object (the same as you would have done in ES5). You can export the constructor. You can call the constructor with new Animal()
. Everything is the same for using it. Only the declaration syntax is different. There's even still an Animal.prototype
that has all your methods on it. The ES6 way really does create the same coding result, just with fancier/nicer syntax.
On the import side, this would then be used like this:
const Animal = require('./animal.js').Animal;
let a = new Animal();
This scheme exports the Animal constructor as the .Animal
property which allows you to export more than one thing from that module.
If you don't need to export more than one thing, you can do this:
// animal.js
class Animal {
...
}
module.exports = Animal;
And, then import it with:
const Animal = require('./animal.js');
let a = new Animal();
In practical terms, Alnitak is correct and makes it easy to understand, but ultimately in JavaScript, everything is passed by value.
What is the "value" of an object? It is the object reference.
When you pass in an object, you get a copy of this value (hence the 'copy of a reference' that Alnitak described). If you change this value, you do not change the original object; you are changing your copy of that reference.
As of AngularJS v1.2.0rc, ng-class
and even ng-attr-class
fail with SVG elements (They did work earlier, even with normal binding inside the class attribute)
Specifically, none of these work now:
ng-class="current==this_element?'active':' ' "
ng-attr-class="{{current==this_element?'active':' '}}"
class="class1 class2 .... {{current==this_element?'active':''}}"
As a workaround, I've to use
ng-attr-otherAttr="{{current==this_element?'active':''}}"
and then style using
[otherAttr='active'] {
... styles ...
}
A build, as Makefile understands it, consists of a lot of targets. For example, to build a project you might need
If you implemented this workflow with makefile, you could make each of the targets separately. For example, if you wrote
make file1.o
it would only build that file, if necessary.
The name of all
is not fixed. It's just a conventional name; all
target denotes that if you invoke it, make will build all what's needed to make a complete build. This is usually a dummy target, which doesn't create any files, but merely depends on the other files. For the example above, building all necessary is building executables, the other files being pulled in as dependencies. So in the makefile it looks like this:
all: executable1 executable2
all
target is usually the first in the makefile, since if you just write make
in command line, without specifying the target, it will build the first target. And you expect it to be all
.
all
is usually also a .PHONY
target. Learn more here.
Use Control.ControlCollection.Find.
TextBox tbx = this.Controls.Find("textBox1", true).FirstOrDefault() as TextBox;
tbx.Text = "found!";
EDIT for asker:
Control[] tbxs = this.Controls.Find(txtbox_and_message[0,0], true);
if (tbxs != null && tbxs.Length > 0)
{
tbxs[0].Text = "Found!";
}
For a private repository, you will need to obtain a Personal Access Token from https://github.com/settings/tokens.
Then use the following curl command to get the details (substituting in values for [token], [owner] and [name]):
curl -u git:[token] https://api.github.com/repos/[owner]/[name] 2> /dev/null | grep size
As mentioned earlier, size may be in MB or KB.
Note: When you pass setDate, you are calling a method which assumes the datepicker has already been initialized on that object.
$(function() {
$('#date').datepicker();
$('#date').datepicker('setDate', '04/23/2014');
});
http://docs.python.org/library/logging.handlers.html#filehandler
The
FileHandler
class, located in the corelogging
package, sends logging output to a disk file.
Rank() SQL function generates rank of the data within ordered set of values but next rank after previous rank is row_number of that particular row. On the other hand, Dense_Rank() SQL function generates next number instead of generating row_number. Below is the SQL example which will clarify the concept:
Select ROW_NUMBER() over (order by Salary) as RowNum, Salary,
RANK() over (order by Salary) as Rnk,
DENSE_RANK() over (order by Salary) as DenseRnk from (
Select 1000 as Salary union all
Select 1000 as Salary union all
Select 1000 as Salary union all
Select 2000 as Salary union all
Select 3000 as Salary union all
Select 3000 as Salary union all
Select 8000 as Salary union all
Select 9000 as Salary) A
It will generate following output:
----------------------------
RowNum Salary Rnk DenseRnk
----------------------------
1 1000 1 1
2 1000 1 1
3 1000 1 1
4 2000 4 2
5 3000 5 3
6 3000 5 3
7 8000 7 4
8 9000 8 5
Actually, wouldn't we want to do this?
import sys
sys.argv = ['abc.py','arg1', 'arg2']
execfile('abc.py')
it's android:button="@drawable/selector_checkbox"
to make it work
Majorly there are 3 ways of creating Objects-
Simplest one is using object literals.
const myObject = {}
Though this method is the simplest but has a disadvantage i.e if your object has behaviour(functions in it),then in future if you want to make any changes to it you would have to change it in all the objects.
So in that case it is better to use Factory or Constructor Functions.(anyone that you like)
Factory Functions are those functions that return an object.e.g-
function factoryFunc(exampleValue){
return{
exampleProperty: exampleValue
}
}
Constructor Functions are those functions that assign properties to objects using "this" keyword.e.g-
function constructorFunc(exampleValue){
this.exampleProperty= exampleValue;
}
const myObj= new constructorFunc(1);
you can save them into a $_SESSION variable and then when the user calls that page again populate all the inputs with their respective session variables.
I believe you are looking for -maxdepth 1
.
@PeterMajeed's comment in the accepted answer helped me out with a related problem. I am not using the portable library, but have the same build error on a fresh Windows Server 2012 install, where I'm running TeamCity.
Installing the Microsoft .NET Framework 4.5.1 Developer Pack took care of the issue (after having separately installed the MS Build Tools).
As of iOS 12.2 and Swift 5.0, AppDelegate
is not a recognized symbol. UIApplicationDelegate
is. Any answers referring to AppDelegate
are therefore no longer correct. The following answer is correct and avoids force-unwrapping, which some developers consider a code smell:
import UIKit
extension UIViewController {
var appDelegate: UIApplicationDelegate {
guard let appDelegate = UIApplication.shared.delegate else {
fatalError("Could not determine appDelegate.")
}
return appDelegate
}
}
\b\d+,
\b------->word boundary
\d+------>one or digit
,-------->containing commas,
Eg:
sddsgg 70,000 sdsfdsf fdgfdg70,00
sfsfsd 5,44,4343 5.7788,44 555
It will match:
70,
5,
44,
,44
Now, one can use Spark to do the same and its way faster than other approaches (such as Hadoop MR). Here is the code snippet.
def traverseDirectory(filePath:String,recursiveTraverse:Boolean,filePaths:ListBuffer[String]) {
val files = FileSystem.get( sparkContext.hadoopConfiguration ).listStatus(new Path(filePath))
files.foreach { fileStatus => {
if(!fileStatus.isDirectory() && fileStatus.getPath().getName().endsWith(".xml")) {
filePaths+=fileStatus.getPath().toString()
}
else if(fileStatus.isDirectory()) {
traverseDirectory(fileStatus.getPath().toString(), recursiveTraverse, filePaths)
}
}
}
}
String withoutQuotes_line1 = line1.replace("\"", "");
have a look here
I recently found out that :active:focus
does the same thing in css as :active:hover
if you need to override a custom css library, they might use both.
Gives you the list of files with full path:
Sys.glob(file.path(file_dir, "*.dbf")) ## file_dir = file containing directory
Before update SDK components, check in Android SDK Manager ? Tools ? Options and set HTTP proxy and port if it is set in local LAN.
The best and easy solution for solving this issue is pass your data from this function in controller.
$scope.trustSrcurl = function(data)
{
return $sce.trustAsResourceUrl(data);
}
In html page
<iframe class="youtube-player" type="text/html" width="640" height="385" ng-src="{{trustSrcurl(video.src)}}" allowfullscreen frameborder="0"></iframe>
Try using these theme: Theme.AppCompat.Light.NoActionBar
Mi Style XML file looks like these and works just fine:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
getElementById
is defined by DOM Level 1 HTML to return null
in the case no element is matched.
!==null
is the most explicit form of the check, and probably the best, but there is no non-null
falsy value that getElementById
can return - you can only get null
or an always-truthy Element object. So there's no practical difference here between !==null
, !=null
or the looser if (document.getElementById('xx'))
.
By default TortoiseSVN always has a GUI (Graphical User Interface) associated with it. But on the installer (of version 1.7 and later) you can select the "command line client tools" option so you can call svn commands (like svn commit and svn update) from the command line.
Here's a screenshot of the "command line client tools" option in the installer, you need to make sure you select it:
This is long over due, but if i interpret the problem correctly i have found a simple solution, note, this is an explanation in my own terminology:
git stash [save]
will save away current changes and set your current branch to the "clean state"
git stash list
gives something like: stash@{0}: On develop: saved testing-stuff
git apply stash@{0}
will set current branch as before stash [save]
git checkout .
Will set current branch as after stash [save]
The code that is saved in the stash is not lost, it can be found by git apply stash@{0}
again.
Anywhay, this worked for me!
Directory Services/LDAP lookups can be used to serve this purpose. It involves some changes at infrastructure level, but most production environments have such provision
You can try with both the ways with XML and programmatically. But the issue you may face is (below API 21) by doing it with XML will not work . So it's better to set it programmatically in your Activity / Fragment.
XML code:
<android.support.v7.widget.RecyclerView
android:id="@+id/recycleView"
android:layout_width="match_parent"
android:visibility="gone"
android:nestedScrollingEnabled="false"
android:layout_height="wrap_content"
android:layout_below="@+id/linearLayoutBottomText" />
Programmatically:
recycleView = (RecyclerView) findViewById(R.id.recycleView);
recycleView.setNestedScrollingEnabled(false);
Split Method
data = input_string
df = pd.DataFrame([x.split(';') for x in data.split('\n')])
print(df)
That would be the final solution. (inspired by @Hollan_Risley's post)
'use strict';
angular.module('app')
.config(function($provide) {
$provide.decorator('$state', function($delegate, $stateParams) {
$delegate.forceReload = function() {
return $delegate.go($delegate.current, $stateParams, {
reload: true,
inherit: false,
notify: true
});
};
return $delegate;
});
});
Now, whenever you need to reload, simply call:
$state.forceReload();
Try using list.AddRange(VTSWeb.GetDailyWorktimeViolations(VehicleID2));
I usually prefix the 'bin/pip' folder for the specific environment you want to install the package before the 'pip' command. For instance, if you would like to install pymc3 in the environment py34, you should use this command:
~/anaconda/envs/py34/bin/pip install git+https://github.com/pymc-devs/pymc3
You basically just need to find the right path to your environment 'bin/pip' folder and put it before the install command.
pytest captures the stdout from individual tests and displays them only on certain conditions, along with the summary of the tests it prints by default.
Extra summary info can be shown using the '-r' option:
pytest -rP
shows the captured output of passed tests.
pytest -rx
shows the captured output of failed tests (default behaviour).
The formatting of the output is prettier with -r than with -s.
Turns out that to copy a complete directory structure gulp
needs to be provided with a base for your gulp.src()
method.
So gulp.src( [ files ], { "base" : "." })
can be used in the structure above to copy all the directories recursively.
If, like me, you may forget this then try:
gulp.copy=function(src,dest){
return gulp.src(src, {base:"."})
.pipe(gulp.dest(dest));
};
use &
in place of &
change to
<string name="magazine">Newspaper & Magazines</string>
" In computer networking, a network host, Internet host, host, or Internet node is a computer connected to the Internet - or more generically - to any type of data network. A network host can host information resources as well as application software for providing network services. "-Wikipedia
Local host is a special name given to the local machine or that you are working on, ussually its IP Address is 127.0.0.1. However you can define it to be anything.
There are multiple Network services running on each host for example Apache/IIS( Http Web Server),Mail Clients, FTP clients etc. Each service has a specific port associated with it. You can think of it as this.
In every home, there is one mailbox and multiple people. The mailbox is a host. Your own home mailbox is a localhost. Each person in a home has a room. All letters for that person are sent to his room, hence the room number is a port.
Variables and properties
1/ Keeping your headers clean, hiding implementation
Don't include instance variables in your header. Private variables put into class continuation as properties. Public variables declare as public properties in your header.
If it should be only read, declare it as readonly and overwrite it as readwrite in class continutation.
Basically I am not using variables at all, only properties.
2/ Give your properties a non-default variable name, example:
@synthesize property = property_;
Reason 1: You will catch errors caused by forgetting "self." when assigning the property. Reason 2: From my experiments, Leak Analyzer in Instruments has problems to detect leaking property with default name.
3/ Never use retain or release directly on properties (or only in very exceptional situations). In your dealloc just assign them a nil. Retain properties are meant to handle retain/release by themselves. You never know if a setter is not, for example, adding or removing observers. You should use the variable directly only inside its setter and getter.
Views
1/ Put every view definition into a xib, if you can (the exception is usually dynamic content and layer settings). It saves time (it's easier than writing code), it's easy to change and it keeps your code clean.
2/ Don't try to optimize views by decreasing the number of views. Don't create UIImageView in your code instead of xib just because you want to add subviews into it. Use UIImageView as background instead. The view framework can handle hundreds of views without problems.
3/ IBOutlets don't have to be always retained (or strong). Note that most of your IBOutlets are part of your view hierarchy and thus implicitly retained.
4/ Release all IBOutlets in viewDidUnload
5/ Call viewDidUnload from your dealloc method. It is not implicitly called.
Memory
1/ Autorelease objects when you create them. Many bugs are caused by moving your release call into one if-else branch or after a return statement. Release instead of autorelease should be used only in exceptional situations - e.g. when you are waiting for a runloop and you don't want your object to be autoreleased too early.
2/ Even if you are using Authomatic Reference Counting, you have to understand perfectly how retain-release methods work. Using retain-release manually is not more complicated than ARC, in both cases you have to thing about leaks and retain-cycles. Consider using retain-release manually on big projects or complicated object hierarchies.
Comments
1/ Make your code autodocumented. Every variable name and method name should tell what it is doing. If code is written correctly (you need a lot of practice in this), you won't need any code comments (not the same as documentation comments). Algorithms can be complicated but the code should be always simple.
2/ Sometimes, you'll need a comment. Usually to describe a non apparent code behavior or hack. If you feel you have to write a comment, first try to rewrite the code to be simpler and without the need of comments.
Indentation
1/ Don't increase indentation too much. Most of your method code should be indented on the method level. Nested blocks (if, for etc.) decrease readability. If you have three nested blocks, you should try to put the inner blocks into a separate method. Four or more nested blocks should be never used. If most of your method code is inside of an if, negate the if condition, example:
if (self) {
//... long initialization code ...
}
return self;
if (!self) {
return nil;
}
//... long initialization code ...
return self;
Understand C code, mainly C structs
Note that Obj-C is only a light OOP layer over C language. You should understand how basic code structures in C work (enums, structs, arrays, pointers etc). Example:
view.frame = CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, view.frame.size.height + 20);
is the same as:
CGRect frame = view.frame;
frame.size.height += 20;
view.frame = frame;
And many more
Mantain your own coding standards document and update it often. Try to learn from your bugs. Understand why a bug was created and try to avoid it using coding standards.
Our coding standards have currently about 20 pages, a mix of Java Coding Standards, Google Obj-C/C++ Standards and our own addings. Document your code, use standard standard indentation, white spaces and blank lines on the right places etc.
There are various ways to get a Set
as:
List<Integer> sourceList = new ArrayList();
sourceList.add(1);
sourceList.add(2);
sourceList.add(3);
sourceList.add(4);
// Using Core Java
Set<Integer> set1 = new HashSet<>(sourceList); //needs null-check if sourceList can be null.
// Java 8
Set<Integer> set2 = sourceList.stream().collect(Collectors.toSet());
Set<Integer> set3 = sourceList.stream().collect(Collectors.toCollection(HashSet::new));
//Guava
Set<Integer> set4 = Sets.newHashSet(sourceList);
// Apache commons
Set<Integer> set5 = new HashSet<>(4);
CollectionUtils.addAll(set5, sourceList);
When we use Collectors.toSet()
it returns a set and as per the doc:There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned
. If we want to get a HashSet
then we can use the other alternative to get a set (check set3
).
It is a dummy table with one element in it. It is useful because Oracle doesn't allow statements like
SELECT 3+4
You can work around this restriction by writing
SELECT 3+4 FROM DUAL
instead.
ubar jar is also known as fat jar i.e. jar with dependencies.
There are three common methods for constructing an uber jar:
You should either create a FOREIGN KEY
with ON DELETE CASCADE
:
ALTER TABLE usersmessages
ADD CONSTRAINT fk_usermessages_messageid
FOREIGN KEY (messageid)
REFERENCES messages (messageid)
ON DELETE CASCADE
, or do it using two queries in a transaction:
START TRANSACTION;;
DELETE
FROM usermessages
WHERE messageid = 1
DELETE
FROM messages
WHERE messageid = 1;
COMMIT;
Transaction affects only InnoDB
tables, though.
You can use TextWatcher for TextView, is more flexible than ClickLinstener (not best or worse, only more one way).
holder.bt_foo_ex.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// code during!
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// code before!
}
@Override
public void afterTextChanged(Editable s) {
// code after!
}
});
The Ruby File class will give you the ins and outs of ::new
and ::open
but its parent, the IO class, gets into the depth of #read
and #write
.
The first screenshot in your question is not a public widget. The support SearchView (android.support.v7.widget.SearchView
) mimics Android 5.0 Lollipop's SearchView (android.widget.SearchView
). Your second screenshot is used by other material designed apps like Google Play.
The SearchView in your first screenshot is used in Drive, YouTube and other closed source Google Apps. Fortunately, it is also used in the Android 5.0 Dialer. You can try to backport the view, but it uses some 5.0 APIs.
The classes which you will want to look at are:
SearchEditTextLayout, AnimUtils, and DialtactsActivity to understand how to use the View. You will also need resources from ContactsCommon.
Best of luck.
By default, oracle date subtraction returns a result in # of days.
So just multiply by 24 to get # of hours, and again by 60 for # of minutes.
Example:
select
round((second_date - first_date) * (60 * 24),2) as time_in_minutes
from
(
select
to_date('01/01/2008 01:30:00 PM','mm/dd/yyyy hh:mi:ss am') as first_date
,to_date('01/06/2008 01:35:00 PM','mm/dd/yyyy HH:MI:SS AM') as second_date
from
dual
) test_data
I put together this test app to reproduce the issue using the HTTP testing framework from the Apache HttpClient package:
ClassLoader cl = HCTest.class.getClassLoader();
URL url = cl.getResource("test.keystore");
KeyStore keystore = KeyStore.getInstance("jks");
char[] pwd = "nopassword".toCharArray();
keystore.load(url.openStream(), pwd);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keystore);
TrustManager[] tm = tmf.getTrustManagers();
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(keystore, pwd);
KeyManager[] km = kmfactory.getKeyManagers();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(km, tm, null);
LocalTestServer localServer = new LocalTestServer(sslcontext);
localServer.registerDefaultHandlers();
localServer.start();
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
TrustStrategy trustStrategy = new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
for (X509Certificate cert: chain) {
System.err.println(cert);
}
return false;
}
};
SSLSocketFactory sslsf = new SSLSocketFactory("TLS", null, null, keystore, null,
trustStrategy, new AllowAllHostnameVerifier());
Scheme https = new Scheme("https", 443, sslsf);
httpclient.getConnectionManager().getSchemeRegistry().register(https);
InetSocketAddress address = localServer.getServiceAddress();
HttpHost target1 = new HttpHost(address.getHostName(), address.getPort(), "https");
HttpGet httpget1 = new HttpGet("/random/100");
HttpResponse response1 = httpclient.execute(target1, httpget1);
System.err.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
EntityUtils.consume(entity1);
HttpHost target2 = new HttpHost("www.verisign.com", 443, "https");
HttpGet httpget2 = new HttpGet("/");
HttpResponse response2 = httpclient.execute(target2, httpget2);
System.err.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
EntityUtils.consume(entity2);
} finally {
localServer.stop();
}
Even though, Sun's JSSE implementation appears to always read the trust material from the default trust store for some reason, it does not seem to get added to the SSL context and to impact the process of trust verification during the SSL handshake.
Here's the output of the test app. As you can see, the first request succeeds whereas the second fails as the connection to www.verisign.com is rejected as untrusted.
[
[
Version: V1
Subject: CN=Simple Test Http Server, OU=Jakarta HttpClient Project, O=Apache Software Foundation, L=Unknown, ST=Unknown, C=Unknown
Signature Algorithm: SHA1withDSA, OID = 1.2.840.10040.4.3
Key: Sun DSA Public Key
Parameters:DSA
p: fd7f5381 1d751229 52df4a9c 2eece4e7 f611b752 3cef4400 c31e3f80 b6512669
455d4022 51fb593d 8d58fabf c5f5ba30 f6cb9b55 6cd7813b 801d346f f26660b7
6b9950a5 a49f9fe8 047b1022 c24fbba9 d7feb7c6 1bf83b57 e7c6a8a6 150f04fb
83f6d3c5 1ec30235 54135a16 9132f675 f3ae2b61 d72aeff2 2203199d d14801c7
q: 9760508f 15230bcc b292b982 a2eb840b f0581cf5
g: f7e1a085 d69b3dde cbbcab5c 36b857b9 7994afbb fa3aea82 f9574c0b 3d078267
5159578e bad4594f e6710710 8180b449 167123e8 4c281613 b7cf0932 8cc8a6e1
3c167a8b 547c8d28 e0a3ae1e 2bb3a675 916ea37f 0bfa2135 62f1fb62 7a01243b
cca4f1be a8519089 a883dfe1 5ae59f06 928b665e 807b5525 64014c3b fecf492a
y:
f0cc639f 702fd3b1 03fa8fa6 676c3756 ea505448 23cd1147 fdfa2d7f 662f7c59
a02ddc1a fd76673e 25210344 cebbc0e7 6250fff1 a814a59f 30ff5c7e c4f186d8
f0fd346c 29ea270d b054c040 c74a9fc0 55a7020f eacf9f66 a0d86d04 4f4d23de
7f1d681f 45c4c674 5762b71b 808ded17 05b74baf 8de3c4ab 2ef662e3 053af09e
Validity: [From: Sat Dec 11 14:48:35 CET 2004,
To: Tue Dec 09 14:48:35 CET 2014]
Issuer: CN=Simple Test Http Server, OU=Jakarta HttpClient Project, O=Apache Software Foundation, L=Unknown, ST=Unknown, C=Unknown
SerialNumber: [ 41bafab3]
]
Algorithm: [SHA1withDSA]
Signature:
0000: 30 2D 02 15 00 85 BE 6B D0 91 EF 34 72 05 FF 1A 0-.....k...4r...
0010: DB F6 DE BF 92 53 9B 14 27 02 14 37 8D E8 CB AC .....S..'..7....
0020: 4E 6C 93 F2 1F 7D 20 A1 2D 6F 80 5F 58 AE 33 Nl.... .-o._X.3
]
HTTP/1.1 200 OK
[
[
Version: V3
Subject: CN=www.verisign.com, OU=" Production Security Services", O="VeriSign, Inc.", STREET=487 East Middlefield Road, L=Mountain View, ST=California, OID.2.5.4.17=94043, C=US, SERIALNUMBER=2497886, OID.2.5.4.15="V1.0, Clause 5.(b)", OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, OID.1.3.6.1.4.1.311.60.2.1.3=US
Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5
Key: Sun RSA public key, 2048 bits
modulus: 20699622354183393041832954221256409980425015218949582822286196083815087464214375375678538878841956356687753084333860738385445545061253653910861690581771234068858443439641948884498053425403458465980515883570440998475638309355278206558031134532548167239684215445939526428677429035048018486881592078320341210422026566944903775926801017506416629554190534665876551381066249522794321313235316733139718653035476771717662585319643139144923795822646805045585537550376512087897918635167815735560529881178122744633480557211052246428978388768010050150525266771462988042507883304193993556759733514505590387262811565107773578140271
public exponent: 65537
Validity: [From: Wed May 26 02:00:00 CEST 2010,
To: Sat May 26 01:59:59 CEST 2012]
Issuer: CN=VeriSign Class 3 Extended Validation SSL SGC CA, OU=Terms of use at https://www.verisign.com/rpa (c)06, OU=VeriSign Trust Network, O="VeriSign, Inc.", C=US
SerialNumber: [ 53d2bef9 24a7245e 83ca01e4 6caa2477]
Certificate Extensions: 10
[1]: ObjectId: 1.3.6.1.5.5.7.1.1 Criticality=false
AuthorityInfoAccess [
[accessMethod: 1.3.6.1.5.5.7.48.1
accessLocation: URIName: http://EVIntl-ocsp.verisign.com, accessMethod: 1.3.6.1.5.5.7.48.2
accessLocation: URIName: http://EVIntl-aia.verisign.com/EVIntl2006.cer]
]
...
]
Exception in thread "main" javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
at com.sun.net.ssl.internal.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:345)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128)
at org.apache.http.conn.ssl.SSLSocketFactory.createLayeredSocket(SSLSocketFactory.java:446)
...
I solved this by writing the explicit IP address defined in the Listener.ora file as the hostname.
So, instead of "localhost", I wrote "192.168.1.2" as the "Hostname" in the SQL Developer field.
In the below picture I highlighted the input boxes that I've modified:
I have solved this by manually copying EntityFramework.SqlServer.dll
file to the bin folder
of the main application.
Go to conversation tab then come down there is one "close pull request" button is there use that button to close pull request, Take ref of attached image
I did discover .NET has a built in way to cast the JSON string into a Dictionary<String, Object>
via the System.Web.Script.Serialization.JavaScriptSerializer
type in the 3.5 System.Web.Extensions
assembly. Use the method DeserializeObject(String)
.
I stumbled upon this when doing an ajax post (via jquery) of content type 'application/json' to a static .net Page Method and saw that the method (which had a single parameter of type Object
) magically received this Dictionary.
By adding the external jar into your build path just adds the jar to your package, but it will not be available during runtime.
In order for the jar to be available at runtime, you need to:
assets
folder Try the Vjet Javascript IDE from ebay (installation)
I found a solution while tinkering around.
People who directly wanna see the results:
With click: https://jsfiddle.net/dt52jazg/
With Hover: https://jsfiddle.net/7gkufLsh/1/
Below is the code:
HTML
<ul class="list">
<li>Hey</li>
<li>This</li>
<li>is</li>
<li>just</li>
<li>a</li>
<li>test</li>
</ul>
<button class="click-me">
Click me
</button>
CSS
.list li {
min-height: 0;
max-height: 0;
opacity: 0;
-webkit-transition: all .3s ease-in-out;
transition: all .3s ease-in-out;
}
.active li {
min-height: 20px;
opacity: 1;
}
JS
(function() {
$('.click-me').on('click', function() {
$('.list').toggleClass('active');
});
})();
Please let me know whether there is any problem with this solution 'coz I feel there would be no restriction of max-height with this solution.
You could consider using PDFObject by Philip Hutchison.
Alternatively, if you're looking for a non-Javascript solution, you could use markup like this:
<object data="myfile.pdf" type="application/pdf" width="100%" height="100%">
<p>Alternative text - include a link <a href="myfile.pdf">to the PDF!</a></p>
</object>
CSS:
.rate-container > i {
float: right;
}
.rate-container > i:HOVER,
.rate-container > i:HOVER ~ i {
color: gold;
}
HTML:
<div class="rate-container">
<i class="fa fa-star "></i>
<i class="fa fa-star "></i>
<i class="fa fa-star "></i>
<i class="fa fa-star "></i>
<i class="fa fa-star "></i>
</div>
There is still no solution that preserves newlines.
This is not true - you're probably just being misled by the behaviour of echo:
echo $VAR # strips newlines
echo "$VAR" # preserves newlines
I would put A_Rank
et al into a 2D NumPy array, and then use numpy.mean()
and numpy.std()
to compute the means and the standard deviations:
In [17]: import numpy
In [18]: arr = numpy.array([A_rank, B_rank, C_rank])
In [20]: numpy.mean(arr, axis=0)
Out[20]:
array([ 0.7 , 2.2 , 1.8 , 2.13333333, 3.36666667,
5.1 ])
In [21]: numpy.std(arr, axis=0)
Out[21]:
array([ 0.45460606, 1.29614814, 1.37355985, 1.50628314, 1.15566239,
1.2083046 ])
You need to disable quoting.
cit <- read.csv("citations.CSV", quote = "",
row.names = NULL,
stringsAsFactors = FALSE)
str(cit)
## 'data.frame': 112543 obs. of 13 variables:
## $ row.names : chr "10.2307/675394" "10.2307/30007362" "10.2307/4254931" "10.2307/20537934" ...
## $ id : chr "10.2307/675394\t" "10.2307/30007362\t" "10.2307/4254931\t" "10.2307/20537934\t" ...
## $ doi : chr "Archaeological Inference and Inductive Confirmation\t" "Sound and Sense in Cath Almaine\t" "Oak Galls Preserved by the Eruption of Mount Vesuvius in A.D. 79_ and Their Probable Use\t" "The Arts Four Thousand Years Ago\t" ...
## $ title : chr "Bruce D. Smith\t" "Tomás Ó Cathasaigh\t" "Hiram G. Larew\t" "\t" ...
## $ author : chr "American Anthropologist\t" "Ériu\t" "Economic Botany\t" "The Illustrated Magazine of Art\t" ...
## $ journaltitle : chr "79\t" "54\t" "41\t" "1\t" ...
## $ volume : chr "3\t" "\t" "1\t" "3\t" ...
## $ issue : chr "1977-09-01T00:00:00Z\t" "2004-01-01T00:00:00Z\t" "1987-01-01T00:00:00Z\t" "1853-01-01T00:00:00Z\t" ...
## $ pubdate : chr "pp. 598-617\t" "pp. 41-47\t" "pp. 33-40\t" "pp. 171-172\t" ...
## $ pagerange : chr "American Anthropological Association\tWiley\t" "Royal Irish Academy\t" "New York Botanical Garden Press\tSpringer\t" "\t" ...
## $ publisher : chr "fla\t" "fla\t" "fla\t" "fla\t" ...
## $ type : logi NA NA NA NA NA NA ...
## $ reviewed.work: logi NA NA NA NA NA NA ...
I think is because of this kind of lines (check "Thorn" and "Minus")
readLines("citations.CSV")[82]
[1] "10.2307/3642839,10.2307/3642839\t,\"Thorn\" and \"Minus\" in Hieroglyphic Luvian Orthography\t,H. Craig Melchert\t,Anatolian Studies\t,38\t,\t,1988-01-01T00:00:00Z\t,pp. 29-42\t,British Institute at Ankara\t,fla\t,\t,"
How about this? Assuming SQL Server 2008:
SELECT CAST(StartDate as date) AS ForDate,
DATEPART(hour,StartDate) AS OnHour,
COUNT(*) AS Totals
FROM #Events
GROUP BY CAST(StartDate as date),
DATEPART(hour,StartDate)
For pre-2008:
SELECT DATEADD(day,datediff(day,0,StartDate),0) AS ForDate,
DATEPART(hour,StartDate) AS OnHour,
COUNT(*) AS Totals
FROM #Events
GROUP BY CAST(StartDate as date),
DATEPART(hour,StartDate)
This results in :
ForDate | OnHour | Totals
-----------------------------------------
2011-08-09 00:00:00.000 12 3
You need to make the x-factor into an ordered
factor with the ordering you want, e.g
x <- data.frame("variable"=letters[1:5], "value"=rnorm(5)) ## example data
x <- x[with(x,order(-value)), ] ## Sorting
x$variable <- ordered(x$variable, levels=levels(x$variable)[unclass(x$variable)])
ggplot(x, aes(x=variable,y=value)) + geom_bar() +
scale_y_continuous("",formatter="percent") + coord_flip()
I don't know any better way to do the ordering operation. What I have there will only work if there are no duplicate levels for x$variable
.
I've seen it used when the number of conditions can be variable.
You can concatenate conditions using an " AND " string. Then, instead of counting the number of conditions you're passing in, you place a "WHERE 1=1" at the end of your stock SQL statement and throw on the concatenated conditions.
Basically, it saves you having to do a test for conditions and then add a "WHERE" string before them.
It is OK, but at the same time can cause some browsers to become slow.
http://webdesignfan.com/yslow-tutorial-part-2-of-3-reducing-server-calls/
My advice is use <a href="#"></a>
If you're using JQuery remember to also use:
.click(function(event){
event.preventDefault();
// Click code here...
});
LDAP is a standard, AD is Microsoft's (proprietary) implementation (and more). Wikipedia has a good article that delves into the specifics. I found this document with a very detailed evaluation of AD from an LDAP perspective.
For anyone who's looking to do this in 2018, I've got a much better and simpler solution then all the old stuff posted here. You can make a nice looking drag & drop box with just vanilla HTML, JavaScript and CSS.
(Only works in Chrome so far)
Let's start with the HTML.
<div>
<input type="file" name="file" id="file" class="file">
<span id="value"></span>
</div>
Then we'll get to the styling.
.file {
width: 400px;
height: 50px;
background: #171717;
padding: 4px;
border: 1px dashed #333;
position: relative;
cursor: pointer;
}
.file::before {
content: '';
position: absolute;
background: #171717;
font-size: 20px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100%;
height: 100%;
}
.file::after {
content: 'Drag & Drop';
position: absolute;
color: #808080;
font-size: 20px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
After you've done this it already looks fine. But I imagine you'd like to see what file you actaully uploaded, so we're going to do some JavaScript. Remember that pfp-value span? That's where we'll print out the file name.
let file = document.getElementById('file');
file.addEventListener('change', function() {
if(file && file.value) {
let val = file.files[0].name;
document.getElementById('value').innerHTML = "Selected" + val;
}
});
And that's it.
I had challenge with users innocently entering € and some using double quotes to define their content. I tweaked a couple of answers from this page and others to finally define my small little work-around
$products = array($ofDirtyArray);
if($products !=null) {
header("Content-type: application/json");
header('Content-Type: charset=utf-8');
array_walk_recursive($products, function(&$val) {
$val = html_entity_decode(htmlentities($val, ENT_QUOTES, "UTF-8"));
});
echo json_encode($products, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
}
I hope it helps someone/someone improves it.
You have to mark the single letter as optional too:
([A-Z]{1})? +.*? +
or make the whole part optional
(([A-Z]{1}) +.*? +)?
The ALTER TABLE
MySQL command should do the trick. The following command will change the default character set of your table and the character set of all its columns to UTF8.
ALTER TABLE etape_prospection CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;
This command will convert all text-like columns in the table to the new character set. Character sets use different amounts of data per character, so MySQL will convert the type of some columns to ensure there's enough room to fit the same number of characters as the old column type.
I recommend you read the ALTER TABLE MySQL documentation before modifying any live data.
https://developers.google.com/chrome-developer-tools/docs/settings
In Android file system, "system.img" and "userdata.img" are VMS Alpha executable. "system.img" and "userdata.img" have the contents of /system and /data directory on root file system. They are mapped on NAND devices with yaffs2 file system. Now, yaffs2 image file can not be mounted on linux PC. If you can, maybe you got some rom that not packed in yaffs2 file system. You can check those rom file by execute the command:
file <system.img/userdata.img>
If it show "VMS Alpha executable" then you can use "unyaffs" to extract it.
You need to add -L/opt/lib
to tell ld
to look there for shared objects.
8 years later...
On my mac, I had to put a line into the file
~/.pgpass
like:
<IP>:<PORT>:<dbname>:<user>:<password>
Also see:
https://www.postgresql.org/docs/current/libpq-pgpass.html
https://wiki.postgresql.org/wiki/Pgpass
This has been happening to me after restarts since upgrading from OS X El Capitan (10.11) to macOS Sierra (10.12). The ssh-add
solution worked temporarily but would not persist across another restart.
The permanent solution was to edit (or create) ~/.ssh/config
and enable the UseKeychain
option.
Host *
UseKeychain yes
Related: macOS keeps asking my ssh passphrase since I updated to Sierra
The system
function invokes a shell to run the command. While this is convenient, it has well known security implications. If you can fully specify the path to the program or script that you want to execute, and you can afford losing the platform independence that system
provides, then you can use an execve
wrapper as illustrated in the exec_prog
function below to more securely execute your program.
Here's how you specify the arguments in the caller:
const char *my_argv[64] = {"/foo/bar/baz" , "-foo" , "-bar" , NULL};
Then call the exec_prog
function like this:
int rc = exec_prog(my_argv);
Here's the exec_prog
function:
static int exec_prog(const char **argv)
{
pid_t my_pid;
int status, timeout /* unused ifdef WAIT_FOR_COMPLETION */;
if (0 == (my_pid = fork())) {
if (-1 == execve(argv[0], (char **)argv , NULL)) {
perror("child process execve failed [%m]");
return -1;
}
}
#ifdef WAIT_FOR_COMPLETION
timeout = 1000;
while (0 == waitpid(my_pid , &status , WNOHANG)) {
if ( --timeout < 0 ) {
perror("timeout");
return -1;
}
sleep(1);
}
printf("%s WEXITSTATUS %d WIFEXITED %d [status %d]\n",
argv[0], WEXITSTATUS(status), WIFEXITED(status), status);
if (1 != WIFEXITED(status) || 0 != WEXITSTATUS(status)) {
perror("%s failed, halt system");
return -1;
}
#endif
return 0;
}
Remember the includes:
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
See related SE post for situations that require communication with the executed program via file descriptors such as stdin
and stdout
.
As Phil noted, the empty string is treated as a NULL, and NULL is not equal or unequal to anything. If you expect empty strings or NULLs, you'll need to handle those with NVL()
:
DECLARE
str1 varchar2(4000);
str2 varchar2(4000);
BEGIN
str1:='';
str2:='sdd';
-- Provide an alternate null value that does not exist in your data:
IF(NVL(str1,'X') != NVL(str2,'Y')) THEN
dbms_output.put_line('The two strings are not equal');
END IF;
END;
/
Concerning null comparisons:
According to the Oracle 12c documentation on NULLS, null comparisons using IS NULL
or IS NOT NULL
do evaluate to TRUE
or FALSE
. However, all other comparisons evaluate to UNKNOWN
, not FALSE
. The documentation further states:
A condition that evaluates to UNKNOWN acts almost like FALSE. For example, a SELECT statement with a condition in the WHERE clause that evaluates to UNKNOWN returns no rows. However, a condition evaluating to UNKNOWN differs from FALSE in that further operations on an UNKNOWN condition evaluation will evaluate to UNKNOWN. Thus, NOT FALSE evaluates to TRUE, but NOT UNKNOWN evaluates to UNKNOWN.
A reference table is provided by Oracle:
Condition Value of A Evaluation
----------------------------------------
a IS NULL 10 FALSE
a IS NOT NULL 10 TRUE
a IS NULL NULL TRUE
a IS NOT NULL NULL FALSE
a = NULL 10 UNKNOWN
a != NULL 10 UNKNOWN
a = NULL NULL UNKNOWN
a != NULL NULL UNKNOWN
a = 10 NULL UNKNOWN
a != 10 NULL UNKNOWN
I also learned that we should not write PL/SQL assuming empty strings will always evaluate as NULL:
Oracle Database currently treats a character value with a length of zero as null. However, this may not continue to be true in future releases, and Oracle recommends that you do not treat empty strings the same as nulls.
startActivity(new Intent(context, ListofProducts.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK));
For changing the direction of swipe you can use
reverselayout attribute = true.
In Kotlin,
val layoutManager = LinearLayoutManager(this@MainActivity,LinearLayoutManager.HORIZONTAL,true)
recyclerview.layoutManager = layoutManager
In Java,
LinearLayoutManager layoutManager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,true);
recyclerview.setLayoutManager(layoutManager);
Actually it reverses the layout.
If it shows like below
1.2..3....10
it will change to
10.9..8....1
For creating Horizontal RecyclerView there are many ways.
That is by design.
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.
Thanks for all the answers. It seems Prototype already has a function that does this (the page() function). By viewing the source code of the function, I found that it first calculates the element offset position relative to the page (i.e. the document top), then subtracts the scrollTop from that. See the source code of prototype for more details.
Definitely use a service to share data between controllers, here is a working example. $broadcast is not the way to go, you should avoid using the eventing system when there is a more appropriate way. Use a 'service', 'value' or 'constant' (for global constants).
http://plnkr.co/edit/ETWU7d0O8Kaz6qpFP5Hp
Here is an example with an input so you can see the data mirror on the page: http://plnkr.co/edit/DbBp60AgfbmGpgvwtnpU
var testModule = angular.module('testmodule', []);
testModule
.controller('QuestionsStatusController1',
['$rootScope', '$scope', 'myservice',
function ($rootScope, $scope, myservice) {
$scope.myservice = myservice;
}]);
testModule
.controller('QuestionsStatusController2',
['$rootScope', '$scope', 'myservice',
function ($rootScope, $scope, myservice) {
$scope.myservice = myservice;
}]);
testModule
.service('myservice', function() {
this.xxx = "yyy";
});
For deduplicate / dedupe / remove duplication / remove repeated rows / ??? ?? / ??? ?? ????, there are multiple ways.
If duplicated rows are exact the same, use group by
create table TABLE_NAME_DEDUP
as select column1, column2, ... (all column names)
from TABLE_NAME group by column1, column2, -- all column names
Then TABLE_NAME_DEDUP is the deduplicated table.
For example,
create table test (t1 varchar(5), t2 varchar(5));
insert into test values ('12345', 'ssdlh');
insert into test values ('12345', 'ssdlh');
create table test_dedup as
select * from test
group by t1, t2;
-----optional
--remove original table and rename dedup table to previous table
--this is not recommend in dev or qa. DROP table test; Alter table test_dedup rename to test;
You have a rowid, the rowid has duplication but other columns are different Records partial same, this may happened in a transactional system while update a row, and the rows failed to update will have nulls. You want to remove the duplication
create table test_dedup as select column1, column2, ... (all column names) from ( select * , row_number() over (partition by rowid order by column1, column2, ... (all column names except rowid) ) as cn from test ) where cn =1
This is using the feature that when you use order by, the null value will be ordered behind the non-null value.
create table test (rowid_ varchar(5), t1 varchar(5), t2 varchar(5));
insert into test values ('12345', 'ssdlh', null);
insert into test values ('12345', 'ssdlh', 'lhbzj');
create table test_dedup as
select rowid_, t1, t2 from
(select *
, row_number() over (partition by rowid_ order by t1, t2) as cn
from test)
where cn =1
;
-----optional
--remove original table and rename dedup table to previous table
--this is not recommend in dev or qa. DROP table test; Alter table test_dedup rename to test;
for sbt, use below versions
val glassfishEl = "org.glassfish" % "javax.el" % "3.0.1-b09"
val hibernateValidator = "org.hibernate.validator" % "hibernate-validator" % "6.0.17.Final"
val hibernateValidatorCdi = "org.hibernate.validator" % "hibernate-validator-cdi" % "6.0.17.Final"
A quick definition of the "permanent generation":
"The permanent generation is used to hold reflective data of the VM itself such as class objects and method objects. These reflective objects are allocated directly into the permanent generation, and it is sized independently from the other generations." [ref]
In other words, this is where class definitions go (and this explains why you may get the message OutOfMemoryError: PermGen space
if an application loads a large number of classes and/or on redeployment).
Note that PermSize
is additional to the -Xmx
value set by the user on the JVM options. But MaxPermSize
allows for the JVM to be able to grow the PermSize
to the amount specified. Initially when the VM is loaded, the MaxPermSize
will still be the default value (32mb for -client
and 64mb for -server
) but will not actually take up that amount until it is needed. On the other hand, if you were to set BOTH PermSize
and MaxPermSize
to 256mb, you would notice that the overall heap has increased by 256mb additional to the -Xmx
setting.
You need to use the overflow option, but with the following parameters:
.nav {
max-height:300px;
overflow-y:auto;
}
Use overflow-y:auto; so the scrollbar only appears when the content exceeds the maximum height.
If you use overflow-y:scroll, the scrollbar will always be visible - on all .nav - regardless if the content exceeds the maximum heigh or not.
Presumably you want something that adapts itself to the content rather then the the opposite.
Hope it may helpful
Of course @Stephan202 has given a really nice answer. I am providing an alternative.
def compressx(min_index = 3, max_index = 6, x = ['a', 'b', 'c', 'd', 'e', 'f', 'g']):
x = x[:min_index] + [''.join(x[min_index:max_index])] + x[max_index:]
return x
compressx()
>>>['a', 'b', 'c', 'def', 'g']
You can also do the following.
x = x[:min_index] + [''.join(x[min_index:max_index])] + x[max_index:]
print(x)
>>>['a', 'b', 'c', 'def', 'g']
I think I have a simpler solution -- set the initial date to the epoch and add UTC units. Say you have a UTC epoch var stored in seconds. How about 1234567890
. To convert that to a proper date in the local time zone:
var utcSeconds = 1234567890;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(utcSeconds);
d
is now a date (in my time zone) set to Fri Feb 13 2009 18:31:30 GMT-0500 (EST)
OK, here's the solution I settled on.
First you create a seed value using the "newseed()" function. Then you pass the seed value to the "srandom()" function. Lastly, the "srandom()" function returns a pseudo random value between 0 and 1.
The crucial bit is that the seed value is stored inside an array. If it were simply an integer or float, the value would get overwritten each time the function were called, since the values of integers, floats, strings and so forth are stored directly in the stack versus just the pointers as in the case of arrays and other objects. Thus, it's possible for the value of the seed to remain persistent.
Finally, it is possible to define the "srandom()" function such that it is a method of the "Math" object, but I'll leave that up to you to figure out. ;)
Good luck!
JavaScript:
// Global variables used for the seeded random functions, below.
var seedobja = 1103515245
var seedobjc = 12345
var seedobjm = 4294967295 //0x100000000
// Creates a new seed for seeded functions such as srandom().
function newseed(seednum)
{
return [seednum]
}
// Works like Math.random(), except you provide your own seed as the first argument.
function srandom(seedobj)
{
seedobj[0] = (seedobj[0] * seedobja + seedobjc) % seedobjm
return seedobj[0] / (seedobjm - 1)
}
// Store some test values in variables.
var my_seed_value = newseed(230951)
var my_random_value_1 = srandom(my_seed_value)
var my_random_value_2 = srandom(my_seed_value)
var my_random_value_3 = srandom(my_seed_value)
// Print the values to console. Replace "WScript.Echo()" with "alert()" if inside a Web browser.
WScript.Echo(my_random_value_1)
WScript.Echo(my_random_value_2)
WScript.Echo(my_random_value_3)
Lua 4 (my personal target environment):
-- Global variables used for the seeded random functions, below.
seedobja = 1103515.245
seedobjc = 12345
seedobjm = 4294967.295 --0x100000000
-- Creates a new seed for seeded functions such as srandom().
function newseed(seednum)
return {seednum}
end
-- Works like random(), except you provide your own seed as the first argument.
function srandom(seedobj)
seedobj[1] = mod(seedobj[1] * seedobja + seedobjc, seedobjm)
return seedobj[1] / (seedobjm - 1)
end
-- Store some test values in variables.
my_seed_value = newseed(230951)
my_random_value_1 = srandom(my_seed_value)
my_random_value_2 = srandom(my_seed_value)
my_random_value_3 = srandom(my_seed_value)
-- Print the values to console.
print(my_random_value_1)
print(my_random_value_2)
print(my_random_value_3)
In the UK it's also best practice to include a real physical address for your company and its registered number.
That way it's all open and honest and they're less likely to manually mark it as spam.
A common case for simply setting -fpermissive and not sweating it exists: the thoroughly-tested and working third-party library that won't compile on newer compiler versions without -fpermissive. These libraries exist, and are very likely not the application developer's problem to solve, nor in the developer's schedule budget to do it.
Set -fpermissive and move on in that case.
App Size for iOS (& tvOS) only
Your app’s total uncompressed size must be less than 4GB. Each Mach-O executable file (for example,
app_name.app/app_name
) must not exceed these limits:
- For apps whose
MinimumOSVersion
is less than 7.0: maximum of 80 MB for the total of all__TEXT
sections in the binary.- For apps whose
MinimumOSVersion
is 7.x through 8.x: maximum of 60 MB per slice for the__TEXT
section of each architecture slice in the binary.- For apps whose
MinimumOSVersion
is 9.0 or greater: maximum of 500 MB for the total of all__TEXT
sections in the binary.However, consider download times when determining your app’s size. Minimize the file’s size as much as possible, keeping in mind that there is a 100 MB limit for over-the-air downloads.
This information can be found at iTunes Connect Developer Guide: Submitting the App to App Review.
(iOS only) App Size
iOS App binary files can be as large as 4 GB, but each executable file (app_name.app/app_name) must not exceed 60 MB. Additionally, the total uncompressed size of the app must be less than 4 billion bytes. However, consider download times when determining your app’s size. Minimize the file’s size as much as possible, keeping in mind that there is a 100 MB limit for over-the-air downloads.
This information can be found on page 77 of the iTunes Connect Developer Guide.
(iOS only) App Size
iOS App binary files can be as large as 2 GB, but the executable file (app_name.app/app_name) cannot exceed 60MB. However, consider download times when determining your app’s size. Minimize the file’s size as much as possible, keeping in mind that there is a 100 MB limit for over-the-air downloads.
This information can be found on page 58 of the iTunes Connect Developer Guide.
The above information is still the same with the exception of the Executable File size which is now limited to 60MB's. These changes can be found on page 237 of the guide.
The above information is still the same with the exception of the Executable File size which is now limited to 60MB's. These changes can be found on page 208 of the guide.
The above information is still the same with the exception of Over The Air downloads which is now 50MB's. These changes can be found on page 206 of the guide. Thanks to comment from Ozair Kafray.
The above information is still the same with the exception of Over The Air downloads which is now 50MB's. These changes can be found on page 214 of the guide. Thanks to comment from marsbear. In addition, the document has moved here:
The above information is still the same with the exception of Over The Air downloads which is now 50MB's. These changes can be found on page 209 of the guide.
The above information is still the same with the exception of Over The Air downloads which is now 50MB's. These changes can be found on page 209 of the guide.
The above information is still the same, however, it can be found on page 172 of the guide.
The above information is still the same, however, it can be found on page 180 of the guide. Thanks to comment from Luke for the update.
The above information is still the same, however, it can be found on page 179 of the guide. Thanks to comment from Saxon Druce for the update.
Using DatabaseUtils.queryNumEntries()
:
public long getProfilesCount() {
SQLiteDatabase db = this.getReadableDatabase();
long count = DatabaseUtils.queryNumEntries(db, TABLE_NAME);
db.close();
return count;
}
or (more inefficiently)
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
return count;
}
In Activity:
int profile_counts = db.getProfilesCount();
db.close();
use the HorizontalContentAlignment property.
Sample
<Label HorizontalContentAlignment="Center"/>
For a fairly easy copy / paste for .NET applications, I wrote this to enable CORS from within a global.asax
file. This code follows the advice given in the currently accepted answer, reflecting whatever origin back is given in the request into the response. This effectively achieves '*' without using it.
The reason for this is that it enables multiple other CORS features, including the ability to send an AJAX XMLHttpRequest with the 'withCredentials' attribute set to 'true'.
void Application_BeginRequest(object sender, EventArgs e)
{
if (Request.HttpMethod == "OPTIONS")
{
Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
Response.AddHeader("Access-Control-Max-Age", "1728000");
Response.End();
}
else
{
Response.AddHeader("Access-Control-Allow-Credentials", "true");
if (Request.Headers["Origin"] != null)
Response.AddHeader("Access-Control-Allow-Origin" , Request.Headers["Origin"]);
else
Response.AddHeader("Access-Control-Allow-Origin" , "*");
}
}
Update: There are now better, cleaner solutions to this problem. Please consider the other answers first.
I eventually found an answer to this by ronen on his blog. The problem I was having is due to the method Mockito.mock(Class c)
declaring a return type of Object
. Consequently Spring is unable to infer the bean type from the factory method return type.
Ronen's solution is to create a FactoryBean
implementation that returns mocks. The FactoryBean
interface allows Spring to query the type of objects created by the factory bean.
My mocked bean definition now looks like:
<bean id="mockDaoFactory" name="dao" class="com.package.test.MocksFactory">
<property name="type" value="com.package.Dao" />
</bean>
i was also getting the same error repeatedly but could not solve it as i am complete new to android development. But then it came to my mind that the error is appearing because its not able to install the apk in the device as the error says. So i make sure that my Oneplus3 is in debugging mode and also allowing file transfer when connected via USB. And this solved the problem.
Also previously it was not doing the instant run but now it does.
So check whether your android device is allowed to transfer files while connected via USB. This might help.
Is there any reason I don't see this in C++? Is it bad practice?
No. It is not a bad practice, but the following approach renders your code certain flexibility.
Usually, pre-C++11 the code for iterating over container elements uses iterators, something like:
std::vector<int>::iterator it = vector.begin();
This is because it makes the code more flexible.
All standard library containers support and provide iterators. If at a later point of development you need to switch to another container, then this code does not need to be changed.
Note: Writing code which works with every possible standard library container is not as easy as it might seem to be.
input
fields can be styled as you wish. So instead of zoom, you could have
input[type="checkbox"]{
width: 30px; /*Desired width*/
height: 30px; /*Desired height*/
}
EDIT:
You would have to add extra rules like this:
input[type="checkbox"]{
width: 30px; /*Desired width*/
height: 30px; /*Desired height*/
cursor: pointer;
-webkit-appearance: none;
appearance: none;
}
Check this fiddle http://jsfiddle.net/p36tqqyq/1/
The constant values (uses in fixtures or assertions) should be initialized in their declarations and final
(as never change)
the object under test should be initialized in the setup method because we may set things on. Of course we may not set something now but we could set it later. Instantiating in the init method would ease the changes.
dependencies of the object under test if these are mocked, should not even be instantiated by yourself : today the mock frameworks can instantiate it by reflection.
A test without dependency to mock could look like :
public class SomeTest {
Some some; //instance under test
static final String GENERIC_ID = "123";
static final String PREFIX_URL_WS = "http://foo.com/ws";
@Before
public void beforeEach() {
some = new Some(new Foo(), new Bar());
}
@Test
public void populateList()
...
}
}
A test with dependencies to isolate could look like :
@RunWith(org.mockito.runners.MockitoJUnitRunner.class)
public class SomeTest {
Some some; //instance under test
static final String GENERIC_ID = "123";
static final String PREFIX_URL_WS = "http://foo.com/ws";
@Mock
Foo fooMock;
@Mock
Bar barMock;
@Before
public void beforeEach() {
some = new Some(fooMock, barMock);
}
@Test
public void populateList()
...
}
}
Windows 10 includes tar.exe
:
# example 1
tar.exe -a -c -f out.zip in.txt
# example 2
tar.exe -x -f out.zip
https://techcommunity.microsoft.com/t5/containers/-/ba-p/382409
If you have older Windows, you can still download it:
https://github.com/libarchive/libarchive/releases
# example 1
Compress-Archive in.txt out.zip
# example 2
Expand-Archive out.zip
https://docs.microsoft.com/powershell/module/microsoft.powershell.archive
For both tools, you can use a file or directory for the input.
I think you don't have to use sub query in this scenario.You can directly left outer join the DEPRMNT table .
While using Left Outer Join ,don't use columns in the RHS table of the join in the where condition, you ll get wrong output
var timeout_check_change_class;
function check_change_class( selector )
{
$(selector).each(function(index, el) {
var data_old_class = $(el).attr('data-old-class');
if (typeof data_old_class !== typeof undefined && data_old_class !== false)
{
if( data_old_class != $(el).attr('class') )
{
$(el).trigger('change_class');
}
}
$(el).attr('data-old-class', $(el).attr('class') );
});
clearTimeout( timeout_check_change_class );
timeout_check_change_class = setTimeout(check_change_class, 10, selector);
}
check_change_class( '.breakpoint' );
$('.breakpoint').on('change_class', function(event) {
console.log('haschange');
});
from tkinter import *
window = tk()
window.geometry("300x300")
def close_window ():
window.destroy()
button = Button ( text = "Good-bye", command = close_window)
button.pack()
window.mainloop()
I found that adjusting the scale ratio helped slightly.
Using scale(1.048)
over (1.05)
seemed to generate a better approximation to a whole-pixel font size, reducing the sub-pixel blurring.
I also used translateZ(0)
which seems to adjust Chrome's final rounding step in the transform animation. This is a plus for my onhover usage because it increases speed and reduces visual noise. For an onclick function however, I wouldn't use it because, the transformed font doesn't appear to be as crispy.
There have been a lot of good answers around the use of crontab, but no mention of a simpler method, such as using cron
.
Using cron
would take advantage of system files and directories located at /etc/crontab
, /etc/cron.daily,weekly,hourly
or /etc/cron.d/
:
cat > /etc/cron.d/<job> << EOF
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root HOME=/
01 * * * * <user> <command>
EOF
In this above example, we created a file in /etc/cron.d/
, provided the environment variables for the command to execute successfully, and provided the user
for the command, and the command
itself. This file should not be executable and the name should only contain alpha-numeric and hyphens (more details below).
To give a thorough answer though, let's look at the differences between crontab
vs cron/crond
:
crontab -- maintain tables for driving cron for individual users
For those who want to run the job in the context of their user on the system, using crontab
may make perfect sense.
cron -- daemon to execute scheduled commands
For those who use configuration management or want to manage jobs for other users, in which case we should use cron
.
A quick excerpt from the manpages gives you a few examples of what to and not to do:
/etc/crontab and the files in /etc/cron.d must be owned by root, and must not be group- or other-writable. In contrast to the spool area, the files under /etc/cron.d or the files under /etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly and /etc/cron.monthly may also be symlinks, provided that both the symlink and the file it points to are owned by root. The files under /etc/cron.d do not need to be executable, while the files under /etc/cron.hourly, /etc/cron.daily, /etc/cron.weekly and /etc/cron.monthly do, as they are run by run-parts (see run-parts(8) for more information).
Source: http://manpages.ubuntu.com/manpages/trusty/man8/cron.8.html
Managing crons in this manner is easier and more scalable from a system perspective, but will not always be the best solution.
The servlet API lacks this feature because it was created in a time when many believed that the query string and the message body was just two different ways of sending parameters, not realizing that the purposes of the parameters are fundamentally different.
The query string parameters ?foo=bar are a part of the URL because they are involved in identifying a resource (which could be a collection of many resources), like "all persons aged 42":
GET /persons?age=42
The message body parameters in POST or PUT are there to express a modification to the target resource(s). Fx setting a value to the attribute "hair":
PUT /persons?age=42
hair=grey
So it is definitely RESTful to use both query parameters and body parameters at the same time, separated so that you can use them for different purposes. The feature is definitely missing in the Java servlet API.
since you are using jquery
library, i would advise you utilize the reset()
method.
Firstly, add an id attribute to the form tag
<form id='myForm'>
Then on completion, clear your input fields as:
$('#myForm')[0].reset();
First, angular-cli
is deprecated and has been replaced with @angular/cli
. So if you uninstall your existing angular-cli with npm uninstall angular-cli
, then reinstall the package with the new name @angular/cli you might get some conflicts. My story on Windows 7 is:
I had installed angular-cli and reinstalled using npm install -g @angular/cli
, but after doing some config changes to command-line tools, I started getting the ng command not found issue. I spent several hours trying to fix this but none of the above issues alone worked. I was able to fix it using these steps:
Install Rapid Environment Editor and remove any PATH entries for node, npm, angular-cli or @angular/cli. Node.js will be in your System path, npm and angular entries are in the User path.
Uninstall node.js and reinstall the current version (for me 6.11.1). Run Rapid Environment Editor again and make sure node.js and npm are in your System or User path. Uninstall any existing ng versions with:
npm uninstall -g angular-cli
npm uninstall -g @angular/cli
npm cache clean
Delete the C:\Users\%YOU%\AppData\Roaming\npm\node_modules\@angular folder.
Reboot, then, finally, run:
npm install -g @angular/cli
Then hold your breath and run:
ng -v
If you're lucky, you'll get some love. Hold your breath henceforward every time you run the ng command, because 'command not found' has magically reappeared for me several times after ng was running fine and I thought the problem was solved.
Please check this example here: Accessing Structure Members
There is explained that the right way to do it is like this:
strcpy(s1.name , "Egzona");
printf( "Name : %s\n", s1.name);
When using angularjs with express
On my example I was using angularjs with express doing the routing so using $routeParams would mess up with my routing. I used the following code to get what I was expecting:
const getParameters = (temp, path) => {
const parameters = {};
const tempParts = temp.split('/');
const pathParts = path.split('/');
for (let i = 0; i < tempParts.length; i++) {
const element = tempParts[i];
if(element.startsWith(':')) {
const key = element.substring(1,element.length);
parameters[key] = pathParts[i];
}
}
return parameters;
};
This receives a URL template and the path of the given location. The I just call it with:
const params = getParameters('/:table/:id/visit/:place_id/on/:interval/something', $location.path());
Putting it all together my controller is:
.controller('TestController', ['$scope', function($scope, $window) {
const getParameters = (temp, path) => {
const parameters = {};
const tempParts = temp.split('/');
const pathParts = path.split('/');
for (let i = 0; i < tempParts.length; i++) {
const element = tempParts[i];
if(element.startsWith(':')) {
const key = element.substring(1,element.length);
parameters[key] = pathParts[i];
}
}
return parameters;
};
const params = getParameters('/:table/:id/visit/:place_id/on/:interval/something', $window.location.pathname);
}]);
The result will be:
{ table: "users", id: "1", place_id: "43", interval: "week" }
Hope this helps someone out there!
Consider what happens if you go back and forth between B and C...voila
(relevant only if the graph is not directed)
Edited: I believe the problem has to do with the fact that the path with AC* can only be better than AB with the existence of negative weight edges, so it doesn't matter where you go after AC, with the assumption of non-negative weight edges it is impossible to find a path better than AB once you chose to reach B after going AC.
I created an online tool that is going to solve your problem! You can write your string and apply styles graphically and the tool gives you objective-c and swift code to generate that string.
Also is open source so feel free to extend it and send PRs.
I think one of the major reasons is locality. Your input file size is 165G, the file's related blocks certainly distributed over multiple DataNodes, more executors can avoid network copy.
Try to set executor num equal blocks count, i think can be faster.
Please take into account that sorting the array will only be faster that looping up to certain size of the array. If your array is small (and it will be like that any time) then your solution is perfectly fine. But if it might get too large you should use a conditional to use the sort approach when the array is small, and the normal iteration when it is too large
ActiveModel::Dirty
didn't work for me because the @model.update_attributes()
hid the changes. So this is how I detected changes it in an update
method in a controller:
def update
@model = Model.find(params[:id])
detect_changes
if @model.update_attributes(params[:model])
do_stuff if attr_changed?
end
end
private
def detect_changes
@changed = []
@changed << :attr if @model.attr != params[:model][:attr]
end
def attr_changed?
@changed.include :attr
end
If you're trying to detect a lot of attribute changes it could get messy though. Probably shouldn't do this in a controller, but meh.
I found this problem too. Because centos service depend on multi-user.target for none desktop Cenots 7.2. so I delete multi-user.target from my .service file. It had missed.
Python 2.6 and 3.x supports proper relative imports, where you can avoid doing anything hacky. With this method, you know you are getting a relative import rather than an absolute import. The '..' means, go to the directory above me:
from ..Common import Common
As a caveat, this will only work if you run your python as a module, from outside of the package. For example:
python -m Proj
This method is still commonly used in some situations, where you aren't actually ever 'installing' your package. For example, it's popular with Django users.
You can add Common/ to your sys.path (the list of paths python looks at to import things):
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'Common'))
import Common
os.path.dirname(__file__)
just gives you the directory that your current python file is in, and then we navigate to 'Common/' the directory and import 'Common' the module.
You can read it, but you can't set it. value="123"
will be ignored, so it won't have a value until you click on it and pick a file.
Even then, the value will likely be mangled with something like c:\fakepath\
to keep the details of the user's filesystem private.
By default mesh
will color surface values based on the (default) jet
colormap (i.e. hot is higher). You can additionally use surf
for filled surface patches and set the 'EdgeColor'
property to 'None'
(so the patch edges are non-visible).
[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
% surface in 3D
figure;
surf(Z,'EdgeColor','None');
2D map: You can get a 2D map by switching the view
property of the figure
% 2D map using view
figure;
surf(Z,'EdgeColor','None');
view(2);
... or treating the values in Z
as a matrix, viewing it as a scaled image using imagesc
and selecting an appropriate colormap.
% using imagesc to view just Z
figure;
imagesc(Z);
colormap jet;
The color pallet of the map is controlled by colormap(map)
, where map
can be custom or any of the built-in colormaps provided by MATLAB:
Update/Refining the map: Several design options on the map (resolution, smoothing, axis etc.) can be controlled by the regular MATLAB options. As @Floris points out, here is a smoothed, equal-axis, no-axis labels maps, adapted to this example:
figure;
surf(X, Y, Z,'EdgeColor', 'None', 'facecolor', 'interp');
view(2);
axis equal;
axis off;
"toString()" is Very useful method which returns a string representation of an object. The "toString()" method returns a string reperentation an object.It is recommended that all subclasses override this method.
Declaration: java.lang.Object.toString()
Since, you have not mentioned which object you want to convert, so I am just using any object in sample code.
Integer integerObject = 5;
String convertedStringObject = integerObject .toString();
System.out.println(convertedStringObject );
You can find the complete code here. You can test the code here.
Because of an annoying design choice in Ruby before 1.9 — some_string[0]
returns the character code of the first character — the most portable way to write this is some_string[0,1]
, which tells it to get a substring at index 0 that's 1 character long.
Now, these methods I tried myself, and I got exactly what was advertised: All the modules.
Alas, really you don't care much about the stdlib, you know what you get with a python install.
Really, I want the stuff that I installed.
What actually, surprisingly, worked just fine was:
pip freeze
Which returned:
Fabric==0.9.3
apache-libcloud==0.4.0
bzr==2.3b4
distribute==0.6.14
docutils==0.7
greenlet==0.3.1
ipython==0.10.1
iterpipes==0.4
libxml2-python==2.6.21
I say "surprisingly" because the package install tool is the exact place one would expect to find this functionality, although not under the name 'freeze' but python packaging is so weird, that I am flabbergasted that this tool makes sense. Pip 0.8.2, Python 2.7.
This error message means that Windows isn't able to find "cygwin1.dll". The Programs that the Cygwin gcc create depend on this DLL. The file is part of cygwin , so most likely it's located in C:\cygwin\bin. To fix the problem all you have to do is add C:\cygwin\bin (or the location where cygwin1.dll can be found) to your system path. Alternatively you can copy cygwin1.dll into your Windows directory.
There is a nice tool called DependencyWalker that you can download from http://www.dependencywalker.com . You can use it to check dependencies of executables, so if you inspect your generated program it tells you which dependencies are missing and which are resolved.
How about just using
void feedInputToOutput(InputStream in, OutputStream out) {
IOUtils.copy(in, out);
}
and be done with it?
from jakarta apache commons i/o library which is used by a huge amount of projects already so you probably already have the jar in your classpath already.
This is because Cascade Deletes are enabled by default. The problem is that when you call a delete on the entity, it will delete each of the f-key referenced entities as well. You should not make 'required' values nullable to fix this problem. A better option would be to remove EF Code First's Cascade delete convention:
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
It's probably safer to explicitly indicate when to do a cascade delete for each of the children when mapping/config. the entity.
new and delete are operators in c++; which can be overloaded too. malloc and free are function in c;
malloc returns null ptr when fails while new throws exception.
address returned by malloc need to by type casted again as it returns the (void*)malloc(size) New return the typed pointer.
In addition to the answer given by @Marcus you can now also delete a remote branch via:
git push [remote-name] --delete [branch-name]
An iterative function to free your list:
void freeList(struct node* head)
{
struct node* tmp;
while (head != NULL)
{
tmp = head;
head = head->next;
free(tmp);
}
}
What the function is doing is the follow:
check if head
is NULL, if yes the list is empty and we just return
Save the head
in a tmp
variable, and make head
point to the next node on your list (this is done in head = head->next
free(tmp)
variable, and head
just points to the rest of the list, go back to step 1 Real VNC Viewer (5.0.3) - Free :
Options->Expert->UseAllMonitors = True
I had the same question except that I wanted to combine the criteria into an OR condition. The format given by Wouter Overmeire combines the criteria into an AND condition such that both must be satisfied:
In [96]: df
Out[96]:
A B C D
a 1 4 9 1
b 4 5 0 2
c 5 5 1 0
d 1 3 9 6
In [99]: df[(df.A == 1) & (df.D == 6)]
Out[99]:
A B C D
d 1 3 9 6
But I found that, if you wrap each condition in (... == True)
and join the criteria with a pipe, the criteria are combined in an OR condition, satisfied whenever either of them is true:
df[((df.A==1) == True) | ((df.D==6) == True)]
Just use parenthesis for SELECT clause into INSERT. For example like this :
INSERT INTO Table1 (col1, col2, your_desired_value_from_select_clause, col3)
VALUES (
'col1_value',
'col2_value',
(SELECT col_Table2 FROM Table2 WHERE IdTable2 = 'your_satisfied_value_for_col_Table2_selected'),
'col3_value'
);
I've got this problem for long that I cant get my android emulator or device connect to the debugger while both the console and the emulator were displaying waiting for connecting to the debugger.
And configuration for debug inside eclipse also confused me so much before, but today, i got this problem solved, by the following steps:
When you want to debug a android project, for instance, mypro. you would right click on it in the "Package Explorer". Then choose "Debug as"-->"Android Application"
.
Then the emulator might stop at the "Waiting for connecting to debugger"(or something else similar to this).
Then you need to connect to the debugger yourself by click "DDMS" to open the DDMS perspective, and click "Devices" tab.
Then you can see a list of processes that are running on your emulator or device.
Double click on the one which you are debugging, then change to the Debug perspective, you can see the debugger is connected and you could debug your program. That's how I solved this problem.
By the way, my OS is Win7 32-bit. Eclipse's version is Helios Service Release 2. Android SDK is rev. 16 and platform-tools' 10.
Update.
I found that it is the problem of my TCP/IP configuration. The debugger can't be connected when i assign a static IP address(for access to internet).
So every time when the debugger is unable to connect, I always do the following steps:
1.close current eclipse window.
2.change the config of IP address to dynamic, it means getting a IP address by DHCP.
3.open up the eclipse again.
then the debugger is able to be connected. I thought it might be a issue of the internal mechanism of java debugger which is using socket connection.
You can either
1) Declare printMenu()
, getUserchoice()
and input as static
OR
2) If you want to design it better, move the logic from your main
into a separate instance method. And then from the main
create a new instance of your class and call your instance method(s)
String text = "In early March, the city of Topeka, Kansas," + "<br>" +
"temporarily changed its name to Google..." + "<br>" + "<br>" +
"...in an attempt to capture a spot" + "<br>" +
"in Google's new broadband/fiber-optics project." + "<br>" + "<br>" +"<br>" +
"source: http://en.wikipedia.org/wiki/Google_server#Oil_Tanker_Data_Center";
JLabel label = new JLabel("<html><div style='text-align: center;'>" + text + "</div></html>");
I have implemented the Samsung File Selector Dialog, it provides the ability to open, save file, file extension filter, and create new directory in the same dialog I think it worth trying Here is the Link you have to log in to Samsung developer site to view the solution
I used this way:-
var fs = require('fs');
var parse = require('csv-parse');
var csvData=[];
fs.createReadStream(req.file.path)
.pipe(parse({delimiter: ':'}))
.on('data', function(csvrow) {
console.log(csvrow);
//do something with csvrow
csvData.push(csvrow);
})
.on('end',function() {
//do something with csvData
console.log(csvData);
});
Either declare set1 and set2 as floats instead of integers or cast them to floats as part of the calculation:
SET @weight= CAST(@set1 AS float) / CAST(@set2 AS float);
I use sql-workbench for working with H2 and any other DBMS I have to deal with and it makes me smile :-)
Try this: B = A ( : )
, or try the reshape
function.
http://www.mathworks.com/access/helpdesk/help/techdoc/ref/reshape.html
In case you do not want to use Asset Catalog, you can add an iOS 7 icon for an old app by creating a 120x120 .png image. Name it Icon-120.png
and drag in to the project.
Under TARGET > Your App > Info > Icon files, add one more entry in the Target Properties:
I tested on Xcode 5 and an app was submitted without the missing retina icon warning.
I've seen this issue before with 2.7.14. Fixed it by :
In cmd, run "where python" and then "where pip". Which will show for example:
? where python
C:\Python\python.exe
? where pip
C:\Python\Scripts\pip.exe
Run pip, then it should show different pip run command options.
I know this post is old. But after gathering all code from above I made a nice method (solution) to handle ajax running and regular pages. The code is made for C# only (since Selenium is definitely a best fit for C# Visual Studio after a year of messing around).
The method is used as an extension method, which means to put it simple; that you can add more functionality (methods) in this case, to the object IWebDriver. Important is that you have to define: 'this' in the parameters to make use of it.
The timeout variable is the amount of seconds for the webdriver to wait, if the page is not responding. Using 'Selenium' and 'Selenium.Support.UI' namespaces it is possible to execute a piece of javascript that returns a boolean, whether the document is ready (complete) and if jQuery is loaded. If the page does not have jQuery then the method will throw an exception. This exception is 'catched' by error handling. In the catch state the document will only be checked for it's ready state, without checking for jQuery.
public static void WaitUntilDocumentIsReady(this IWebDriver driver, int timeoutInSeconds) {
var javaScriptExecutor = driver as IJavaScriptExecutor;
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
try {
Func<IWebDriver, bool> readyCondition = webDriver => (bool)javaScriptExecutor.ExecuteScript("return (document.readyState == 'complete' && jQuery.active == 0)");
wait.Until(readyCondition);
} catch(InvalidOperationException) {
wait.Until(wd => javaScriptExecutor.ExecuteScript("return document.readyState").ToString() == "complete");
}
}
I would like to compliment Ram Narasimhans answer with some tips I found on an Excel blog
Non-uniformly distributed data can be plotted in excel in
Just like Ram Narasimhan suggested, to have the points centered you will want the mid point but you don't need to move to a numeric format, you can stay in the time format.
1- Add the center point to your data series
+---------------+-------+------+
| Time | Time | Freq |
+---------------+-------+------+
| 08:00 - 09:00 | 08:30 | 12 |
| 09:00 - 10:00 | 09:30 | 13 |
| 10:00 - 11:00 | 10:30 | 10 |
| 13:00 - 14:00 | 13:30 | 5 |
| 14:00 - 15:00 | 14:30 | 14 |
+---------------+-------+------+
2- Create a Scatter Plot
3- Excel allows you to specify time values for the axis options. Time values are a parts per 1 of a 24-hour day. Therefore if we want to 08:00 to 15:00, then we Set the Axis options to:
Alternative Display:
To be able to represent these points as bars instead of just point we need to draw disjoint lines. Here is a way to go about getting this type of chart.
1- You're going to need to add several rows where we draw the line and disjoint the data
+-------+------+
| Time | Freq |
+-------+------+
| 08:30 | 0 |
| 08:30 | 12 |
| | |
| 09:30 | 0 |
| 09:30 | 13 |
| | |
| 10:30 | 0 |
| 10:30 | 10 |
| | |
| 13:30 | 0 |
| 13:30 | 5 |
| | |
| 14:30 | 0 |
| 14:30 | 14 |
+-------+------+
2- Plot an X Y (Scatter) Chart with Lines.
3- Now you can tweak the data series to have a fatter line, no markers, etc.. to get a bar/column type chart with non-uniformly distributed data.
In addition to all of the great answers, there is a concept called lazy loading:
Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed.
Using it properly, you can reduce the loading time of your application. And Kotlin way of it's implementation is by lazy()
which loads the needed value to your variable whenever it's needed.
But lateinit is used when you are sure a variable won't be null or empty and will be initialized before you use it -e.g. in onResume()
method for android- and so you don't want to declare it as a nullable type.
I found that although the shims from answers above worked, they did not match the behaviour of desktop browsers' implementations of btoa()
and atob()
:
const btoa = function(str){ return Buffer.from(str).toString('base64'); }
// returns "4pyT", yet in desktop Chrome would throw an error.
btoa('?');
// returns "fsO1w6bCvA==", yet in desktop Chrome would return "fvXmvA=="
btoa(String.fromCharCode.apply(null, new Uint8Array([0x7e, 0xf5, 0xe6, 0xbc])));
As it turns out, Buffer
instances represent/interpret strings encoded in UTF-8 by default. By contrast, in desktop Chrome, you can't even input a string that contains characters outside of the latin1 range into btoa()
, as it will throw an exception: Uncaught DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.
Therefore, you need to explicitly set the encoding type to latin1
in order for your Node.js shim to match the encoding type of desktop Chrome:
const btoaLatin1 = function(str) { return Buffer.from(str, 'latin1').toString('base64'); }
const atobLatin1 = function(b64Encoded) {return Buffer.from(b64Encoded, 'base64').toString('latin1');}
const btoaUTF8 = function(str) { return Buffer.from(str, 'utf8').toString('base64'); }
const atobUTF8 = function(b64Encoded) {return Buffer.from(b64Encoded, 'base64').toString('utf8');}
btoaLatin1('?'); // returns "Ew==" (would be preferable for it to throw error because this is undecodable)
atobLatin1(btoa('?')); // returns "\u0019" (END OF MEDIUM)
btoaUTF8('?'); // returns "4pyT"
atobUTF8(btoa('?')); // returns "?"
// returns "fvXmvA==", just like desktop Chrome
btoaLatin1(String.fromCharCode.apply(null, new Uint8Array([0x7e, 0xf5, 0xe6, 0xbc])));
// returns "fsO1w6bCvA=="
btoaUTF8(String.fromCharCode.apply(null, new Uint8Array([0x7e, 0xf5, 0xe6, 0xbc])));
I've tried the above methods, end the adb process through task manager and all, it didn't work. But when I ran the adb.exe file as admin it worked fine.
My answer directly inspired from @valex very usefull, if you need several cols in the ORDER BY clause.
SELECT u.*
FROM users AS u
INNER JOIN (
SELECT p.*,
@num := if(@id = user_id, @num + 1, 1) as row_number,
@id := user_id as tmp
FROM (SELECT * FROM payments ORDER BY p.user_id ASC, date DESC) AS p,
(SELECT @num := 0) x,
(SELECT @id := 0) y
)
ON (p.user_id = u.id) and (p.row_number=1)
WHERE u.package = 1
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function dateCheck(inputText) {
debugger;
var dateFormat = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
var flag = 1;
if (inputText.value.match(dateFormat)) {
document.myForm.dateInput.focus();
var inputFormat1 = inputText.value.split('/');
var inputFormat2 = inputText.value.split('-');
linputFormat1 = inputFormat1.length;
linputFormat2 = inputFormat2.length;
if (linputFormat1 > 1) {
var pdate = inputText.value.split('/');
}
else if (linputFormat2 > 1) {
var pdate = inputText.value.split('-');
}
var date = parseInt(pdate[0]);
var month = parseInt(pdate[1]);
var year = parseInt(pdate[2]);
var ListofDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (month == 1 || month > 2) {
if (date > ListofDays[month - 1]) {
alert("Invalid date format!");
return false;
}
}
if (month == 2) {
var leapYear = false;
if ((!(year % 4) && year % 100) || !(year % 400)) {
leapYear = true;
}
if ((leapYear == false) && (date >= 29)) {
alert("Invalid date format!");
return false;
}
if ((leapYear == true) && (date > 29)) {
alert("Invalid date format!");
return false;
}
}
if (flag == 1) {
alert("Valid Date");
}
}
else {
alert("Invalid date format!");
document.myForm.dateInput.focus();
return false;
}
}
function restrictCharacters(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (((charCode >= '48') && (charCode <= '57')) || (charCode == '47')) {
return true;
}
else {
return false;
}
}
</script>
</head>
<body>
<div>
<form name="myForm" action="#">
<table>
<tr>
<td>Enter Date</td>
<td><input type="text" onkeypress="return restrictCharacters(event);" name="dateInput"/></td>
<td></td>
<td><span id="span2"></span></td>
</tr>
<tr>
<td></td>
<td><input type="button" name="submit" value="Submit" onclick="dateCheck(document.myForm.dateInput)" /></td>
</tr>
</table>
</form>
</div>
</body>
</html>
Button imageLogo = (Button)findViewById(R.id.iv_logo);
imageLogo.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "http://www.gobloggerslive.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
As some people have mentioned, Javascript is the way to go. Bear in mind that the "validation" here is only by file extension, it won't validate that the file is a real excel spreadsheet!
To get the index
values as a list
/list
of tuple
s for Index
/MultiIndex
do:
df.index.values.tolist() # an ndarray method, you probably shouldn't depend on this
or
list(df.index.values) # this will always work in pandas
Use VirtualBox. Create a machine on the drive you wish. Enable guest aditions and activate seamless mode.
Benefits:
Drawbacks:
This is the solution i am using and am very happy with it but i am not your average professional programmer. I just create small windows form applications like file uploaders, chat apps etc. Try it out. It will take some time to setup but this experimentation isn't risky.
Bash:
find -type f -printf "%T@ %p \n" \
| sort \
| tail -n 1 \
| sed -r "s/^\S+\s//;s/\s*$//" \
| xargs -iSTR cp STR newestfile
where "newestfile" will become the newestfile
alternatively, you could do newdir/STR or just newdir
Breakdown:
Important
After running this once, the newest file will be whatever you just copied :p ( assuming they're both in the same search scope that is ). So you may have to adjust which filenumber you copy if you want this to work more than once.
Off the top of my head, I can shorten it by one line:
List<String> newList = new ArrayList<String>(listOne);
newList.addAll(listTwo);
A quick search for keywords background generator shows this CSS3 produced background pattern that's dynamically created.
By keeping the image small and repeatable, you won't have problems with it loading on mobile devices and the small image file-size takes care of memory concerns.
Here's the markup for the head
section:
<style type="text/css">
body {
background-image:url('path/to/your/image/background.png');
width: 100%;
height: 100%;
}
</style>
If your going to use an image of something that should preserve aspect ratio, such as people or objects, then you don't want 100% for width and height since that will stretch the image out of proportion. Instead check out this quick tutorial that shows different methods for applying background images using CSS.
Remove any capital letters or other not allowed symbols in resource file name.
Example: activity_parkingList --> activity_parking_list
Right click on your website go to property pages and check both the check-boxes under Accessibility validation click on ok. run the website.
I'll third or fifth or whatever the recommendation for making your fraction immutable. I'd also recommend that you have it extend the Number class. I'd probably look at the Double class, since you're probably going to want to implement many of the same methods.
You should probably also implement Comparable and Serializable since this behavior will probably be expected. Thus, you will need to implement compareTo(). You will also need to override equals() and I cannot stress strongly enough that you also override hashCode(). This might be one of the few cases though where you don't want compareTo() and equals() to be consistent since fractions reducable to each other are not necessarily equal.
try setting this
CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"
in {$tomcat-folder}\bin\setenv.sh
(create it if necessary).
See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.
Sorry I am 9 years late, but this might work for the viewers in 2020.
So suppose you have a line like "Hello my name is Jello"
.
Now you want to find the words that start with 'H'
and end with 'o'
, with any number of characters in between. And we don't want lines we just want words. So for that we can use the expression:
grep "H[^ ]*o" file
This will return all the words. The way this works is that: It will allow all the characters instead of space character in between, this way we can avoid multiple words in the same line.
Now you can replace the space character with any other character you want.
Suppose the initial line was "Hello-my-name-is-Jello"
, then you can get words using the expression:
grep "H[^-]*o" file
Just try " gcc filename.c -lm" while compiling the program ...it worked for me
Here is a simple example without threads or classes.
import signal
run = True
def handler_stop_signals(signum, frame):
global run
run = False
signal.signal(signal.SIGINT, handler_stop_signals)
signal.signal(signal.SIGTERM, handler_stop_signals)
while run:
pass # do stuff including other IO stuff
Another way of accomplishing this is using animation
which provides more control.
#content #nav a {
background-color: #FF0;
/* only animation-duration here is required, rest are optional (also animation-name but it will be set on hover)*/
animation-duration: 1s; /* same as transition duration */
animation-timing-function: linear; /* kind of same as transition timing */
animation-delay: 0ms; /* same as transition delay */
animation-iteration-count: 1; /* set to 2 to make it run twice, or Infinite to run forever!*/
animation-direction: normal; /* can be set to "alternate" to run animation, then run it backwards.*/
animation-fill-mode: none; /* can be used to retain keyframe styling after animation, with "forwards" */
animation-play-state: running; /* can be set dynamically to pause mid animation*/
/* declaring the states of the animation to transition through */
/* optionally add other properties that will change here, or new states (50% etc) */
@keyframes onHoverAnimation {
0% {
background-color: #FF0;
}
100% {
background-color: #AD310B;
}
}
}
#content #nav a:hover {
/* animation wont run unless the element is given the name of the animation. This is set on hover */
animation-name: onHoverAnimation;
}
Very easy:
To set a menu item's image dynamically, only do the following:
MyMenuItem.ImageSource =
new BitmapImage(new Uri("Resource/icon.ico",UriKind.Relative));
...whereas "icon.ico" can be located everywhere (currently it's located in the 'Resources' directory) and must be linked as Resource...
Following document published by W3C also describes the differences between SOAP 1.1 and 1.2:
Sohnee solutions is cleaner, but you can also try
window["bootbox"]
When you cherry-pick, it creates a new commit with a new SHA. If you do:
git cherry-pick -x <sha>
then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.
I see that this problem was discussed some time ago, but if anyone 'll meet with this again, here is my solution:
In your *.cshtml View file:
<script>
var data = JsFunction("@Html.Raw(Model.Path)");
$(function () {
$("#btn").click(function () {
var model = { Id: '@Html.Raw(Model.Id)', Data: data }
$.ajax({
type: "POST",
url: "/Controller/Action",
data: model,
datatype: "html",
success: function() {
console.log('Success');
}
});
});
});
</script>
JavaScript variable model is something that I need to pass to Razor ViewModel. It can be done with ajax request. You just need to have proper argument/s in your action, that matches Json object created in JavaScript.
Hope it'll help someone!
The System.Windows.Media.Imaging
namespace is part of PresentationCore.dll (if you are using Visual Studio 2008 then the WPF application template will automatically add this reference). Note that this namespace is not a direct wrapping of the WIC library, although a large proportion of the more common uses are still available and it is relatively obvious how these map to the WIC versions. For more information on the classes in this namespace check out
http://msdn2.microsoft.com/en-us/library/system.windows.media.imaging.aspx
using System.ComponentModel;
private readonly BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
// run all background tasks here
}
private void worker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
//update ui once worker complete his work
}
worker.RunWorkerAsync();
Track progress (optional, but often useful)
a) subscribe to ProgressChanged
event and use ReportProgress(Int32)
in DoWork
b) set worker.WorkerReportsProgress = true;
(credits to @zagy)
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class readFile {
/**
* feel free to make any modification I have have been here so I feel you
*
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
File dir = new File(".");// read file from same directory as source //
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (File file : files) {
// if you wanna read file name with txt files
if (file.getName().contains("txt")) {
System.out.println(file.getName());
}
// if you want to open text file and read each line then
if (file.getName().contains("txt")) {
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(
file.getAbsolutePath());
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(
fileReader);
String line;
// get file details and get info you need.
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
// here you can say...
// System.out.println(line.substring(0, 10)); this
// prints from 0 to 10 indext
}
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '"
+ file.getName() + "'");
} catch (IOException ex) {
System.out.println("Error reading file '"
+ file.getName() + "'");
// Or we could just do this:
ex.printStackTrace();
}
}
}
}
}`enter code here`
}
Here is one aditional free Floating Action Button library for Android. It has many customizations and requires SDK version 9 and higher
dependencies {
compile 'com.scalified:fab:1.1.2'
}
You may connect to Oracle database using sqlplus:
sqlplus "/as sysdba"
Then create new users and assign privileges.
grant all privileges to dac;
Answered here: Can't install pg gem on Windows
There is no Windows native version of latest release of pg (0.10.0) released yesterday, but if you install 0.9.0 it should install binaries without issues.
This question has relevant answers and link to official Java guidance: Is there a Mutex in Java?
I was making a drop-down menu for a language selector - but I needed the dropdown menu to display the current language upon page load. I would either be getting my initial language from a URL param example.com?user_language=fr
, or detecting it from the user’s browser settings. Then when the user interacted with the dropdown, the selected language would be updated and the language selector dropdown would display the currently selected language.
Since this whole thread has been giving fruit examples, I got all sorts of fruit goodness for you.
First up, answering the initially asked question with a basic React functional component - two examples with and without props, then how to import the component elsewhere.
Next up, the same example - but juiced up with Typescript.
Then a bonus finale - A language selector dropdown component using Typescript.
FruitSelectDropdown
, one without props & one with accepting props fruitDetector
import React, { useState } from 'react'
export const FruitSelectDropdown = () => {
const [currentFruit, setCurrentFruit] = useState('oranges')
const changeFruit = (newFruit) => {
setCurrentFruit(newFruit)
}
return (
<form>
<select
onChange={(event) => changeFruit(event.target.value)}
value={currentFruit}
>
<option value="apples">Red Apples</option>
<option value="oranges">Outrageous Oranges</option>
<option value="tomatoes">Technically a Fruit Tomatoes</option>
<option value="bananas">Bodacious Bananas</option>
</select>
</form>
)
}
Or you can have FruitSelectDropdown accept props, maybe you have a function that outputs a string, you can pass it through using the fruitDetector
prop
import React, { useState } from 'react'
export const FruitSelectDropdown = ({ fruitDetector }) => {
const [currentFruit, setCurrentFruit] = useState(fruitDetector)
const changeFruit = (newFruit) => {
setCurrentFruit(newFruit)
}
return (
<form>
<select
onChange={(event) => changeFruit(event.target.value)}
value={currentFruit}
>
<option value="apples">Red Apples</option>
<option value="oranges">Outrageous Oranges</option>
<option value="tomatoes">Technically a Fruit Tomatoes</option>
<option value="bananas">Bodacious Bananas</option>
</select>
</form>
)
}
Then import the FruitSelectDropdown
elsewhere in your app
import React from 'react'
import { FruitSelectDropdown } from '../path/to/FruitSelectDropdown'
const App = () => {
return (
<div className="page-container">
<h1 className="header">A webpage about fruit</h1>
<div className="section-container">
<h2>Pick your favorite fruit</h2>
<FruitSelectDropdown fruitDetector='bananas' />
</div>
</div>
)
}
export default App
FruitSelectDropdown
with Typescriptimport React, { FC, useState } from 'react'
type FruitProps = {
fruitDetector: string;
}
export const FruitSelectDropdown: FC<FruitProps> = ({ fruitDetector }) => {
const [currentFruit, setCurrentFruit] = useState(fruitDetector)
const changeFruit = (newFruit: string): void => {
setCurrentFruit(newFruit)
}
return (
<form>
<select
onChange={(event) => changeFruit(event.target.value)}
value={currentFruit}
>
<option value="apples">Red Apples</option>
<option value="oranges">Outrageous Oranges</option>
<option value="tomatoes">Technically a Fruit Tomatoes</option>
<option value="bananas">Bodacious Bananas</option>
</select>
</form>
)
}
Then import the FruitSelectDropdown
elsewhere in your app
import React, { FC } from 'react'
import { FruitSelectDropdown } from '../path/to/FruitSelectDropdown'
const App: FC = () => {
return (
<div className="page-container">
<h1 className="header">A webpage about fruit</h1>
<div className="section-container">
<h2>Pick your favorite fruit</h2>
<FruitSelectDropdown fruitDetector='bananas' />
</div>
</div>
)
}
export default App
import React, { FC, useState } from 'react'
import { useTranslation } from 'react-i18next'
export const LanguageSelectDropdown: FC = () => {
const { i18n } = useTranslation()
const i18nLanguage = i18n.language
const [currentI18nLanguage, setCurrentI18nLanguage] = useState(i18nLanguage)
const changeLanguage = (language: string): void => {
i18n.changeLanguage(language)
setCurrentI18nLanguage(language)
}
return (
<form>
<select
onChange={(event) => changeLanguage(event.target.value)}
value={currentI18nLanguage}
>
<option value="en">English</option>
<option value="de">Deutsch</option>
<option value="es">Español</option>
<option value="fr">Français</option>
</select>
</form>
)
}
Sure, convert the file to ascii and blast all unicode characters away. It will probably work.... BUT...
Two more sugrical approaches to fixing the problem:
Regex search all unicode characters not part non-extended ascii. In notepad++ I can search up to FFFF, which hasn't failed me yet.
[\x{80}-\x{FFFF}]
80 is hex for 128, the first extended ascii character.
After hitting "find next" and highlighting what appears to be empty space, you can close your search dialog and press CTRL+C to copy to clipboard.
Then paste the character into a unicode search tool. I usually use an online one. http://unicode.scarfboy.com/
Example: I had a bullet point (•) in my code somehow. The unicode value is 2022 (hex), but when read as ascii by the compiler you get \342 \200 \242 (3 octal values). It's not as simple as converting each octal values to hex and smashing them together. So "E2 80 A2" is NOT the hex unicode point in your code.
It is a unicode char \u003C = <
Another way of doing this:
# find . |xargs file {} \; |grep "ASCII text"
If you want empty files too:
# find . |xargs file {} \; |egrep "ASCII text|empty"
In addition to the accepted answer, I would like to add one info, that NuGet packages in Visual Studio 2017 are located in the project file itself. I.e., right click on the project -> edit, to find all package reference entries.
An alternative is to use NodeJS.
Here is an example:
const os = require('os');
const colors = require('colors');
console.log("Operative System:".green,os.type(),os.release());
console.log("Uptime:".blue,os.uptime());
And this is the result:
class Second:
def __init__(self, data):
self.data = data
class First:
def SecondClass(self, data):
return Second(data)
FirstClass = First()
SecondClass = FirstClass.SecondClass('now you see me')
print SecondClass.data
You're right that the SD Card directory is /sdcard
but you shouldn't be hard coding it. Instead, make a call to Environment.getExternalStorageDirectory()
to get the directory:
File sdDir = Environment.getExternalStorageDirectory();
If you haven't done so already, you will need to give your app the correct permission to write to the SD Card by adding the line below to your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Sometimes, when you add a new library, in introduces a clashing version of System.Windows.Interactivity.dll
.
For example, the NuGet package MVVM light
might require v4.2 of System.Windows.Interactivity.dll
, but the NuGet package Rx-XAML
might require v4.5 of System.Windows.Interactivity.dll
. This will prevent the the project from working, because no matter which version of System.Windows.Interactivity.dll
you include, one of the libraries will refuse to compile.
To fix, add an Assembly Binding Redirect by editing your app.config
to look something like this:
<?xml version="1.0"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Windows.Interactivity"
publicKeyToken="31bf3856ad364e35"
culture="neutral"/>
<bindingRedirect oldVersion="4.0.0.0"
newVersion="4.5.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/></startup>
<appSettings>
<add key="TestKey" value="true"/>
</appSettings>
Don't worry about changing the PublicKeyToken
, that's constant across all versions, as it depends on the name of the .dll, not the version.
Ensure that you match the newVersion
in your appConfig
to the actual version that you end up pointing at:
net stop <your service> && net start <your service>
No net restart
, unfortunately.