I had a problem with this kind of sql, I was giving empty list in IN clause(always check the list if it is not empty). Maybe my practice will help somebody.
I used to always get confused whether I should use break, or continue. This is what helps me remember:
If you are getting an error saying something about deprecated functions, try doing #define _CRT_SECURE_NO_WARNINGS
or #define _CRT_SECURE_NO_DEPRECATE
. These should fix it. You can also use Microsoft's "secure" functions, if you want.
For :
OS X : 10.11.6
Java : 8
I confirm the answer of @Morrie .
export JAVA_HOME=/Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home;
But if you are running containers your life will be easier
Close all browsers and tabs to ensure that the ActiveX control is not reside in memory. Open a fresh IE9 browser. Select Tools->Manage Add-ons. Change the drop down to "All add-ons" since the default only shows ones that are loaded.
Now select the add-on you wish to remove. There will be a link displayed on the lower left that says "More information". Click it.
This opens a further dialog that allows you to safely un-install the ActiveX control.
If you follow the direction of manually running the 'regsvr32' to remove the OCX it is not sufficient. ActiveX controls are wrapped up as signed CAB files and they extract to multiple DLLs and OCXs potentially. You wish to use IE to safely and correctly unregister every COM DLL and OCX.
There you have it! The problem is that in IE 9 it is somewhat hidden since you have to click the "More information" whereas IE8 you could do it from the same UI.
My 2 cents on @K_Anas answer. I performed a simple test on finish() method. Listed important callback methods in activity life cycle
What I mean to say is that counterparts of the methods along with any methods in between are called when finish() is executed.
eg:
onCreate() counter part is onDestroy()
onStart() counter part is onStop()
onPause() counter part is onResume()
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--disable-logging')
# Update your desired_capabilities dict withe extra options.
desired_capabilities.update(options.to_capabilities())
driver = webdriver.Remote(desired_capabilities=options.to_capabilities())
Both the desired_capabilities and options.to_capabilities() are dictionaries. You can use the dict.update() method to add the options to the main set.
If you don't call the favicon, favicon.ico
, you can use that tag to specify the actual path (incase you have it in an images/
directory). The browser/webpage looks for favicon.ico
in the root directory by default.
The command setwd("~/")
should set your working directory to your home directory. You might be experiencing problems because the OS you are using does not recognise "~/"
as your home directory: this might be because of the OS, or it might be because of not having set that as your home directory elsewhere.
As you have tagged the post using RStudio:
You will now have set the folder as your working directory. Use the command getwd()
to get the working directory as it is now set, and save that as a variable string at the top of your script. Then use setwd
with that string as the argument, so that each time you run the script you use the same directory.
For example at the top of my script I would have:
work_dir <- "C:/Users/john.smith/Documents"
setwd(work_dir)
The Best way is to create a user for your application and assign the permissions that are suitable for that user. Dont use 'NT AUTHORITY\NETWORK SERVICE' as your user it has its own vulnerability and it is a user that has permissions to so many things on the OS level. Stay away from this built in user.
Just Need to Start MySQL Service after installation:
For Ubuntu:
sudo service mysql start;
For CentOS or RHEL:
sudo service mysqld start;
Usually, we define classes for this.
class XClass( object ):
def __init__( self ):
self.myAttr= None
x= XClass()
x.myAttr= 'magic'
x.myAttr
However, you can, to an extent, do this with the setattr
and getattr
built-in functions. However, they don't work on instances of object
directly.
>>> a= object()
>>> setattr( a, 'hi', 'mom' )
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'hi'
They do, however, work on all kinds of simple classes.
class YClass( object ):
pass
y= YClass()
setattr( y, 'myAttr', 'magic' )
y.myAttr
The client has a pre-seeded store of SSL certificate authorities' public keys. There must be a chain of trust from the certificate for the server up through intermediate authorities up to one of the so-called "root" certificates in order for the server to be trusted.
You can examine and/or alter the list of trusted authorities. Often you do this to add a certificate for a local authority that you know you trust - like the company you work for or the school you attend or what not.
The pre-seeded list can vary depending on which client you use. The big SSL certificate vendors insure that their root certs are in all the major browsers ($$$).
Monkey-in-the-middle attacks are "impossible" unless the attacker has the private key of a trusted root certificate. Since the corresponding certificates are widely deployed, the exposure of such a private key would have serious implications for the security of eCommerce generally. Because of that, those private keys are very, very closely guarded.
I think the best way to get the full name is:
this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;
or try this
string method = string.Format("{0}.{1}", MethodBase.GetCurrentMethod().DeclaringType.FullName, MethodBase.GetCurrentMethod().Name);
I found another solution here, since I ran into both post...
This is from the Myles answer:
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
</Style>
</ListBox.ItemContainerStyle>
This worked for me.
Generate random number between 0 to 99:
int x = arc4random()%100;
Generate random number between 500 and 1000:
int x = (arc4random()%501) + 500;
I have found that Furius ISO mount works best for me. I am using a Debian based distro Knoppix. I use this to Open system.img
files all the time.
Furius ISO mount: https://packages.debian.org/sid/otherosfs/furiusisomount
"When I want to mount userdata.img by mount -o loop userdata.img /mnt/userdata (the same as system.img), it tells me mount: you must specify the filesystem type so I try the mount -t ext2 -o loop userdata.img /mnt/userdata, it said mount: wrong fs type, bad option, bad superblock on...
So, how to get the file from the inside of userdata.img?"
To load .img
files you have to select loop and load the .img
Select loop
Next you select mount Select mount
Furius ISO mount handles all the other options loading the .img
file to your /home/dir.
I was looking for solution for exactly the same problem. To remove all classes starting with prefix "fontid_" After reading this article I wrote a small plugin which I'm using now.
(function ($) {
$.fn.removePrefixedClasses = function (prefix) {
var classNames = $(this).attr('class').split(' '),
className,
newClassNames = [],
i;
//loop class names
for(i = 0; i < classNames.length; i++) {
className = classNames[i];
// if prefix not found at the beggining of class name
if(className.indexOf(prefix) !== 0) {
newClassNames.push(className);
continue;
}
}
// write new list excluding filtered classNames
$(this).attr('class', newClassNames.join(' '));
};
}(fQuery));
Usage:
$('#elementId').removePrefixedClasses('prefix-of-classes_');
Below code might help you to copy the first level objects
let original = [{ a: 1 }, {b:1}]
const copy = [ ...original ].map(item=>({...item}))
so for below case, values remains intact
copy[0].a = 23
console.log(original[0].a) //logs 1 -- value didn't change voila :)
Fails for this case
let original = [{ a: {b:2} }, {b:1}]
const copy = [ ...original ].map(item=>({...item}))
copy[0].a.b = 23;
console.log(original[0].a) //logs 23 -- lost the original one :(
Final advice:
I would say go for lodash cloneDeep
API which helps you to copy the objects inside objects completely dereferencing from original one's. This can be installed as a separate module.
Refer documentation: https://github.com/lodash/lodash
Individual Package : https://www.npmjs.com/package/lodash.clonedeep
Dirk's answer here is everything you need. Here's a minimal reproducible example.
I made two files: exmpl.bat
and exmpl.R
.
exmpl.bat
:
set R_Script="C:\Program Files\R-3.0.2\bin\RScript.exe"
%R_Script% exmpl.R 2010-01-28 example 100 > exmpl.batch 2>&1
Alternatively, using Rterm.exe
:
set R_TERM="C:\Program Files\R-3.0.2\bin\i386\Rterm.exe"
%R_TERM% --no-restore --no-save --args 2010-01-28 example 100 < exmpl.R > exmpl.batch 2>&1
exmpl.R
:
options(echo=TRUE) # if you want see commands in output file
args <- commandArgs(trailingOnly = TRUE)
print(args)
# trailingOnly=TRUE means that only your arguments are returned, check:
# print(commandArgs(trailingOnly=FALSE))
start_date <- as.Date(args[1])
name <- args[2]
n <- as.integer(args[3])
rm(args)
# Some computations:
x <- rnorm(n)
png(paste(name,".png",sep=""))
plot(start_date+(1L:n), x)
dev.off()
summary(x)
Save both files in the same directory and start exmpl.bat
. In the result you'll get:
example.png
with some plotexmpl.batch
with all that was doneYou could also add an environment variable %R_Script%
:
"C:\Program Files\R-3.0.2\bin\RScript.exe"
and use it in your batch scripts as %R_Script% <filename.r> <arguments>
Differences between RScript
and Rterm
:
Rscript
has simpler syntaxRscript
automatically chooses architecture on x64 (see R Installation and Administration, 2.6 Sub-architectures for details)Rscript
needs options(echo=TRUE)
in the .R file if you want to write the commands to the output fileI found that I couldn't use multiple databases within the same database model when using EF. But in linq2sql I could just by prefixing the schema names with database names.
This was one of the reasons I originally began working with linq2sql. I do not know if EF has yet allowed this functionality, but I remember reading that it was intended for it not to allow this.
A Python 2+3 compatible solution is:
import sys
if sys.version_info[0] >= 3:
from urllib.request import urlretrieve
else:
# Not Python 3 - today, it is most likely to be Python 2
# But note that this might need an update when Python 4
# might be around one day
from urllib import urlretrieve
# Get file from URL like this:
urlretrieve("http://www-scf.usc.edu/~chiso/oldspice/m-b1-hello.mp3")
Are you trying to remove a single value or all matching values?
If you are trying to remove a single value, how do you define the value you wish to remove?
The reason you don't get a key back when querying on values is because the dictionary could contain multiple keys paired with the specified value.
If you wish to remove all matching instances of the same value, you can do this:
foreach(var item in dic.Where(kvp => kvp.Value == value).ToList())
{
dic.Remove(item.Key);
}
And if you wish to remove the first matching instance, you can query to find the first item and just remove that:
var item = dic.First(kvp => kvp.Value == value);
dic.Remove(item.Key);
Note: The ToList()
call is necessary to copy the values to a new collection. If the call is not made, the loop will be modifying the collection it is iterating over, causing an exception to be thrown on the next attempt to iterate after the first value is removed.
Primes are used because you have good chances of obtaining a unique value for a typical hash-function which uses polynomials modulo P. Say, you use such hash-function for strings of length <= N, and you have a collision. That means that 2 different polynomials produce the same value modulo P. The difference of those polynomials is again a polynomial of the same degree N (or less). It has no more than N roots (this is here the nature of math shows itself, since this claim is only true for a polynomial over a field => prime number). So if N is much less than P, you are likely not to have a collision. After that, experiment can probably show that 37 is big enough to avoid collisions for a hash-table of strings which have length 5-10, and is small enough to use for calculations.
Position your <div>
absolutely at the bottom and don't forget to give div.A
a position: relative
- http://jsfiddle.net/TTaMx/
.A {
position: relative;
margin: 40px 0;
height: 40px;
width: 200px;
background: #eee;
}
.A:after {
content: " ";
display: block;
background: #c00;
height: 29px;
width: 100%;
position: absolute;
bottom: -29px;
}?
You can use the ZipArchive
class to create a ZIP file and stream it to the client. Something like:
$files = array('readme.txt', 'test.html', 'image.gif');
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
$zip->addFile($file);
}
$zip->close();
and to stream it:
header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);
The second line forces the browser to present a download box to the user and prompts the name filename.zip. The third line is optional but certain (mainly older) browsers have issues in certain cases without the content size being specified.
This thread is pretty old I suppose, but in case anyone else stumbles across this question... I had to grab a value from the selected row of a table, but I didn't want to show the column that row was from. I used hideCol, but had the same problem as Andy where it looked messy. To fix it (call it a hack) I just re-set the width of the grid.
jQuery(document).ready(function() {
jQuery("#ItemGrid").jqGrid({
...,
width: 700,
...
}).hideCol('StoreId').setGridWidth(700)
Since my row widths are automatic, when I reset the width of the table it reset the column widths but excluded the hidden one, so they filled in the gap.
Firstly, a code block that looks like (function(){})()
is merely a function that is executed in place. Let's break it down a little.
1. (
2. function(){}
3. )
4. ()
Line 2 is a plain function, wrapped in parenthesis to tell the runtime to return the function to the parent scope, once it's returned the function is executed using line 4, maybe reading through these steps will help
1. function(){ .. }
2. (1)
3. 2()
You can see that 1 is the declaration, 2 is returning the function and 3 is just executing the function.
An example of how it would be used.
(function(doc){
doc.location = '/';
})(document);//This is passed into the function above
As for the other questions about the plugins:
Type 1: This is not a actually a plugin, it's an object passed as a function, as plugins tend to be functions.
Type 2: This is again not a plugin as it does not extend the $.fn
object. It's just an extenstion of the jQuery core, although the outcome is the same. This is if you want to add traversing functions such as toArray and so on.
Type 3: This is the best method to add a plugin, the extended prototype of jQuery takes an object holding your plugin name and function and adds it to the plugin library for you.
You need to check for the parameter being blank: if "%~1"=="" goto blank
Once you've done that, then do an if/else switch on -b: if "%~1"=="-b" (goto specific) else goto unknown
Surrounding the parameters with quotes makes checking for things like blank/empty/missing parameters easier. "~" ensures double quotes are stripped if they were on the command line argument.
I've been using Michael G. Emmons' answer for about a year now, works great. I did notice recently that calling resignFirstResponder and then becomeFirstResponder immediately can cause the keyboard to "glitch", disappearing and then appearing immediately. I changed his version slightly to skip the resignFirstResponder if the nextField is available.
- (BOOL)textFieldShouldReturn:(UITextField *)textField { if ([textField isKindOfClass:[NRTextField class]]) { NRTextField *nText = (NRTextField*)textField; if ([nText nextField] != nil){ dispatch_async(dispatch_get_main_queue(), ^ { [[nText nextField] becomeFirstResponder]; }); } else{ [textField resignFirstResponder]; } } else{ [textField resignFirstResponder]; } return true; }
As was mentioned in an older version (2009) of the "Tree Conflict" design document:
XFAIL conflict from merge of add over versioned file
This test does a merge which brings a file addition without history onto an existing versioned file.
This should be a tree conflict on the file of the 'local obstruction, incoming add upon merge
' variety. Fixed expectations in r35341.
(This is also called "evil twins" in ClearCase by the way):
a file is created twice (here "added" twice) in two different branches, creating two different histories for two different elements, but with the same name.
The theoretical solution is to manually merge those files (with an external diff tool) in the destination branch 'B2
'.
If you still are working on the source branch, the ideal scenario would be to remove that file from the source branch B1
, merge back from B2
to B1
in order to make that file visible on B1
(you will then work on the same element).
If a merge back is not possible because merges only occurs from B1
to B2
, then a manual merge will be necessary for each B1->B2
merges.
Simple use this great free online tool:
Putting the various suggestions together, the cleanest version I was able to come up with (without unreliable grep which triggers parts of words) is:
kill -0 $(pidof mysql) 2> /dev/null || echo "Mysql ain't runnin' message/actions"
kill -0 doesn't kill the process but checks if it exists and then returns true, if you don't have pidof on your system, store the pid when you launch the process:
$ mysql &
$ echo $! > pid_stored
then in the script:
kill -0 $(cat pid_stored) 2> /dev/null || echo "Mysql ain't runnin' message/actions"
It is possible. With vanilla Javascript, you can use the function below for reference.
function updateIframeBackground(iframeId) {
var x = document.getElementById(iframeId);
var y = (x.contentWindow || x.contentDocument);
if (y.document) y = y.document;
y.body.style.backgroundColor = "#2D2D2D";
}
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_iframe_contentdocument
In Bootstrap, the .btn
class has a white-space: nowrap;
property, making it so that the button text won't wrap. So, after setting that to normal
, and giving the button a width
, the text should wrap to the next line if the text would exceed the set width
.
#new-board-btn {
white-space: normal;
}
This is really easy using package lubridate. All you have to do is tell R what format your date is already in. It then converts it into the standard format
nzd$date <- dmy(nzd$date)
that's it.
Often when there is a drastic difference from run to run of a query I find that it is often one of 5 issues.
STATISTICS - Statistics are out of date. A database stores statistics on the range and distribution of the types of values in various column on tables and indexes. This helps the query engine to develop a "Plan" of attack for how it will do the query, for example the type of method it will use to match keys between tables using a hash or looking through the entire set. You can call Update Statistics on the entire database or just certain tables or indexes. This slows down the query from one run to another because when statistics are out of date, its likely the query plan is not optimal for the newly inserted or changed data for the same query (explained more later below). It may not be proper to Update Statistics immediately on a Production database as there will be some overhead, slow down and lag depending on the amount of data to sample. You can also choose to use a Full Scan or Sampling to update Statistics. If you look at the Query Plan, you can then also view the statistics on the Indexes in use such using the command DBCC SHOW_STATISTICS (tablename, indexname). This will show you the distribution and ranges of the keys that the query plan is using to base its approach on.
PARAMETER SNIFFING - The query plan that is cached is not optimal for the particular parameters you are passing in, even though the query itself has not changed. For example, if you pass in a parameter which only retrieves 10 out of 1,000,000 rows, then the query plan created may use a Hash Join, however if the parameter you pass in will use 750,000 of the 1,000,000 rows, the plan created may be an index scan or table scan. In such a situation you can tell the SQL statement to use the option OPTION (RECOMPILE) or an SP to use WITH RECOMPILE. To tell the Engine this is a "Single Use Plan" and not to use a Cached Plan which likely does not apply. There is no rule on how to make this decision, it depends on knowing the way the query will be used by users.
INDEXES - Its possible that the query haven't changed, but a change elsewhere such as the removal of a very useful index has slowed down the query.
ROWS CHANGED - The rows you are querying drastically changes from call to call. Usually statistics are automatically updated in these cases. However if you are building dynamic SQL or calling SQL within a tight loop, there is a possibility you are using an outdated Query Plan based on the wrong drastic number of rows or statistics. Again in this case OPTION (RECOMPILE) is useful.
THE LOGIC Its the Logic, your query is no longer efficient, it was fine for a small number of rows, but no longer scales. This usually involves more indepth analysis of the Query Plan. For example, you can no longer do things in bulk, but have to Chunk things and do smaller Commits, or your Cross Product was fine for a smaller set but now takes up CPU and Memory as it scales larger, this may also be true for using DISTINCT, you are calling a function for every row, your key matches don't use an index because of CASTING type conversion or NULLS or functions... Too many possibilities here.
In general when you write a query, you should have some mental picture of roughly how certain data is distributed within your table. A column for example, can have an evenly distributed number of different values, or it can be skewed, 80% of the time have a specific set of values, whether the distribution will varying frequently over time or be fairly static. This will give you a better idea of how to build an efficient query. But also when debugging query performance have a basis for building a hypothesis as to why it is slow or inefficient.
You need to return a Callable<>
if you want spring.mvc.async.request-timeout=5000
to work.
@RequestMapping(method = RequestMethod.GET)
public Callable<String> getFoobar() throws InterruptedException {
return new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(8000); //this will cause a timeout
return "foobar";
}
};
}
It is an implementation of Pythagorean theorem. Link: http://en.wikipedia.org/wiki/Pythagorean_theorem
It's ridiculous how bad Mysql and MariaDB are optimized when it comes to inserts. I tested mysql 5.7 and mariadb 10.3, no real difference on those.
I've tested this on a server with NVME disks, 70,000 IOPS, 1.1 GB/sec seq throughput and that's possible full duplex (read and write).
The server is a high performance server as well.
Gave it 20 GB of ram.
The database completely empty.
The speed I receive was 5000 inserts per second when doing multi row inserts (tried it with 1MB up to 10MB chunks of data)
Now the clue:
If I add another thread and insert into the SAME tables I suddenly have 2x5000 /sec.
One more thread and I have 15000 total /sec
Consider this: When doing ONE thread inserts it means you can sequentially write to the disk (with exceptions to indexes). When using threads you actually degrade the possible performance because it now needs to do a lot more random accesses. But reality check shows mysql is so badly optimized that threads help a lot.
The real performance possible with such a server is probably millions per second, the CPU is idle the disk is idle.
The reason is quite clearly that mariadb just as mysql has internal delays.
Using VS 2010:
Let's say you have a Windows.Forms project. You add a UserControl (say MyControl) to the project, and design it all up. Now you want to add it to your toolbox.
As soon as the project is successfully built once, it will appear in your Framework Components. Right click the Toolbox to get the context menu, select "Choose Items...", and browse to the name of your control (MyControl) under the ".NET Framework Components" tab.
Advantage over using dlls: you can edit the controls in the same project as your form, and the form will build with the new controls. However, the control will only be avilable to this project.
Note: If the control has build errors, resolve them before moving on to the containing forms, or the designer has a heart attack.
This warning comes because your dataframe x
is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.
You can either create a proper dataframe
out of x by doing
x = x.copy()
This will remove the warning, but it is not the proper way
You should be using the DataFrame.loc
method, as the warning suggests, like this:
x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)
similar to substr('abcdefg', 2-1, 3) in php:
echo 'abcdefg'|tail -c +2|head -c 3
In the component's componentDidMount
lifecycle method, you can set an interval to call a function which updates the state.
componentDidMount() {
setInterval(() => this.setState({ time: Date.now()}), 1000)
}
As a general rule, converting a Web Forms or MVC5 application to ASP.NET Core will require a significant amount of refactoring.
HttpContext.Current
was removed in ASP.NET Core. Accessing the current HTTP context from a separate class library is the type of messy architecture that ASP.NET Core tries to avoid. There are a few ways to re-architect this in ASP.NET Core.
You can access the current HTTP context via the HttpContext
property on any controller. The closest thing to your original code sample would be to pass HttpContext
into the method you are calling:
public class HomeController : Controller
{
public IActionResult Index()
{
MyMethod(HttpContext);
// Other code
}
}
public void MyMethod(Microsoft.AspNetCore.Http.HttpContext context)
{
var host = $"{context.Request.Scheme}://{context.Request.Host}";
// Other code
}
If you're writing custom middleware for the ASP.NET Core pipeline, the current request's HttpContext
is passed into your Invoke
method automatically:
public Task Invoke(HttpContext context)
{
// Do something with the current HTTP context...
}
Finally, you can use the IHttpContextAccessor
helper service to get the HTTP context in any class that is managed by the ASP.NET Core dependency injection system. This is useful when you have a common service that is used by your controllers.
Request this interface in your constructor:
public MyMiddleware(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
You can then access the current HTTP context in a safe way:
var context = _httpContextAccessor.HttpContext;
// Do something with the current HTTP context...
IHttpContextAccessor
isn't always added to the service container by default, so register it in ConfigureServices
just to be safe:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
// if < .NET Core 2.2 use this
//services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// Other code...
}
U can use eclipse. but u need to download pydev addon for that.
You can choose only install the client during server install. The website only offers to let you download the full installer (grab whatever version you want from http://www.mysql.com/downloads/mysql/).
In the install wizard, when prompted for installation type (typical, minimal, custom), choose 'Custom'. On the next screen, select to NOT install the server, and proceed with the rest of the install as normal.
When you're done, you should see just the relevant client programs (mysql, mysqldump, etc) in C:\Program Files\MySQL..\bin
This is good for taking multiple line input
import java.util.Scanner;
public class JavaApp {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String line;
while(true){
line = scanner.nextLine();
System.out.println(line);
if(line.equals("")){
break;
}
}
}
}
You could use one of these (you can both use them online or download them, there is some info about each of them) : http://www.javadecompilers.com/
The one IntelliJ IDEA uses is fernflower, but it can't handle recent things - like String/Enum switches, generics (didn't test this one personally, only read about it), ... I just tried cfr from the above website and the result was the same as with the built-in decompiler (except for the Enum switch I had in my class).
Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.
But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)
You want reorder()
. Here is an example with dummy data
set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))
require("ggplot2")
p1 <- ggplot(df, aes(x = Category, y = Count)) +
geom_bar(stat = "identity")
p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
geom_bar(stat = "identity")
require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))
Giving:
Use reorder(Category, Count)
to have Category
ordered from low-high.
The Set interface itself does not stipulate any particular order. The SortedSet does however.
OpenSuse
"sudo zypper install libxml2-devel"
It will install any other dependencies or required packages/libraries
I used AndExplorer for this purpose and my solution is popup a dialog and then redirect on the market to install the misssing application:
My startCreation is trying to call external file/directory picker. If it is missing call show installResultMessage function.
private void startCreation(){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
Uri startDir = Uri.fromFile(new File("/sdcard"));
intent.setDataAndType(startDir,
"vnd.android.cursor.dir/lysesoft.andexplorer.file");
intent.putExtra("browser_filter_extension_whitelist", "*.csv");
intent.putExtra("explorer_title", getText(R.string.andex_file_selection_title));
intent.putExtra("browser_title_background_color",
getText(R.string.browser_title_background_color));
intent.putExtra("browser_title_foreground_color",
getText(R.string.browser_title_foreground_color));
intent.putExtra("browser_list_background_color",
getText(R.string.browser_list_background_color));
intent.putExtra("browser_list_fontscale", "120%");
intent.putExtra("browser_list_layout", "2");
try{
ApplicationInfo info = getPackageManager()
.getApplicationInfo("lysesoft.andexplorer", 0 );
startActivityForResult(intent, PICK_REQUEST_CODE);
} catch( PackageManager.NameNotFoundException e ){
showInstallResultMessage(R.string.error_install_andexplorer);
} catch (Exception e) {
Log.w(TAG, e.getMessage());
}
}
This methos is just pick up a dialog and if user wants install the external application from market
private void showInstallResultMessage(int msg_id) {
AlertDialog dialog = new AlertDialog.Builder(this).create();
dialog.setMessage(getText(msg_id));
dialog.setButton(getText(R.string.button_ok),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
dialog.setButton2(getText(R.string.button_install),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=lysesoft.andexplorer"));
startActivity(intent);
finish();
}
});
dialog.show();
}
I was able to fix this problem by setting font-size: 0 .
Python function subset that return subset of list that adds up to a particular value
def subset(ln, tar):#ln=Lenght Of String, tar= Target
s=[ int(input('Insert Numeric Value Into List:')) for i in range(ln) ]#Inserting int Values in s of type<list>
if sum(s) < tar:#Sum of List is less than Target Value
return
elif sum(s) == tar:#Sum of list is equal to Target Value i.e for all values combinations
return s
elif tar in s:#Target value present in List i.e for single value
return s[s.index(tar)]
else:#For remaining possibilities i.e for all except( single and all values combinations )
from itertools import combinations# To check all combinations ==> itertools.combinations(list,r) OR return list of all subsets of length r
r=[i+1 for i in range(1,ln-1)]# Taking r as only remaining value combinations, i.e.
# Except( r=1 => for single value combinations AND r=length(list) || r=ln => For all value combinations
lst=list()#For Storing all remaining combinations
for i in range(len(r)):
lst.extend(list( combinations(s,r[i]) ))
for i in range(len(lst)):# To check remaining possibilities
if tar == sum(lst[i]):
return list(lst[i])
subset( int(input('Length of list:')), int(input('Target:')))
I faced the same problem. And with the help of guys I came up with a really smart solution that solve that problem totally (run on chrome ) .
Extract all images from the network
function AllImagesUrl (domain){
return performance.getEntries()
.filter( e=>
e.initiatorType == "img" &&
new RegExp(domain).test(e.name)
)
.map( e=> e.name.replace('some cleaning work here','') ) ```
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
JSONObject JObj = new JSONObject();
try {
JObj.put("Id","1");
JObj.put("Name", "abc");
} catch (Exception e) {
e.printStackTrace();
}
params.put("params", JObj.toString());
// Map.Entry<String,String>
Log.d("Parameter", params.toString());
return params;
}
Try upgrade pip with the below command and retry
python -m pip install -U pip
The naive algorithm, which is what you've got once you correct it as noted in comments, is O(n^3).
There do exist algorithms that reduce this somewhat, but you're not likely to find an O(n^2) implementation. I believe the question of the most efficient implementation is still open.
See this wikipedia article on Matrix Multiplication for more information.
Run dos2unix or similar utility on it to remove the carriage returns (^M).
This message indicates that your file has dos-style lineendings:
-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory
Utilities like dos2unix
will fix it:
dos2unix <backup.bash >improved-backup.sh
Or, if no such utility is installed, you can accomplish the same thing with translate:
tr -d "\015\032" <backup.bash >improved-backup.sh
As for how those characters got there in the first place, @MadPhysicist had some good comments.
I ended up following @vicenteherrera's approach, with some tweaks (that are possibly bootstrap 3 specific).
Basically; we can't break tr
s, or td
s because they're not block-level elements. So we embed div
s into each, and apply our page-break-*
rules against the div
. Secondly; we add some padding to the top of each of these divs, to compensate for any styling artifacts.
<style>
@media print {
/* avoid cutting tr's in half */
th div, td div {
margin-top:-8px;
padding-top:8px;
page-break-inside:avoid;
}
}
</style>
<script>
$(document).ready(function(){
// Wrap each tr and td's content within a div
// (todo: add logic so we only do this when printing)
$("table tbody th, table tbody td").wrapInner("<div></div>");
})
</script>
The margin and padding adjustments were necessary to offset some kind of jitter that was being introduced (by my guess - from bootstrap). I'm not sure that I'm presenting any new solution from the other answers to this question, but I figure maybe this will help someone.
Goto my blog : retrofit with kotlin
the link below explains everything step by step.
http://loopj.com/android-async-http/
Here are sample apps:
Create a class :
public class HttpUtils {
private static final String BASE_URL = "http://api.twitter.com/1/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(url, params, responseHandler);
}
public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(url, params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
Call Method :
RequestParams rp = new RequestParams();
rp.add("username", "aaa"); rp.add("password", "aaa@123");
HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
Log.d("asd", "---------------- this is response : " + response);
try {
JSONObject serverResp = new JSONObject(response.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline
}
});
Please grant internet permission in your manifest file.
<uses-permission android:name="android.permission.INTERNET" />
you can add compile 'com.loopj.android:android-async-http:1.4.9'
for Header[]
and compile 'org.json:json:20160212'
for JSONObject
in build.gradle file if required.
points_small = dict(filter(lambda (a,(b,c)): b<5 and c < 5, points.items()))
You need to add the new line character \n
:
console.log('line one \nline two')
would display:
line one
line two
You are close already. Just make sure to hide the checkbox and associate it with a label you style via input[checkbox] + label
Complete Code: http://gist.github.com/592332
JSFiddle: http://jsfiddle.net/4huzr/
Ofcourse this is a closed issue, i would like to add something to your discussion
In mozilla i have observed a weird behaviour for this code
$(document).keydown(function(){
//my code
});
the code is being triggered twice. When debugged i found that actually there are two events getting fired: 'keypress' and 'keydown'. I disabled one of the event and the code shown me expected behavior.
$(document).unbind('keypress');
$(document).keydown(function(){
//my code
});
This works for all browsers and also there is no need to check for browser specific(if($.browser.mozilla){ }).
Hope this might be useful for someone
In the Cygwin package manager, click on curl from within the "net" category. Yes, it's that simple.
prefer struct, and it's what std::greater do
struct Compare {
bool operator()(Node const&, Node &) {}
}
Storing with json or serialized array is the best solution for now. With some situations (trimming " ' characters) json might be getting trouble but serialize should be great choice.
Note: If you change serialized data manually, you need to be careful about character count.
This has always worked well for me:
yAxes: [{
ticks: {
display: false;
},
Another possible solution:
sek=[]
L=[1,2,3,4,5,6,7,8,9,0]
for i in [2, 4, 7, 0, 3]:
a=[L[i]]
sek=sek+a
print (sek)
Here is a general solution that doesn't rely on JQuery. Simply modify the definition of window.location.
<html>
<head>
<script>
function loadNewDoc(){
var loc = window.location;
window.location = loc.hostname + loc.port + loc.pathname + loc.search;
};
</script>
</head>
<body onLoad="loadNewDoc()">
</body>
</html>
Also worth noting window.scrollBy(dx,dy)
(ref)
This links might be helpful to convert.
https://code.google.com/p/flying-saucer/
https://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html
If it is a college Project, you can even go for these, http://pd4ml.com/examples.htm
Example is given to convert HTML to PDF
If you want to install Symfony2.2, you can see the complete change in your composer.json
on the Symfony blog.
Just update your file according to that and run composer update
after that. That will install all new dependencies and Symfony2.2 on your project.
If you don't want to update to Symfony2.2, but have dependency errors, you should post these, so we can help you further.
You're doing a few things wrong.
First, browserHistory isn't a thing in V4, so you can remove that.
Second, you're importing everything from react-router
, it should be react-router-dom
.
Third, react-router-dom
doesn't export a Router
, instead, it exports a BrowserRouter
so you need to import { BrowserRouter as Router } from 'react-router-dom
.
Looks like you just took your V3 app and expected it to work with v4, which isn't a great idea.
You can't directly instantiate an abstract class, but you can create an anonymous class when there is no concrete class:
public class AbstractTest {
public static void main(final String... args) {
final Printer p = new Printer() {
void printSomethingOther() {
System.out.println("other");
}
@Override
public void print() {
super.print();
System.out.println("world");
printSomethingOther(); // works fine
}
};
p.print();
//p.printSomethingOther(); // does not work
}
}
abstract class Printer {
public void print() {
System.out.println("hello");
}
}
This works with interfaces, too.
Woff is a compressed (zipped) form of the TrueType - OpenType font. It is small and can be delivered over the network like a graphic file. Most importantly, this way the font is preserved completely including rendering rule tables that very few people care about because they use only Latin script.
Take a look at [dead URL removed]. The font you see is an experimental web delivered smartfont (woff) that has thousands of combined characters making complex shapes. The underlying text is simple Latin code of romanized Singhala. (Copy and paste to Notepad and see).
Only woff can do this because nobody has this font and yet it is seen anywhere (Mac, Win, Linux and even on smartphones by all browsers except by IE. IE does not have full support for Open Types).
Don't forget to add "inplace=True" to Wes' answer or set the result to a new DataFrame.
df.sort_index(axis=1, inplace=True)
You can also use the following attr
thing;
HTML
<div id="mydiv" data-myval="JohnCena"></div>
Script
$('#mydiv').attr('data-myval', 'Undertaker'); // sets
$('#mydiv').attr('data-myval'); // gets
OR
$('#mydiv').data('myval'); // gets value
$('#mydiv').data('myval','John Cena'); // sets value
cd venv
source bin/activate
export PYTHONPATH='/home/django/srmvenv/lib/python3.4'
python
\>\> import sys
\>\> sys.path
Check the installation directories (typically C:\Program Files (x86)
or C:\Program Files
) for the java folder. If it contains the JRE you have java installed.
If you have Bluetooth, Use twedge on windows and getblue app on android, they also have a few videos of it. It's made by TEC-IT. I've got it to work by setting the interface option to bluetooth server in TWedge and setting the output setting in getblue to Bluetooth client and selecting my computer from the Bluetooth devices list. Make sure your computer and phone is paired. Also to get the barcode as input set the action setting in TWedge to Keyboard Wedge. This will allow for you to first click the input text box on said form, then scan said product with your phone and wait a sec for the barcode number to be put into the text box. Using this method requires no php that doesn't already exist in your current form processing, just process the text box as usual and viola your phone scans bar codes, sends them to your pc via Bluetooth wirelessly, your computer inserts the barcode into whatever text field is selected in any application or website. Hope this helps.
All depends on the app you're trying to build. Use Window
s if you're building a dialog based app. Use Page
s if you're building a navigation based app. UserControl
s will be useful regardless of the direction you go as you can use them in both Windows and Pages.
A good place to start exploring is here: http://windowsclient.net/learn
You could encode the binary data using base64 and put it into a Base64 element; the below article is a pretty good one on the subject.
Yes of course you can write a text on canvas with ease, and you can set the font name, font size and font color. There are two method to build a text on Canvas, i.e. fillText() and strokeText(). fillText() method is used to make a text that can only be filled with color, whereas strokeText() is used to make a text that can only be given an outline color. So if we want to build a text that filled with color and have outline color, we must use both of them.
here the full example, how to write text on canvas :
<canvas id="Canvas01" width="400" height="200" style="border:2px solid #bbb; margin-left:10px; margin-top:10px;"></canvas>
<script>
var canvas = document.getElementById('Canvas01');
var ctx = canvas.getContext('2d');
ctx.fillStyle= "red";
ctx.font = "italic bold 35pt Tahoma";
//syntax : .fillText("text", x, y)
ctx.fillText("StacOverFlow",30,80);
</script>
Here the demo for this, and you can try your self for any modification: http://okeschool.com/examples/canvas/html5-canvas-text-color
After establising the connection and executing the query try this:
ResultSet resultSet;
int columnCount = resultSet.getMetaData().getColumnCount();
System.out.println("column count : "+columnCount);
If your local installation is running XAMPP on Windows , That's enough : you can open the file "\xampp\php\php.ini" to activate the php exstension by removing the beginning semicolon at the line ";extension=php_imap.dll". It should be:
;extension=php_imap.dll
to
extension=php_imap.dll
It's difficult to answer this question with the information given. Nothing looks particularly wrong with how you are using HashSet.
Well, I'll hazard a guess that it's not a compilation issue and, when you say "getting errors," you mean "not getting the behavior [you] want."
I'll also go out on a limb and suggest that maybe your Block's equals an hashCode methods are not properly overridden.
There are already answers which are giving light on how to unset. Rather than repeating code in all your classes make function like below and use it in code whenever required. In business logic, sometimes you don't want to expose some properties. Please see below one liner call to remove
public static function removeKeysFromAssociativeArray($associativeArray, $keysToUnset)
{
if (empty($associativeArray) || empty($keysToUnset))
return array();
foreach ($associativeArray as $key => $arr) {
if (!is_array($arr)) {
continue;
}
foreach ($keysToUnset as $keyToUnset) {
if (array_key_exists($keyToUnset, $arr)) {
unset($arr[$keyToUnset]);
}
}
$associativeArray[$key] = $arr;
}
return $associativeArray;
}
Call like:
removeKeysFromAssociativeArray($arrValues, $keysToRemove);
As @weichsel stated, CGFloat is just a typedef for either float
or double
. You can see for yourself by Command-double-clicking on "CGFloat" in Xcode — it will jump to the CGBase.h header where the typedef is defined. The same approach is used for NSInteger and NSUInteger as well.
These types were introduced to make it easier to write code that works on both 32-bit and 64-bit without modification. However, if all you need is float
precision within your own code, you can still use float
if you like — it will reduce your memory footprint somewhat. Same goes for integer values.
I suggest you invest the modest time required to make your app 64-bit clean and try running it as such, since most Macs now have 64-bit CPUs and Snow Leopard is fully 64-bit, including the kernel and user applications. Apple's 64-bit Transition Guide for Cocoa is a useful resource.
Check out the HTML5 PDF viewer:
Convert ArrayList to JsonArray : Like these [{"title":"value1"}, {"title":"value2"}]
Example below :
Model class having one param title and override toString method
class Model(
var title: String,
var id: Int = -1
){
override fun toString(): String {
return "{\"title\":\"$title\"}"
}
}
create List of model class and print toString
var list: ArrayList<Model>()
list.add("value1")
list.add("value2")
Log.d(TAG, list.toString())
and Here is your output
[{"title":"value1"}, {"title":"value2"}]
I wish I still had a link to the source that lead me in this direction, but this is the code that ended up working for me. By looking over the JavaDoc for X509TrustManager it looks like the way the TrustManager
s work is by returning nothing on successful validation, otherwise throwing an exception. Thus, with a null implementation, it is treated as a successful validation. Then you remove all other implementations.
import javax.net.ssl.*;
import java.security.*;
import java.security.cert.X509Certificate;
public final class SSLUtil{
private static final TrustManager[] UNQUESTIONING_TRUST_MANAGER = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers(){
return null;
}
public void checkClientTrusted( X509Certificate[] certs, String authType ){}
public void checkServerTrusted( X509Certificate[] certs, String authType ){}
}
};
public static void turnOffSslChecking() throws NoSuchAlgorithmException, KeyManagementException {
// Install the all-trusting trust manager
final SSLContext sc = SSLContext.getInstance("SSL");
sc.init( null, UNQUESTIONING_TRUST_MANAGER, null );
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
public static void turnOnSslChecking() throws KeyManagementException, NoSuchAlgorithmException {
// Return it to the initial state (discovered by reflection, now hardcoded)
SSLContext.getInstance("SSL").init( null, null, null );
}
private SSLUtil(){
throw new UnsupportedOperationException( "Do not instantiate libraries.");
}
}
Thanks to CSS3 there is a solution !
The solution is to put the image as background-image
and then set the background-size
to contain
.
HTML
<div class='bounding-box'>
</div>
CSS
.bounding-box {
background-image: url(...);
background-repeat: no-repeat;
background-size: contain;
}
Test it here: http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size&preval=contain
Full compatibility with latest browsers: http://caniuse.com/background-img-opts
To align the div in the center, you can use this variation:
.bounding-box {
background-image: url(...);
background-size: contain;
position: absolute;
background-position: center;
background-repeat: no-repeat;
height: 100%;
width: 100%;
}
Reason is the old database credentials are cached /bootstap/cache/config.php
In the .env file, I modified it as follow
DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
Then removed that file
/bootstap/cache/config.php
If the issue still there you might try the following.
php artisan config:clear php artisan cache:clear php artisan config:cache
Exit vagrant by writing the exit
command
Then restart vargarnt/homestead config
vagrant reload --provision
Then opened vagrant again
Vagrant Up
Vagrant ssh
This orders a list vertically without bullet points. In just one line!
li {
display: block;
}
<div id="rr-element">
<label for="rr-1">
<input type="checkbox" value="1" id="rr-1" name="rr[]">
Value 1
</label>
</div>
//do this on the css
div label input { margin-right:100px; }
One option is to declare a default value for 'new_field':
new_field = models.CharField(max_length=140, default='DEFAULT VALUE')
another option is to declare 'new_field' as a nullable field:
new_field = models.CharField(max_length=140, null=True)
If you decide to accept 'new_field' as a nullable field you may want to accept 'no input' as valid input for 'new_field'. Then you have to add the blank=True
statement as well:
new_field = models.CharField(max_length=140, blank=True, null=True)
Even with null=True
and/or blank=True
you can add a default value if necessary:
new_field = models.CharField(max_length=140, default='DEFAULT VALUE', blank=True, null=True)
You can't modify strings; they're immutable. You can do this instead:
txtBox.Text = txtBox.Text.Substring(0, i) + "TEXT" + txtBox.Text.Substring(i);
As explained in short C# (but also for other language compilers as well, like Java)
There is a predefined implicit conversion from short to int, long, float, double, or decimal.
You cannot implicitly convert nonliteral numeric types of larger storage size to short (see Integral Types Table for the storage sizes of integral types). Consider, for example, the following two short variables x and y:
short x = 5, y = 12;
The following assignment statement will produce a compilation error, because the arithmetic expression on the right-hand side of the assignment operator evaluates to int by default.
short z = x + y; // Error: no conversion from int to short
To fix this problem, use a cast:
short z = (short)(x + y); // OK: explicit conversion
It is possible though to use the following statements, where the destination variable has the same storage size or a larger storage size:
int m = x + y;
long n = x + y;
A good follow-up question is:
"why arithmetic expression on the right-hand side of the assignment operator evaluates to int by default" ?
A first answer can be found in:
Classifying and Formally Verifying Integer Constant Folding
The Java language specification defines exactly how integer numbers are represented and how integer arithmetic expressions are to be evaluated. This is an important property of Java as this programming language has been designed to be used in distributed applications on the Internet. A Java program is required to produce the same result independently of the target machine executing it.
In contrast, C (and the majority of widely-used imperative and object-oriented programming languages) is more sloppy and leaves many important characteristics open. The intention behind this inaccurate language specification is clear. The same C programs are supposed to run on a 16-bit, 32-bit, or even 64-bit architecture by instantiating the integer arithmetics of the source programs with the arithmetic operations built-in in the target processor. This leads to much more e?cient code because it can use the available machine operations directly. As long as the integer computations deal only with numbers being “sufficiently small”, no inconsistencies will arise.
In this sense, the C integer arithmetic is a placeholder which is not defined exactly by the programming language specification but is only completely instantiated by determining the target machine.
Java precisely defines how integers are represented and how integer arithmetic is to be computed.
Java Integers
--------------------------
Signed | Unsigned
--------------------------
long (64-bit) |
int (32-bit) |
short (16-bit) | char (16-bit)
byte (8-bit) |
Char is the only unsigned integer type. Its values represent Unicode characters, from
\u0000
to\uffff
, i.e. from 0 to 216-1.If an integer operator has an operand of type long, then the other operand is also converted to type long. Otherwise the operation is performed on operands of type int, if necessary shorter operands are converted into int. The conversion rules are exactly specified.
[From Electronic Notes in Theoretical Computer Science 82 No. 2 (2003)
Blesner-Blech-COCV 2003: Sabine GLESNER, Jan Olaf BLECH,
Fakultät für Informatik,
Universität Karlsruhe
Karlsruhe, Germany]
If you want to use strings of the numbers better take another list as shown in my code it will work fine.
list1=["1","10","3","22","23","4","2","200"]
k=[]
for item in list1:
k.append(int(item))
k.sort()
print(k)
# [1, 2, 3, 4, 10, 22, 23, 200]
None of the solutions out there worked for me. What I eventually discovered was the following combination:
Apparently, it was this last option that was causing the issue. I discovered this by trying to open the web service URL directly in Internet Explorer. It just hung indefinitely trying to load the page. Disabling "Accept client certificates" allowed the page to load normally. I am not sure if it was a problem with this specific system (maybe a glitched client certificate?) Since I wasn't using client certificates this option worked for me.
In theory, malloc gets memory from the operating system for this application. However, since you may only want 4 bytes, and the OS needs to work in pages (often 4k), malloc does a little more than that. It takes a page, and puts it's own information in there so it can keep track of what you have allocated and freed from that page.
When you allocate 4 bytes, for instance, malloc gives you a pointer to 4 bytes. What you may not realize is that the memory 8-12 bytes before your 4 bytes is being used by malloc to make a chain of all the memory you have allocated. When you call free, it takes your pointer, backs up to where it's data is, and operates on that.
When you free memory, malloc takes that memory block off the chain... and may or may not return that memory to the operating system. If it does, than accessing that memory will probably fail, as the OS will take away your permissions to access that location. If malloc keeps the memory ( because it has other things allocated in that page, or for some optimization ), then the access will happen to work. It's still wrong, but it might work.
DISCLAIMER: What I described is a common implementation of malloc, but by no means the only possible one.
In case someone is using php7 under a Linux environment
Make sure you enable php7
sudo a2enmod php7
Restart the mysql service and Apache
sudo systemctl restart mysql
sudo systemctl restart apache2
An easy solution, if you've got ES6, uses Set:
function checkIfArrayIsUnique(myArray) {_x000D_
return myArray.length === new Set(myArray).size;_x000D_
}_x000D_
_x000D_
let uniqueArray = [1, 2, 3, 4, 5];_x000D_
console.log(`${uniqueArray} is unique : ${checkIfArrayIsUnique(uniqueArray)}`);_x000D_
_x000D_
let nonUniqueArray = [1, 1, 2, 3, 4, 5];_x000D_
console.log(`${nonUniqueArray} is unique : ${checkIfArrayIsUnique(nonUniqueArray)}`);
_x000D_
in coffeescript:
b = (a.splice(0, len) while a.length)
demo
a = [1, 2, 3, 4, 5, 6, 7]
b = (a.splice(0, 2) while a.length)
[ [ 1, 2 ],
[ 3, 4 ],
[ 5, 6 ],
[ 7 ] ]
Try / \([\s\S]*?\)/g
Where
(space) matches the character
(space) literally
\(
matches the character (
literally
[\s\S]
matches any character (\s
matches any whitespace character and \S
matches any non-whitespace character)
*?
matches between zero and unlimited times
\)
matches the character )
literally
g
matches globally
Code Example:
var str = "Hello, this is Mike (example)";
str = str.replace(/ \([\s\S]*?\)/g, '');
console.log(str);
_x000D_
.as-console-wrapper {top: 0}
_x000D_
If you grab the MVC Futures assembly (which I would highly recommend) you can then use a generic when creating the ActionLink and a lambda to construct the route:
<%=Html.ActionLink<Product>(c => c.Action( o.Value ), "Details" ) %>
You can get the futures assembly here: http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24471
Here is what worked for me:
const fsp = require('fs-promise');
(async () => {
try {
const names = await fsp.readdir('path/to/dir');
console.log(names[0]);
} catch (e) {
console.log('error: ', e);
}
})();
This code works in node 7.6 without babel when harmony flag is enabled: node --harmony my-script.js
. And starting with node 7.7, you don't even need this flag!
The fsp
library included in the beginning is just a promisified wrapper for fs
(and fs-ext
).
I’m really exited about what you can do in node without babel these days! Native async
/await
make writing code such a pleasure!
UPDATE 2017-06: fs-promise module was deprecated. Use fs-extra
instead with the same API.
Like the previous replies, I'm also suggesting xcopy
. However, I would like to add to Hallgeir Engen's answer with the /exclude
parameter. There seems to be a bug with the parameter preventing it from working with path names that are long or that contain spaces, as quotes will not work. The path names need to be in the "DOS"-format with "Documents" translating to "DOCUME~1" (according to this source).
So, if you want to use the \exclude parameter, there is a workaround here:
cd $(SolutionDir)
xcopy "source-relative-to-path-above" "destination-relative-to-path-above
/exclude:exclude-file-relative-path
Note that the source and destination paths can (and should, if they contain spaces) be within quotes, but not the path to the exclude file.
From a controller or view - use the following to display the version:
<?php
echo CI_VERSION;
?>
Another example to output date and time using zero as a fill character on instances of single digit values: 2017-06-04 18:13:02
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
int main()
{
time_t t = time(0); // Get time now
struct tm * now = localtime(&t);
cout.fill('0');
cout << (now->tm_year + 1900) << '-'
<< setw(2) << (now->tm_mon + 1) << '-'
<< setw(2) << now->tm_mday << ' '
<< setw(2) << now->tm_hour << ':'
<< setw(2) << now->tm_min << ':'
<< setw(2) << now->tm_sec
<< endl;
return 0;
}
In the “Subclass of” field, select UITableViewController.
The class title changes to xxxxTableViewController. Leave that as is.
Make sure the “Also create XIB file” option is selected.
You have a misplaced closing brace before the return
statement.
Is there any reason for a class declaration to inherit from
object
?
In Python 3, apart from compatibility between Python 2 and 3, no reason. In Python 2, many reasons.
In Python 2.x (from 2.2 onwards) there's two styles of classes depending on the presence or absence of object
as a base-class:
"classic" style classes: they don't have object
as a base class:
>>> class ClassicSpam: # no base class
... pass
>>> ClassicSpam.__bases__
()
"new" style classes: they have, directly or indirectly (e.g inherit from a built-in type), object
as a base class:
>>> class NewSpam(object): # directly inherit from object
... pass
>>> NewSpam.__bases__
(<type 'object'>,)
>>> class IntSpam(int): # indirectly inherit from object...
... pass
>>> IntSpam.__bases__
(<type 'int'>,)
>>> IntSpam.__bases__[0].__bases__ # ... because int inherits from object
(<type 'object'>,)
Without a doubt, when writing a class you'll always want to go for new-style classes. The perks of doing so are numerous, to list some of them:
Support for descriptors. Specifically, the following constructs are made possible with descriptors:
classmethod
: A method that receives the class as an implicit argument instead of the instance.staticmethod
: A method that does not receive the implicit argument self
as a first argument.property
: Create functions for managing the getting, setting and deleting of an attribute. __slots__
: Saves memory consumptions of a class and also results in faster attribute access. Of course, it does impose limitations.The __new__
static method: lets you customize how new class instances are created.
Method resolution order (MRO): in what order the base classes of a class will be searched when trying to resolve which method to call.
Related to MRO, super
calls. Also see, super()
considered super.
If you don't inherit from object
, forget these. A more exhaustive description of the previous bullet points along with other perks of "new" style classes can be found here.
One of the downsides of new-style classes is that the class itself is more memory demanding. Unless you're creating many class objects, though, I doubt this would be an issue and it's a negative sinking in a sea of positives.
In Python 3, things are simplified. Only new-style classes exist (referred to plainly as classes) so, the only difference in adding object
is requiring you to type in 8 more characters. This:
class ClassicSpam:
pass
is completely equivalent (apart from their name :-) to this:
class NewSpam(object):
pass
and to this:
class Spam():
pass
All have object
in their __bases__
.
>>> [object in cls.__bases__ for cls in {Spam, NewSpam, ClassicSpam}]
[True, True, True]
In Python 2: always inherit from object
explicitly. Get the perks.
In Python 3: inherit from object
if you are writing code that tries to be Python agnostic, that is, it needs to work both in Python 2 and in Python 3. Otherwise don't, it really makes no difference since Python inserts it for you behind the scenes.
Some things of top of my head.
Method 1.
Application.Union(Range("a1"), Range("b1"), Range("d1"), Range("e1"), Range("g1"), Range("h1")).EntireColumn.Select
Method 2.
Range("a1,b1,d1,e1,g1,h1").EntireColumn.Select
Method 3.
Application.Union(Columns("a"), Columns("b"), Columns("d"), Columns("e"), Columns("g"), Columns("h")).Select
I've seen projects implemented using a number of different approaches, each have their merits and drawbacks.
I'd say the resource method you've chosen makes a lot of sense. It would be interesting to see other people's answers too as I often wonder if there's a better way of doing things like this. I've seen numerous resources that all point to the using resources method, including one right here on SO.
In iOS 8.0 and above it can be done by setting the property modalPresentationStyle to UIModalPresentationOverCurrentContext
//Set property **definesPresentationContext** YES to avoid presenting over presenting-viewController's navigation bar
self.definesPresentationContext = YES; //self is presenting view controller
presentedController.view.backgroundColor = [YOUR_COLOR with alpha OR clearColor]
presentedController.modalPresentationStyle = UIModalPresentationOverCurrentContext;
[self presentViewController:presentedController animated:YES completion:nil];
Add the following line to .git/info/exclude:
Hello.class
The accepted answer will also list the files that exist in both directories, but have different content. To list ONLY the files that exist in dir1 you can use:
diff -r dir1 dir2 | grep 'Only in' | grep dir1 | awk '{print $4}' > difference1.txt
Explanation:
You can't cast a base object to a derived type - it isn't of that type.
If you have a base type pointer to a derived object, then you can cast that pointer around using dynamic_cast. For instance:
DerivedType D;
BaseType B;
BaseType *B_ptr=&B
BaseType *D_ptr=&D;// get a base pointer to derived type
DerivedType *derived_ptr1=dynamic_cast<DerivedType*>(D_ptr);// works fine
DerivedType *derived_ptr2=dynamic_cast<DerivedType*>(B_ptr);// returns NULL
If it is just single column to delete the below syntax works
ALTER TABLE tablename DROP COLUMN column1;
For deleting multiple columns, using the DROP COLUMN
doesnot work, the below syntax works
ALTER TABLE tablename DROP (column1, column2, column3......);
Works particularly great for Google Earth Studio images:
ffmpeg -framerate 24 -i Project%03d.png Project.mp4
along with answer of this link
https://stackoverflow.com/a/19844531/6767365
rename these files. I renamed my project to MvcMovie and it works fine
The answer would slightly tilt towards quicksort w.r.t to changes brought with DualPivotQuickSort for primitive values . It is used in JAVA 7 to sort in java.util.Arrays
It is proved that for the Dual-Pivot Quicksort the average number of
comparisons is 2*n*ln(n), the average number of swaps is 0.8*n*ln(n),
whereas classical Quicksort algorithm has 2*n*ln(n) and 1*n*ln(n)
respectively. Full mathematical proof see in attached proof.txt
and proof_add.txt files. Theoretical results are also confirmed
by experimental counting of the operations.
You can find the JAVA7 implmentation here - http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/util/Arrays.java
Further Awesome Reading on DualPivotQuickSort - http://permalink.gmane.org/gmane.comp.java.openjdk.core-libs.devel/2628
If you set the editable div style to "display:inline-block; white-space: pre-wrap" you don't get new child divs when you enter a new line, you just get LF character (i.e. 
);.
function showCursPos(){
selection = document.getSelection();
childOffset = selection.focusOffset;
const range = document.createRange();
eDiv = document.getElementById("eDiv");
range.setStart(eDiv, 0);
range.setEnd(selection.focusNode, childOffset);
var sHtml = range.toString();
p = sHtml.length;
sHtml=sHtml.replace(/(\r)/gm, "\\r");
sHtml=sHtml.replace(/(\n)/gm, "\\n");
document.getElementById("caretPosHtml").value=p;
document.getElementById("exHtml").value=sHtml;
}
_x000D_
click/type in div below:
<br>
<div contenteditable name="eDiv" id="eDiv"
onkeyup="showCursPos()" onclick="showCursPos()"
style="width: 10em; border: 1px solid; display:inline-block; white-space: pre-wrap; "
>123 456 789</div>
<p>
html caret position:<br> <input type="text" id="caretPosHtml">
<p>
html from start of div:<br> <input type="text" id="exHtml">
_x000D_
What I noticed was when you press "enter" in the editable div, it creates a new node, so the focusOffset resets to zero. This is why I've had to add a range variable, and extend it from the child nodes' focusOffset back to the start of eDiv (and thus capturing all text in-between).
This is my solution to create a fullscreen div, using pure css. It displays a full screen div that is persistent on scrolling. And if the page content fits on the screen, the page won't show a scroll-bar.
Tested in IE9+, Firefox 13+, Chrome 21+
<!doctype html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title> Fullscreen Div </title>_x000D_
<style>_x000D_
.overlay {_x000D_
position: fixed;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
left: 0;_x000D_
top: 0;_x000D_
background: rgba(51,51,51,0.7);_x000D_
z-index: 10;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div class='overlay'>Selectable text</div>_x000D_
<p> This paragraph is located below the overlay, and cannot be selected because of that :)</p>_x000D_
</body>_x000D_
</html>
_x000D_
ng-model
and ng-checked
directives should not be used togetherFrom the Docs:
ngChecked
Sets the checked attribute on the element, if the expression inside
ngChecked
is truthy.Note that this directive should not be used together with
ngModel
, as this can lead to unexpected behavior.
Instead set the desired initial value from the controller:
<input type="checkbox" name="test" ng-model="testModel['item1']" ?n?g?-?c?h?e?c?k?e?d?=?"?t?r?u?e?"? />
Testing<br />
<input type="checkbox" name="test" ng-model="testModel['item2']" /> Testing 2<br />
<input type="checkbox" name="test" ng-model="testModel['item3']" /> Testing 3<br />
<input type="button" ng-click="submit()" value="Submit" />
$scope.testModel = { item1: true };
The other answers all recommend to use AddRange with an IList.
A more elegant solution that avoids the casting is to implement an extension to IList to do the job.
In VB.NET:
<Extension()>
Public Sub AddRange(Of T)(ByRef Exttype As IList(Of T), ElementsToAdd As IEnumerable(Of T))
For Each ele In ElementsToAdd
Exttype.Add(ele)
Next
End Sub
And in C#:
public void AddRange<T>(this ref IList<T> Exttype, IEnumerable<T> ElementsToAdd)
{
foreach (var ele in ElementsToAdd)
{
Exttype.Add(ele);
}
}
Here's an example:
public class Main {
public static void main(String[] args) {
double val1 = 100;
double val2 = 10;
char operation = 'd';
double result = 0;
switch (operation) {
case 'a':
result = val1 + val2; break;
case 's':
result = val1 - val2; break;
case 'd':
if (val2 != 0)
result = val1 / val2; break;
case 'm':
result = val1 * val2; break;
default: System.out.println("Not a defined operation");
}
System.out.println(result);
}
}
If you have the file descriptor fstat()
returns a stat structure which contain the file size.
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
// fd = fileno(f); //if you have a stream (e.g. from fopen), not a file descriptor.
struct stat buf;
fstat(fd, &buf);
off_t size = buf.st_size;
This is typical programming practice for defining variables that are member variables. So when you're using them later, you don't need to see where they're defined to know their scope. This is also great if you already know the scope and you're using something like intelliSense, you can start with m_
and a list of all your member variables are shown. Part of Hungarian notation, see the part about scope in the examples here.
So now assume the Customer wants to change his name in the webui - then there will be some controller action, where there will be the updated DTO with the old ID and the new name.
Normally, you have the following workflow:
P.S. This operation will inevitably issue 2 queries: select and update. Again, 2 queries, even if you wanna update a single field. However, if you utilize Hibernate's proprietary @DynamicUpdate annotation on top of entity class, it will help you not to include into update statement all the fields, but only those that actually changed.
P.S. If you do not wanna pay for first select statement and prefer to use Spring Data's @Modifying query, be prepared to lose L2C cache region related to modifiable entity; even worse situation with native update queries (see this thread) and also of course be prepared to write those queries manually, test them and support them in the future.
For Sublime Text Editor
Indentation Error generally occurs when the code contains a mix of both tabs and spaces for indentation. I have got a very nice solution to correct it, just open your code in a sublime text editor and find 'Tab Size'
in the bottom right corner of Sublime Text Editor and click it. Now select either
'Convert Indentation to Spaces'
OR
'Convert Indentation to Tabs'
Your code will work in either case.
Additionally, if you want Sublime text to do it automatically for you for every code you can update the Preference settings as below:-
Sublime Text menu > Preferences > Settings - Syntax Specific :
Python.sublime-settings
{
"tab_size": 4,
"translate_tabs_to_spaces": true
}
I used ng-click
directive to call a function, while requesting route templateUrl, to decide which <div>
has to be show
or hide
inside route templateUrl page or for different scenarios.
AngularJS 1.6.9
Lets see an example, when in routing page, I need either the add <div>
or the edit <div>
, which I control using the parent controller models $scope.addProduct
and $scope.editProduct
boolean.
RoutingTesting.html
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<title>Testing</title>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-route.min.js"></script>_x000D_
<script>_x000D_
var app = angular.module("MyApp", ["ngRoute"]);_x000D_
_x000D_
app.config(function($routeProvider){_x000D_
$routeProvider_x000D_
.when("/TestingPage", {_x000D_
templateUrl: "TestingPage.html"_x000D_
});_x000D_
});_x000D_
_x000D_
app.controller("HomeController", function($scope, $location){_x000D_
_x000D_
$scope.init = function(){_x000D_
$scope.addProduct = false;_x000D_
$scope.editProduct = false;_x000D_
}_x000D_
_x000D_
$scope.productOperation = function(operationType, productId){_x000D_
$scope.addProduct = false;_x000D_
$scope.editProduct = false;_x000D_
_x000D_
if(operationType === "add"){_x000D_
$scope.addProduct = true;_x000D_
console.log("Add productOperation requested...");_x000D_
}else if(operationType === "edit"){_x000D_
$scope.editProduct = true;_x000D_
console.log("Edit productOperation requested : " + productId);_x000D_
}_x000D_
_x000D_
//*************** VERY IMPORTANT NOTE ***************_x000D_
//comment this $location.path("..."); line, when using <a> anchor tags,_x000D_
//only useful when <a> below given are commented, and using <input> controls_x000D_
$location.path("TestingPage");_x000D_
};_x000D_
_x000D_
});_x000D_
</script>_x000D_
</head>_x000D_
<body ng-app="MyApp" ng-controller="HomeController">_x000D_
_x000D_
<div ng-init="init()">_x000D_
_x000D_
<!-- Either use <a>anchor tag or input type=button -->_x000D_
_x000D_
<!--<a href="#!TestingPage" ng-click="productOperation('add', -1)">Add Product</a>-->_x000D_
<!--<br><br>-->_x000D_
<!--<a href="#!TestingPage" ng-click="productOperation('edit', 10)">Edit Product</a>-->_x000D_
_x000D_
<input type="button" ng-click="productOperation('add', -1)" value="Add Product"/>_x000D_
<br><br>_x000D_
<input type="button" ng-click="productOperation('edit', 10)" value="Edit Product"/>_x000D_
<pre>addProduct : {{addProduct}}</pre>_x000D_
<pre>editProduct : {{editProduct}}</pre>_x000D_
<ng-view></ng-view>_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
TestingPage.html
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<title>Title</title>_x000D_
<style>_x000D_
.productOperation{_x000D_
position:fixed;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
width:30em;_x000D_
height:18em;_x000D_
margin-left: -15em; /*set to a negative number 1/2 of your width*/_x000D_
margin-top: -9em; /*set to a negative number 1/2 of your height*/_x000D_
border: 1px solid #ccc;_x000D_
background: yellow;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="productOperation" >_x000D_
_x000D_
<div ng-show="addProduct">_x000D_
<h2 >Add Product enabled</h2>_x000D_
</div>_x000D_
_x000D_
<div ng-show="editProduct">_x000D_
<h2>Edit Product enabled</h2>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
both pages -
RoutingTesting.html
(parent), TestingPage.html
(routing page) are in the same directory,
Hope this will help someone.
For .htaccess rewrite: http://learn.iis.net/page.aspx/557/translate-htaccess-content-to-iis-webconfig/
Or try aping .htaccess: http://www.helicontech.com/ape/
To stop the user from getting annoyed when the whole text gets selected every time they try to move the caret using their mouse, you should do this using the focus
event, not the click
event. The following will do the job and works around a problem in Chrome that prevents the simplest version (i.e. just calling the textarea's select()
method in a focus
event handler) from working.
jsFiddle: http://jsfiddle.net/NM62A/
Code:
<textarea id="foo">Some text</textarea>
<script type="text/javascript">
var textBox = document.getElementById("foo");
textBox.onfocus = function() {
textBox.select();
// Work around Chrome's little problem
textBox.onmouseup = function() {
// Prevent further mouseup intervention
textBox.onmouseup = null;
return false;
};
};
</script>
jQuery version:
$("#foo").focus(function() {
var $this = $(this);
$this.select();
// Work around Chrome's little problem
$this.mouseup(function() {
// Prevent further mouseup intervention
$this.unbind("mouseup");
return false;
});
});
You can change the database name using MySQL interface.
Go to http://www.hostname.com/phpmyadmin
Go to database which you want to rename. Next, go to the operation tab. There you will find the input field to rename the database.
Use datetime.timetuple()
to convert your datetime
object to a time.struct_time
object then get its tm_yday
property:
from datetime import datetime
day_of_year = datetime.now().timetuple().tm_yday # returns 1 for January 1st
Recursively delete all children of the file ...
public static void DeleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory()) {
for (File child : fileOrDirectory.listFiles()) {
DeleteRecursive(child);
}
}
fileOrDirectory.delete();
}
In most of the general cases 'Length' and 'Count' are used.
Array:
int[] myArray = new int[size];
int noOfElements = myArray.Length;
Typed List Array:
List <int> myArray = new List<int>();
int noOfElements = myArray.Count;
In order to represent a single digit in the form of a regular expression you can use either:
[0-9] or \d
In order to specify how many times the number appears you would add
[0-9]*: the star means there are zero or more digits
[0-9]{2}: {N} means N digits
[0-9]{0,2}: {N,M} N digits or M digits
[0-9]{0-9}: {N-M} N digits to M digits. Note: M can be left blank for an infinite representation
Lets say I want to represent a number between 1 and 99 I would express it as such:
[0-9]{1-2} or [0-9]{1,2} or \d{1-2} or \d{1,2}
Or lets say we were working with binary display, displaying a byte size, we would want our digits to be between 0 and 1 and length of a byte size, 8, so we would represent it as follows:
[0-1]{8} representation of a binary byte
Then if you want to add a , or a . symbol you would use:
\, or \. or you can use [.] or [,]
You can also state a selection between possible values as such
[.,] means either a dot or a comma symbol
And you just need to concatenate the pieces together, so in the case where you want to represent a 1 or 2 digit number followed by either a comma or a period and followed by two more digits you would express it as follows: >
[0-9]{1,2}[.,]\d{1-2}
Also note that regular expression strings inside C++ strings must be double-back-slashed so every \ becomes \\
At first glance, your code will not compile. Since the nested if statement doesn't have any braces, it will consider the next line the code that it should execute. Also, you are comparing a char against a String, " ". Try comparing the values as chars instead. I think the correct syntax would be:
if(c == ' '){
//do something here
}
But then again, I am not familiar with the "Equal"
class
Once you declare the type of a variable, you don't need to cast it to that same type. So you can write a=&b;
. Finally, you declared c
incorrectly. Since you assign it to be the address of a
, where a
is a pointer to int
, you must declare it to be a pointer to a pointer to int
.
#include <stdio.h>
int main(void)
{
int b=10;
int *a=&b;
int **c=&a;
printf("%d", **c);
return 0;
}
For those trying to get everything after the first occurance:
Something like "Nic K Cage"
to "K Cage"
.
You can use slice to get everything from a certain character. In this case from the first space:
const delim = " "
const name = "Nic K Cage"
const end = name.split(delim).slice(1).join(delim) // prints: "K Cage"
Or if OP's string had two hyphens:
const text = "sometext-20202-03"
// Option 1
const op1 = text.slice(text.indexOf('-')).slice(1) // prints: 20202-03
// Option 2
const op2 = text.split('-').slice(1).join("-") // prints: 20202-03
Indeed, use onclick="this.select();"
but remember not to combine it with disabled="disabled"
- it will not work then and you will need to manually select or multi-click to select, still. If you wish to lock the content value to be selected, combine with the attribute readonly
.
It bothered me too much while updating node version from 8.1.0 to 10.14.0
Here is what worked for me:
Open terminal (Ctrl+Alt+T).
Type which node
, which will give a path something like /usr/local/bin/node
Run the command sudo rm /usr/local/bin/node
to remove the binary (adjust the path according to what you found in step 2). Now node -v
shows you have no node version
Download a script and run it to set up the environment:
curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
Install using sudo apt-get install nodejs
Note: If you are getting error like
node /usr/bin/env: node: No such file or directory
just run
ln -s /usr/bin/nodejs /usr/bin/node
Now node -v
will give v10.14.0
Worked for me.
You should find the 'expect' command will do what you need it to do. Its widely available. See here for an example : http://www.thegeekstuff.com/2010/10/expect-examples/
(very rough example)
#!/usr/bin/expect
set pass "mysecret"
spawn /usr/bin/passwd
expect "password: "
send "$pass"
expect "password: "
send "$pass"
open the "edit the system environment variables". then click on "environment variables".
Under "User variables" click on "Path" then "Edit".
Find your Java path and click "Edit".
then paste the path of your java installation folder. Mostly you can find it on a path similar to this. C:\Program Files\Java\jdk-12.0.2\bin
Then click OK. now in the start menu, type cmd. open the command prompt. type java -version If you did it right,it should show something like this.
Try following Steps for Apache
Go to Windows Services by typing Window + R, then typing services.msc
Enter a new service name as Apache2
(or similar)
Repeat the steps for the MySQL service
No, grep works just fine for this:
grep -rl "filename" [starting point]
grep -rL "not in filename"
Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.
-
is the 'binary operator' your error is referencing, and either CurrentDay
or MA
(or both) are non-numeric.
A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). +
is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).
R only knows how to apply +
(and other binary operators, such as -
) to numeric arguments:
> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator
When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.
EDIT:
Your error lies in the use of [
instead of [[
. Because Day
is a list, subsetting with [
will return a list, not a numeric vector. [[
, however, returns an object of the class of the item contained in the list:
> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator
> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3
Transaction
, as you've defined it, returns a list of two vectors. Above, Day
is a list contain one vector. Day2
, however, is simply a vector.
Doesn't have to be; "64-bit machine" can mean many things, but typically means that the CPU has registers that big. The sizeof a type is determined by the compiler, which doesn't have to have anything to do with the actual hardware (though it typically does); in fact, different compilers on the same machine can have different values for these.
Parameters are key-value pairs that can appear inside URL path, and start with a semicolon character (;
).
Query string appears after the path (if any) and starts with a question mark character (?
).
Both parameters and query string contain key-value pairs.
In a GET
request, parameters appear in the URL itself:
<scheme>://<username>:<password>@<host>:<port>/<path>;<parameters>?<query>#<fragment>
In a POST
request, parameters can appear in the URL itself, but also in the datastream (as known as content).
Query string is always a part of the URL.
Parameters can be buried in form-data
datastream when using POST method so they may not appear in the URL. Yes a POST
request can define parameters as form data and in the URL, and this is not inconsistent because parameters can have several values.
I've found no explaination for this behavior so far. I guess it might be useful sometimes to "unhide" parameters from a POST
request, or even let the code handling a GET
request share some parts with the code handling a POST
. Of course this can work only with server code supporting parameters in a URL.
Until you get better insights, I suggest you to use parameters only in form-data
datastream of POST
requests.
Sources:
I don't know if the answer will be late, but I have used this form.
JS:
function getPDF() {
html2canvas(document.getElementById("toPDF"),{
onrendered:function(canvas){
var img=canvas.toDataURL("image/png");
var doc = new jsPDF('l', 'cm');
doc.addImage(img,'PNG',2,2);
doc.save('reporte.pdf');
}
});
}
HTML:
<div id="toPDF">
#your content...
</div>
<button id="getPDF" type="button" class="btn btn-info" onclick="getPDF()">
Download PDF
</button>
If you want to sort by report key, then student number, then school, you should do something like this:
public class ReportComparator implements Comparator<Report>
{
public int compare(Report r1, Report r2)
{
int result = r1.getReportKey().compareTo(r2.getReportKey());
if (result != 0)
{
return result;
}
result = r1.getStudentNumber().compareTo(r2.getStudentNumber());
if (result != 0)
{
return result;
}
return r1.getSchool().compareTo(r2.getSchool());
}
}
This assumes none of the values can be null, of course - it gets more complicated if you need to allow for null values for the report, report key, student number or school.
While you could get the string concatenation version to work using spaces, it would still fail in strange cases if you had odd data which itself included spaces etc. The above code is the logical code you want... compare by report key first, then only bother with the student number if the report keys are the same, etc.
Within Apache Commons, commons-codec-1.7.jar contains a Base64 class which can be used to encode.
Via Maven:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>20041127.091804</version>
</dependency>
In fact in the last answer String strAsciiTab = Character.toString((char) iAsciiValue); the essential part is (char)iAsciiValue which is doing the job (Character.toString useless)
Meaning the first answer was correct actually char ch = (char) yourInt;
if in yourint=49 (or 0x31), ch will be '1'
Well, this is a feature that is only possible because of the language support.
The compiler interprets a[i]
as *(a+i)
and the expression 5[a]
evaluates to *(5+a)
. Since addition is commutative it turns out that both are equal. Hence the expression evaluates to true
.
I had the same issue, couldn't find a right solution so I have manually deleted the component folder and then updated the app.module.ts file (removed the references to the deleted component) and it worked for me.
This is how I solved the problem. Add below code in your AndroidMainfest.xml
<activity android:name=".YourClass"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
</activity>
Using Java 8 - Stream Funtion:
Converting A String into Character List:
ArrayList<Character> characterList = givenStringVariable
.chars()
.mapToObj(c-> (char)c)
.collect(collectors.toList());
Converting A Character List into String:
String givenStringVariable = characterList
.stream()
.map(String::valueOf)
.collect(Collectors.joining())
With current methods available in Linq it looks quite ugly:
var tasks = items.Select(
async item => new
{
Item = item,
IsValid = await IsValid(item)
});
var tuples = await Task.WhenAll(tasks);
var validItems = tuples
.Where(p => p.IsValid)
.Select(p => p.Item)
.ToList();
Hopefully following versions of .NET will come up with more elegant tooling to handle collections of tasks and tasks of collections.
#include"stdio.h"
#include"conio.h"
#include"time.h"
void main()
{
time_t t;
int i;
srand(time(&t));
for(i=1;i<=10;i++)
printf("%c\t",rand()%10);
getch();
}
intent.getAction().equals(SMS_RECEIVED)
I have tried it out successfully.
Never faced this problem before (not worked much on email, I avoid it like the plague) but you could try declaring the bullet with the unicode code point (different notation for CSS than for HTML): content: '\2022'
. (you need to use the hex number, not the 8226 decimal one)
Then, in case you use something that picks up those characters and HTML-encodes them into entities (which won't work for CSS strings), I guess it will ignore that.
http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html
You will find these methods in it:
getValueAt(int row, int column)
getSelectedRow()
getSelectedColumn()
Use a mix of these to achieve your result.
In case you did what the questioner hinted at (forgot to fork and just locally cloned a repo, made changes and now need to issue a pull request) you can get back on track:
You haven't really said much about what sort of random string you need. But in any case, you should look into the random
module.
A very simple solution is pasted below.
import random
def randstring(length=10):
valid_letters='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
return ''.join((random.choice(valid_letters) for i in xrange(length)))
print randstring()
print randstring(20)
Sometimes you need to grep the process by name - in that case:
ps aux | grep simple-scan
Example output:
simple-scan 1090 0.0 0.1 4248 1432 ? S Jun11 0:00
For those who uses last versions of spring boot will help this:
.properties:
spring.jpa.properties.hibernate.default_schema=<name of your schema>
.yml:
spring:
jpa:
properties:
hibernate:
default_schema: <name of your schema>
p=[2,3,4,4,4]
p.clear()
print(p)
[]
Only with Python 3
If you're only interested in the keys, you can iterate through the keySet()
of the map:
Map<String, Object> map = ...;
for (String key : map.keySet()) {
// ...
}
If you only need the values, use values()
:
for (Object value : map.values()) {
// ...
}
Finally, if you want both the key and value, use entrySet()
:
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// ...
}
One caveat: if you want to remove items mid-iteration, you'll need to do so via an Iterator (see karim79's answer). However, changing item values is OK (see Map.Entry
).
Put the following to your .bashrc
shopt -s extglob
It extends regexes. You can then move all files except one by
mv !(fileOne) ~/path/newFolder
Note that, in copying directories, the forward-flash cannot be used in the name as noticed in the thread Why extglob except breaking except condition?:
cp -r !(Backups.backupdb) /home/masi/Documents/
so Backups.backupdb/
is wrong here before the negation and I would not use it neither in moving directories because of the risk of using wrongly then globs with other commands and possible other exceptions.
If you're not afraid of old java-style (non type safe generic) semantics, this also works and is simple'ish:
ArgumentCaptor<List> argument = ArgumentCaptor.forClass(List.class);
verify(subject.method(argument.capture()); // run your code
List<SomeType> list = argument.getValue(); // first captured List, etc.
simply click
'Database'>tables>your table name>keys>copy the constraints like 'PK__TableName__30242045'
and run the below query is :
Query:alter Table 'TableName' drop constraint PK__TableName__30242045
foreach(Foos foo in Enum.GetValues(typeof(Foos)))
If you want to use this in VBA:
For i = 1 To X
UserForm1.Controls("Label" & i).Caption = MySheet.Cells(i + 1, i).Value
Next
I wanted to extend the answers already given to include support for dynamically connected devices that aren't captured with /dev/bus/usb
and how to get this working when using a Windows host along with the boot2docker VM.
If you are working with Windows, you'll need to add any USB rules for devices that you want Docker to access within the VirtualBox manager. To do this you can stop the VM by running:
host:~$ docker-machine stop default
Open the VirtualBox Manager and add USB support with filters as required.
Start the boot2docker VM:
host:~$ docker-machine start default
Since the USB devices are connected to the boot2docker VM, the commands need to be run from that machine. Open up a terminal with the VM and run the docker run command:
host:~$ docker-machine ssh
docker@default:~$ docker run -it --privileged ubuntu bash
Note, when the command is run like this, then only previously connected USB devices will be captures. The volumes flag is only required if you want this to work with devices connected after the container is started. In that case, you can use:
docker@default:~$ docker run -it --privileged -v /dev:/dev ubuntu bash
Note, I had to use /dev
instead of /dev/bus/usb
in some cases to capture a device like /dev/sg2
. I can only assume the same would be true for devices like /dev/ttyACM0
or /dev/ttyUSB0
.
The docker run commands will work with a Linux host as well.
In Notepad++ :
<option value value='1' >A
<option value value='2' >B
<option value value='3' >C
<option value value='4' >D
Find what: (.*)(>)(.)
Replace with: \3
Replace All
A
B
C
D
I think this should work:
#open file for reading
fn = input("Enter file to open: ")
try:
fh = open(fn,'r')
except:
# if file does not exist, create it
fh = open(fn,'w')
Also, you incorrectly wrote fh = open ( fh, "w")
when the file you wanted open was fn
You didn't say what you're trying to do, but you hinted at it well enough in the comments to the other answer. I think you're probably looking for an auto increment column
create table logins (userid int auto_increment primary key,
username varchar(30), password varchar(30));
then no special code is needed on insert. Just
insert into logins (username, password) values ('user','pass');
The MySQL API has functions to tell you what userid was created when you execute this statement in client code.
exit
did it for me.
My results after pressing return;
my-mac:Car Game mymac$ exit
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.
[Process completed]
Use javascript array push()
method,
it adds the given object in the end of the array.
JS Arrays are pretty flexible,you can push as many objects as you wish in an array without specifying its length beforehand. Also,different types of objects can be pushed to the same Array.
You can also use pageMethods in asp.net. So that you can call javascript functions from asp.net functions. E.g.
[WebMethod]_x000D_
public static string showTxtbox(string name)_x000D_
{_x000D_
return showResult(name);_x000D_
}_x000D_
_x000D_
public static string showResult(string name)_x000D_
{_x000D_
Database databaseObj = new Database();_x000D_
DataTable dtObj = databaseObj.getMatches(name);_x000D_
_x000D_
string result = "<table border='1' cellspacing='2' cellpadding='2' >" +_x000D_
"<tr>" +_x000D_
"<td><b>Name</b></td>" +_x000D_
"<td><b>Company Name</b></td>" +_x000D_
"<td><b>Phone</b></td>"+_x000D_
"</tr>";_x000D_
_x000D_
for (int i = 0; i < dtObj.Rows.Count; i++)_x000D_
{_x000D_
result += "<tr> <td><a href=\"javascript:link('" + dtObj.Rows[i][0].ToString().Trim() + "','" +_x000D_
dtObj.Rows[i][1].ToString().Trim() +"','"+dtObj.Rows[i][2]+ "');\">" + Convert.ToString(dtObj.Rows[i]["name"]) + "</td>" +_x000D_
"<td>" + Convert.ToString(dtObj.Rows[i]["customerCompany"]) + "</td>" +_x000D_
"<td>"+Convert.ToString(dtObj.Rows[i]["Phone"])+"</td>"+_x000D_
"</tr>";_x000D_
}_x000D_
_x000D_
result += "</table>";_x000D_
return result;_x000D_
}
_x000D_
Here above code is written in .aspx.cs page. Database is another class. In showResult() function I've called javascript's link() function. Result is displayed in the form of table.
ALT + p works for me on Enthought Python in Windows.
I'm going to leave this one here: https://stackoverflow.com/a/14509697/1356953
Please note that this works with java.lang.SuppressWarnings
so no need to use a separate annotation.
@SuppressWarnings on a field only suppresses findbugs warnings reported for that field declaration, not every warning associated with that field.
For example, this suppresses the "Field only ever set to null" warning:
@SuppressWarnings("UWF_NULL_FIELD") String s = null; I think the best you can do is isolate the code with the warning into the smallest method you can, then suppress the warning on the whole method.
Some cases may be
$('#gate option[value='+data.Gateway2+']').attr('selected', true);
The other solution are OK, but there is no need to add separator at the very last if using :after or at the very beginning if using :before.
SO:
case :after
.link:after {
content: '|';
padding: 0 1rem;
}
.link:last-child:after {
content: '';
}
case :before
.link:before {
content: '|';
padding: 0 1rem;
}
.link:first-child:before {
content: '';
}
You can also face problems if a subdirectory itself is a git repository - ie .has a .git directory - check with ls -a
.
To remove go to the subdirectory and rm .git -rf
.
Using apkanalyzer
that is now part of cmdline-tools
:
$ apkanalyzer manifest version-code my_app.apk
1
$ apkanalyzer manifest version-name my_app.apk
1.2.3.4
var q = from s in db.Serials
group s by s.Serial_Number into g
select new {Serial_Number = g.Key, MaxUid = g.Max(s => s.uid) }
UPDATE - As mentioned in one of the answers below, PM2 has some really nice functionality missing from forever. Consider using it.
Original Answer
Use nohup:
nohup node server.js &
EDIT I wanted to add that the accepted answer is really the way to go. I'm using forever on instances that need to stay up. I like to do npm install -g forever
so it's in the node path and then just do forever start server.js
Apart from creating a custom template file and assigning that template to a page (like in the example in the accepted answer), there is also a way with the template naming convention that WordPress uses for loading templates (template hierarchy).
Create a new page and use the slug of that page for the template filename (create a template file named page-{slug}.php). WordPress will automatically load the template that fits to this rule.
In VB code, when trying to submit an INSERT
query, you must submit a double query in the same 'executenonquery' like this:
sqlQuery = "SET IDENTITY_INSERT dbo.TheTable ON; INSERT INTO dbo.TheTable (Col1, COl2) VALUES (Val1, Val2); SET IDENTITY_INSERT dbo.TheTable OFF;"
I used a ;
separator instead of a GO.
Works for me. Late but efficient!
The easier way to do it is just:
ul li:after {
content: url('../images/small_triangle.png');
}
Following options were elaborated starting from this answer. Same tree for both :
var o = { a: { b: { c: 1 } } };
var u = undefined;
o.a ? o.a.b ? o.a.b.c : u : u // 1
o.x ? o.x.y ? o.x.y.z : u : u // undefined
(o = o.a) ? (o = o.b) ? o.c : u : u // 1
var $ = function (empty) {
return function (node) {
return node || empty;
};
}({});
$($(o.a).b).c // 1
$($(o.x).y).z // undefined
If your context allows it (technical constraints, etc.), use the JsonConvert.SerializeObject
method from Newtonsoft.Json : it will make your life easier.
Dictionary<string, string> localizedWelcomeLabels = new Dictionary<string, string>();
localizedWelcomeLabels.Add("en", "Welcome");
localizedWelcomeLabels.Add("fr", "Bienvenue");
localizedWelcomeLabels.Add("de", "Willkommen");
Console.WriteLine(JsonConvert.SerializeObject(localizedWelcomeLabels));
// Outputs : {"en":"Welcome","fr":"Bienvenue","de":"Willkommen"}