That's the Unicode Replacement Character, \uFFFD. (info)
Something like this should work:
String strImport = "For some reason my ?double quotes? were lost.";
strImport = strImport.replaceAll("\uFFFD", "\"");
Help\Productivity Guide
It tells you what are the shortcuts you use/don't use and displays usage statistics. It will guide you to the unknown features.
I had the same issue when i was creating a MVC application using with master pages. Tried looking for element with 'submit' as names as mentioned above but it wasn't the case.
For my case it created multiple tags on my page so there were some issues referencing the correct form.
To work around this i'll let the button handle which form object to use:
onclick="return SubmitForm(this.form)"
and with the js:
function SubmitForm(frm) {
frm.submit();
}
Check if you are able to connect to eclipse market place url (http://marketplace.eclipse.org/) from browser. If its working then the issue is because of proxy server using in your network. We have to update eclipse with proxy server details used in our network.
Go to :- Windows-> Preference -> General -> Network Connections.
And edit HTTP ,with proxy details.
Click OK
Done.
I just got the solution to this problem from a friend. he said: Add ob_start(); under your session code. You can add exit(); under the header. I tried it and it worked. Hope this helps
This is for those on a rented Hosting sever who do not have access to php.init file.
Make the radio component as dumb component and pass props to from parent.
import React from "react";
const Radiocomponent = ({ value, setGender }) => (
<div onChange={setGender.bind(this)}>
<input type="radio" value="MALE" name="gender" defaultChecked={value ==="MALE"} /> Male
<input type="radio" value="FEMALE" name="gender" defaultChecked={value ==="FEMALE"}/> Female
</div>
);
export default Radiocomponent;
git rev-parse
is an ancillary plumbing
command primarily used for manipulation.
One common usage of git rev-parse
is to print the SHA1 hashes given a revision specifier. In addition, it has various options to format this output such as --short
for printing a shorter unique SHA1.
There are other use cases as well (in scripts and other tools built on top of git) that I've used for:
--verify
to verify that the specified object is a valid git object.--git-dir
for displaying the abs/relative path of the the .git
directory.--is-inside-git-dir
or within a work-tree using --is-inside-work-tree
--is-bare-repository
--branches
), tags (--tags
) and the refs can also be filtered based on the remote (using --remote
)--parse-opt
to normalize arguments in a script (kind of similar to getopt
) and print an output string that can be used with eval
Massage
just implies that it is possible to convert the info from one form into another i.e. a transformation command. These are some quick examples I can think of:
A..B
for git log
or git diff
into the equivalent arguments for the underlying plumbing command as B ^A
Try this:
git add .
git commit -m "your commit message"
git remote add origin *remote repository URL*
git push origin *your-branch-name*
First, generate an Interface
Assuming you are using TypeScript & Angular CLI, you can generate one by using the following command
ng g interface car
After that set the data types of its properties
// car.interface.ts
export interface car {
id: number;
eco: boolean;
wheels: number;
name: string;
}
You can now import your interface in the class that you want.
import {car} from "app/interfaces/car.interface";
And update the collection/array of car objects by pushing items in the array.
this.car.push({
id: 12345,
eco: true,
wheels: 4,
name: 'Tesla Model S',
});
More on interfaces:
An interface is a TypeScript artifact, it is not part of ECMAScript. An interface is a way to define a contract on a function with respect to the arguments and their type. Along with functions, an interface can also be used with a Class as well to define custom types. An interface is an abstract type, it does not contain any code as a class does. It only defines the 'signature' or shape of an API. During transpilation, an interface will not generate any code, it is only used by Typescript for type checking during development. - https://angular-2-training-book.rangle.io/handout/features/interfaces.html
Make sure to target x86 on your project in Visual Studio. This should fix your trouble.
title
is a local variable. They only exists within its scope (current block)
@title
is an instance variable - and is available to all methods within the class.
You can read more here: http://strugglingwithruby.blogspot.dk/2010/03/variables.html
In Ruby on Rails - declaring your variables in your controller as instance variables (@title
) makes them available to your view.
getline
, as it name states, read a whole line, or at least till a delimiter that can be specified.
So the answer is "no", getline
does not match your need.
But you can do something like:
inFile >> first_name >> last_name >> age;
name = first_name + " " + last_name;
It's not good for several reasons:
eval
The simplest thing would be to add a name
attribute to your <a>
element, then you could do:
document.myelement.onclick = function() {
window.popup('/map/', 300, 300, 'map');
return false;
};
although modern best practise would be to use an id
instead of a name, and use addEventListener()
instead of using onclick
since that allows you to bind multiple functions to a single event.
I can attest to the fact that -webkit-transform: translate3d(0, 0, 0);
will mess with the new position: -webkit-sticky;
property. With a left drawer navigation pattern that I was working on, the hardware acceleration I wanted with the transform property was messing with the fixed positioning of my top nav bar. I turned off the transform and the positioning worked fine.
Luckily, I seem to have had hardware acceleration on already, because I had -webkit-font-smoothing: antialiased
on the html element. I was testing this behavior in iOS7 and Android.
You can try something like this :
String variable = ""; #write a string name
StringBuffer rev = new StringBuffer(variable).reverse();
String strRev = rev.toString();
if(variable.equalsIgnoreCase(strRev)) # Check the condition
i was looking for the same problem and stumbled upon the following code.
How to get Client MAC address(Web):
To get the client MAC address only way we can rely on JavaScript and Active X control of Microsoft.It is only work in IE if Active X enable for IE. As the ActiveXObject is not available with the Firefox, its not working with the firefox and is working fine in IE.
This script is for IE only:
function showMacAddress() {_x000D_
var obj = new ActiveXObject("WbemScripting.SWbemLocator");_x000D_
var s = obj.ConnectServer(".");_x000D_
var properties = s.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration");_x000D_
var e = new Enumerator(properties);_x000D_
var output;_x000D_
output = '<table border="0" cellPadding="5px" cellSpacing="1px" bgColor="#CCCCCC">';_x000D_
output = output + '<tr bgColor="#EAEAEA"><td>Caption</td><td>MACAddress</td></tr>';_x000D_
while (!e.atEnd()) {_x000D_
e.moveNext();_x000D_
var p = e.item();_x000D_
if (!p) continue;_x000D_
output = output + '<tr bgColor="#FFFFFF">';_x000D_
output = output + '<td>' + p.Caption; +'</td>';_x000D_
output = output + '<td>' + p.MACAddress + '</td>';_x000D_
output = output + '</tr>';_x000D_
}_x000D_
output = output + '</table>';_x000D_
document.getElementById("box").innerHTML = output;_x000D_
}_x000D_
_x000D_
showMacAddress();
_x000D_
<div id='box'></div>
_x000D_
In my case even though I was using the above options of uninstall and installing using pip the code was still giving me same errors.
Finally, I created a vritual environment and Installed numpy and pandas using pip in my virtual env. Now the code is running.
Steps: for Anaconda3 - Please change according to your installation type: [if you dont have virtual env package installed]
$ pip install virtualenv
[from command prompt go to the directory by c:\anadonda3\scripts
[write the following command to use virtual env to create a virtual env for you in your desired location]
$virtualenv c:\anaconda3\envs\my_virtual_env
[once created you will have to activate your virtual env]
$c:\anaconda3\envs\my_virtual_env\scripts activate
[now pip install numpy and pandas and other required packages using pip]
[once installations are done exit from the virtual env]
$c:\anaconda3\envs\my_virtual_env\scripts deactivate
now use the python.exe inside your virtual env folder to run the script and it will run even with python 3.7.
You could have your controller action take an object which would reflect the form input names and the default model binder will automatically create this object for you:
[HttpPost]
public ActionResult SubmitAction(SomeModel model)
{
var value1 = model.SimpleProp1;
var value2 = model.SimpleProp2;
var value3 = model.ComplexProp1.SimpleProp1;
...
... return something ...
}
Another (obviously uglier) way is:
[HttpPost]
public ActionResult SubmitAction()
{
var value1 = Request["SimpleProp1"];
var value2 = Request["SimpleProp2"];
var value3 = Request["ComplexProp1.SimpleProp1"];
...
... return something ...
}
<gradient android:startColor="#ffdd00"
android:endColor="@color/colorPrimary"
android:centerColor="#ffff" />
<corners android:radius="33dp"/>
<padding
android:bottom="7dp"
android:left="7dp"
android:right="7dp"
android:top="7dp"
/>
Alternatively you could use minio-js client library get-object.js
var Minio = require('minio')
var s3Client = new Minio({
endPoint: 's3.amazonaws.com',
accessKey: 'YOUR-ACCESSKEYID',
secretKey: 'YOUR-SECRETACCESSKEY'
})
var size = 0
// Get a full object.
s3Client.getObject('my-bucketname', 'my-objectname', function(e, dataStream) {
if (e) {
return console.log(e)
}
dataStream.on('data', function(chunk) {
size += chunk.length
})
dataStream.on('end', function() {
console.log("End. Total size = " + size)
})
dataStream.on('error', function(e) {
console.log(e)
})
})
Disclaimer: I work for Minio Its open source, S3 compatible object storage written in golang with client libraries available in Java, Python, Js, golang.
Easy peasy:
var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));
Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings
string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");
Simply we can trace the request message as.
OperationContext context = OperationContext.Current;
if (context != null && context.RequestContext != null)
{
Message msg = context.RequestContext.RequestMessage;
string reqXML = msg.ToString();
}
Check the MySQL Datetime Functions:
Try this:
SELECT *
FROM tableA
WHERE YEAR(columnName) = YEAR(CURRENT_DATE()) AND
MONTH(columnName) = MONTH(CURRENT_DATE());
All functions in Java are virtual by default.
You have to go out of your way to write non-virtual functions by adding the "final" keyword.
This is the opposite of the C++/C# default. Class functions are non-virtual by default; you make them so by adding the "virtual" modifier.
I don't think you can. Your best option might be to encapsulate the thing you want to pass "by ref" onto another class instance, and pass the (outer) class's reference (by value). If you see what I mean...
i.e. your method changes the internal state of the object it is passed, which is then visible to the caller.
With SQL Server 2017 and Visual Studio 2015, I used localhost\SQLEXPRESS
We should always add scrollView.getPaddingBottom()
to match full scrollview height because some time scroll view has padding in xml file so that case its not going to work.
scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
if (scrollView != null) {
View view = scrollView.getChildAt(scrollView.getChildCount()-1);
int diff = (view.getBottom()+scrollView.getPaddingBottom()-(scrollView.getHeight()+scrollView.getScrollY()));
// if diff is zero, then the bottom has been reached
if (diff == 0) {
// do stuff
}
}
}
});
Also make sure to check out how to use Angular includes (using AngularJS). It's pretty straight forward…
<body ng-app="">
<div ng-include="'myFile.htm'"></div>
</body>
Other way :
zeroos="000"
echo
for num in {99..105};do
echo ${zeroos:${#num}:${#zeroos}}${num}
done
So simple function to convert any number would be:
function leading_zero(){
local num=$1
local zeroos=00000
echo ${zeroos:${#num}:${#zeroos}}${num}
}
This might work:
public int binaryToInteger(String binary) {
char[] numbers = binary.toCharArray();
int result = 0;
for(int i=numbers.length - 1; i>=0; i--)
if(numbers[i]=='1')
result += Math.pow(2, (numbers.length-i - 1));
return result;
}
You can use str.contains
alone with a regex pattern using OR (|)
:
s[s.str.contains('og|at')]
Or you could add the series to a dataframe
then use str.contains
:
df = pd.DataFrame(s)
df[s.str.contains('og|at')]
Output:
0 cat
1 hat
2 dog
3 fog
If you've landed here looking for a quick array-to-string conversion, try Arrays.toString().
Creates a String representation of the
Object[]
passed. The result is surrounded by brackets ("[]"
), each element is converted to a String via theString.valueOf(Object)
and separated by", "
. If the array isnull
, then"null"
is returned.
The java standard answer is often:
--create a user that you want to use the database as:
create role neil;
--create the user for the web server to connect as:
create role webgui noinherit login password 's3cr3t';
--let webgui set role to neil:
grant neil to webgui; --this looks backwards but is correct.
webgui
is now in the neil
group, so webgui
can call set role neil
. However, webgui
did not inherit neil
's permissions.
Later, login as webgui:
psql -d some_database -U webgui
(enter s3cr3t as password)
set role neil;
webgui
does not need superuser
permission for this.
You want to set role
at the beginning of a database session and reset it at the end of the session. In a web app, this corresponds to getting a connection from your database connection pool and releasing it, respectively. Here's an example using Tomcat's connection pool and Spring Security:
public class SetRoleJdbcInterceptor extends JdbcInterceptor {
@Override
public void reset(ConnectionPool connectionPool, PooledConnection pooledConnection) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(authentication != null) {
try {
/*
use OWASP's ESAPI to encode the username to avoid SQL Injection. Can't use parameters with SET ROLE. Need to write PG codec.
Or use a whitelist-map approach
*/
String username = ESAPI.encoder().encodeForSQL(MY_CODEC, authentication.getName());
Statement statement = pooledConnection.getConnection().createStatement();
statement.execute("set role \"" + username + "\"");
statement.close();
} catch(SQLException exp){
throw new RuntimeException(exp);
}
}
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("close".equals(method.getName())){
Statement statement = ((Connection)proxy).createStatement();
statement.execute("reset role");
statement.close();
}
return super.invoke(proxy, method, args);
}
}
In MSVC to suppress a particular warning it is enough to specify the it's number to compiler as /wd#. My CMakeLists.txt contains such the block:
If (MSVC)
Set (CMAKE_EXE_LINKER_FLAGS "$ {CMAKE_EXE_LINKER_FLAGS} / NODEFAULTLIB: LIBCMT")
Add_definitions (/W4 /wd4512 /wd4702 /wd4100 /wd4510 /wd4355 /wd4127)
Add_definitions (/D_CRT_SECURE_NO_WARNINGS)
Elseif (CMAKE_COMPILER_IS_GNUCXX OR CMAKE_COMPILER_IS_GNUC)
Add_definitions (-Wall -W -pedantic)
Else ()
Message ("Unknown compiler")
Endif ()
Now I can not say what exactly /wd4512 /wd4702 /wd4100 /wd4510 /wd4355 /wd4127 mean, because I do not pay any attention to MSVC for three years, but they suppress superpedantic warnings that does not influence the result.
And note that since Python types are only checked at runtime you can have code like:
if True:
x = 2
y = 4
else:
x = "One"
y = "Two"
print(x + y)
But I'm having trouble thinking of other ways in which the code would operate without an error because of type issues.
I have seen people use Throwable to catch some errors that might happen due to infra failure/ non availability.
Create a xml file in drawable folder like below
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<!-- you can use any color you want I used here gray color-->
<solid android:color="#ABABAB"/>
<corners android:radius="10dp"/>
</shape>
Apply this as background to button you want make corners round.
Or you can use separate radius for every corner like below
android:bottomRightRadius="10dp"
android:bottomLeftRadius="10dp"
android:topLeftRadius="10dp"
android:topRightRadius="10dp"
.NET has some handy utility methods for this sort of thing in System.Array:
PS> $a = 'a','b','c'
PS> [array]::IndexOf($a, 'b')
1
PS> [array]::IndexOf($a, 'c')
2
Good points on the above approach in the comments. Besides "just" finding an index of an item in an array, given the context of the problem, this is probably more suitable:
$letters = { 'A', 'B', 'C' }
$letters | % {$i=0} {"Value:$_ Index:$i"; $i++}
Foreach (%) can have a Begin sciptblock that executes once. We set an index variable there and then we can reference it in the process scripblock where it gets incremented before exiting the scriptblock.
Just define your action method like this
public string ThemePath()
and simply return the string itself.
if you are using netbeans you can add a jlabel to the frame and through properties change its icon to your image and remove the text. then move the jlabel to the bottom of the Jframe or any content pane through navigator
document.getElementById('file').addEventListener('change', (e) => {
const file = e.target.files[0];
const reader = new FileReader();
reader.onloadend = () => {
// convert file to base64 String
const base64String = reader.result.replace('data:', '').replace(/^.+,/, '');
// store file
localStorage.setItem('wallpaper', base64String);
// display image
document.body.style.background = `url(data:image/png;base64,${base64String})`;
};
reader.readAsDataURL(file);
});
try also Dollar (check this revision):
import static com.humaorie.dollar.Dollar.*
...
List<Integer> source = ...;
int[] ints = $(source).convert().toIntArray();
<View
android:id="@+id/view"
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#000000" />
If you have the google collections library, Tom's answer can be simplified a lot by using ImmutableSet (http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ImmutableSet.html)
This really removes a lot of clutter from the initialization proposed
private static final Set<String> VALUES = ImmutableSet.of("AB","BC","CD","AE");
Thanks to "Darin Dimitrov", This is the extension methods.
public static partial class Ext
{
public static Uri GetUriWithparameters(this Uri uri,Dictionary<string,string> queryParams = null,int port = -1)
{
var builder = new UriBuilder(uri);
builder.Port = port;
if(null != queryParams && 0 < queryParams.Count)
{
var query = HttpUtility.ParseQueryString(builder.Query);
foreach(var item in queryParams)
{
query[item.Key] = item.Value;
}
builder.Query = query.ToString();
}
return builder.Uri;
}
public static string GetUriWithparameters(string uri,Dictionary<string,string> queryParams = null,int port = -1)
{
var builder = new UriBuilder(uri);
builder.Port = port;
if(null != queryParams && 0 < queryParams.Count)
{
var query = HttpUtility.ParseQueryString(builder.Query);
foreach(var item in queryParams)
{
query[item.Key] = item.Value;
}
builder.Query = query.ToString();
}
return builder.Uri.ToString();
}
}
You can use mb_chars
. This respects umlaute:
class String
# Only capitalize first letter of a string
def capitalize_first
self[0] = self[0].mb_chars.upcase
self
end
end
Example:
"ümlaute".capitalize_first
#=> "Ümlaute"
If you don't absolutely need to use a regex, useconsider using Perl's Text::Balanced to remove the parenthesis.
use Text::Balanced qw(extract_bracketed);
my ($extracted, $remainder, $prefix) = extract_bracketed( $filename, '()', '[^(]*' );
{ no warnings 'uninitialized';
$filename = (defined $prefix or defined $remainder)
? $prefix . $remainder
: $extracted;
}
You may be thinking, "Why do all this when a regex does the trick in one line?"
$filename =~ s/\([^}]*\)//;
Text::Balanced handles nested parenthesis. So $filename = 'foo_(bar(baz)buz)).foo'
will be extracted properly. The regex based solutions offered here will fail on this string. The one will stop at the first closing paren, and the other will eat them all.
$filename =~ s/\([^}]*\)//;
# returns 'foo_buz)).foo'
$filename =~ s/\(.*\)//;
# returns 'foo_.foo'
# text balanced example returns 'foo_).foo'
If either of the regex behaviors is acceptable, use a regex--but document the limitations and the assumptions being made.
Model:
namespace MvcApplicationrazor.Models
{
public class CountryModel
{
public List<State> StateModel { get; set; }
public SelectList FilteredCity { get; set; }
}
public class State
{
public int Id { get; set; }
public string StateName { get; set; }
}
public class City
{
public int Id { get; set; }
public int StateId { get; set; }
public string CityName { get; set; }
}
}
Controller:
public ActionResult Index()
{
CountryModel objcountrymodel = new CountryModel();
objcountrymodel.StateModel = new List<State>();
objcountrymodel.StateModel = GetAllState();
return View(objcountrymodel);
}
//Action result for ajax call
[HttpPost]
public ActionResult GetCityByStateId(int stateid)
{
List<City> objcity = new List<City>();
objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
return Json(obgcity);
}
// Collection for state
public List<State> GetAllState()
{
List<State> objstate = new List<State>();
objstate.Add(new State { Id = 0, StateName = "Select State" });
objstate.Add(new State { Id = 1, StateName = "State 1" });
objstate.Add(new State { Id = 2, StateName = "State 2" });
objstate.Add(new State { Id = 3, StateName = "State 3" });
objstate.Add(new State { Id = 4, StateName = "State 4" });
return objstate;
}
//collection for city
public List<City> GetAllCity()
{
List<City> objcity = new List<City>();
objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
return objcity;
}
View:
@model MvcApplicationrazor.Models.CountryModel
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
function GetCity(_stateId) {
var procemessage = "<option value='0'> Please wait...</option>";
$("#ddlcity").html(procemessage).show();
var url = "/Test/GetCityByStateId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#ddlcity").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
</script>
<h4>
MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
<br />
<br />
<select id="ddlcity" name="ddlcity" style="width: 200px">
</select>
<br /><br />
}
Some shortcut is to create a NumberFormatInfo class, set its NumberDecimalSeparator property to "." and use the class as parameter to ToString() method whenever u need it.
using System.Globalization;
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ".";
value.ToString(nfi);
If you're sure that your script runs and that it is a false alarm, Go to Preferences > PyDev > Editor > Code Analysis. Demote the errors to warnings.
Solution 1:
For some reason, virtualenvwrapper.sh
installed in /usr/bin/virtualenvwrapper.sh
, instead of under /usr/local/bin
.
The following in my .bash_profile
works...
source "/usr/bin/virtualenvwrapper.sh"
export WORKON_HOME="/opt/virtual_env/"
My install seems to work fine without sourcing virtualenvwrapper_bashrc
Solution 2:
Alternatively as mentioned below, you could leverage the chance that virtualenvwrapper.sh
is already in your shell's PATH
and just issue a source `which virtualenvwrapper.sh`
I had many issues involving C# and SqlServer. I ended up doing the following:
Also make sure that all your machines run on the same timezone.
Regarding the different result sets you get, your first example is "July First" while the second is "4th of July" ...
Also, the second example can be also interpreted as "April 7th", it depends on your server localization configuration (my solution doesn't suffer from this issue).
EDIT: hh was replaced with HH, as it doesn't seem to capture the correct hour on systems with AM/PM as opposed to systems with 24h clock. See the comments below.
Flexbox is the solution:
.separator {
display: flex;
align-items: center;
text-align: center;
}
.separator::before,
.separator::after {
content: '';
flex: 1;
border-bottom: 1px solid #000;
}
.separator:not(:empty)::before {
margin-right: .25em;
}
.separator:not(:empty)::after {
margin-left: .25em;
}
_x000D_
<div class="separator">Next section</div>
_x000D_
Nowadays every browser supports it, and you can ensure compatibility with decade-old browsers by adding respective vendor prefixes if needed. It would degrade gracefully anyways.
Try
switch($value) {
case 1:
case 2:
echo "the value is either 1 or 2";
break;
}
1.If we want to pass argument in the call then we need to call the method like below
As we are using arrow functions no need to bind the method in cunstructor
.
onClick={() => this.save(id)}
when we bind the method in constructor like this
this.save= this.save.bind(this);
then we need to call the method without passing any argument like below
onClick={this.save}
and we try to pass argument while calling the function as shown below then error comes like maximum depth exceeded.
onClick={this.save(id)}
Two options:
Use the LIKE
keyword, along with percent signs in the string
select * from table where field like '%a%' or field like '%b%'.
(note: If your search string contains percent signs, you'll need to escape them)
If you're looking for more a complex combination of strings than you've specified in your example, you could regular expressions (regex):
See the MySQL manual for more on how to use them: http://dev.mysql.com/doc/refman/5.1/en/regexp.html
Of these, using LIKE
is the most usual solution -- it's standard SQL, and in common use. Regex is less commonly used but much more powerful.
Note that whichever option you go with, you need to be aware of possible performance implications. Searching for sub-strings like this will mean that the query will have to scan the entire table. If you have a large table, this could make for a very slow query, and no amount of indexing is going to help.
If this is an issue for you, and you'r going to need to search for the same things over and over, you may prefer to do something like adding a flag field to the table which specifies that the string field contains the relevant sub-strings. If you keep this flag field up-to-date when you insert of update a record, you could simply query the flag when you want to search. This can be indexed, and would make your query much much quicker. Whether it's worth the effort to do that is up to you, it'll depend on how bad the performance is using LIKE
.
word-break: normal seems better to use than word-break: break-word because break-word breaks initials such as EN
word-break: normal
If you want to guarantee the same order regardless of the order of elements in the input array, here is a stable sorting:
myArray.sort(function(a, b) {
/* Storing case insensitive comparison */
var comparison = a.toLowerCase().localeCompare(b.toLowerCase());
/* If strings are equal in case insensitive comparison */
if (comparison === 0) {
/* Return case sensitive comparison instead */
return a.localeCompare(b);
}
/* Otherwise return result */
return comparison;
});
(np.where(np.isnan(A)))[0].shape[0]
will be greater than 0
if A
contains at least one element of nan
, A
could be an n x m
matrix.
Example:
import numpy as np
A = np.array([1,2,4,np.nan])
if (np.where(np.isnan(A)))[0].shape[0]:
print "A contains nan"
else:
print "A does not contain nan"
If you use RAC then you need to use GV$*
views instead V$*
.
Try to find your session by
select * from gv$session where username = 'test';
and then you can kill the session by
alter system kill session 'sid, serial#, @inst_id' immediate;
If you can use jQuery, it now supports :focus, just make sure you are using version 1.6+.
This statement will get you the currently focused element.
$(":focus")
From: How to select an element that has focus on it with jQuery
If you are using c# on the desktop, you can use SimpleMapi. That way it will be sent using the default mail client, and the user has the option of reviewing the message before sending, just like mailto:
.
To use it you add the Simple-MAPI.NET package (it's 13Kb), and run:
var mapi = new SimpleMapi();
mapi.AddRecipient(null, address, false);
mapi.Attach(path);
//mapi.Logon(ParentForm.Handle); //not really necessary
mapi.Send(subject, body, true);
For CentOS Linux release 7.3
The mysql.sock file path is /var/lib/mysql/mysql.sock
Edit /etc/my.cnf file and put below entry
This will solve your problem.
[client]
user=root
password=Passw0rd
port=3306
socket=/var/lib/mysql/mysql.sock
[mysqld]
bind-address=0.0.0.0
After this restart the service
service mysql restart
In my opinion,the starting point to create this kind of recyclerView is the knowledge of this method. Since this method is optional to override therefore it is not visible in RecylerView class by default which in turn makes many developers(including me) wonder where to begin. Once you know that this method exists, creating such RecyclerView would be a cakewalk.
You can create a RecyclerView
with any number of different Views(ViewHolders). But for better readability lets take an example of RecyclerView
with two Viewholders
.
Remember these 3 simple steps and you will be good to go.
getItemViewType(int position)
ViewType
in
onCreateViewHolder() methodPopulate View based on the itemViewType in onBindViewHolder()
method
Here is a code snippet for you
public class YourListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int LAYOUT_ONE= 0;
private static final int LAYOUT_TWO= 1;
@Override
public int getItemViewType(int position)
{
if(position==0)
return LAYOUT_ONE;
else
return LAYOUT_TWO;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view =null;
RecyclerView.ViewHolder viewHolder = null;
if(viewType==LAYOUT_ONE)
{
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.one,parent,false);
viewHolder = new ViewHolderOne(view);
}
else
{
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.two,parent,false);
viewHolder= new ViewHolderTwo(view);
}
return viewHolder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
if(holder.getItemViewType()== LAYOUT_ONE)
{
// Typecast Viewholder
// Set Viewholder properties
// Add any click listener if any
}
else {
ViewHolderOne vaultItemHolder = (ViewHolderOne) holder;
vaultItemHolder.name.setText(displayText);
vaultItemHolder.name.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
.......
}
});
}
}
/**************** VIEW HOLDER 1 ******************//
public class ViewHolderOne extends RecyclerView.ViewHolder {
public TextView name;
public ViewHolderOne(View itemView) {
super(itemView);
name = (TextView)itemView.findViewById(R.id.displayName);
}
}
//**************** VIEW HOLDER 2 ******************//
public class ViewHolderTwo extends RecyclerView.ViewHolder{
public ViewHolderTwo(View itemView) {
super(itemView);
..... Do something
}
}
}
Here is a project where I have implemented a RecyclerView with multiple ViewHolders.
Of course your logs return undefined
: you log before the request is done. The problem isn't scope but asynchronicity.
http.request
is asynchronous, that's why it takes a callback as parameter. Do what you have to do in the callback (the one you pass to response.end
):
callback = function(response) {
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(req.data);
console.log(str);
// your code here if you want to use the results !
});
}
var req = http.request(options, callback).end();
It depends of your definition of "better".
The other answers point out the use of map, which is natural (especially for guys used to functional style) and concise. I strongly recommend using it (if you don't bother with the few IE8- IT guys). So if "better" means "more concise", "maintainable", "understandable" then yes, it's way better.
In the other hand, this beauty don't come without additional costs. I'm not a big fan of microbench, but I've put up a small test here. The result are predictable, the old ugly way seems to be faster than the map function. So if "better" means "faster", then no, stay with the old school fashion.
Again this is just a microbench and in no way advocating against the use of map
, it's just my two cents :).
Several problems here:
import java.util.Iterator
Map.Entry entry = (Map.Entry) iter.next();
then you need to use hm.entrySet().iterator()
, not hm.keySet().iterator()
. Either you iterate on the keys, or on the entries.Since Python 3.5, subprocess.run() is recommended over subprocess.check_output():
>>> int(subprocess.run(["pidof", "-s", "your_process"], stdout=subprocess.PIPE).stdout)
Also, since Python 3.7, you can use the capture_output=true
parameter to capture stdout and stderr:
>>> int(subprocess.run(["pidof", "-s", "your process"], capture_output=True).stdout)
// iterate through key-value gracefully
const obj = { a: 5, b: 7, c: 9 };
for (const [key, value] of Object.entries(obj)) {
console.log(`${key} ${value}`); // "a 5", "b 7", "c 9"
}
Refer MDN
background-size
is working in Chrome 4.1, but so far I couldn't make it work in Firefox 3.6.
function getWeekDays(curr, firstDay = 1 /* 0=Sun, 1=Mon, ... */) {
var cd = curr.getDate() - curr.getDay();
var from = new Date(curr.setDate(cd + firstDay));
var to = new Date(curr.setDate(cd + 6 + firstDay));
return {
from,
to,
};
};
export enum WEEK_DAYS {
Sunday = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
}
export const getWeekDays = (
curr: Date,
firstDay: WEEK_DAYS = WEEK_DAYS.Monday
): { from: Date; to: Date } => {
const cd = curr.getDate() - curr.getDay();
const from = new Date(curr.setDate(cd + firstDay));
const to = new Date(curr.setDate(cd + 6 + firstDay));
return {
from,
to,
};
};
The problem with inline styles is Content Security Policies (CSP) are becoming more common, which do not allow it. Therefore, I recommend avoiding inline styles completely.
Update: To explain further, CSP is HTTP headers sent by the server that restrict what content can appear on the page. It is simply further mitigation that can be applied to a server to stop an attacker from doing something naughty if the developer code the site poorly.
The purpose of most of these restrictions is to stop XSS (cross-site scripting) attacks. XSS is where an attacker figures out a way to include his own javascript on your page (for example, if I make my username bob<SCRIPT>alert("hello")</SCRIPT>
and then post a comment, and you visit the page, it shouldn't show an alert). Developers should deny the ability to have a user add content like this to the site, but just in case they made a mistake, then CSP blocks the page from loading if it finds any script>
tags.
CSP is just an extra level of protection for developers to ensure if they made a mistake, that an attacker can't cause problems to visitors to that site.
So that all is XSS, but what if the attacker can't include <script>
tags but can include <style>
tags or include a style=
parameter on a tag? Then he might be able to change the look of the site in such a way that you're tricked into clicking the wrong button, or some other problem. This is much less of a concern, but still something to avoid, and CSP does that for you.
A good resource for testing a site for CSP is https://securityheaders.io/
You can read more about CSP at http://www.html5rocks.com/en/tutorials/security/content-security-policy/
For the most part you treat it as if you are validating any other kind of control but use the InitialValue property of the required field validator.
<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="your-dropdownlist" InitialValue="Please select" ErrorMessage="Please select something" />
Basically what it's saying is that validation will succeed if any other value than the 1 set in InitialValue is selected in the dropdownlist.
If databinding you will need to insert the "Please select" value afterwards as follows
this.ddl1.Items.Insert(0, "Please select");
If you're getting the #2002 Cannot log in to the MySQL server
error while logging in to phpmyadmin, try editing phpmyadmin/config.inc.php
and change:
$cfg['Servers'][$i]['host'] = 'localhost';
to:
$cfg['Servers'][$i]['host'] = '127.0.0.1';
Solution from Ryan's blog
Edit (20-Mar-2015):
Note that if you're on a fresh install, config.inc.php may not exist. You need to rename / copy config.sample.inc.php and then change the relevant line
Here's a more flexible way.
let's say this is your form.
<form>
<input type='checkbox' name='user_ids[]' value='1'id='checkbox_1' />
<input type='checkbox' name='user_ids[]' value='2'id='checkbox_2' />
<input type='checkbox' name='user_ids[]' value='3'id='checkbox_3' />
<input name="confirm" type="button" value="confirm" onclick="submit_form();" />
</form>
And this is your jquery ajax below...
// Don't get confused at this portion right here
// cuz "var data" will get all the values that the form
// has submitted in the $_POST. It doesn't matter if you
// try to pass a text or password or select form element.
// Remember that the "form" is not a name attribute
// of the form, but the "form element" itself that submitted
// the current post method
var data = $("form").serialize();
$.ajax({
url: "link/of/your/ajax.php", // link of your "whatever" php
type: "POST",
async: true,
cache: false,
data: data, // all data will be passed here
success: function(data){
alert(data) // The data that is echoed from the ajax.php
}
});
And in your ajax.php, you try echoing or print_r your post to see what's happening inside it. This should look like this. Only checkboxes that you checked will be returned. If you didn't checked any, it will return an error.
<?php
print_r($_POST); // this will be echoed back to you upon success.
echo "This one too, will be echoed back to you";
Hope that is clear enough.
So the issue is that UTF-8 code unit values have been stored as a sequence of 16-bit code units in a C# string
. You simply need to verify that each code unit is within the range of a byte, copy those values into bytes, and then convert the new UTF-8 byte sequence into UTF-16.
public static string DecodeFromUtf8(this string utf8String)
{
// copy the string as UTF-8 bytes.
byte[] utf8Bytes = new byte[utf8String.Length];
for (int i=0;i<utf8String.Length;++i) {
//Debug.Assert( 0 <= utf8String[i] && utf8String[i] <= 255, "the char must be in byte's range");
utf8Bytes[i] = (byte)utf8String[i];
}
return Encoding.UTF8.GetString(utf8Bytes,0,utf8Bytes.Length);
}
DecodeFromUtf8("d\u00C3\u00A9j\u00C3\u00A0"); // déjà
This is easy, however it would be best to find the root cause; the location where someone is copying UTF-8 code units into 16 bit code units. The likely culprit is somebody converting bytes into a C# string
using the wrong encoding. E.g. Encoding.Default.GetString(utf8Bytes, 0, utf8Bytes.Length)
.
Alternatively, if you're sure you know the incorrect encoding which was used to produce the string, and that incorrect encoding transformation was lossless (usually the case if the incorrect encoding is a single byte encoding), then you can simply do the inverse encoding step to get the original UTF-8 data, and then you can do the correct conversion from UTF-8 bytes:
public static string UndoEncodingMistake(string mangledString, Encoding mistake, Encoding correction)
{
// the inverse of `mistake.GetString(originalBytes);`
byte[] originalBytes = mistake.GetBytes(mangledString);
return correction.GetString(originalBytes);
}
UndoEncodingMistake("d\u00C3\u00A9j\u00C3\u00A0", Encoding(1252), Encoding.UTF8);
If you are using a JetBrains IDE (anything IntelliJ based), you can recover even your uncommited changes via their "Local History" feature.
Right-click on your top-level directory in your file tree, find "Local History" in the context menu, and choose "Show History". This will open up a view where your recent edits can be found, and once you have found the revision you want to go back to, right click on it and click "Revert".
Try putting the components.json
file in the public
directory of your application, rather than the root directory, then re-run bower install
...try this in your app home directory:
cp components.json public
cd public
bower install
I have found a way to use JSONP
method in $http
directly and with support of params
in the config object:
params = {
'a': b,
'callback': 'JSON_CALLBACK'
};
$http({
url: url,
method: 'JSONP',
params: params
})
Global exclusions look like they're being worked on, but until then...
From the Sonatype maven reference (bottom of the page):
Dependency management in a top-level POM is different from just defining a dependency on a widely shared parent POM. For starters, all dependencies are inherited. If mysql-connector-java were listed as a dependency of the top-level parent project, every single project in the hierarchy would have a reference to this dependency. Instead of adding in unnecessary dependencies, using dependencyManagement allows you to consolidate and centralize the management of dependency versions without adding dependencies which are inherited by all children. In other words, the dependencyManagement element is equivalent to an environment variable which allows you to declare a dependency anywhere below a project without specifying a version number.
As an example:
<dependencies>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.0.5.RELEASE</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</dependencyManagement>
It doesn't make the code less verbose overall, but it does make it less verbose where it counts. If you still want it less verbose you can follow these tips also from the Sonatype reference.
Goto Package properties->Configurations->Enable Package Configurations->Add->xml configuration file->Specify dtsconfig file->click next->In OLEDB Properties tick the connection string->connection string value will be displayed->click next and finish package is hence configured.
You can add Environment variable also in this process
This builds upon @Pavel's answer, to solve the possibility of Spring context not being initialized when accessing from the static getBean method:
@Component
public class Spring {
private static final Logger LOG = LoggerFactory.getLogger (Spring.class);
private static Spring spring;
@Autowired
private ApplicationContext context;
@PostConstruct
public void registerInstance () {
spring = this;
}
private Spring (ApplicationContext context) {
this.context = context;
}
private static synchronized void initContext () {
if (spring == null) {
LOG.info ("Initializing Spring Context...");
ApplicationContext context = new AnnotationConfigApplicationContext (io.zeniq.spring.BaseConfig.class);
spring = new Spring (context);
}
}
public static <T> T getBean(String name, Class<T> className) throws BeansException {
initContext();
return spring.context.getBean(name, className);
}
public static <T> T getBean(Class<T> className) throws BeansException {
initContext();
return spring.context.getBean(className);
}
public static AutowireCapableBeanFactory getBeanFactory() throws IllegalStateException {
initContext();
return spring.context.getAutowireCapableBeanFactory ();
}
}
The important piece here is the initContext
method. It ensures that the context will always get initialized. But, do note that initContext
will be a point of contention in your code as it is synchronized. If your application is heavily parallelized (for eg: the backend of a high traffic site), this might not be a good solution for you.
The state of the checkbox will be reflected on whatever model you have it bound to, in this case, $scope.answers[item.questID]
Just saying...here is a more simple approach to this:
declare @sdate date = '2017-06-25'
, @edate date = '2017-07-24';
with dates_CTE (date) as (
select @sdate
Union ALL
select DATEADD(day, 1, date)
from dates_CTE
where date < @edate
)
select *
from dates_CTE;
My work around was that I opened the csv
file in a text editor, removed the excessive commas on the last value, then saved the file. For example for the following file
Test1,Test2,Test3
1,1,1
2,2,2
3,3,3
4,4,
5,5,
,6,,
Remove the commas after 6, then save the file.
Here is some better usage of java for scanner
try(Scanner sc = new Scanner(System.in)) {
//Use sc as you need
} catch (Exception e) {
// handle exception
}
If you're not worried about a couple minutes time to do so, a solution would be to rm -rf node_modules
and npm install
again to rebuild the local modules.
Let's see this in action:
var b = true;_x000D_
_x000D_
console.log(b); // true_x000D_
_x000D_
b = !b;_x000D_
console.log(b); // false_x000D_
_x000D_
b = !b;_x000D_
console.log(b); // true
_x000D_
Anyways, there is no shorter way than what you currently have.
You just need to wrap object in ()
var arr = [{_x000D_
id: 1,_x000D_
name: 'bill'_x000D_
}, {_x000D_
id: 2,_x000D_
name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
Windows ? Preferences ? General ? Text Editors ? Show numberlines
I didn't find any of the existing solutions fitting - simple HTML emails to simple plain text files.
I've opened up this repository, hope it helps someone. MIT license, by the way :)
https://github.com/RobQuistNL/SimpleHtmlToText
Example:
$myHtml = '<b>This is HTML</b><h1>Header</h1><br/><br/>Newlines';
echo (new Parser())->parseString($myHtml);
returns:
**This is HTML**
### Header ###
Newlines
have you tried with a condition in ng-class like here : http://jsfiddle.net/DotDotDot/zvLvg/ ?
<span id='1' ng-class='{"myclass":tog==1}' ng-click='tog=1'>span 1</span>
<span id='2' ng-class='{"myclass":tog==2}' ng-click='tog=2'>span 2</span>
This is because of
String outStr = obj.toString("UTF-8");
Send the byte[]
which you can get from your ByteArrayOutputStream
and use it as such in your ByteArrayInputStream
to construct your GZIPInputStream
. Following are the changes which need to be done in your code.
byte[] compressed = compress(string); //In the main method
public static byte[] compress(String str) throws Exception {
...
...
return obj.toByteArray();
}
public static String decompress(byte[] bytes) throws Exception {
...
GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
...
}
I have just faced this issue in VS 2013 .NET 4.5 with a MapInfo DLL. Turns out, the problem was that I changed the Platform for Build from x86 to Any CPU and that was enough to trigger this error. Changing it back to x86 did the trick. Might help someone.
@HostListener("window:resize", [])
public onResize() {
this.detectScreenSize();
}
public ngAfterViewInit() {
this.detectScreenSize();
}
private detectScreenSize() {
const height = window.innerHeight;
const width = window.innerWidth;
}
Try linux command chsh
.
The detailed command is chsh -s /bin/bash
.
It will prompt you to enter your password.
Your default login shell is /bin/bash
now. You must log out and log back in to see this change.
The following is quoted from man page:
The chsh command changes the user login shell. This determines the name of the users initial login command. A normal user may only change the login shell for her own account, the superuser may change the login shell for any account
This command will change the default login shell permanently.
Note: If your user account is remote such as on Kerberos authentication (e.g. Enterprise RHEL) then you will not be able to use chsh
.
The best script I found is on this page : http://northernmost.org/blog/find-out-what-is-using-your-swap/
Here's one variant of the script and no root needed:
#!/bin/bash
# Get current swap usage for all running processes
# Erik Ljungstrom 27/05/2011
# Modified by Mikko Rantalainen 2012-08-09
# Pipe the output to "sort -nk3" to get sorted output
# Modified by Marc Methot 2014-09-18
# removed the need for sudo
SUM=0
OVERALL=0
for DIR in `find /proc/ -maxdepth 1 -type d -regex "^/proc/[0-9]+"`
do
PID=`echo $DIR | cut -d / -f 3`
PROGNAME=`ps -p $PID -o comm --no-headers`
for SWAP in `grep VmSwap $DIR/status 2>/dev/null | awk '{ print $2 }'`
do
let SUM=$SUM+$SWAP
done
if (( $SUM > 0 )); then
echo "PID=$PID swapped $SUM KB ($PROGNAME)"
fi
let OVERALL=$OVERALL+$SUM
SUM=0
done
echo "Overall swap used: $OVERALL KB"
Tl;dr: Use a regex approach. It is 39x faster than the rescue approach in the accepted answer and also handles cases like "1,000"
def regex_is_number? string
no_commas = string.gsub(',', '')
matches = no_commas.match(/-?\d+(?:\.\d+)?/)
if !matches.nil? && matches.size == 1 && matches[0] == no_commas
true
else
false
end
end
--
The accepted answer by @Jakob S works for the most part, but catching exceptions can be really slow. In addition, the rescue approach fails on a string like "1,000".
Let's define the methods:
def rescue_is_number? string
true if Float(string) rescue false
end
def regex_is_number? string
no_commas = string.gsub(',', '')
matches = no_commas.match(/-?\d+(?:\.\d+)?/)
if !matches.nil? && matches.size == 1 && matches[0] == no_commas
true
else
false
end
end
And now some test cases:
test_cases = {
true => ["5.5", "23", "-123", "1,234,123"],
false => ["hello", "99designs", "(123)456-7890"]
}
And a little code to run the test cases:
test_cases.each do |expected_answer, cases|
cases.each do |test_case|
if rescue_is_number?(test_case) != expected_answer
puts "**rescue_is_number? got #{test_case} wrong**"
else
puts "rescue_is_number? got #{test_case} right"
end
if regex_is_number?(test_case) != expected_answer
puts "**regex_is_number? got #{test_case} wrong**"
else
puts "regex_is_number? got #{test_case} right"
end
end
end
Here is the output of the test cases:
rescue_is_number? got 5.5 right
regex_is_number? got 5.5 right
rescue_is_number? got 23 right
regex_is_number? got 23 right
rescue_is_number? got -123 right
regex_is_number? got -123 right
**rescue_is_number? got 1,234,123 wrong**
regex_is_number? got 1,234,123 right
rescue_is_number? got hello right
regex_is_number? got hello right
rescue_is_number? got 99designs right
regex_is_number? got 99designs right
rescue_is_number? got (123)456-7890 right
regex_is_number? got (123)456-7890 right
Time to do some performance benchmarks:
Benchmark.ips do |x|
x.report("rescue") { test_cases.values.flatten.each { |c| rescue_is_number? c } }
x.report("regex") { test_cases.values.flatten.each { |c| regex_is_number? c } }
x.compare!
end
And the results:
Calculating -------------------------------------
rescue 128.000 i/100ms
regex 4.649k i/100ms
-------------------------------------------------
rescue 1.348k (±16.8%) i/s - 6.656k
regex 52.113k (± 7.8%) i/s - 260.344k
Comparison:
regex: 52113.3 i/s
rescue: 1347.5 i/s - 38.67x slower
Jquery :-
jQuery is a lightweight and feature-rich JavaScript Library that helps web developers
by simplifying the usage of client-side scripting for web applications using JavaScript.
It extensively simplifies using JavaScript on a website and it’s lightweight as well as fast.
So, using jQuery, we can:
easily manipulate the contents of a webpage
apply styles to make UI more attractive
easy DOM traversal
effects and animation
simple to make AJAX calls and
utilities and much more…
AngularJS :-
AngularJS is a product by none other the Search Engine Giant Google and it’s an open source
MVC-based framework(considered to be the best and only next generation framework). AngularJS
is a great tool for building highly rich client-side web applications.
As being a framework, it dictates us to follow some rules and a structured approach. It’s
not just a JavaScript library but a framework that is perfectly designed (framework tools
are designed to work together in a truly interconnected way).
In comparison of features jQuery Vs AngularJS, AngularJS simply offers more features:
Two-Way data binding
REST friendly
MVC-based Pattern
Deep Linking
Template
Form Validation
Dependency Injection
Localization
Full Testing Environment
Server Communication
You can use the v$sql_monitor view to find queries that are running longer than 5 seconds. This may only be available in Enterprise versions of Oracle. For example this query will identify slow running queries from my TEST_APP service:
select to_char(sql_exec_start, 'dd-Mon hh24:mi'), (elapsed_time / 1000000) run_time,
cpu_time, sql_id, sql_text
from v$sql_monitor
where service_name = 'TEST_APP'
order by 1 desc;
Note elapsed_time is in microseconds so / 1000000 to get something more readable
In Python 2.7.1, you may calculate standard deviation using numpy.std()
for:
numpy.std()
with no additional arguments besides to your data list.numpy.std(< your-list >, ddof=1)
The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.
It calculates sample std rather than population std.
If you wish, you can also use the column names instead of column numbers.
For example, if you want to read data from DataGridView on the 4. row and the "Name" column. It provides me a better understanding for which variable I am dealing with.
dataGridView.Rows[4].Cells["Name"].Value.ToString();
Hope it helps.
I do not know of any in-built method, but you could just use linq:
parameterList = parameterList.Where(x => x != null).ToList();
In case you don't have some id, e.g., mysite.com/something/9182301, you can use get_object_or_404
importing by from django.shortcuts import get_object_or_404
.
Use example:
def myFunc(request, my_pk):
my_var = get_object_or_404(CLASS_NAME, pk=my_pk)
Pretty sure you can't do that, as it violates the purpose of uniques.
However, this person seems to have a decent work around: http://sqlservercodebook.blogspot.com/2008/04/multiple-null-values-in-unique-index-in.html
Use either of the Map
implementations bundled with Java 6 and later that implement NavigableMap
(the successor to SortedMap
):
TreeMap
if running single-threaded, or if the map is to be read-only across threads after first being populated. ConcurrentSkipListMap
if manipulating the map across threads.NavigableMap
FYI, the SortedMap
interface was succeeded by the NavigableMap
interface.
You would only need to use SortedMap
if using 3rd-party implementations that have not yet declared their support of NavigableMap
. Of the maps bundled with Java, both of the implementations that implement SortedMap
also implement NavigableMap
.
s SortedMap the best answer? TreeMap?
As others mentioned, SortedMap
is an interface while TreeMap
is one of multiple implementations of that interface (and of the more recent NavigableMap
.
Having an interface allows you to write code that uses the map without breaking if you later decide to switch between implementations.
NavigableMap< Employee , Project > currentAssignments = new TreeSet<>() ;
currentAssignments.put( alice , writeAdCopyProject ) ;
currentAssignments.put( bob , setUpNewVendorsProject ) ;
This code still works if later change implementations. Perhaps you later need a map that supports concurrency for use across threads. Change that declaration to:
NavigableMap< Employee , Project > currentAssignments = new ConcurrentSkipListMap<>() ;
…and the rest of your code using that map continues to work.
There are ten implementations of Map
bundled with Java 11. And more implementations provided by 3rd parties such as Google Guava.
Here is a graphic table I made highlighting the various features of each. Notice that two of the bundled implementations keep the keys in sorted order by examining the key’s content. Also, EnumMap
keeps its keys in the order of the objects defined on that enum. Lastly, the LinkedHashMap
remembers original insertion order.
You can do it with a custom view, like this RoundAppBar and RoundBottomAppBar.
Here a path
is used to clipPath
the canvas.
What are iml files in Android Studio project?
A Google search on iml file
turns up:
IML is a module file created by IntelliJ IDEA, an IDE used to develop Java applications. It stores information about a development module, which may be a Java, Plugin, Android, or Maven component; saves the module paths, dependencies, and other settings.
(from this page)
why not to use gradle scripts to integrate with external modules that you add to your project.
You do "use gradle scripts to integrate with external modules", or your own modules.
However, Gradle is not IntelliJ IDEA's native project model — that is separate, held in .iml
files and the metadata in .idea/
directories. In Android Studio, that stuff is largely generated out of the Gradle build scripts, which is why you are sometimes prompted to "sync project with Gradle files" when you change files like build.gradle
. This is also why you don't bother putting .iml
files or .idea/
in version control, as their contents will be regenerated.
If I have a team that work in different IDE's like Eclipse and AS how to make project IDE agnostic?
To a large extent, you can't.
You are welcome to have an Android project that uses the Eclipse-style directory structure (e.g., resources and manifest in the project root directory). You can teach Gradle, via build.gradle
, how to find files in that structure. However, other metadata (compileSdkVersion
, dependencies, etc.) will not be nearly as easily replicated.
Other alternatives include:
Move everybody over to another build system, like Maven, that is equally integrated (or not, depending upon your perspective) to both Eclipse and Android Studio
Hope that Andmore takes off soon, so that perhaps you can have an Eclipse IDE that can build Android projects from Gradle build scripts
Have everyone use one IDE
Just leaving the default navbar built in with bootstrap works fine.
You just need to add the custom css below, that way everything still works as it should.
HTML:
<nav class="navbar navbar-default">
CSS:
.navbar-default {
background-color: transparent;
}
After reading your clarification, @Ates Goral's answer provides how to perform the same operation you're doing in C# in JavaScript.
@Gumbo's answer provides the best way to check for null; however, it's important to note the difference in ==
versus ===
in JavaScript especially when it comes to issues of checking for undefined
and/or null
.
There's a really good article about the difference in two terms here. Basically, understand that if you use ==
instead of ===
, JavaScript will try to coalesce the values you're comparing and return what the result of the comparison after this coalescence.
My alternative solution to using Valgrind:
I'm very happy because I just helped my friend debug a program. His program had this exact problem (malloc()
causing abort), with the same error message from GDB.
I compiled his program using Address Sanitizer with
gcc -Wall -g3 -fsanitize=address -o new new.c
^^^^^^^^^^^^^^^^^^
And then ran gdb new
. When the program gets terminated by SIGABRT
caused in a subsequent malloc()
, a whole lot of useful information is printed:
=================================================================
==407==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x6060000000b4 at pc 0x7ffffe49ed1a bp 0x7ffffffedc20 sp 0x7ffffffed3c8
WRITE of size 104 at 0x6060000000b4 thread T0
#0 0x7ffffe49ed19 (/usr/lib/x86_64-linux-gnu/libasan.so.4+0x5ed19)
#1 0x8001dab in CreatHT2 /home/wsl/Desktop/hash/new.c:59
#2 0x80031cf in main /home/wsl/Desktop/hash/new.c:209
#3 0x7ffffe061b96 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)
#4 0x8001679 in _start (/mnt/d/Desktop/hash/new+0x1679)
0x6060000000b4 is located 0 bytes to the right of 52-byte region [0x606000000080,0x6060000000b4)
allocated by thread T0 here:
#0 0x7ffffe51eb50 in __interceptor_malloc (/usr/lib/x86_64-linux-gnu/libasan.so.4+0xdeb50)
#1 0x8001d56 in CreatHT2 /home/wsl/Desktop/hash/new.c:55
#2 0x80031cf in main /home/wsl/Desktop/hash/new.c:209
#3 0x7ffffe061b96 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)
Let's take a look at the output, especially the stack trace:
The first part says there's a invalid write operation at new.c:59
. That line reads
memset(len,0,sizeof(int*)*p);
^^^^^^^^^^^^
The second part says the memory that the bad write happened on is created at new.c:55
. That line reads
if(!(len=(int*)malloc(sizeof(int)*p))){
^^^^^^^^^^^
That's it. It only took me less than half a minute to locate the bug that confused my friend for a few hours. He managed to locate the failure, but it's a subsequent malloc()
call that failed, without being able to spot this error in previous code.
Sum up: Try the -fsanitize=address
of GCC or Clang. It can be very helpful when debugging memory issues.
Step 1 : import MyIcon from './img/icon.png'
step 2 :
<img
src={MyIcon}
style={{width:'100%', height:'100%'}}
/>
You can try this:
(cat ./body.txt)|mailx -s "subject text" -a "attchement file" [email protected]
I followed the solution above from Jonas and it worked well until I needed to add a second column. What I found is that when making the columns visible again Oracle does not necessarily set them visible in the order listed in the statement.
To demonstrate this follow Jonas' example above. As he showed, once the steps are complete the table is in the order that you'd expect. Things then break down when you add another column as shown below:
Example (continued from Jonas'):
Add another column which is to be inserted before column C.
ALTER TABLE t ADD (b2 INT);
Use the technique demonstrated above to move the newly added B2 column before column C.
ALTER TABLE t MODIFY (c INVISIBLE, d INVISIBLE, e INVISIBLE);
ALTER TABLE t MODIFY (c VISIBLE, d VISIBLE, e VISIBLE);
DESCRIBE t;
Name
----
A
B
B2
D
E
C
As shown above column C has moved to the end. It seems that the ALTER TABLE statement above processed the columns in the order D, E, C rather than in the order specified in the statement (perhaps in physical table order). To ensure that the column is placed where desired it is necessary to make the columns visible one by one in the desired order.
ALTER TABLE t MODIFY (c INVISIBLE, d INVISIBLE, e INVISIBLE);
ALTER TABLE t MODIFY c VISIBLE;
ALTER TABLE t MODIFY d VISIBLE;
ALTER TABLE t MODIFY e VISIBLE;
DESCRIBE t;
Name
----
A
B
B2
C
D
E
I would use Joda Time, parse the time as a LocalTime
, and then use
time = time.plusMinutes(10);
Short but complete program to demonstrate this:
import org.joda.time.*;
import org.joda.time.format.*;
public class Test {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
LocalTime time = formatter.parseLocalTime("14:10");
time = time.plusMinutes(10);
System.out.println(formatter.print(time));
}
}
Note that I would definitely use Joda Time instead of java.util.Date/Calendar if you possibly can - it's a much nicer API.
A reasonable solution would be to use an iterator if you don't know anything about the underlying Collection, but do know that there is a "last" element. This isn't always the case, not all Collections are ordered.
Object lastElement = null;
for (Iterator collectionItr = c.iterator(); collectionItr.hasNext(); ) {
lastElement = collectionItr.next();
}
It is also worth noting the sorted()
function:
for x in sorted(list):
print x
This returns a new, sorted version of a list without changing the original list.
string.Join(" ,", myArrayList.ToArray());
This will work with .net framework 4.5
I did the following to make this run on AS 3.5
app/ build.gradle
apply plugin: 'com.android.application'
android { compileSdkVersion 21 buildToolsVersion "25.0.0"
defaultConfig {
applicationId "com.example.android.mobileperf.render"
minSdkVersion 14
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:21.0.0' implementation 'com.squareup.picasso:picasso:2.71828' }
build.gradle
buildscript { repositories { jcenter() mavenCentral() maven { url 'https://maven.google.com/' name 'Google' } google() } dependencies { classpath 'com.android.tools.build:gradle:3.0.1' } } allprojects { repositories { jcenter() google() } }
gradle-wrapper.properties
distributionUrl=https://services.gradle.org/distributions/gradle-4.1-all.zip
Because on the second loop, $v
is still a reference to the last array item, so it's overwritten each time.
You can see it like that:
$a = array ('zero','one','two', 'three');
foreach ($a as &$v) {
}
foreach ($a as $v) {
echo $v.'-'.$a[3].PHP_EOL;
}
As you can see, the last array item takes the current loop value: 'zero', 'one', 'two', and then it's just 'two'... : )
We can create method for it. Simply use it.
public func createBorderForView(color: UIColor, radius: CGFloat, width: CGFloat = 0.7) {
self.layer.borderWidth = width
self.layer.cornerRadius = radius
self.layer.shouldRasterize = false
self.layer.rasterizationScale = 2
self.clipsToBounds = true
self.layer.masksToBounds = true
let cgColor: CGColor = color.cgColor
self.layer.borderColor = cgColor
}
In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])
In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]:
A B C D
1 0.319124 0.296653 0.138206 0.246017
2 0.376994 0.326481 0.230464 0.066062
3 0.036134 0.192954 0.430341 0.340571
I'm using 2.5, 2.6, and 3.0 from the shell with one line batch scripts of the form:
:: The @ symbol at the start turns off the prompt from displaying the command.
:: The % represents an argument, while the * means all of them.
@c:\programs\pythonX.Y\python.exe %*
Name them pythonX.Y.bat
and put them somewhere in your PATH. Copy the file for the preferred minor version (i.e. the latest) to pythonX.bat
. (E.g. copy python2.6.bat python2.bat
.) Then you can use python2 file.py
from anywhere.
However, this doesn't help or even affect the Windows file association situation. For that you'll need a launcher program that reads the #!
line, and then associate that with .py and .pyw files.
you must be using old version of wget i had same issue. i was using wget 1.12.so to solve this issue there are 2 way:
Update wget
or use curl
curl -LO 'https://example.com/filename.tar.gz'
inline if:
(('hypothesis') ? 'truthy conclusion' : 'falsey conclusion')
truthy conclusion: statements executed when hypothesis is true
falsey conclusion: statements executed when hypothesis is false
your example:
var c = ((a < b) ? 'a<b statements' : '!(a<b) statements');
new String(byteArray, Charset.defaultCharset())
This will convert a byte array to the default charset in java. It may throw exceptions depending on what you supply with the byteArray.
Component
import { Component, ElementRef, ViewChild, AfterViewInit} from '@angular/core';
...
@ViewChild('input1', {static: false}) inputEl: ElementRef;
ngAfterViewInit() {
setTimeout(() => this.inputEl.nativeElement.focus());
}
HTML
<input type="text" #input1>
Using require.js you can do the same thing in a safer way. You can just define your dependency on jquery and then execute the code you want using the dependency when it is loaded without polluting the namespace:
I generally recommend this library for managing all dependencies on Javascript. It's simple and allows for an efficient optimization of resource loading. However there's some precautions you may need to take when using it with JQuery . My favourite way to deal with them is explained in this github repo and reflected by the following code sample:
<title>jQuery+RequireJS Sample Page</title>
<script src="scripts/require.js"></script>
<script>
require({
baseUrl: 'scripts',
paths: {
jquery: 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min'
},
priority: ['jquery']
}, ['main']);
</script>
You can use netstat command
netstat --listen
To display open ports and established TCP connections,
netstat -vatn
To display only open UDP ports try the following command:
netstat -vaun
This worked!
gulp.task('script', done => {
// ... code gulp.src( ... )
done();
});
gulp.task('css', done => {
// ... code gulp.src( ... )
done();
});
gulp.task('default', gulp.parallel(
'script',
'css'
)
);
This is actually javascript but related/relevant because .querySelectorAll targets by CSS syntax:
var i_will_target_self = document.querySelectorAll("ul.menu li a#example")
this example uses css to target links in a menu with id = "example"
that creates a variable which is a collection of the elements we want to change, but we still have actually change them by setting the new target ("_blank"):
for (var i = 0; i < 5; i++) {
i_will_target_self[i].target = "_blank";
}
That code assumes that there are 5 or less elements. That can be changed easily by changing the phrase "i < 5."
read more here: http://xahlee.info/js/js_get_elements.html
<div
style="-moz-user-select: none; -webkit-user-select: none; -ms-user-select:none; user-select:none;-o-user-select:none;"
unselectable="on"
onselectstart="return false;"
onmousedown="return false;">
Blabla
</div>
For right to left (entry animation) and left to right (exit animation):
styles.xml:
<style name="CustomDialog" parent="@android:style/Theme.Dialog">
<item name="android:windowAnimationStyle">@style/CustomDialogAnimation</item>
</style>
<style name="CustomDialogAnimation">
<item name="android:windowEnterAnimation">@anim/translate_left_side</item>
<item name="android:windowExitAnimation">@anim/translate_right_side</item>
</style>
Create two files in res/anim/:
translate_right_side.xml:
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXDelta="0%" android:toXDelta="100%"
android:fromYDelta="0%" android:toYDelta="0%"
android:duration="600"/>
translate_left_side.xml:
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="600"
android:fromXDelta="100%"
android:toXDelta="0%"/>
In you Fragment/Activity:
Dialog dialog = new Dialog(getActivity(), R.style.CustomDialog);
This worked for me (Select2 4.0.4):
$(document).on('change', 'select#your_id', function(e) {
// your code
console.log('this.value', this.value);
});
Even though I had gcc already installed, I had to run
sudo apt-get install build-essential
to get rid of that error
Update On 18-Dec-2017
You can update Google Play Services via the Play Store app in your emulator just as you would on a physical Android device from API 24.
check Emulator new features added with stable update from Android Studio v 3.0
Google Play Support - From Google : We know that many app developers use Google Play Services, and it can be difficult to keep the service up to date in the Android Emulator system images. To solve this problem, we now offer versions of Android System Images that include the Play Store app. The Google Play images are available starting with Android Nougat (API 24). With these new emulator images, you can update Google Play Services via the Play Store app in your emulator just as you would on a physical Android device. Plus, you can now test end-to-end install, update, and purchase flows with the Google Play Store.
Quick Boot - Quick Boot allows you to resume your Android Emulator session in under 6 seconds
Android CTS Compatibility
Performance Improvements - With the latest versions of the Android Emulator, we now allocate RAM on demand, instead of allocating and pinning the memory to the max RAM size defined in your AVD.
Virtual sensors
Wi-Fi support
GPS location and Many more...
OR
Update this SDK Build-Tools and Android Emulator to latest and this alert message will not come again,
Settings --> Android SDK --> SDK Tools(tab) --> Android SDK Build-Tools
Another interesting solution in ORACLE PL/SQL:
SELECT LEVEL n
FROM DUAL
CONNECT BY LEVEL <= 100;
My one line solution:
hash.each { |key, array| puts "#{key}-----", array }
I think it is pretty easy to read.
In order to make the terminal always have the file ~/.bashrc
and there put the path you wish to use, by adding:
export PATH=$PATH:/XXX
where XXX is the path that you wish to use.
for adb, here's what i use:
export PATH=$PATH:/home/user/Android/android-sdk-linux_x86/platform-tools/
(where "user" is my user name).
If you have MAMP PRO you can set up a host like mysite.local, then add some options from the 'Advanced' panel in the main window. Just switch on the options 'Indexes' and 'MultiViews'. 'Includes' and 'FollowSymLinks' should already be checked.
To check file exists or not you can use
System.IO.File.Exists(path)
@echo off
call :isAdmin
if %errorlevel% == 0 (
goto :run
) else (
echo Requesting administrative privileges...
goto :UACPrompt
)
exit /b
:isAdmin
fsutil dirty query %systemdrive% >nul
exit /b
:run
<YOUR BATCH SCRIPT HERE>
exit /b
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "cmd.exe", "/c %~s0 %~1", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B`
Is this a one time script, or regularly occurring job?
In the past, for special projects that temporarily require lots of space for the log file, I created a second log file and made it huge. Once the project is complete we then removed the extra log file.
If you see this error when running tests, make sure you have imported the module the pipe belongs to, e.g.:
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [CustomPipeModule],
declarations: [...],
providers: [...],
...
}).compileComponents();
}));
/*
This function is as JSON.Stringify (but if you has not in your js-engine you can use this)
Params:
obj - your object
inc_ident - can be " " or "\t".
show_types - show types of object or not
ident - need for recoursion but you can not set this parameter.
*/
function getAsText(obj, inc_ident, show_types, ident) {
var res = "";
if (!ident)
ident = "";
if (typeof(obj) == "string") {
res += "\"" + obj + "\" ";
res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
} else if (typeof(obj) == "number" || typeof(obj) == "boolean") {
res += obj;
res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
} else if (obj instanceof Array) {
res += "[ ";
res += show_types ? "/* typeobj: " + typeof(obj) + "*/" : "";
res += "\r\n";
var new_ident = ident + inc_ident;
var arr = [];
for(var key in obj) {
arr.push(new_ident + getAsText(obj[key], inc_ident, show_types, new_ident));
}
res += arr.join(",\r\n") + "\r\n";
res += ident + "]";
} else {
var new_ident = ident + inc_ident;
res += "{ ";
res += (show_types == true) ? "/* typeobj: " + typeof(obj) + "*/" : "";
res += "\r\n";
var arr = [];
for(var key in obj) {
arr.push(new_ident + '"' + key + "\" : " + getAsText(obj[key], inc_ident, show_types, new_ident));
}
res += arr.join(",\r\n") + "\r\n";
res += ident + "}\r\n";
}
return res;
};
example to use:
var obj = {
str : "hello",
arr : ["1", "2", "3", 4],
b : true,
vobj : {
str : "hello2"
}
}
var ForReading = 1, ForWriting = 2;
var fso = new ActiveXObject("Scripting.FileSystemObject")
f1 = fso.OpenTextFile("your_object1.txt", ForWriting, true)
f1.Write(getAsText(obj, "\t"));
f1.Close();
f2 = fso.OpenTextFile("your_object2.txt", ForWriting, true)
f2.Write(getAsText(obj, "\t", true));
f2.Close();
your_object1.txt:
{
"str" : "hello" ,
"arr" : [
"1" ,
"2" ,
"3" ,
4
],
"b" : true,
"vobj" : {
"str" : "hello2"
}
}
your_object2.txt:
{ /* typeobj: object*/
"str" : "hello" /* typeobj: string*/,
"arr" : [ /* typeobj: object*/
"1" /* typeobj: string*/,
"2" /* typeobj: string*/,
"3" /* typeobj: string*/,
4/* typeobj: number*/
],
"b" : true/* typeobj: boolean*/,
"vobj" : { /* typeobj: object*/
"str" : "hello2" /* typeobj: string*/
}
}
Use this simple javascript code to redirect page to another page using specific interval of time...
Please add this code into your web site page, which is you want to redirect :
<script type="text/javascript">
(function(){
setTimeout(function(){
window.location="http://brightwaay.com/";
},3000); /* 1000 = 1 second*/
})();
</script>
Most answers are way too complicated in my opinion, how about this?
digits = 2 # Specify how many digits you want
fnum = '122.485221'
truncated_float = float(fnum[:fnum.find('.') + digits + 1])
>>> 122.48
Simply scanning for the index of '.' and truncate as desired (no rounding). Convert string to float as final step.
Or in your case if you get a float as input and want a string as output:
fnum = str(122.485221) # convert float to string first
truncated_float = fnum[:fnum.find('.') + digits + 1] # string output
It seems that the problem is in eslint-plugin-react
.
It can not correctly detect what props were mentioned in propTypes
if you have annotated named objects via destructuring anywhere in the class.
There was similar problem in the past
Use the HttpClient
class from HttpClientModule
if you're using Angular 4.3.x and above:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
HttpClientModule
],
...
class MyService() {
constructor(http: HttpClient) {...}
It's an upgraded version of http
from @angular/http
module with the following improvements:
- Interceptors allow middleware logic to be inserted into the pipeline
- Immutable request/response objects
- Progress events for both request upload and response download
You can read about how it works in Insider’s guide into interceptors and HttpClient mechanics in Angular.
- Typed, synchronous response body access, including support for JSON body types
- JSON is an assumed default and no longer needs to be explicitly parsed
- Post-request verification & flush based testing framework
Going forward the old http client will be deprecated. Here are the links to the commit message and the official docs.
Also pay attention that old http was injected using Http
class token instead of the new HttpClient
:
import { HttpModule } from '@angular/http';
@NgModule({
imports: [
BrowserModule,
HttpModule
],
...
class MyService() {
constructor(http: Http) {...}
Also, new HttpClient
seem to require tslib
in runtime, so you have to install it npm i tslib
and update system.config.js
if you're using SystemJS
:
map: {
...
'tslib': 'npm:tslib/tslib.js',
And you need to add another mapping if you use SystemJS:
'@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',
Gonna post this answer here after seeing some of the answers (including the accepted one) which claim to "do the trick". First, we need to identify the issue before fixing it.
the requested PHP extension gd is missing from your system.
As the above line clearly states, we need to install the extension php-gd.
So, we can go with sudo apt install php<version>-gd
and it should fix this error unless the system needs more extensions which happens to be the exact case here in the system in question. It needs a couple more extensions php-intl and php-xsl.
So let it be mbstring or mcrypt, you should install whatever the extensions your system is missing. How can you find what is missing? Just read the error message, it is there.
If there is a piece of code that you repeat all the time according to Don't Repeat Yourself you should put it in your own library and call that. With that in mind there are 2 aspects to getting the right answer here. The first is clarity and brevity in the code that calls the library function. The second is the performance implications of foreach.
First let's think about the clarity and brevity in the calling code.
You can do foreach in a number of ways:
Out of all the ways to do a foreach List.ForEach with a lamba is the clearest and briefest.
list.ForEach(i => Console.Write("{0}\t", i));
So at this stage it may look like the List.ForEach is the way to go. However what's the performance of this? It's true that in this case the time to write to the console will govern the performance of the code. When we know something about performance of a particular language feature we should certainly at least consider it.
According to Duston Campbell's performance measurements of foreach the fastest way of iterating the list under optimised code is using a for loop without a call to List.Count.
The for loop however is a verbose construct. It's also seen as a very iterative way of doing things which doesn't match with the current trend towards functional idioms.
So can we get brevity, clarity and performance? We can by using an extension method. In an ideal world we would create an extension method on Console that takes a list and writes it with a delimiter. We can't do this because Console is a static class and extension methods only work on instances of classes. Instead we need to put the extension method on the list itself (as per David B's suggestion):
public static void WriteLine(this List<int> theList)
{
foreach (int i in list)
{
Console.Write("{0}\t", t.ToString());
}
Console.WriteLine();
}
This code is going to used in many places so we should carry out the following improvements:
Here's how the code for the function would look:
public static void WriteToConsole<T>(this IList<T> collection)
{
int count = collection.Count();
for(int i = 0; i < count; ++i)
{
Console.Write("{0}\t", collection[i].ToString(), delimiter);
}
Console.WriteLine();
}
We can improve this even further by allowing the client to pass in the delimiter. We could then provide a second function that writes to console with the standard delimiter like this:
public static void WriteToConsole<T>(this IList<T> collection)
{
WriteToConsole<T>(collection, "\t");
}
public static void WriteToConsole<T>(this IList<T> collection, string delimiter)
{
int count = collection.Count();
for(int i = 0; i < count; ++i)
{
Console.Write("{0}{1}", collection[i].ToString(), delimiter);
}
Console.WriteLine();
}
So now, given that we want a brief, clear performant way of writing lists to the console we have one. Here is entire source code including a demonstration of using the the library function:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleWritelineTest
{
public static class Extensions
{
public static void WriteToConsole<T>(this IList<T> collection)
{
WriteToConsole<T>(collection, "\t");
}
public static void WriteToConsole<T>(this IList<T> collection, string delimiter)
{
int count = collection.Count();
for(int i = 0; i < count; ++i)
{
Console.Write("{0}{1}", collection[i].ToString(), delimiter);
}
Console.WriteLine();
}
}
internal class Foo
{
override public string ToString()
{
return "FooClass";
}
}
internal class Program
{
static void Main(string[] args)
{
var myIntList = new List<int> {1, 2, 3, 4, 5};
var myDoubleList = new List<double> {1.1, 2.2, 3.3, 4.4};
var myDoubleArray = new Double[] {12.3, 12.4, 12.5, 12.6};
var myFooList = new List<Foo> {new Foo(), new Foo(), new Foo()};
// Using the standard delimiter /t
myIntList.WriteToConsole();
myDoubleList.WriteToConsole();
myDoubleArray.WriteToConsole();
myFooList.WriteToConsole();
// Using our own delimiter ~
myIntList.WriteToConsole("~");
Console.Read();
}
}
}
=======================================================
You might think that this should be the end of the answer. However there is a further piece of generalisation that can be done. It's not clear from fatcat's question if he is always writing to the console. Perhaps something else is to be done in the foreach. In that case Jason Bunting's answer is going to give that generality. Here is his answer again:
list.ForEach(i => Console.Write("{0}\t", i));
That is unless we make one more refinement to our extension methods and add FastForEach as below:
public static void FastForEach<T>(this IList<T> collection, Action<T> actionToPerform)
{
int count = collection.Count();
for (int i = 0; i < count; ++i)
{
actionToPerform(collection[i]);
}
Console.WriteLine();
}
This allows us to execute any arbitrary code against every element in the collection using the fastest possible iteration method.
We can even change the WriteToConsole function to use FastForEach
public static void WriteToConsole<T>(this IList<T> collection, string delimiter)
{
collection.FastForEach(item => Console.Write("{0}{1}", item.ToString(), delimiter));
}
So now the entire source code, including an example usage of FastForEach is:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleWritelineTest
{
public static class Extensions
{
public static void WriteToConsole<T>(this IList<T> collection)
{
WriteToConsole<T>(collection, "\t");
}
public static void WriteToConsole<T>(this IList<T> collection, string delimiter)
{
collection.FastForEach(item => Console.Write("{0}{1}", item.ToString(), delimiter));
}
public static void FastForEach<T>(this IList<T> collection, Action<T> actionToPerform)
{
int count = collection.Count();
for (int i = 0; i < count; ++i)
{
actionToPerform(collection[i]);
}
Console.WriteLine();
}
}
internal class Foo
{
override public string ToString()
{
return "FooClass";
}
}
internal class Program
{
static void Main(string[] args)
{
var myIntList = new List<int> {1, 2, 3, 4, 5};
var myDoubleList = new List<double> {1.1, 2.2, 3.3, 4.4};
var myDoubleArray = new Double[] {12.3, 12.4, 12.5, 12.6};
var myFooList = new List<Foo> {new Foo(), new Foo(), new Foo()};
// Using the standard delimiter /t
myIntList.WriteToConsole();
myDoubleList.WriteToConsole();
myDoubleArray.WriteToConsole();
myFooList.WriteToConsole();
// Using our own delimiter ~
myIntList.WriteToConsole("~");
// What if we want to write them to separate lines?
myIntList.FastForEach(item => Console.WriteLine(item.ToString()));
Console.Read();
}
}
}
Definitely, git filter-branch
is the way to go.
Sadly, this will not suffice to completely remove filename.orig
from your repo, as it can be still be referenced by tags, reflog entries, remotes and so on.
I recommend removing all these references as well, and then calling the garbage collector. You can use the git forget-blob
script from this website to do all this in one step.
git forget-blob filename.orig
I had the same problem trying to show a Toast in a fragment.
After some debugging I found out that I was removing the fragment before calling:
Toast.makeText(getContext(), "text", Toast.LENGTH_SHORT).show();
Because the fragment had been removed, the context became null, causing the exception.
Simple solution: call the getContext()
before removing the fragment.
Angular hasn't provided a way to signal when a page finished loading, maybe because "finished" depends on your application. For example, if you have hierarchical tree of partials, one loading the others. "Finish" would mean that all of them have been loaded. Any framework would have a hard time analyzing your code and understanding that everything is done, or still waited upon. For that, you would have to provide application-specific logic to check and determine that.
to add to John's answer:
what you want to pass to the shuffle
function is a deck of cards from the class deckOfCards
that you've declared in main; however, the deck of cards or vector<Card> deck
that you've declared in your class is private, so not accessible from outside the class. this means you'd want a getter function, something like this:
class deckOfCards
{
private:
vector<Card> deck;
public:
deckOfCards();
static int count;
static int next;
void shuffle(vector<Card>& deck);
Card dealCard();
bool moreCards();
vector<Card>& getDeck() { //GETTER
return deck;
}
};
this will in turn allow you to call your shuffle function from main like this:
deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck.getDeck()); // shuffle the cards in the deck
however, you have more problems, specifically when calling cout
. first, you're calling the dealCard
function wrongly; as dealCard
is a memeber function of a class, you should be calling it like this cardDeck.dealCard();
instead of this dealCard(cardDeck);
.
now, we come to your second problem - print to standard output. you're trying to print your deal card, which is an object of type Card
by using the following instruction:
cout << cardDeck.dealCard();// deal the cards in the deck
yet, the cout
doesn't know how to print it, as it's not a standard type. this means you should overload your <<
operator to print whatever you want it to print when calling with a Card
type.
Instead of just doing this quoted method from https://stackoverflow.com/a/4635440/3787376,
You can do something like this:
// show loading image $('#loader_img').show(); // main image loaded ? $('#main_img').on('load', function(){ // hide/remove the loading image $('#loader_img').hide(); });
You assign
load
event to the image which fires when image has finished loading. Before that, you can show your loader image.
you can use a different jQuery function to make the loading image fade away, then be hidden:
// Show the loading image.
$('#loader_img').show();
// When main image loads:
$('#main_img').on('load', function(){
// Fade out and hide the loading image.
$('#loader_img').fadeOut(100); // Time in milliseconds.
});
"Once the opacity reaches 0, the display style property is set to none." http://api.jquery.com/fadeOut/
Or you could not use the jQuery library because there are already simple cross-browser JavaScript methods.
You can always use multiplication if you don't immediately recall the .empty
or .full
methods:
>>> np.nan * np.ones(shape=(3,2))
array([[ nan, nan],
[ nan, nan],
[ nan, nan]])
Of course it works with any other numerical value as well:
>>> 42 * np.ones(shape=(3,2))
array([[ 42, 42],
[ 42, 42],
[ 42, 42]])
But the @u0b34a0f6ae's accepted answer is 3x faster (CPU cycles, not brain cycles to remember numpy syntax ;):
$ python -mtimeit "import numpy as np; X = np.empty((100,100));" "X[:] = np.nan;"
100000 loops, best of 3: 8.9 usec per loop
(predict)laneh@predict:~/src/predict/predict/webapp$ master
$ python -mtimeit "import numpy as np; X = np.ones((100,100));" "X *= np.nan;"
10000 loops, best of 3: 24.9 usec per loop
SELECT MAX(ID) FROM tablename LIMIT 1
Use this query to find the highest ID in the MySQL table.
See if this helps :
Set a flag inside the exception handler and check it before working on the s.
flagBreak = false;
while True :
if flagBreak : break
if s :
print s
try :
s = i.next()
except StopIteration :
flagBreak = true
print "done"
you'd use another join, something along these lines:
SELECT toD.dom_url AS ToURL,
fromD.dom_url AS FromUrl,
rvw.*
FROM reviews AS rvw
LEFT JOIN domain AS toD
ON toD.Dom_ID = rvw.rev_dom_for
LEFT JOIN domain AS fromD
ON fromD.Dom_ID = rvw.rev_dom_from
EDIT:
All you're doing is joining in the table multiple times. Look at the query in the post: it selects the values from the Reviews tables (aliased as rvw), that table provides you 2 references to the Domain table (a FOR and a FROM).
At this point it's a simple matter to left join the Domain table to the Reviews table. Once (aliased as toD) for the FOR, and a second time (aliased as fromD) for the FROM.
Then in the SELECT list, you will select the DOM_URL fields from both LEFT JOINS of the DOMAIN table, referencing them by the table alias for each joined in reference to the Domains table, and alias them as the ToURL and FromUrl.
For more info about aliasing in SQL, read here.
When we apply local url, ErrorDocument directive expect the full path from DocumentRoot. There fore,
ErrorDocument 404 /yourfoldernames/errors/404.html
SERIOUS DISCLAIMER
This solution has a serious security flaw. Please use at your own risk.
Have a look at the comments on this post, and look at all the answers to this question.
OK, I had to go to the customer premises and found a solution. I:
Then I opened the JAWS application without any warning. This is a little bit cumbersome, but much cheaper than buying a signed certificate!
First Install This Package:
Install-Package SixLabors.ImageSharp -Version 1.0.0-beta0007
[SixLabors.ImageSharp][1] [1]: https://www.nuget.org/packages/SixLabors.ImageSharp
Then use Below Code For Cast Byte Array To Image :
Image<Rgba32> image = Image.Load(byteArray);
For Get ImageFormat Use Below Code:
IImageFormat format = Image.DetectFormat(byteArray);
For Mutate Image Use Below Code:
image.Mutate(x => x.Resize(new Size(1280, 960)));
You can instantiate it after you implemented all the methods. Then the constructor will be called.
SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS
(SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)
or
SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN
(SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)
or
SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B
ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL
Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.
This will work nicely if it is in a gem lib directory and this is the tokenizer.rb
require_relative 'tokenizer/main'
.then(() => new Promise((resolve) => setTimeout(resolve, 15000)))
UPDATE:
when I need sleep in async function I throw in
await new Promise(resolve => setTimeout(resolve, 1000))
Just in case someone stumbles upon this like I did and doesn't realise, the two variations above are for different use cases.
The following:
.blue-border, .background {
border: 1px solid #00f;
background: #fff;
}
is for when you want to add styles to elements that have either the blue-border or background class, for example:
<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>
would all get a blue border and white background applied to them.
However, the accepted answer is different.
.blue-border.background {
border: 1px solid #00f;
background: #fff;
}
This applies the styles to elements that have both classes so in this example only the <div>
with both classes should get the styles applied (in browsers that interpret the CSS properly):
<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>
So basically think of it like this, comma separating applies to elements with one class OR another class and dot separating applies to elements with one class AND another class.
If you're using GNU make, you could try
NUMBERS = 1 2 3 4 doit: $(foreach var,$(NUMBERS),./a.out $(var);)
which will generate and execute
./a.out 1; ./a.out 2; ./a.out 3; ./a.out 4;
Be carefully though. If you return Collections.emptyList()
and then try to do some changes with it like add()
or smth like that, u will have an UnsupportedOperationException()
because Collections.emptyList()
returns an immutable object.
list comprehension formula:
[<value_when_condition_true> if <condition> else <value_when_condition_false> for value in list_name]
thus you can do it like this:
[y for y in a if y not in b]
Only for demonstration purpose : [y if y not in b else False for y in a ]
An Alternative Solution to the above
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(topLeft: Radius.circular(20), topRight: Radius.circular(20))),
color: Colors.white,
child: ...
)
You can use BorderRadius.only() to customize the corners you wish to manage.
I'm guessing from your last question, asked 20 minutes before this one, that you are trying to parse (read and convert) the XML found through using GeoNames' FindNearestAddress.
If your XML is in a string variable called txt
and looks like this:
<address>
<street>Roble Ave</street>
<mtfcc>S1400</mtfcc>
<streetNumber>649</streetNumber>
<lat>37.45127</lat>
<lng>-122.18032</lng>
<distance>0.04</distance>
<postalcode>94025</postalcode>
<placename>Menlo Park</placename>
<adminCode2>081</adminCode2>
<adminName2>San Mateo</adminName2>
<adminCode1>CA</adminCode1>
<adminName1>California</adminName1>
<countryCode>US</countryCode>
</address>
Then you can parse the XML with Javascript DOM like this:
if (window.DOMParser)
{
parser = new DOMParser();
xmlDoc = parser.parseFromString(txt, "text/xml");
}
else // Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(txt);
}
And get specific values from the nodes like this:
//Gets house address number
xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue;
//Gets Street name
xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue;
//Gets Postal Code
xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue;
In response to @gaugeinvariante's concerns about xml with Namespace prefixes. Should you have a need to parse xml with Namespace prefixes, everything should work almost identically:
NOTE: this will only work in browsers that support xml namespace prefixes such as Microsoft Edge
// XML with namespace prefixes 's', 'sn', and 'p' in a variable called txt_x000D_
txt = `_x000D_
<address xmlns:p='example.com/postal' xmlns:s='example.com/street' xmlns:sn='example.com/streetNum'>_x000D_
<s:street>Roble Ave</s:street>_x000D_
<sn:streetNumber>649</sn:streetNumber>_x000D_
<p:postalcode>94025</p:postalcode>_x000D_
</address>`;_x000D_
_x000D_
//Everything else the same_x000D_
if (window.DOMParser)_x000D_
{_x000D_
parser = new DOMParser();_x000D_
xmlDoc = parser.parseFromString(txt, "text/xml");_x000D_
}_x000D_
else // Internet Explorer_x000D_
{_x000D_
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");_x000D_
xmlDoc.async = false;_x000D_
xmlDoc.loadXML(txt);_x000D_
}_x000D_
_x000D_
//The prefix should not be included when you request the xml namespace_x000D_
//Gets "streetNumber" (note there is no prefix of "sn"_x000D_
console.log(xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue);_x000D_
_x000D_
//Gets Street name_x000D_
console.log(xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue);_x000D_
_x000D_
//Gets Postal Code_x000D_
console.log(xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue);
_x000D_
Have you tried using @JsonProperty?
@Entity
public class City {
@id
Long id;
String name;
@JsonProperty("label")
public String getName() { return name; }
public void setName(String name){ this.name = name; }
@JsonProperty("value")
public Long getId() { return id; }
public void setId(Long id){ this.id = id; }
}
Unless you have a mail server set up on your local computer, setting SMTP = localhost won't have any effect.
In days gone by (long ago), it was sufficient to set the value of SMTP to the address of your ISP's SMTP server. This now rarely works because most ISPs insist on authentication with a username and password. However, the PHP mail() function doesn't support SMTP authentication. It's designed to work directly with the mail transport agent of the local server.
You either need to set up a local mail server or to use a PHP classs that supports SMTP authentication, such as Zend_Mail or PHPMailer. The simplest solution, however, is to upload your mail processing script to your remote server.
From the Android documentation:
The
CookieSyncManager
is used to synchronize the browser cookie store between RAM and permanent storage. To get the best performance, browser cookies are saved in RAM. A separate thread saves the cookies between, driven by a timer.To use the
CookieSyncManager
, the host application has to call the following when the application starts:CookieSyncManager.createInstance(context)
To set up for sync, the host application has to call
CookieSyncManager.getInstance().startSync()
in Activity.onResume(), and call
CookieSyncManager.getInstance().stopSync()
in Activity.onPause().
To get instant sync instead of waiting for the timer to trigger, the host can call
CookieSyncManager.getInstance().sync()
The sync interval is 5 minutes, so you will want to force syncs manually anyway, for instance in onPageFinished(WebView, String). Note that even sync() happens asynchronously, so don't do it just as your activity is shutting down.
Finally something like this should work:
// use cookies to remember a logged in status
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
WebView webview = new WebView(this);
webview.getSettings().setJavaScriptEnabled(true);
setContentView(webview);
webview.loadUrl([MY URL]);
Not answering OPs question directly, but for the people finding this question in search of clarity on what's the difference between allow,deny
and deny,allow
:
Read the comma as a "but".
allow but deny
: whitelist with exceptions.deny but allow
: blacklist with exceptions.allow only one country access, but exclude proxies within this country
OP needed a whitelist with exceptions, therefore allow,deny
instead of deny,allow
Interesting that these answers utilize printf
like it is a given.
printf
converts the integer to a Hexadecimal string value.
//*************************************************************
// void prntnum(unsigned long n, int base, char sign, char *outbuf)
// unsigned long num = number to be printed
// int base = number base for conversion; decimal=10,hex=16
// char sign = signed or unsigned output
// char *outbuf = buffer to hold the output number
//*************************************************************
void prntnum(unsigned long n, int base, char sign, char *outbuf)
{
int i = 12;
int j = 0;
do{
outbuf[i] = "0123456789ABCDEF"[num % base];
i--;
n = num/base;
}while( num > 0);
if(sign != ' '){
outbuf[0] = sign;
++j;
}
while( ++i < 13){
outbuf[j++] = outbuf[i];
}
outbuf[j] = 0;
}
It reappears because your submit button reloads the page. The simplest way to prevent this behavior is to add a return false
to the onclick
like so:
<input type="submit" value="Remove DUMMY" onclick="removeDummy(); return false;" />
This is super old, but I came across it and this worked for me.
<?php
//Get absolute path
$path = getcwd();
//strip the path at your root dir name and everything that follows it
$path = substr($path, 0, strpos($path, "root"));
echo "This Is Your Absolute Path: ";
echo $path; //This will output /home/public_html/
?>
First read your excel spreadsheet into pandas, below code will import your excel spreadsheet into pandas as a OrderedDict type which contain all of your worksheet as dataframes. Then simply use worksheet_name as a key to access specific worksheet as a dataframe and save only required worksheet as csv file by using df.to_csv(). Hope this will workout in your case.
import pandas as pd
df = pd.read_excel('YourExcel.xlsx', sheet_name=None)
df['worksheet_name'].to_csv('YourCsv.csv')
If your Excel file contain only one worksheet then simply use below code:
import pandas as pd
df = pd.read_excel('YourExcel.xlsx')
df.to_csv('YourCsv.csv')
If someone want to convert all the excel worksheets from single excel workbook to the different csv files, try below code:
import pandas as pd
def excelTOcsv(filename):
df = pd.read_excel(filename, sheet_name=None)
for key, value in df.items():
return df[key].to_csv('%s.csv' %key)
This function is working as a multiple Excel sheet of same excel workbook to multiple csv file converter. Where key is the sheet name and value is the content inside sheet.
You probably have something like:
"typescript":"~2.1.6"
in your package.json
which npm updates to the latest minor version, in your case being 2.4.1
Edit: Question from OP
But that doesn't explain why "npm install" would change the lock file. Isn't the lock file meant to create a reproducible build? If so, regardless of the semver value, it should still use the same 2.1.6 version.
Answer:
This is intended to lock down your full dependency tree. Let's say
typescript v2.4.1
requireswidget ~v1.0.0
. When you npm install it grabswidget v1.0.0
. Later on your fellow developer (or CI build) does an npm install and getstypescript v2.4.1
butwidget
has been updated towidget v1.0.1
. Now your node module are out of sync. This is whatpackage-lock.json
prevents.Or more generally:
As an example, consider
package A:
{ "name": "A", "version": "0.1.0", "dependencies": { "B": "<0.1.0" } }
package B:
{ "name": "B", "version": "0.0.1", "dependencies": { "C": "<0.1.0" } }
and package C:
{ "name": "C", "version": "0.0.1" }
If these are the only versions of A, B, and C available in the registry, then a normal npm install A will install:
[email protected] -- [email protected] -- [email protected]
However, if [email protected] is published, then a fresh npm install A will install:
[email protected] -- [email protected] -- [email protected] assuming the new version did not modify B's dependencies. Of course, the new version of B could include a new version of C and any number of new dependencies. If such changes are undesirable, the author of A could specify a dependency on [email protected]. However, if A's author and B's author are not the same person, there's no way for A's author to say that he or she does not want to pull in newly published versions of C when B hasn't changed at all.
OP Question 2: So let me see if I understand correctly. What you're saying is that the lock file specifies the versions of the secondary dependencies, but still relies on the fuzzy matching of package.json to determine the top-level dependencies. Is that accurate?
Answer: No. package-lock locks the entire package tree, including the root packages described in
package.json
. Iftypescript
is locked at2.4.1
in yourpackage-lock.json
, it should remain that way until it is changed. And lets say tomorrowtypescript
releases version2.4.2
. If I checkout your branch and runnpm install
, npm will respect the lockfile and install2.4.1
.
More on package-lock.json
:
package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.
This file is intended to be committed into source repositories, and serves various purposes:
Describe a single representation of a dependency tree such that teammates, deployments, and continuous integration are guaranteed to install exactly the same dependencies.
Provide a facility for users to "time-travel" to previous states of node_modules without having to commit the directory itself.
To facilitate greater visibility of tree changes through readable source control diffs.
And optimize the installation process by allowing npm to skip repeated metadata resolutions for previously-installed packages.
This is what I did. Works well.
First add the OkHttp to the gradle build file of the app module:
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.squareup.okhttp3:okhttp:3.10.0'
compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'
Then make a class extending Application
import android.app.Application;
import com.jakewharton.picasso.OkHttp3Downloader;
import com.squareup.picasso.Picasso;
public class Global extends Application {
@Override
public void onCreate() {
super.onCreate();
Picasso.Builder builder = new Picasso.Builder(this);
builder.downloader(new OkHttp3Downloader(this,Integer.MAX_VALUE));
Picasso built = builder.build();
built.setIndicatorsEnabled(true);
built.setLoggingEnabled(true);
Picasso.setSingletonInstance(built);
}
}
add it to the Manifest file as follows :
<application
android:name=".Global"
.. >
</application>
Now use Picasso as you normally would. No changes.
EDIT:
if you want to use cached images only. Call the library like this. I've noticed that if we don't add the networkPolicy, images won't show up in an fully offline start even if they are cached. The code below solves the problem.
Picasso.with(this)
.load(url)
.networkPolicy(NetworkPolicy.OFFLINE)
.into(imageView);
EDIT #2
the problem with the above code is that if you clear cache, Picasso will keep looking for it offline in cache and fail, the following code example looks at the local cache, if not found offline, it goes online and replenishes the cache.
Picasso.with(getActivity())
.load(imageUrl)
.networkPolicy(NetworkPolicy.OFFLINE)
.into(imageView, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
//Try again online if cache failed
Picasso.with(getActivity())
.load(posts.get(position).getImageUrl())
.error(R.drawable.header)
.into(imageView, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
Log.v("Picasso","Could not fetch image");
}
});
}
});
In SQL, there is only one kind of relationship, it is called a Reference. (Your front end may do helpful or confusing things [such as in some of the Answers], but that is a different story.)
In SQL terms, Bar references Foo
Not the other way around
CREATE TABLE Foo (
Foo CHAR(10) NOT NULL, -- primary key
Name CHAR(30) NOT NULL
CONSTRAINT PK -- constraint name
PRIMARY KEY (Foo) -- pk
)
CREATE TABLE Bar (
Bar CHAR(10) NOT NULL, -- primary key
Foo CHAR(10) NOT NULL, -- foreign key to Foo
Name CHAR(30) NOT NULL
CONSTRAINT PK -- constraint name
PRIMARY KEY (Bar), -- pk
CONSTRAINT Foo_HasMany_Bars -- constraint name
FOREIGN KEY (Foo) -- fk in (this) referencing table
REFERENCES Foo(Foo) -- pk in referenced table
)
Since Foo.Foo
is a Primary Key, it is unique, there is only one row for any given value of Foo
Bar.Foo
is a Reference, a Foreign Key, and there is no unique index on it, there can be many rows for any given value of Foo
Foo::Bar
is one-to-many Bar::Foo
is many-to-one
Bar
row, there is just one Foo
row that it ReferencesWhat is the real difference between one to many and many to one relationship?
There is only one relation, therefore there is no difference. Perception (from one "end" or the other "end") or reading it backwards, does not change the relation.
Cardinality is declared first in the data model, which means Logical and Physical (the intent), and then in the implementation (the intent realised).
One to zero-to-many
In SQL that (the above) is all that is required.
One to one-to-many
You need a Transaction to enforce the one in the Referencing table.
One to zero-to-one
You need in Bar
:
CONSTRAINT AK -- constraint name
UNIQUE (Foo) -- unique column, which makes it an Alternate Key
One to one
You need a Transaction to enforce the one in the Referencing table.
Many to many
There is no such thing at the Physical level (recall, there is only one type of relation in SQL).
At the early Logical levels during the modelling exercise, it is convenient to draw such a relation. Before the model gets close to implementation, it had better be elevated to using only things that can exist. Such a relation is resolved by implementing an Associative Table.
This one combines many of the answers give.
var randNo = Math.floor(Math.random() * 100) + 2 + "" + new Date().getTime() + Math.floor(Math.random() * 100) + 2 + (Math.random().toString(36).replace(/[^a-zA-Z]+/g, '').substr(0, 5));_x000D_
_x000D_
console.log(randNo);
_x000D_
I have been using it for 1 month with great results.
I had the same issue of multiple DocumentCompleted
fired events and tried out all the suggestions above. Finally, seems that in my case neither IsBusy
property works right nor Url
property, but the ReadyState
seems to be what I needed, because it has the status 'Interactive' while loading the multiple frames and it gets the status 'Complete' only after loading the last one. Thus, I know when the page is fully loaded with all its components.
I hope this may help others too :)
Do something like this:
A <div>
with ID of #imageDIV
, another one with ID #download
and a hidden <div>
with ID #previewImage
.
Include the latest version of jquery, and jspdf.debug.js from the jspdf CDN
Then add this script:
var element = $("#imageDIV"); // global variable
var getCanvas; // global variable
$('document').ready(function(){
html2canvas(element, {
onrendered: function (canvas) {
$("#previewImage").append(canvas);
getCanvas = canvas;
}
});
});
$("#download").on('click', function () {
var imgageData = getCanvas.toDataURL("image/png");
// Now browser starts downloading it instead of just showing it
var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
$("#download").attr("download", "image.png").attr("href", newData);
});
The div will be saved as a PNG on clicking the #download
Reference taken from this blog:
Below is a list of hashing algorithm along with its require bit size:
Created one sample table with require CHAR(n):
CREATE TABLE tbl_PasswordDataType
(
ID INTEGER
,MD5_128_bit CHAR(32)
,SHA_160_bit CHAR(40)
,SHA_224_bit CHAR(56)
,SHA_256_bit CHAR(64)
,SHA_384_bit CHAR(96)
,SHA_512_bit CHAR(128)
);
INSERT INTO tbl_PasswordDataType
VALUES
(
1
,MD5('SamplePass_WithAddedSalt')
,SHA1('SamplePass_WithAddedSalt')
,SHA2('SamplePass_WithAddedSalt',224)
,SHA2('SamplePass_WithAddedSalt',256)
,SHA2('SamplePass_WithAddedSalt',384)
,SHA2('SamplePass_WithAddedSalt',512)
);
The following signature will do:
List<Email> findByEmailIdInAndPincodeIn(List<String> emails, List<String> pinCodes);
Spring Data JPA supports a large number of keywords to build a query. IN
and AND
are among them.
IIRC the tables you need are DBA_TABLES, DBA_EXTENTS or DBA_SEGMENTS and DBA_DATA_FILES. There are also USER_ and ALL_ versions of these for tables you can see if you don't have administration permissions on the machine.
The "pre" and "post" nature of increment and decrement operators can tend to be confusing for those who are not familiar with them; that's one way in which they can be tricky.
I strongly prefer HomeBrew over MacPorts for installing software from source.
HomeBrew sequesters everything in /usr/local/Cellar so it doesn't spew files all over the place. (Yes, MacPorts keeps everything in /opt/local, but it requires sudo access, and I don't trust MacPorts with root.)
Installing MySQL is as simple as:
brew install mysql
mysql_install_db
To start mysql, in Terminal type:
mysqld&
There's a way to start it upon boot, but I like to start it manually.
Try putting \
at the end of each line before copying it.
Example:
echo "Hello world" && \
script_b.sh
echo $?
The exit code ($?
) is now the full sequence of commands, and not just the last command.
There you go, this is what I used to fix your problem:
CSS CODE
nav ul { list-style-type: none; }
HTML CODE
<nav>
<ul>
<li><a href="#">Milk</a>
<ul>
<li><a href="#">Goat</a></li>
<li><a href="#">Cow</a></li>
</ul>
</li>
<li><a href="#">Eggs</a>
<ul>
<li><a href="#">Free-range</a></li>
<li><a href="#">Other</a></li>
</ul>
</li>
<li><a href="#">Cheese</a>
<ul>
<li><a href="#">Smelly</a></li>
<li><a href="#">Extra smelly</a></li>
</ul>
</li>
</ul>
</nav>
This type of situation is implementation dependent and consequently it will require a vendor specific mechanism in order to trap. With Microsoft this will involve SEH, and *nix will involve a signal
In general though catching an Access Violation exception is a very bad idea. There is almost no way to recover from an AV exception and attempting to do so will just lead to harder to find bugs in your program.