jasonmp85 is right about passing a different array to String.format
. The size of an array can't be changed once constructed, so you'd have to pass a new array instead of modifying the existing one.
Object newArgs = new Object[args.length+1];
System.arraycopy(args, 0, newArgs, 1, args.length);
newArgs[0] = extraVar;
String.format(format, extraVar, args);
What I have done on my own windows computer where I have Python 2.7 and Python 3.4 installed is I wrote a simple .bat file in the same directory as my Python.exe files. They look something like,
cmd /k "c:\python27\python.exe" %*
The %* allows you to add arguments (Python files) afterwards. I believe /k keeps the prompt open after it finishes running the script. Then I save that as python27.bat Then I go to my Python 3 directory and make a bat file there. Now in my command line I can write
Python27 helloworld.py
Or
Python34 helloworld.py
And they will run in their respective versions of Python. Make sure that c:\python27 and c:\python34 are in your environment variables.
I got my answer from here
You Just execute the following commands in your command prompt,
For 32 bit machine,
cd C:\Windows\System32
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb
For 64 bit machine,
cd C:\Windows\SysWOW64
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb
KLSingleton is:
- Subclassible (to the n-th degree)
- ARC compatible
- Safe with
alloc
andinit
- Loaded lazily
- Thread-safe
- Lock-free (uses +initialize, not @synchronize)
- Macro-free
- Swizzle-free
- Simple
Here's a slightly more concise version of @vbem's solution:
from datetime import datetime as dt
dt.utcnow().astimezone().tzinfo
The only substantive difference is that I replaced datetime.datetime.now(datetime.timezone.utc)
with datetime.datetime.utcnow()
. For brevity, I also aliased datetime.datetime
as dt
.
For my purposes, I want the UTC offset in seconds. Here's what that looks like:
dt.utcnow().astimezone().utcoffset().total_seconds()
The filter option filters only the first level subkey below ansible_facts
You should use jwt.verify it will check if the token is expired. jwt.decode should not be used if the source is not trusted as it doesn't check if the token is valid.
If the mongo instance is build on the cloud.mongodb.com this error appears when the instance can work only from known IP addresses set in the IP whitelist pool when the instance was configured.
So from the mongo dashboard need to be set the current IP address on the IP whitelist from network access menu on the left.
BR,
you don't need. int[]
is an object and can be used as a key inside a map.
Map<int[], Double> frequencies = new HashMap<int[], Double>();
is the proper definition of the frequencies map.
This was wrong :-). The proper solution is posted too :-).
The information schema views and pg_typeof() return incomplete type information. Of these answers, psql
gives the most precise type information. (The OP might not need such precise information, but should know the limitations.)
create domain test_domain as varchar(15);
create table test (
test_id test_domain,
test_vc varchar(15),
test_n numeric(15, 3),
big_n bigint,
ip_addr inet
);
Using psql
and \d public.test
correctly shows the use of the data type test_domain
, the length of varchar(n) columns, and the precision and scale of numeric(p, s) columns.
sandbox=# \d public.test Table "public.test" Column | Type | Modifiers ---------+-----------------------+----------- test_id | test_domain | test_vc | character varying(15) | test_n | numeric(15,3) | big_n | bigint | ip_addr | inet |
This query against an information_schema view does not show the use of test_domain
at all. It also doesn't report the details of varchar(n) and numeric(p, s) columns.
select column_name, data_type
from information_schema.columns
where table_catalog = 'sandbox'
and table_schema = 'public'
and table_name = 'test';
column_name | data_type -------------+------------------- test_id | character varying test_vc | character varying test_n | numeric big_n | bigint ip_addr | inet
You might be able to get all that information by joining other information_schema views, or by querying the system tables directly. psql -E
might help with that.
The function pg_typeof()
correctly shows the use of test_domain
, but doesn't report the details of varchar(n) and numeric(p, s) columns.
select pg_typeof(test_id) as test_id,
pg_typeof(test_vc) as test_vc,
pg_typeof(test_n) as test_n,
pg_typeof(big_n) as big_n,
pg_typeof(ip_addr) as ip_addr
from test;
test_id | test_vc | test_n | big_n | ip_addr -------------+-------------------+---------+--------+--------- test_domain | character varying | numeric | bigint | inet
Right click project solution
Properties -> Configuration Properties -> C/C++ -> Precompiled Headers
Click on "Precompiled Headers" change to "Not Using Precompiled Headers".
Erase the "pch.h"/"stdafx.h" field in "Precompiled Header File" for the EOF error at the end of the build for the project.
Then you can feel free to delete the pch./stdafx. files in your project
this
SELECT field,datetime_field
FROM database
WHERE datetime_field > (sysdate-1)
will work. The question is: is the 'datetime_field' has the same format as sysdate ? My way to handle that: use 'to_char()' function (only works in Oracle).
samples: previous day:
select your_column
from your_table
where to_char(sysdate-1, 'dd.mm.yyyy')
or
select extract(day from date_field)||'/'||
extract(month from date_field)||'/'||
extract(year from date_field)||'/'||
as mydate
from dual(or a_table)
where extract(day from date_field) = an_int_number and
extract(month from date_field) = an_int_number and so on..
comparing date:
select your_column
from your_table
where
to_char(a_datetime_column, 'dd.mm.yyyy') > or < or >= or <= to_char(sysdate, 'dd.mm.yyyy')
time range between yesterday and a day before yesterday:
select your_column
from your_table
where
to_char(a_datetime_column, 'dd.mm.yyyy') > or < or >= or <= to_char(sysdate-1, 'dd.mm.yyyy') and
to_char(a_datetime_column, 'dd.mm.yyyy') > or < or >= or <= to_char(sysdate-2, 'dd.mm.yyyy')
other time range variation
select your_column
from your_table
where
to_char(a_datetime_column, 'dd.mm.yyyy') is between to_char(sysdate-1, 'dd.mm.yyyy')
and to_char(sysdate-2, 'dd.mm.yyyy')
There second method will be many times more effective (mostly because of compilers inlining and boxing but still numbers are very expressive):
public static bool CheckObjectImpl(object o)
{
return o != null;
}
public static bool CheckNullableImpl<T>(T? o) where T: struct
{
return o.HasValue;
}
Benchmark test:
BenchmarkDotNet=v0.10.5, OS=Windows 10.0.14393
Processor=Intel Core i5-2500K CPU 3.30GHz (Sandy Bridge), ProcessorCount=4
Frequency=3233539 Hz, Resolution=309.2587 ns, Timer=TSC
[Host] : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1648.0
Clr : Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1648.0
Core : .NET Core 4.6.25009.03, 64bit RyuJIT
Method | Job | Runtime | Mean | Error | StdDev | Min | Max | Median | Rank | Gen 0 | Allocated |
-------------- |----- |-------- |-----------:|----------:|----------:|-----------:|-----------:|-----------:|-----:|-------:|----------:|
CheckObject | Clr | Clr | 80.6416 ns | 1.1983 ns | 1.0622 ns | 79.5528 ns | 83.0417 ns | 80.1797 ns | 3 | 0.0060 | 24 B |
CheckNullable | Clr | Clr | 0.0029 ns | 0.0088 ns | 0.0082 ns | 0.0000 ns | 0.0315 ns | 0.0000 ns | 1 | - | 0 B |
CheckObject | Core | Core | 77.2614 ns | 0.5703 ns | 0.4763 ns | 76.4205 ns | 77.9400 ns | 77.3586 ns | 2 | 0.0060 | 24 B |
CheckNullable | Core | Core | 0.0007 ns | 0.0021 ns | 0.0016 ns | 0.0000 ns | 0.0054 ns | 0.0000 ns | 1 | - | 0 B |
Benchmark code:
public class BenchmarkNullableCheck
{
static int? x = (new Random()).Next();
public static bool CheckObjectImpl(object o)
{
return o != null;
}
public static bool CheckNullableImpl<T>(T? o) where T: struct
{
return o.HasValue;
}
[Benchmark]
public bool CheckObject()
{
return CheckObjectImpl(x);
}
[Benchmark]
public bool CheckNullable()
{
return CheckNullableImpl(x);
}
}
https://github.com/dotnet/BenchmarkDotNet was used
So if you have an option (e.g. writing custom serializers) to process Nullable in different pipeline than object
- and use their specific properties - do it and use Nullable specific properties.
So from consistent thinking point of view HasValue
should be preferred. Consistent thinking can help you to write better code do not spending too much time in details.
PS. People say that advice "prefer HasValue because of consistent thinking" is not related and useless. Can you predict the performance of this?
public static bool CheckNullableGenericImpl<T>(T? t) where T: struct
{
return t != null; // or t.HasValue?
}
PPS People continue minus, seems nobody tries to predict performance of CheckNullableGenericImpl
. I will tell you: there compiler will not help you replacing !=null
with HasValue
. HasValue
should be used directly if you are interested in performance.
ES6 function
/**
* Returns true if an object is empty.
* @param {*} obj the object to test
* @return {boolean} returns true if object is empty, otherwise returns false
*/
const pureObjectIsEmpty = obj => obj && obj.constructor === Object && Object.keys(obj).length === 0
Examples:
let obj = "this is an object with String constructor"
console.log(pureObjectIsEmpty(obj)) // empty? true
obj = {}
console.log(pureObjectIsEmpty(obj)) // empty? true
obj = []
console.log(pureObjectIsEmpty(obj)) // empty? true
obj = [{prop:"value"}]
console.log(pureObjectIsEmpty(obj)) // empty? true
obj = {prop:"value"}
console.log(pureObjectIsEmpty(obj)) // empty? false
I got the same issues when trying to clone to c/code
But this folder contains a whole bunch of projects.
I created a new folder in c/code/newproject and mapped my clone to this folder.
git for desktop then asked of my user and then cloned fine.
This could be a one way of doing it. If you know what line of the file you have your grep word and how many lines you have in your file:
grep -A466 'TERMINATE' file
The Bootstrap team seems to have removed it. See here: https://github.com/twbs/bootstrap/issues/8922 . @Skelly's answer involves custom css which I didn't want to do so I used the grid system and nav-pills. It worked fine and looked great. The code looks like so:
<div class="row">
<!-- Navigation Buttons -->
<div class="col-md-3">
<ul class="nav nav-pills nav-stacked" id="myTabs">
<li class="active"><a href="#home" data-toggle="pill">Home</a></li>
<li><a href="#profile" data-toggle="pill">Profile</a></li>
<li><a href="#messages" data-toggle="pill">Messages</a></li>
</ul>
</div>
<!-- Content -->
<div class="col-md-9">
<div class="tab-content">
<div class="tab-pane active" id="home">Home</div>
<div class="tab-pane" id="profile">Profile</div>
<div class="tab-pane" id="messages">Messages</div>
</div>
</div>
</div>
You can see this in action here: http://bootply.com/81948
[Update]
@SeanK gives the option of not having to enable the nav-pills through Javascript and instead using data-toggle="pill"
. Check it out here: http://bootply.com/96067. Thanks Sean.
Following up to @edovino's answer, the way of clearing all of an application's preferences programmatically would be
private void clearPreferences() {
try {
// clearing app data
Runtime runtime = Runtime.getRuntime();
runtime.exec("pm clear YOUR_APP_PACKAGE_GOES HERE");
} catch (Exception e) {
e.printStackTrace();
}
}
Warning: the application will force close.
You can also import as
from math import *
Then you can use any mathematical function without prefixing math. e.g.
sqrt(4)
FYI, I have used UI_USER_INTERFACE_IDIOM()
for my app written in Swift. The app can be compiled well with XCode 6.3.1 without any warning on that command, runs well on Simulator (with any selected devices) and on all my real devices (iPhone, iPad) with iOS versions from 7.1 to 8.3.
However, the app crashed on Apple reviewers' devices (and was refused). That took me few days to detect the problem with few more re-uploads to iTunes Connect.
Now I use UIDevice.currentDevice().userInterfaceIdiom
instead and my app can survive from such crashes.
If you remove directives attribute it should work.
@Component({
selector: 'parent',
template: `
<h1>Parent Component</h1>
<child></child>
`
})
export class ParentComponent{}
@Component({
selector: 'child',
template: `
<h4>Child Component</h4>
`
})
export class ChildComponent{}
Directives are like components but they are used in attributes. They also have a declarator @Directive
. You can read more about directives Structural Directives and Attribute Directives.
There are two other kinds of Angular directives, described extensively elsewhere: (1) components and (2) attribute directives.
A component manages a region of HTML in the manner of a native HTML element. Technically it's a directive with a template.
Also if you are open the glossary you can find that components are also directives.
Directives fall into one of the following categories:
Components combine application logic with an HTML template to render application views. Components are usually represented as HTML elements. They are the building blocks of an Angular application.
Attribute directives can listen to and modify the behavior of other HTML elements, attributes, properties, and components. They are usually represented as HTML attributes, hence the name.
Structural directives are responsible for shaping or reshaping HTML layout, typically by adding, removing, or manipulating elements and their children.
The difference that components have a template. See Angular Architecture overview.
A directive is a class with a
@Directive
decorator. A component is a directive-with-a-template; a@Component
decorator is actually a@Directive
decorator extended with template-oriented features.
The @Component
metadata doesn't have directives
attribute. See Component decorator.
here is mine
echo Math+
ECHO First num:
SET /P a=
ECHO Second num:
SET /P b=
set /a s=%a%+%b%
echo Result: %s%
I tried several of the suggested solutions, but none of them worked for me. After some research I stumbled upon a hint to move some apps from /data/app
to /system/app
. That freed up enough space to install new apps and update existing ones.
I can recommend the free utility SystemCleanup for moving the apps.
As constraint has unpredictable name, you can write special script(DropConstraint) to remove it without knowing it's name (was tested at EF 6.1.3):
public override void Up()
{
DropConstraint();
AlterColumn("dbo.MyTable", "Rating", c => c.Double(nullable: false));
}
private void DropConstraint()
{
Sql(@"DECLARE @var0 nvarchar(128)
SELECT @var0 = name
FROM sys.default_constraints
WHERE parent_object_id = object_id(N'dbo.MyTable')
AND col_name(parent_object_id, parent_column_id) = 'Rating';
IF @var0 IS NOT NULL
EXECUTE('ALTER TABLE [dbo].[MyTable] DROP CONSTRAINT [' + @var0 + ']')");
}
public override void Down()
{
AlterColumn("dbo.MyTable", "Rating", c => c.Int(nullable: false));
}
There are a problem with Metro using some NPM and Node versions.
You can fix the problem changing some code in the file \node_modules\metro-config\src\defaults\blacklist.js
.
Search this variable:
var sharedBlacklist = [
/node_modules[/\\]react[/\\]dist[/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
and change to this:
var sharedBlacklist = [
/node_modules[\/\\]react[\/\\]dist[\/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
Please note that if you run an npm install or a yarn install you need to change the code again.
I was able to export a jar file in Android Studio using this tutorial: https://www.youtube.com/watch?v=1i4I-Nph-Cw "How To Export Jar From Android Studio "
I updated my answer to include all the steps for exporting a JAR in Android Studio:
1) Create Android application project, go to app->build.gradle
2) Change the following in this file:
modify apply plugin: 'com.android.application' to apply plugin: 'com.android.library'
remove the following: applicationId, versionCode and versionName
Add the following code:
// Task to delete old jar task deleteOldJar(type: Delete){ delete 'release/AndroidPlugin2.jar' }
// task to export contents as jar
task exportJar(type: Copy) {
from ('build/intermediates/bundles/release/')
into ('release/')
include ('classes.jar')
rename('classes.jar', 'AndroidPlugin2.jar')
}
exportJar.dependsOn(deleteOldJar, build)
3) Don't forget to click sync now in this file (top right or use sync button).
4) Click on Gradle tab (usually middle right) and scroll down to exportjar
5) Once you see the build successful message in the run window, using normal file explorer go to exported jar using the path: C:\Users\name\AndroidStudioProjects\ProjectName\app\release you should see in this directory your jar file.
Good Luck :)
I tested and the script run ok!
INSERT INTO HISTORICAL_CAR_STATS (HISTORICAL_CAR_STATS_ID, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT)
WITH DATA AS
(
SELECT '2010' YEAR,'12' MONTH ,'ALL' MAKE,'ALL' MODEL,REGION,sum(AVG_MSRP*COUNT)/sum(COUNT) AVG_MSRP,sum(Count) COUNT
FROM HISTORICAL_CAR_STATS
WHERE YEAR = '2010' AND MONTH = '12'
AND MAKE != 'ALL' GROUP BY REGION
)
SELECT MY_SEQ.NEXTVAL, YEAR,MONTH,MAKE,MODEL,REGION,AVG_MSRP,COUNT
FROM DATA;
you can read this article to understand more! http://www.orafaq.com/wiki/ORA-02287
Use this:
$(function(){
$("tr.b_row").each(function(){
var a_href = $(this).find('div.cpt h2 a').attr('href');
alert ("Href is: "+a_href);
});
});
See a working demo: http://jsfiddle.net/usmanhalalit/4Ea4k/1/
you can reset your branch with HEAD
git reset --hard branch_name
then fetch branches and delete branches which are not on remote from local,
git fetch -p
I'd argue that the primary concern isn't performance, but safety. You can make a lot of mistakes with arrays (consider resizing, for example), where a vector would save you a lot of pain.
This snippet invokes when a link of class 'menu_link' is clicked, and shows the text and url of the link. The return false prevents the link from being followed.
<a rel='1' class="menu_link" href="option1.html">Option 1</a>
<a rel='2' class="menu_link" href="option2.html">Option 2</a>
$('.menu_link').live('click', function() {
var thelink = $(this);
alert ( thelink.html() );
alert ( thelink.attr('href') );
alert ( thelink.attr('rel') );
return false;
});
Declare an object arr
to hold the unique set as keys. Populate arr
by looping through the array once using map. If the key has not been previously found then add the key and assign a value of zero. On each iteration increment the key's value.
Given testArray:
var testArray = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
solution:
var arr = {};
testArray.map(x=>{ if(typeof(arr[x])=="undefined") arr[x]=0; arr[x]++;});
JSON.stringify(arr)
will output
{"a":3,"b":2,"c":2,"d":2,"e":2,"f":1,"g":1,"h":3}
Object.keys(arr)
will return ["a","b","c","d","e","f","g","h"]
To find the occurrences of any item e.g. b arr['b']
will output 2
Encapsulation means that the the state of an object only happens through a defined interface, and because of this the class can make sure that this state is always valid and in keeping with the purpose of the class.
In some cases therefore, it's perfectly in keeping with the principle of encapsulation to just expose a field publicly - all possible values for the field are valid with all other possible values of all other fields, and therefore the programmer can actively decide to allow the field to be manipulated freely by outside code.
These cases are though mostly restricted to classes that are mostly "plain old data". They also aren't very interesting in this regard, so enough about them.
In other cases, in other languages, one would have a getter and setter method, something like int getId()
to obtain a value and void setId(int val)
to update it.
Properties let us use the same syntax for reading and writing through such methods as we would use to read and write a field. This is a good syntactic sugar, though not vital.
(Actually, due to the way that reflection works and cases such as DataBinder.Eval
it can be handy to have a property even when a field would work fine, but that's another matter).
Up until private setters being introduced (actually, what changed with C# 2 is the syntax for having a private setter and a public or protected getter in the same block), we could have a private method to do the work of the private setter, so private setters aren't really necessary. They're handy though, so while just syntactic sugar, they're pretty useful.
Encapsulation is a matter not of whether your setters (or getters) are public, private, protected or internal, but a matter of whether they are appropriate. Start with a default of every field being private (and for that matter readonly
) and then as necessary add members (whether properties or methods) that alter those fields, and ensure that the object remains valid as they change. This ensures that a class' invariant is kept, which means the rules describing the valid set of states it can be in are never broken (constructors also help by making sure it starts in such a valid state).
As for your last question, to be immutable means that a class has no public, protected or internal setters and no public, protected or internal methods that change any fields. There are degrees of this, in C# there are three degrees possible:
All of a class' instance field's are readonly
, hence even private code can't alter it. It is guaranteed to be immutable (anything that tries to change it won't compile) and possibly optimisations can be done on the back of this.
A class is immutable from the outside because no public member changes anything, but not guaranteed by use of readonly
to not be changed from the inside.
A class is immutable as seen from the outside, though some state is change as an implementation detail. E.g. a field could be memoised, and hence while from the outside an attempt to get it just retrieves the same value, the first such attempt actually calculates it and then stores it for retrieval on subsequent attempts.
I could have sworn there used to be a convenient fields
property on a form but … Must have been my imagination.
I just do this (for <form name="my_form"></form>
) because I usually don't want fieldsets themselves:
let fields = Array.from(document.forms.my_form.querySelectorAll('input, select, textarea'));
You can see the resolutions for those categories in the Table 2, in this section: http://developer.android.com/guide/practices/screens_support.html#testing
LocalDate maxDate = dates.stream()
.max( Comparator.comparing( LocalDate::toEpochDay ) )
.get();
LocalDate minDate = dates.stream()
.min( Comparator.comparing( LocalDate::toEpochDay ) )
.get();
On macos Sierra this work for me, where python is managed by anaconda:
anaconda search -t conda mysql-python
anaconda show CEFCA/mysql-python
conda install --channel https://conda.anaconda.org/CEFCA mysql-python
The to use with SQLAlchemy:
Python 2.7.13 |Continuum Analytics, Inc.| (default, Dec 20 2016, 23:05:08) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. Anaconda is brought to you by Continuum Analytics. Please check out: http://continuum.io/thanks and https://anaconda.org
>>> from sqlalchemy import *
>>>dbengine = create_engine('mysql://....')
Another approach is to indicate the languages you intend to support and filter out the rest using the 'resConfigs' option with Gradle.
Check out this other answer for details
This is better, I think, because you don't have to completely ignore legitimate translation mistakes for languages you actually want to support
Here are a few more tips:
In Arch Linux the global one is at /etc/vimrc
. There are some comments in there with helpful details.
Since the filename starts with a .
, it's hidden unless you use ls -a
to show ALL files.
Typing :version
while in Vim will show you a bunch of interesting information including the file location.
If you're not sure what ~/.vimrc
means look at this question.
In MVC, assume you are searching record(s) based on your requirement or information. It is working properly.
[HttpPost]
[ActionName("Index")]
public ActionResult SearchRecord(FormCollection formcollection)
{
EmployeeContext employeeContext = new EmployeeContext();
string searchby=formcollection["SearchBy"];
string value=formcollection["Value"];
if (formcollection["SearchBy"] == "Gender")
{
List<MvcApplication1.Models.Employee> emplist = employeeContext.Employees.Where(x => x.Gender == value).ToList();
return View("Index", emplist);
}
else
{
List<MvcApplication1.Models.Employee> emplist = employeeContext.Employees.Where(x => x.Name == value).ToList();
return View("Index", emplist);
}
}
Here is an easy solution:
git rebase -i HEAD~x
(Note: x
is the number of commits)
upon executing notepad file will open. Enter drop
besides your commit.
If you don’t know Vim, just click on each word pick that you want to edit and then hit the "I" key (for insert mode). Once you’re done typing hit the "esc" key to exit insert mode.
and that's it, you are done... Just sync the git dashboard and the changes will be pushed to remote.
If the commit you drop was already on the remote, you will have to force push. Since --force is considered harmful, use git push --force-with-lease
.
JavaScript doesn't have a built-in init()
function, that is, it's not a part of the language. But it's not uncommon (in a lot of languages) for individual programmers to create their own init()
function for initialisation stuff.
A particular init()
function may be used to initialise the whole webpage, in which case it would probably be called from document.ready or onload processing, or it may be to initialise a particular type of object, or...well, you name it.
What any given init()
does specifically is really up to whatever the person who wrote it needed it to do. Some types of code don't need any initialisation.
function init() {
// initialisation stuff here
}
// elsewhere in code
init();
You can use following code for Alert and Actionsheet for swift4
@IBAction func alert_act(_ sender: Any) {
do {
let alert = UIAlertController(title: "Alert", message: "Would you like to continue learning?", preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))
alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
@IBAction func action_sheet1(_ sender: Any) {
let action_sheet1 = UIAlertController(title: nil, message: "Alert message.", preferredStyle: .actionSheet)
let defaultAction = UIAlertAction(title: "Default", style: .default, handler: nil)
let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler: nil)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
action_sheet1.addAction(defaultAction)
action_sheet1.addAction(deleteAction)
action_sheet1.addAction(cancelAction)
self.present(action_sheet1, animated: true, completion: nil)
}
}
If you just want the last date for each account, you'd use this:
var q = from n in table
group n by n.AccountId into g
select new {AccountId = g.Key, Date = g.Max(t=>t.Date)};
If you want the whole record:
var q = from n in table
group n by n.AccountId into g
select g.OrderByDescending(t=>t.Date).FirstOrDefault();
import datetime
# convert string into date time format.
str_date = '2016-10-06 15:14:54.322989'
d_date = datetime.datetime.strptime(str_date , '%Y-%m-%d %H:%M:%S.%f')
print(d_date)
print(type(d_date)) # check d_date type.
# convert date time to regular format.
reg_format_date = d_date.strftime("%d %B %Y %I:%M:%S %p")
print(reg_format_date)
# some other date formats.
reg_format_date = d_date.strftime("%Y-%m-%d %I:%M:%S %p")
print(reg_format_date)
reg_format_date = d_date.strftime("%Y-%m-%d %H:%M:%S")
print(reg_format_date)
<<<<<< OUTPUT >>>>>>>
2016-10-06 15:14:54.322989
<class 'datetime.datetime'>
06 October 2016 03:14:54 PM
2016-10-06 03:14:54 PM
2016-10-06 15:14:54
There are two solutions posted on that page. The one with lower votes I would recommend if possible.
If you are using HTML5 then it is perfectly valid to put a div
inside of a
. As long as the div doesn't also contain some other specific elements like other link tags.
<a href="Music.html">
<div id="music" class="nav">
Music I Like
</div>
</a>
The solution you are confused about actually makes the link as big as its container div. To make it work in your example you just need to add position: relative
to your div. You also have a small syntax error which is that you have given the span a class instead of an id. You also need to put your span inside the link because that is what the user is clicking on. I don't think you need the z-index
at all from that example.
div { position: relative; }
.hyperspan {
position:absolute;
width:100%;
height:100%;
left:0;
top:0;
}
<div id="music" class="nav">Music I Like
<a href="http://www.google.com">
<span class="hyperspan"></span>
</a>
</div>
When you give absolute
positioning to an element it bases its location and size after the first parent it finds that is relatively positioned. If none, then it uses the document. By adding relative
to the parent div you tell the span to only be as big as that.
Try this one, should work:
cast((convert(bigint,b.tax_id)) as varchar(20))
The jQuery function getScript can also be used to ensure that a js file is indeed loaded every time the page is loaded.
This is how I did it:
$(document).ready(function(){
$.getScript("../data/playlist.js", function(data, textStatus, jqxhr){
startProgram();
});
});
Check the function at http://api.jquery.com/jQuery.getScript/
By default, $.getScript() sets the cache setting to false. This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested.
uniq -u < file
will do the job.
In Internet Explorer 9 (and 8), the console
object is only exposed when the developer tools are opened for a particular tab. If you hide the developer tools window for that tab, the console
object remains exposed for each page you navigate to. If you open a new tab, you must also open the developer tools for that tab in order for the console
object to be exposed.
The console
object is not part of any standard and is an extension to the Document Object Model. Like other DOM objects, it is considered a host object and is not required to inherit from Object
, nor its methods from Function
, like native ECMAScript functions and objects do. This is the reason apply
and call
are undefined on those methods. In IE 9, most DOM objects were improved to inherit from native ECMAScript types. As the developer tools are considered an extension to IE (albeit, a built-in extension), they clearly didn't receive the same improvements as the rest of the DOM.
For what it's worth, you can still use some Function.prototype
methods on console
methods with a little bind()
magic:
var log = Function.prototype.bind.call(console.log, console);
log.apply(console, ["this", "is", "a", "test"]);
//-> "thisisatest"
Try
<?php
$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string,true);
foreach ($json_a as $key => $value){
echo $key . ':' . $value;
}
?>
Always use mongoose.Types.ObjectId('your id')
for conditions in your query it will validate the id field before running your query as a result your app will not crash.
It is not possible. §2.3 says that "." is an unreserved character and that "URIs that differ in the replacement of an unreserved character with its corresponding percent-encoded US-ASCII octet are equivalent". Therefore, /%2E%2E/
is the same as /../
, and that will get normalized away.
(This is a combination of an answer by bobince and a comment by slowpoison.)
Or you can use RFlutter Alert library for that. It is easily customizable and easy-to-use. Its default style includes rounded corners and you can add buttons as much as you want.
Basic Alert:
Alert(context: context, title: "RFLUTTER", desc: "Flutter is awesome.").show();
Alert with Button:
Alert(
context: context,
type: AlertType.error,
title: "RFLUTTER ALERT",
desc: "Flutter is more awesome with RFlutter Alert.",
buttons: [
DialogButton(
child: Text(
"COOL",
style: TextStyle(color: Colors.white, fontSize: 20),
),
onPressed: () => Navigator.pop(context),
width: 120,
)
],
).show();
You can also define generic alert styles.
*I'm one of developer of RFlutter Alert.
There are a number of ways that you could do this, but the fastest might be to use IndexOf to find the index position of the letter you want to replace and then substring out the text before and after what you want to replace.
If you doesn't want to touch the config object, you just hide the grid by css:
.chart-container .highcharts-grid {
display: none;
}
Yo don't need any java code. You just have to :
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="centerCrop" />
The key is in the match parent for width and height
A completely alternative solution is to not use the MVC HandleErrorAttribute
, and instead rely on ASP.Net error handling, which Elmah is designed to work with.
You need to remove the default global HandleErrorAttribute
from App_Start\FilterConfig (or Global.asax), and then set up an error page in your Web.config:
<customErrors mode="RemoteOnly" defaultRedirect="~/error/" />
Note, this can be an MVC routed URL, so the above would redirect to the ErrorController.Index
action when an error occurs.
This is kinda ugly, but its the first thing that popped in my head. This also should allow you to pass in arguments:
eval('var myfunc = ' + variable); myfunc(args, ...);
If you don't need to pass in arguments this might be simpler.
eval(variable + '();');
Standard dry-code warning applies.
Try the Apache POI HSSF. Here's an example on how to read an excel file:
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows();
int cols = 0; // No of columns
int tmp = 0;
// This trick ensures that we get the data properly even if it doesn't start from first few rows
for(int i = 0; i < 10 || i < rows; i++) {
row = sheet.getRow(i);
if(row != null) {
tmp = sheet.getRow(i).getPhysicalNumberOfCells();
if(tmp > cols) cols = tmp;
}
}
for(int r = 0; r < rows; r++) {
row = sheet.getRow(r);
if(row != null) {
for(int c = 0; c < cols; c++) {
cell = row.getCell((short)c);
if(cell != null) {
// Your code here
}
}
}
}
} catch(Exception ioe) {
ioe.printStackTrace();
}
On the documentation page you also have examples of how to write to excel files.
I am posting this for anyone that is using Docker for Mac. This is what worked for me:
$ mkdir mybackup # local directory on Mac
$ docker run --rm --volumes-from <containerid> \
-v `pwd`/mybackup:/backup \
busybox \
cp /data/mydata.txt /backup
Note that when I mount using -v
that backup
directory is automatically created.
I hope this is useful to someone someday. :)
Maybe it's not exactly what you want to do, but using the ajax complete solved my problem of hiding a spinner when the ajax call returned.
So it would look something like this
var table = $('#example').DataTable( {
"ajax": {
"type" : "GET",
"url" : "ajax.php",
"dataSrc": "",
"success": function () {
alert("Done!");
}
},
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
]
} );
Your logic condition is wrong. IIUC, what you want is:
import pyspark.sql.functions as f
df.filter((f.col('d')<5))\
.filter(
((f.col('col1') != f.col('col3')) |
(f.col('col2') != f.col('col4')) & (f.col('col1') == f.col('col3')))
)\
.show()
I broke the filter()
step into 2 calls for readability, but you could equivalently do it in one line.
Output:
+----+----+----+----+---+
|col1|col2|col3|col4| d|
+----+----+----+----+---+
| A| xx| D| vv| 4|
| A| x| A| xx| 3|
| E| xxx| B| vv| 3|
| F|xxxx| F| vvv| 4|
| G| xxx| G| xx| 4|
+----+----+----+----+---+
trick that works for me when target device not found:
click the "attach debugger to android process" button. (that will enable adb integration for you)
click the run button
For MySQL:
SELECT contract, activity
FROM table
GROUP BY contract
HAVING COUNT(DISTINCT activity) = 1
$('#el').prop('disabled', function(i, v) { return !v; });
The .prop()
method accepts two arguments:
So in this case, I used a function that supplied me the index (i) and the current value (v), then I returned the opposite of the current value, so the property state is reversed.
I would suggest concat when dealing with 2 strings, and || when those strings are more than 2:
select concat(a,b)
from dual
or
select 'a'||'b'||'c'||'d'
from dual
Ports This section is used to define the mapping between the host server and Docker container.
ports:
- 10005:80
It means the application running inside the container is exposed at port 80. But external system/entity cannot access it, so it need to be mapped to host server port.
Note: you have to open the host port 10005 and modify firewall rules to allow external entities to access the application.
They can use
http://{host IP}:10005
something like this
EXPOSE This is exclusively used to define the port on which application is running inside the docker container.
You can define it in dockerfile as well. Generally, it is good and widely used practice to define EXPOSE inside dockerfile because very rarely anyone run them on other port than default 80 port
Interfaces are for applying connection between different classes. for example, you have a class for car and a tree;
public class Car { ... }
public class Tree { ... }
you want to add a burnable functionality for both classes. But each class have their own ways to burn. so you simply make;
public class Car : IBurnable
{
public void Burn() { ... }
}
public class Tree : IBurnable
{
public void Burn() { ... }
}
In c++11 you can use:
for ( auto iter : table ) {
key=iter->first;
value=iter->second;
}
In addition to the accepted answer, I would like to add one info, that NuGet packages in Visual Studio 2017 are located in the project file itself. I.e., right click on the project -> edit, to find all package reference entries.
Try this.
var dateAsString = DateTime.Now.ToString("dd/MM/yyyy");
// dateAsString = "09/07/2013"
I came upon this thread today and after having tried out this solution from Mark Rushakoff
from time import sleep
import sys
for i in range(21):
sys.stdout.write('\r')
# the exact output you're looking for:
sys.stdout.write("[%-20s] %d%%" % ('='*i, 5*i))
sys.stdout.flush()
sleep(0.25)
I can say that this works fine on W7-64 with python 3.4.3 64-bit but only in the native console. However when using the built-in console of spyder 3.0.0dev, the line breaks are still/again present. As this took me some time to figure out, I'd like to report this observation here.
Take a pointer to the first element instead:
process_data (&something [0]);
path = path.substring(0, path.length() - 5);
I figured it out. In order to save your Jenkins data on other drive you'll need to do the following:
Workspace Root Directory: E:\Jenkins\${ITEM_FULL_NAME}\workspace
Build Record Root Directory: E:\Jenkins\${ITEM_FULL_NAME}\builds
You should use NVARCHAR anytime you have to store multiple languages. I believe you have to use it for the Asian languages but don't quote me on it.
Here's the problem if you take Russian for example and store it in a varchar, you will be fine so long as you define the correct code page. But let's say your using a default english sql install, then the russian characters will not be handled correctly. If you were using NVARCHAR() they would be handled properly.
Ok let me quote MSDN and maybee I was to specific but you don't want to store more then one code page in a varcar column, while you can you shouldn't
When you deal with text data that is stored in the char, varchar, varchar(max), or text data type, the most important limitation to consider is that only information from a single code page can be validated by the system. (You can store data from multiple code pages, but this is not recommended.) The exact code page used to validate and store the data depends on the collation of the column. If a column-level collation has not been defined, the collation of the database is used. To determine the code page that is used for a given column, you can use the COLLATIONPROPERTY function, as shown in the following code examples:
Here's some more:
This example illustrates the fact that many locales, such as Georgian and Hindi, do not have code pages, as they are Unicode-only collations. Those collations are not appropriate for columns that use the char, varchar, or text data type
So Georgian or Hindi really need to be stored as nvarchar. Arabic is also a problem:
Another problem you might encounter is the inability to store data when not all of the characters you wish to support are contained in the code page. In many cases, Windows considers a particular code page to be a "best fit" code page, which means there is no guarantee that you can rely on the code page to handle all text; it is merely the best one available. An example of this is the Arabic script: it supports a wide array of languages, including Baluchi, Berber, Farsi, Kashmiri, Kazakh, Kirghiz, Pashto, Sindhi, Uighur, Urdu, and more. All of these languages have additional characters beyond those in the Arabic language as defined in Windows code page 1256. If you attempt to store these extra characters in a non-Unicode column that has the Arabic collation, the characters are converted into question marks.
Something to keep in mind when you are using Unicode although you can store different languages in a single column you can only sort using a single collation. There are some languages that use latin characters but do not sort like other latin languages. Accents is a good example of this, I can't remeber the example but there was a eastern european language whose Y didn't sort like the English Y. Then there is the spanish ch which spanish users expet to be sorted after h.
All in all with all the issues you have to deal with when dealing with internalitionalization. It is my opinion that is easier to just use Unicode characters from the start, avoid the extra conversions and take the space hit. Hence my statement earlier.
There are two ways to go about this. You can either use the IDE to generate a WSDL, or you can do it via the command line.
1. To create it via the IDE:
In the solution explorer pane, right click on the project that you would like to add the Service to:
Then, you can enter the path to your service WSDL and hit go:
2. To create it via the command line:
Open a VS 2010 Command Prompt (Programs -> Visual Studio 2010 -> Visual Studio Tools)
Then execute:
WSDL /verbose C:\path\to\wsdl
WSDL.exe will then output a .cs file for your consumption.
If you have other dependencies that you received with the file, such as xsd's, add those to the argument list:
WSDL /verbose C:\path\to\wsdl C:\path\to\some\xsd C:\path\to\some\xsd
If you need VB output, use /language:VB
in addition to the /verbose
.
use this code
while ($rows = mysql_fetch_array($query)):
$name = $rows['Name'];
$address = $rows['Address'];
$email = $rows['Email'];
$subject = $rows['Subject'];
$comment = $rows['Comment'];
echo "$name<br>$address<br>$email<br>$subject<br>$comment<br><br>";
endwhile;
?>
Using ImageMagick, this is very similar to hackerb9 code and result, but is a little simpler command line. It does assume that the top left pixel is the background color. I just flood fill the background with transparency, then select the alpha channel and blur it and remove half of the blurred area using -level 50x100%. Then turn back on all the channels and flatten it against the brown color. The -blur 0x1 -level 50x100% acts to antialias the boundaries of the alpha channel transparency. You can adjust the fuzz value, blur amount and the -level 50% value to change the degree of antialiasing.
convert logo: -fuzz 25% -fill none -draw "matte 0,0 floodfill" -channel alpha -blur 0x1 -level 50x100% +channel -background saddlebrown -flatten result.jpg
request.getRequestDispatcher(“url”) means the dispatch is relative to the current HTTP request.Means this is for chaining two servlets with in the same web application Example
RequestDispatcher reqDispObj = request.getRequestDispatcher("/home.jsp");
getServletContext().getRequestDispatcher(“url”) means the dispatch is relative to the root of the ServletContext.Means this is for chaining two web applications with in the same server/two different servers
Example
RequestDispatcher reqDispObj = getServletContext().getRequestDispatcher("/ContextRoot/home.jsp");
Use this style to get a centered background image without repeat.
.bgImgCenter{
background-image: url('imagePath');
background-repeat: no-repeat;
background-position: center;
position: relative;
}
In HTML, set this style for your div:
<div class="bgImgCenter"></div>
You need to return a Callable<>
if you want spring.mvc.async.request-timeout=5000
to work.
@RequestMapping(method = RequestMethod.GET)
public Callable<String> getFoobar() throws InterruptedException {
return new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(8000); //this will cause a timeout
return "foobar";
}
};
}
geolocator.js can do that. (I'm the author).
Getting City Name (Limited Address)
geolocator.locateByIP(options, function (err, location) {
console.log(location.address.city);
});
Getting Full Address Information
Example below will first try HTML5 Geolocation API to obtain the exact coordinates. If fails or rejected, it will fallback to Geo-IP look-up. Once it gets the coordinates, it will reverse-geocode the coordinates into an address.
var options = {
enableHighAccuracy: true,
fallbackToIP: true, // fallback to IP if Geolocation fails or rejected
addressLookup: true
};
geolocator.locate(options, function (err, location) {
console.log(location.address.city);
});
This uses Google APIs internally (for address lookup). So before this call, you should configure geolocator with your Google API key.
geolocator.config({
language: "en",
google: {
version: "3",
key: "YOUR-GOOGLE-API-KEY"
}
});
Geolocator supports geo-location (via HTML5 or IP lookups), geocoding, address look-ups (reverse geocoding), distance & durations, timezone information and a lot more features...
static means that the variable or method marked as such is available at the class level. In other words, you don't need to create an instance of the class to access it.
public class Foo {
public static void doStuff(){
// does stuff
}
}
So, instead of creating an instance of Foo and then calling doStuff
like this:
Foo f = new Foo();
f.doStuff();
You just call the method directly against the class, like so:
Foo.doStuff();
Text nodes cannot have margins or any other style applied to them, so anything you need style applied to must be in an element. If you want some of the text inside of your element to be styled differently, wrap it in a span
or div
, for example.
The IF/THEN/ELSE construct you are using is only valid in stored procedures and functions. Your query will need to be restructured because you can't use the IF() function to control the flow of the WHERE clause like this.
The IF() function that can be used in queries is primarily meant to be used in the SELECT portion of the query for selecting different data based on certain conditions, not so much to be used in the WHERE portion of the query:
SELECT IF(JQ.COURSE_ID=0, 'Some Result If True', 'Some Result If False'), OTHER_COLUMNS
FROM ...
WHERE ...
You can use serialize()
like this:
$.ajax({
cache: false,
url: 'test.php',
data: $('form').serialize(),
datatype: 'json',
success: function(data) {
}
});
if you want to get the index position of the outliers idx_list
will return it.
def reject_outliers(data, m = 2.):
d = np.abs(data - np.median(data))
mdev = np.median(d)
s = d/mdev if mdev else 0.
data_range = np.arange(len(data))
idx_list = data_range[s>=m]
return data[s<m], idx_list
data_points = np.array([8, 10, 35, 17, 73, 77])
print(reject_outliers(data_points))
after rejection: [ 8 10 35 17], index positions of outliers: [4 5]
I Know this question is very old but every Time i need this code .. by the way if you have tables and views and Functions and PROCEDURES you can delete it all by this Script ..
so why i post this Script ?? because if u delete all tables you will need to delete all views and if you have Functions and PROCEDURES you need to delete it too
i Hope it will help someone
DECLARE @sql NVARCHAR(max)=''
SELECT @sql += ' Drop table ' + QUOTENAME(TABLE_SCHEMA) + '.'+ QUOTENAME(TABLE_NAME)
+ '; '
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
Exec Sp_executesql @sql
DECLARE @sql VARCHAR(MAX) = ''
, @crlf VARCHAR(2) = CHAR(13) + CHAR(10) ;
SELECT @sql = @sql + 'DROP VIEW ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' +
QUOTENAME(v.name) +';' + @crlf
FROM sys.views v
PRINT @sql;
EXEC(@sql);
declare @procName varchar(500)
declare cur cursor
for select [name] from sys.objects where type = 'p'
open cur
fetch next from cur into @procName
while @@fetch_status = 0
begin
exec('drop procedure [' + @procName + ']')
fetch next from cur into @procName
end
close cur
deallocate cur
Declare @sql NVARCHAR(MAX) = N'';
SELECT @sql = @sql + N' DROP FUNCTION '
+ QUOTENAME(SCHEMA_NAME(schema_id))
+ N'.' + QUOTENAME(name)
FROM sys.objects
WHERE type_desc LIKE '%FUNCTION%';
Exec sp_executesql @sql
GO
You need to override the color:
a { color:red } /* Globally */
/* Each state */
a:visited { text-decoration: none; color:red; }
a:hover { text-decoration: none; color:blue; }
a:focus { text-decoration: none; color:yellow; }
a:hover, a:active { text-decoration: none; color:black }
All p
tags with class some_class
which are direct children of a div
tag.
The #1 reason has already been stated - it hides errors that you did not expect.
(#2) - It makes your code difficult for others to read and understand. If you catch a FileNotFoundException when you are trying to read a file, then it is pretty obvious to another developer what functionality the 'catch' block should have. If you do not specify an exception, then you need additional commenting to explain what the block should do.
(#3) - It demonstrates lazy programming. If you use the generic try/catch, it indicates either that you do not understand the possible run-time errors in your program, or that you do not know what exceptions are possible in Python. Catching a specific error shows that you understand both your program and the range of errors that Python throws. This is more likely to make other developers and code-reviewers trust your work.
Just as normal, using data-original-title
:
Html:
<div rel='tooltip' data-original-title='<h1>big tooltip</h1>'>Visible text</div>
Javascript:
$("[rel=tooltip]").tooltip({html:true});
The html parameter specifies how the tooltip text should be turned into DOM elements. By default Html code is escaped in tooltips to prevent XSS attacks. Say you display a username on your site and you show a small bio in a tooltip. If the html code isn't escaped and the user can edit the bio themselves they could inject malicious code.
most editors support save as ‘Unicode’ encoding actually.
This is an unfortunate misnaming perpetrated by Windows.
Because Windows uses UTF-16LE encoding internally as the memory storage format for Unicode strings, it considers this to be the natural encoding of Unicode text. In the Windows world, there are ANSI strings (the system codepage on the current machine, subject to total unportability) and there are Unicode strings (stored internally as UTF-16LE).
This was all devised in the early days of Unicode, before we realised that UCS-2 wasn't enough, and before UTF-8 was invented. This is why Windows's support for UTF-8 is all-round poor.
This misguided naming scheme became part of the user interface. A text editor that uses Windows's encoding support to provide a range of encodings will automatically and inappropriately describe UTF-16LE as “Unicode”, and UTF-16BE, if provided, as “Unicode big-endian”.
(Other editors that do encodings themselves, like Notepad++, don't have this problem.)
If it makes you feel any better about it, ‘ANSI’ strings aren't based on any ANSI standard, either.
Swift 5
@IBAction func buttonPressed(_ sender: Any) {
let videoURL = course.introductionVideoURL
let player = AVPlayer(url: videoURL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
present(playerViewController, animated: true, completion: {
playerViewController.player!.play()
})
// here the course includes a model file, inside it I have given the url, so I am calling the function from model using course function.
// also introductionVideoUrl is a URL which I declared inside model .
var introductionVideoURL: URL
Also alternatively you can use the below code instead of calling the function from model
Replace this code
let videoURL = course.introductionVideoURL
with
guard let videoURL = URL(string: "https://something.mp4) else {
return
A react js solution
handleChange: function(e) {
if (e.key == 'Enter') {
console.log('test');
}
<div>
<Input type="text"
ref = "input"
placeholder="hiya"
onKeyPress={this.handleChange}
/>
</div>
Main Example
The example below will run myfile.sql on database mydatabase using schema myschema.
psql "dbname=mydatabase options=--search_path=myschema" -a -f myfile.sql
The way this works is the first argument to the psql command is the dbname argument. The docs mention a connection string can be provided.
If this parameter contains an = sign or starts with a valid URI prefix (postgresql:// or postgres://), it is treated as a conninfo string
The dbname keyword specifies the database to connect to and the options keyword lets you specify command-line options to send to the server at connection startup. Those options are detailed in the server configuration chapter. The option we are using to select the schema is search_path.
Another Example
The example below will connect to host myhost on database mydatabase using schema myschema. The =
special character must be url escaped with the escape sequence %3D
.
psql postgres://myuser@myhost?options=--search_path%3Dmyschema
Not sure if this completely helps, but I had an issue where I needed a "smart" merge. I had two columns, A & B. I wanted to move B over only if A was blank. See below. It is based on a selection Range, which you could use to offset the first row, perhaps.
Private Sub MergeProjectNameColumns()
Dim rngRowCount As Integer
Dim i As Integer
'Loop through column C and simply copy the text over to B if it is not blank
rngRowCount = Range(dataRange).Rows.Count
ActiveCell.Offset(0, 0).Select
ActiveCell.Offset(0, 2).Select
For i = 1 To rngRowCount
If (Len(RTrim(ActiveCell.Value)) > 0) Then
Dim currentValue As String
currentValue = ActiveCell.Value
ActiveCell.Offset(0, -1) = currentValue
End If
ActiveCell.Offset(1, 0).Select
Next i
'Now delete the unused column
Columns("C").Select
selection.Delete Shift:=xlToLeft
End Sub
You can create a Task with cancellation token, when you app goto background you can cancel this token.
You can do this in PCL https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/app-lifecycle
var cancelToken = new CancellationTokenSource();
Task.Factory.StartNew(async () => {
await Task.Delay(10000);
// call web API
}, cancelToken.Token);
//this stops the Task:
cancelToken.Cancel(false);
Anther solution is user Timer in Xamarin.Forms, stop timer when app goto background https://xamarinhelp.com/xamarin-forms-timer/
Simply run this command for installing composer globally
curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer
Intel HAXM is required to run this AVD. VT-x is disabled in BIOS.
Enable VT-x in your BIOS security settings (refer to documentation for your computer).this error on android studio I dont no how to do Bios Security
You can define an interface as array with simply extending the Array interface.
export interface MyInterface extends Array<MyType> { }
With this, any object which implements the MyInterface
will need to implement all function calls of arrays and only will be able to store objects with the MyType
type.
You're not reading the file content:
my_file_contents = f.read()
See the docs for further infos
You could, without calling read()
or readlines()
loop over your file object:
f = open('goodlines.txt')
for line in f:
print(line)
If you want a list out of it (without \n
as you asked)
my_list = [line.rstrip('\n') for line in f]
You can do something like this to read 10 bytes:
char buffer[10];
read(STDIN_FILENO, buffer, 10);
remember read() doesn't add '\0'
to terminate to make it string (just gives raw buffer).
To read 1 byte at a time:
char ch;
while(read(STDIN_FILENO, &ch, 1) > 0)
{
//do stuff
}
and don't forget to #include <unistd.h>
, STDIN_FILENO
defined as macro in this file.
There are three standard POSIX file descriptors, corresponding to the three standard streams, which presumably every process should expect to have:
Integer value Name
0 Standard input (stdin)
1 Standard output (stdout)
2 Standard error (stderr)
So instead STDIN_FILENO
you can use 0.
Edit:
In Linux System you can find this using following command:
$ sudo grep 'STDIN_FILENO' /usr/include/* -R | grep 'define'
/usr/include/unistd.h:#define STDIN_FILENO 0 /* Standard input. */
Notice the comment /* Standard input. */
Set the value of the input
to null
on each onclick
event. This will reset the input
's value and trigger the onchange
event even if the same path is selected.
input.onclick = function () {
this.value = null;
};
input.onchange = function () {
alert(this.value);
};?
Here's a DEMO.
Note: It's normal if your file is prefixed with 'C:\fakepath\'. That's a security feature preventing JavaScript from knowing the file's absolute path. The browser still knows it internally.
krosenvold's answer inspired the following script which does the following:
the script is restartable and checks the existence of the intermediate files. It also uses pv and qemu-img -p to show the progress of each step.
In my environment 2 x Ubuntu 12.04 LTS the steps took:
#!/bin/bash
# get a dd disk dump and convert it to vmware
# see http://stackoverflow.com/questions/454899/how-to-convert-flat-raw-disk-image-to-vmdk-for-virtualbox-or-vmplayer
# Author: wf 2014-10-1919
#
# get a dd dump from the given host's given disk and create a compressed
# image at the given target
#
# 1: host e.g. somehost.somedomain
# 2: disk e.g. sda
# 3: target e.g. image.gz
#
# http://unix.stackexchange.com/questions/132797/how-to-use-ssh-to-make-a-dd-copy-of-disk-a-from-host-b-and-save-on-disk-b
getdump() {
local l_host="$1"
local l_disk="$2"
local l_target="$3"
echo "getting disk dump of $l_disk from $l_host"
ssh $l_host sudo fdisk -l | egrep "^/dev/$l_disk"
if [ $? -ne 0 ]
then
echo "device $l_disk does not exist on host $l_host" 1>&2
exit 1
else
if [ ! -f $l_target ]
then
ssh $l_host "sudo dd if=/dev/$disk bs=1M | gzip -1 -" | pv | dd of=$l_target
else
echo "$l_target already exists"
fi
fi
}
#
# optionally install command from package if it is not available yet
# 1: command
# 2: package
#
opt_install() {
l_command="$1"
l_package="$2"
echo "checking that $l_command from package $l_package is installed ..."
which $l_command
if [ $? -ne 0 ]
then
echo "installing $l_package to make $l_command available ..."
sudo apt-get install $l_package
fi
}
#
# convert the given image to vmware
# 1: the dd dump image
# 2: the vmware image file to convert to
#
vmware_convert() {
local l_ddimage="$1"
local l_vmwareimage="$2"
echo "converting dd image $l_image to vmware $l_vmwareimage"
# convert to VMware disk format showing progess
# see http://manpages.ubuntu.com/manpages/precise/man1/qemu-img.1.html
qemu-img convert -p -O vmdk "$l_ddimage" "$l_vmwareimage"
}
#
# show usage
#
usage() {
echo "usage: $0 host device"
echo " host: the host to get the disk dump from e.g. frodo.lotr.org"
echo " you need ssh and sudo privileges on that host"
echo "
echo " device: the disk to dump from e.g. sda"
echo ""
echo " examples:
echo " $0 frodo.lotr.org sda"
echo " $0 gandalf.lotr.org sdb"
echo ""
echo " the needed packages pv and qemu-utils will be installed if not available"
echo " you need local sudo rights for this to work"
exit 1
}
# check arguments
if [ $# -lt 2 ]
then
usage
fi
# get the command line parameters
host="$1"
disk="$2"
# calculate the names of the image files
ts=`date "+%Y-%m-%d"`
# prefix of all images
# .gz the zipped dd
# .dd the disk dump file
# .vmware - the vmware disk file
image="${host}_${disk}_image_$ts"
echo "$0 $host/$disk -> $image"
# first check/install necessary packages
opt_install qemu-img qemu-utils
opt_install pv pv
# check if dd files was already loaded
# we don't want to start this tedious process twice if avoidable
if [ ! -f $image.gz ]
then
getdump $host $disk $image.gz
else
echo "$image.gz already downloaded"
fi
# check if the dd file was already uncompressed
# we don't want to start this tedious process twice if avoidable
if [ ! -f $image.dd ]
then
echo "uncompressing $image.gz"
zcat $image.gz | pv -cN zcat > $image.dd
else
echo "image $image.dd already uncompressed"
fi
# check if the vmdk file was already converted
# we don't want to start this tedious process twice if avoidable
if [ ! -f $image.vmdk ]
then
vmware_convert $image.dd $image.vmdk
else
echo "vmware image $image.vmdk already converted"
fi
Calling setDefaultCloseOperation(EXIT_ON_CLOSE)
does exactly this. It causes the application to exit when the application receives a close window event from the operating system. Pressing the close (X) button on your window causes the operating system to generate a close window event and send it to your Java application. The close window event is processed by the AWT event loop in your Java application which will exit the application in response to the event.
If you do not call this method the AWT event loop may not exit the application in response to the close window event but leave it running in the background.
def gen( x,y,list): #to generate all strings inserting y at different positions
list = []
list.append( y+x )
for i in range( len(x) ):
list.append( func(x,0,i) + y + func(x,i+1,len(x)-1) )
return list
def func( x,i,j ): #returns x[i..j]
z = ''
for i in range(i,j+1):
z = z+x[i]
return z
def perm( x , length , list ): #perm function
if length == 1 : # base case
list.append( x[len(x)-1] )
return list
else:
lists = perm( x , length-1 ,list )
lists_temp = lists #temporarily storing the list
lists = []
for i in range( len(lists_temp) ) :
list_temp = gen(lists_temp[i],x[length-2],lists)
lists += list_temp
return lists
I have tried something like this and it works as expected:
f = open("c:\\log.log", 'r+b')
f.write("\x5F\x9D\x3E")
f.read(100)
f.close()
Where:
f.read(size) - To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string.
And:
f.write(string) writes the contents of string to the file, returning None.
Also if you open Python tutorial about reading and writing files you will find that:
'r+' opens the file for both reading and writing.
On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'.
Each answer here has parts of the total solution. Here's the complete solution that I used to get it to work inside of components deeper than where Route was used:
import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
^ You need that second line to import function and to export component at bottom of page.
render() {
return (
...
<div onClick={() => this.props.history.goBack()}>GO BACK</div>
)
}
^ Required the arrow function vs simply onClick={this.props.history.goBack()}
export default withRouter(MyPage)
^ wrap your component's name with 'withRouter()'
In WordPress, the correct way to include the scripts in your website is by using the following functions.
wp_register_script( $handle, $src )
wp_enqueue_script( $handle, $src )
These functions are called inside the hook wp_enqueue_script
.
For more details and examples, you can check Adding JS files in Wordpress using wp_register_script & wp_enqueue_script
Example:
function webolute_theme_scripts() {
wp_register_script( 'script-name', get_template_directory_uri() . '/js/example.js', array('jquery'), '1.0.0', true );
wp_enqueue_script( 'script-name' );
}
add_action( 'wp_enqueue_scripts', 'webolute_theme_scripts' );
try simple way to install intellij idea
Install IntelliJ on Ubuntu using Ubuntu Make
You need to install Ubuntu Make first. If you are using Ubuntu 16.04, 18.04 or a higher version, you can install Ubuntu Make using the command below:
Once you have Ubuntu Make installed, you can use the command below to install IntelliJ IDEA Community edition:
To install the IntelliJ IDEA Ultimate edition, use the command below:
To remove IntelliJ IDEA installed via Ubuntu Make, use the command below for your respective versions:
you may visit for more option.
try this :
sudo apt-get install libblas-dev libatlas-base-dev
I had a similar issue on Ubuntu 14.04. For me the following Ubuntu packages
If you are storing values via any programming language
Here is an example in C#
To store date you have to convert it first and then store it
insert table1 (foodate)
values (FooDate.ToString("MM/dd/yyyy"));
FooDate is datetime variable which contains your date in your format.
Johnathan Sampson's Linux example didn't work so good for me. Here's an improved version:
function getDirSize($path)
{
$io = popen('/usr/bin/du -sb '.$path, 'r');
$size = intval(fgets($io,80));
pclose($io);
return $size;
}
from PIL import Image
import os, os.path
imgs = []
path = "/home/tony/pictures"
valid_images = [".jpg",".gif",".png",".tga"]
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
if ext.lower() not in valid_images:
continue
imgs.append(Image.open(os.path.join(path,f)))
My understanding is that cookies from curl
must be written out to a file (curl -c cookie_file
). If you're running curl
through PHP's exec
or system
functions (or anything in that family), you should be able to save the cookies to a file, then open the file and read them in.
package com.programmingfree.springshop.controller;
import java.util.List;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.programmingfree.springshop.dao.UserShop;
import com.programmingfree.springshop.domain.User;
@RestController
@RequestMapping("/shop/user")
public class SpringShopController {
UserShop userShop=new UserShop();
@RequestMapping(value = "/{id}", method = RequestMethod.GET,headers="Accept=application/json")
public User getUser(@PathVariable int id) {
User user=userShop.getUserById(id);
return user;
}
@RequestMapping(method = RequestMethod.GET,headers="Accept=application/json")
public List<User> getAllUsers() {
List<User> users=userShop.getAllUsers();
return users;
}
}
In the above example they going to display all user and particular id details now I want to use both id and name,
1) localhost:8093/plejson/shop/user <---this link will display all user details
2) localhost:8093/plejson/shop/user/11 <----if i use 11 in link means, it will display particular user 11 details
now I want to use both id and name
localhost:8093/plejson/shop/user/11/raju <-----------------like this it means we can use any one in this please help me out.....
I think that the Import-Module
is trying to find the module in the default directory C:\Windows\System32\WindowsPowerShell\v1.0\Modules
.
Try to put the full path, or copy it to C:\Windows\System32\WindowsPowerShell\v1.0\Modules
You can send data from one actvity to another with an Intent
Intent sendStuff = new Intent(this, TargetActivity.class);
sendStuff.putExtra(key, stringvalue);
startActivity(sendStuff);
You then can retrieve this information in the second activity by getting the intent and extracting the string extra. Do this in your onCreate()
method.
Intent startingIntent = getIntent();
String whatYouSent = startingIntent.getStringExtra(key, value);
Then all you have to do is call setText on your TextView
and use that string.
I often use following command to spin my PHP Laravel framework :
$ php artisan serve --port=8080
or
$ php -S localhost:8080 -t public/
In above command : - Artisan is command-line interface included with Laravel which use serve to call built in php server
To Run with built-in web server.
php -S <addr>:<port> -T
Here,
-S : Switch to Run with built-in web server.
-T : Switch to specify document root for built-in web server.
The Observable Collection constructor will take an IList or an IEnumerable.
If you find that you are going to do this a lot you can make a simple extension method:
public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> enumerable)
{
return new ObservableCollection<T>(enumerable);
}
I am going to be general and not specific to Java as DAO and ORM are used in all languages.
To understand DAO you first need to understand ORM (Object Relational Mapping). This means that if you have a table called "person" with columns "name" and "age", then you would create object-template for that table:
type Person {
name
age
}
Now with help of DAO instead of writing some specific queries, to fetch all persons, for what ever type of db you are using (which can be error-prone) instead you do:
list persons = DAO.getPersons();
...
person = DAO.getPersonWithName("John");
age = person.age;
You do not write the DAO abstraction yourself, instead it is usually part of some opensource project, depending on what language and framework you are using.
Now to the main question here. "..where it is used..". Well usually if you are writing complex business and domain specific code your life will be very difficult without DAO. Of course you do not need to use ORM and DAO provided, instead you can write your own abstraction and native queries. I have done that in the past and almost always regretted it later.
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.1.0'// compulsory
compile 'com.squareup.retrofit2:converter-gson:2.1.0' //for retrofit conversion
Login APi Put Two Parameters
{
"UserId": "1234",
"Password":"1234"
}
Login Response
{
"UserId": "1234",
"FirstName": "Keshav",
"LastName": "Gera",
"ProfilePicture": "312.113.221.1/GEOMVCAPI/Files/1.500534651736E12p.jpg"
}
APIClient.java
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
class APIClient {
public static final String BASE_URL = "Your Base Url ";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
APIInterface interface
interface APIInterface {
@POST("LoginController/Login")
Call<LoginResponse> createUser(@Body LoginResponse login);
}
Login Pojo
package pojos;
import com.google.gson.annotations.SerializedName;
public class LoginResponse {
@SerializedName("UserId")
public String UserId;
@SerializedName("FirstName")
public String FirstName;
@SerializedName("LastName")
public String LastName;
@SerializedName("ProfilePicture")
public String ProfilePicture;
@SerializedName("Password")
public String Password;
@SerializedName("ResponseCode")
public String ResponseCode;
@SerializedName("ResponseMessage")
public String ResponseMessage;
public LoginResponse(String UserId, String Password) {
this.UserId = UserId;
this.Password = Password;
}
public String getUserId() {
return UserId;
}
public String getFirstName() {
return FirstName;
}
public String getLastName() {
return LastName;
}
public String getProfilePicture() {
return ProfilePicture;
}
public String getResponseCode() {
return ResponseCode;
}
public String getResponseMessage() {
return ResponseMessage;
}
}
MainActivity
package com.keshav.retrofitloginexampleworkingkeshav;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import pojos.LoginResponse;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import utilites.CommonMethod;
public class MainActivity extends AppCompatActivity {
TextView responseText;
APIInterface apiInterface;
Button loginSub;
EditText et_Email;
EditText et_Pass;
private Dialog mDialog;
String userId;
String password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apiInterface = APIClient.getClient().create(APIInterface.class);
loginSub = (Button) findViewById(R.id.loginSub);
et_Email = (EditText) findViewById(R.id.edtEmail);
et_Pass = (EditText) findViewById(R.id.edtPass);
loginSub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkValidation()) {
if (CommonMethod.isNetworkAvailable(MainActivity.this))
loginRetrofit2Api(userId, password);
else
CommonMethod.showAlert("Internet Connectivity Failure", MainActivity.this);
}
}
});
}
private void loginRetrofit2Api(String userId, String password) {
final LoginResponse login = new LoginResponse(userId, password);
Call<LoginResponse> call1 = apiInterface.createUser(login);
call1.enqueue(new Callback<LoginResponse>() {
@Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
LoginResponse loginResponse = response.body();
Log.e("keshav", "loginResponse 1 --> " + loginResponse);
if (loginResponse != null) {
Log.e("keshav", "getUserId --> " + loginResponse.getUserId());
Log.e("keshav", "getFirstName --> " + loginResponse.getFirstName());
Log.e("keshav", "getLastName --> " + loginResponse.getLastName());
Log.e("keshav", "getProfilePicture --> " + loginResponse.getProfilePicture());
String responseCode = loginResponse.getResponseCode();
Log.e("keshav", "getResponseCode --> " + loginResponse.getResponseCode());
Log.e("keshav", "getResponseMessage --> " + loginResponse.getResponseMessage());
if (responseCode != null && responseCode.equals("404")) {
Toast.makeText(MainActivity.this, "Invalid Login Details \n Please try again", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Welcome " + loginResponse.getFirstName(), Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
Toast.makeText(getApplicationContext(), "onFailure called ", Toast.LENGTH_SHORT).show();
call.cancel();
}
});
}
public boolean checkValidation() {
userId = et_Email.getText().toString();
password = et_Pass.getText().toString();
Log.e("Keshav", "userId is -> " + userId);
Log.e("Keshav", "password is -> " + password);
if (et_Email.getText().toString().trim().equals("")) {
CommonMethod.showAlert("UserId Cannot be left blank", MainActivity.this);
return false;
} else if (et_Pass.getText().toString().trim().equals("")) {
CommonMethod.showAlert("password Cannot be left blank", MainActivity.this);
return false;
}
return true;
}
}
CommonMethod.java
public class CommonMethod {
public static final String DISPLAY_MESSAGE_ACTION =
"com.codecube.broking.gcm";
public static final String EXTRA_MESSAGE = "message";
public static boolean isNetworkAvailable(Context ctx) {
ConnectivityManager connectivityManager
= (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public static void showAlert(String message, Activity context) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(message).setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
try {
builder.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
activity_main.xml
<LinearLayout android:layout_width="wrap_content"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="@+id/imgLogin"
android:layout_width="200dp"
android:layout_height="150dp"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:padding="5dp"
android:background="@mipmap/ic_launcher_round"
/>
<TextView
android:id="@+id/txtLogo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/imgLogin"
android:layout_centerHorizontal="true"
android:text="Holostik Track and Trace"
android:textSize="20dp"
android:visibility="gone" />
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/box_layout_margin_left"
android:layout_marginRight="@dimen/box_layout_margin_right"
android:layout_marginTop="8dp"
android:padding="@dimen/text_input_padding">
<EditText
android:id="@+id/edtEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:ems="10"
android:fontFamily="sans-serif"
android:gravity="top"
android:hint="Login ID"
android:maxLines="10"
android:paddingLeft="@dimen/edit_input_padding"
android:paddingRight="@dimen/edit_input_padding"
android:paddingTop="@dimen/edit_input_padding"
android:singleLine="true"></EditText>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayout2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textInputLayout1"
android:layout_marginLeft="@dimen/box_layout_margin_left"
android:layout_marginRight="@dimen/box_layout_margin_right"
android:padding="@dimen/text_input_padding">
<EditText
android:id="@+id/edtPass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:fontFamily="sans-serif"
android:hint="Password"
android:inputType="textPassword"
android:singleLine="true" />
</android.support.design.widget.TextInputLayout>
<RelativeLayout
android:id="@+id/rel12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textInputLayout2"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
>
<Button
android:id="@+id/loginSub"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="@drawable/border_button"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:layout_marginRight="10dp"
android:text="Login"
android:textColor="#ffffff" />
</RelativeLayout>
</LinearLayout>
In your example, performance probalby isn't too different but there are other issues to consider: namely memory fragmentation. Even concatenate operation is creating a new string, even if its temporary (it takes time to GC it and it's more work). String.format() is just more readable and it involves less fragmentation.
Also, if you're using a particular format a lot, don't forget you can use the Formatter() class directly (all String.format() does is instantiate a one use Formatter instance).
Also, something else you should be aware of: be careful of using substring(). For example:
String getSmallString() {
String largeString = // load from file; say 2M in size
return largeString.substring(100, 300);
}
That large string is still in memory because that's just how Java substrings work. A better version is:
return new String(largeString.substring(100, 300));
or
return String.format("%s", largeString.substring(100, 300));
The second form is probably more useful if you're doing other stuff at the same time.
Answear taken from Php manual strtotime function comments :
echo date( "Y-m-d", strtotime( "2009-01-31 -1 day"));
Or
$date = "2009-01-31";
echo date( "Y-m-d", strtotime( $date . "-1 day"));
public string GetName<TSource, TField>(Expression<Func<TSource, TField>> Field)
{
return (Field.Body as MemberExpression ?? ((UnaryExpression)Field.Body).Operand as MemberExpression).Member.Name;
}
This handles member and unary expressions. The difference being that you will get a UnaryExpression
if your expression represents a value type whereas you will get a MemberExpression
if your expression represents a reference type. Everything can be cast to an object, but value types must be boxed. This is why the UnaryExpression exists. Reference.
For the sakes of readability (@Jowen), here's an expanded equivalent:
public string GetName<TSource, TField>(Expression<Func<TSource, TField>> Field)
{
if (object.Equals(Field, null))
{
throw new NullReferenceException("Field is required");
}
MemberExpression expr = null;
if (Field.Body is MemberExpression)
{
expr = (MemberExpression)Field.Body;
}
else if (Field.Body is UnaryExpression)
{
expr = (MemberExpression)((UnaryExpression)Field.Body).Operand;
}
else
{
const string Format = "Expression '{0}' not supported.";
string message = string.Format(Format, Field);
throw new ArgumentException(message, "Field");
}
return expr.Member.Name;
}
This may not be what you want to hear, but display: table-cell
does not respect width and will be collapsed based on the width of the entire table. You can get around this easily just by having a display: block
element inside of the table cell itself whose width you specify, e.g
<td><div style="width: 300px;">wide</div></td>
This shouldn't make much of a difference if the <table>
itself is position: fixed
or absolute because the position of the cells are all static relative to the table.
http://jsfiddle.net/ExplosionPIlls/Mkq8L/4/
EDIT: I can't take credit, but as the comments say you can just use min-width
instead of width
on the table cell instead.
jQuery has two methods
// First. Get content as HTML
$("#my_div_id").html();
// Second. Get content as text
$("#my_div_id").text();
The []
s in a regex denote a character class. If no ranges are specified, it implicitly ors every character within it together. Thus, [abcde]
is the same as (a|b|c|d|e)
, except that it doesn't capture anything; it will match any one of a
, b
, c
, d
, or e
. All a range indicates is a set of characters; [ac-eg]
says "match any one of: a
; any character between c
and e
; or g
". Thus, your match says "match any one of: 0
; any character between 1
and 1
(i.e., just 1
); or 2
.
Your goal is evidently to specify a number range: any number between 01
and 12
written with two digits. In this specific case, you can match it with 0[1-9]|1[0-2]
: either a 0
followed by any digit between 1
and 9
, or a 1
followed by any digit between 0
and 2
. In general, you can transform any number range into a valid regex in a similar manner. There may be a better option than regular expressions, however, or an existing function or module which can construct the regex for you. It depends on your language.
Note that the file:///
scheme does not work on the compact framework, at least it doesn't with 5.0.
You will need to use the following:
string appDir = Path.GetDirectoryName(
Assembly.GetExecutingAssembly().GetName().CodeBase);
webBrowser1.Url = new Uri(Path.Combine(appDir, @"Documentation\index.html"));
Selenium does it for you. Or at least it tries its best. Sometimes it falls short, and you must help it a little bit. The usual solution is Implicit Wait
which solves most of the problems.
If you really know what you're doing, and why you're doing it, you could try to write a generic method which would check whether the page is completely loaded. However, it can't be done for every web and for every situation.
Related question: Selenium WebDriver : Wait for complex page with JavaScript(JS) to load, see my answer there.
Shorter version: You'll never be sure.
The "normal" load is easy - document.readyState
. This one is implemented by Selenium, of course. The problematic thing are asynchronous requests, AJAX, because you can never tell whether it's done for good or not. Most of today's webpages have scripts that run forever and poll the server all the time.
The various things you could do are under the link above. Or, like 95% of other people, use Implicit Wait
implicity and Explicit Wait
+ ExpectedConditions
where needed.
E.g. after a click, some element on the page should become visible and you need to wait for it:
WebDriverWait wait = new WebDriverWait(driver, 10); // you can reuse this one
WebElement elem = driver.findElement(By.id("myInvisibleElement"));
elem.click();
wait.until(ExpectedConditions.visibilityOf(elem));
Solved it -- Component is part of the declaration of 2 modules
And Run the command ionic cordova build android --prod --release its Working in my app
It's built in from Sublime Editor 2 at least. Just press the following and it balances the HTML-tag
Shortcut (Mac): Shift + Command + A
Shortcut (Windows): Control + Alt + A
that evidently powershell's cmdlets such as copy-item, test-path, etc do not support alternate credentials...
It looks like they do here, copy-item certainly includes a -Credential parameter.
PS C:\> gcm -syn copy-item Copy-Item [-Path] <String[]> [[-Destination] <String>] [-Container] [-Force] [-Filter <String>] [-I nclude <String[]>] [-Exclude <String[]>] [-Recurse] [-PassThru] [-Credential <PSCredential>] [...]
Are the Android samples not good enough? I've found the ApiDemos to be indispensable when learning a new aspect of Android, myself.
the best explanation i've found is this:
What is the difference betwen INTEGER and NUMBER? When should we use NUMBER and when should we use INTEGER? I just wanted to update my comments here...
NUMBER always stores as we entered. Scale is -84 to 127. But INTEGER rounds to whole number. The scale for INTEGER is 0. INTEGER is equivalent to NUMBER(38,0). It means, INTEGER is constrained number. The decimal place will be rounded. But NUMBER is not constrained.
INTEGER is always slower then NUMBER. Since integer is a number with added constraint. It takes additional CPU cycles to enforce the constraint. I never watched any difference, but there might be a difference when we load several millions of records on the INTEGER column. If we need to ensure that the input is whole numbers, then INTEGER is best option to go. Otherwise, we can stick with NUMBER data type.
Here is the link
I found that the example I was using had an xml document specification on the first line. I was using a stylesheet I got at this blog entry and the first line was
<?xmlversion="1.0"encoding="utf-8"?>
which was causing the error. When I removed that line, so that the stylesheet started with the line
<xsl:stylesheet version="1.0" xmlns:DTS="www.microsoft.com/SqlServer/Dts" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
my transform worked. By the way, that blog post was the first good, easy-to follow example I have found for trying to get information from the XML definition of an SSIS package, but I did have to modify the paths in the example for my SSIS 2008 packages, so you might too. I also created a version to extract the "flow" from the precedence constraints. My final one looks like this:
<xsl:stylesheet version="1.0" xmlns:DTS="www.microsoft.com/SqlServer/Dts" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="utf-8" />
<xsl:template match="/">
<xsl:text>From,To~</xsl:text>
<xsl:text>
</xsl:text>
<xsl:for-each select="//DTS:PrecedenceConstraints/DTS:PrecedenceConstraint">
<xsl:value-of select="@DTS:From"/>
<xsl:text>,</xsl:text>
<xsl:value-of select="@DTS:To"/>
<xsl:text>~</xsl:text>
<xsl:text>
</xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
and gave me a CSV with the tilde as my line delimiter. I replaced that with a line feed in my text editor then imported into excel to get a with look at the data flow in the package.
According to pydoc, hasattr(obj, prop) simply calls getattr(obj, prop) and catches exceptions. So, it is just as valid to wrap the attribute access with a try statement and catch AttributeError as it is to use hasattr() beforehand.
a = SomeClass()
try:
return a.fake_prop
except AttributeError:
return default_value
I have the same problem after update visual studio, so this is how do I solve the problem.
Hope this helpful for anyone who has this problem.
You can use this:
return RedirectToAction("actionName", "controllerName", new { area = "Admin" });
How about something trivial like:
inverting:
$num = -$num;
converting only positive into negative:
if ($num > 0) $num = -$num;
converting only negative into positive:
if ($num < 0) $num = -$num;
MVP:
Advantages:
Presenter will be present in between Model and view.Presenter will fetch data from Model and will do manipulations for data as view wants and give it to view and view is responsible only for rendering.
Disadvantages:
1)We can't use presenter for multiple modules because data is being modified in presenter as desired by one view class.
3)Breaking Clean architecture because data flow should be only outwards but here data is coming back from presenter to View.
MVC:
Advanatages:
Here we have Controller in between view and model.Here data request will be done from controller to view but data will be sent back to view in form of interface but not with controller.So,here controller won't get bloated up because of many transactions.
Disadvantagaes:
Data Manipulation should be done by View as it wants and this will be extra work on UI thread which may effect UI rendering if data processing is more.
MVVM:
After announcing Architectural components,we got access to ViewModel which provided us biggest advantage i.e it's lifecycle aware.So,it won't notify data if view is not available.It is a clean architecture because flow is only in forward mode and data will be notified automatically by LiveData. So,it is Android's recommended architecture.
Even MVVM has a disadvantage. Since it is a lifecycle aware some concepts like alarm or reminder should come outside app.So,in this scenario we can't use MVVM.
You can use nonzero function. it returns the nonzero indices of the given input.
Easy Way
>>> (e > 15).nonzero()
(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
to see the indices more cleaner, use transpose
method:
>>> numpy.transpose((e>15).nonzero())
[[1 6]
[1 7]
[1 8]
[1 9]
[2 0]
...
Not Bad Way
>>> numpy.nonzero(e > 15)
(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
or the clean way:
>>> numpy.transpose(numpy.nonzero(e > 15))
[[1 6]
[1 7]
[1 8]
[1 9]
[2 0]
...
You also can, as Fredigato said, declare a RelativeLayout in a separate Layout file. Then instantiate it using:
for(int i = 0; i < 6; i ++){
LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout row = (RelativeLayout) inflater.inflate(R.layout.table_view,null);
quizesTableLayout.addView(row,i);
}
In this approach you can easily design one custom row using XML and reuse it.
Now, to be able to change the children views in the instantiated RelativeLayout. You can call row.childAt(index).
So lets say you have a TextView in the RelativeLayout, you can use:
TextView tv = (TextView) row.childAt(0);
tv.setText("Text");
All the 3 first ways are identical. You have make sure that if t
is a matrix you add .
before using multiplication or the power.
for matrix:
t= [1 2 3;2 3 4;3 4 5];
tp=t.*t;
x=exp(-(t.^2));
y=exp(-(t.*t));
z=exp(-(tp));
gives the results:
x =
0.3679 0.0183 0.0001
0.0183 0.0001 0.0000
0.0001 0.0000 0.0000
y =
0.3679 0.0183 0.0001
0.0183 0.0001 0.0000
0.0001 0.0000 0.0000
z=
0.3679 0.0183 0.0001
0.0183 0.0001 0.0000
0.0001 0.0000 0.0000
And using a scalar:
p=3;
pp=p^2;
x=exp(-(p^2));
y=exp(-(p*p));
z=exp(-pp);
gives the results:
x =
1.2341e-004
y =
1.2341e-004
z =
1.2341e-004
var array = [];
//length array now = 0
array[array.length] = 'hello';
//length array now = 1
// 0
//array = ['hello'];//length = 1
The standard streams have a boolalpha
flag that determines what gets displayed -- when it's false, they'll display as 0
and 1
. When it's true, they'll display as false
and true
.
There's also an std::boolalpha
manipulator to set the flag, so this:
#include <iostream>
#include <iomanip>
int main() {
std::cout<<false<<"\n";
std::cout << std::boolalpha;
std::cout<<false<<"\n";
return 0;
}
...produces output like:
0
false
For what it's worth, the actual word produced when boolalpha
is set to true is localized--that is, <locale>
has a num_put
category that handles numeric conversions, so if you imbue a stream with the right locale, it can/will print out true
and false
as they're represented in that locale. For example,
#include <iostream>
#include <iomanip>
#include <locale>
int main() {
std::cout.imbue(std::locale("fr"));
std::cout << false << "\n";
std::cout << std::boolalpha;
std::cout << false << "\n";
return 0;
}
...and at least in theory (assuming your compiler/standard library accept "fr" as an identifier for "French") it might print out faux
instead of false
. I should add, however, that real support for this is uneven at best--even the Dinkumware/Microsoft library (usually quite good in this respect) prints false
for every language I've checked.
The names that get used are defined in a numpunct
facet though, so if you really want them to print out correctly for particular language, you can create a numpunct
facet to do that. For example, one that (I believe) is at least reasonably accurate for French would look like this:
#include <array>
#include <string>
#include <locale>
#include <ios>
#include <iostream>
class my_fr : public std::numpunct< char > {
protected:
char do_decimal_point() const { return ','; }
char do_thousands_sep() const { return '.'; }
std::string do_grouping() const { return "\3"; }
std::string do_truename() const { return "vrai"; }
std::string do_falsename() const { return "faux"; }
};
int main() {
std::cout.imbue(std::locale(std::locale(), new my_fr));
std::cout << false << "\n";
std::cout << std::boolalpha;
std::cout << false << "\n";
return 0;
}
And the result is (as you'd probably expect):
0
faux
To reference an element by id, you need to use the #
qualifier.
Try:
alert($("#link1").text());
To replace it, you could use:
$("#link1").text('New text');
The .html()
function would work in this case too.
var arr3 = new arraylist();
for(int i=0, j=0, k=0; i<arr1.size()+arr2.size(); i++){
if(i&1)
arr3.add(arr1[j++]);
else
arr3.add(arr2[k++]);
}
as you say, "the names and numbers beside each other".
Aleksander Blomskøld's solution did not work for me for parameterized tests @RunWith(Parameterized.class)
when using Maven. The tests were named correctly and also where found but not executed:
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running some.properly.named.test.run.with.maven.SomeTest
Tests run: 0, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.123 sec
A similar issue has been reported here.
In my case @Parameters
is creating instances of each class in a package. The tests worked well when run locally in the IDE. However, when running Maven no classes where found with Aleksander Blomskøld's solution.
I did make it work with the following snipped which was inspired by David Pärsson's comment on Aleksander Blomskøld's answer:
Reflections reflections = new Reflections(new ConfigurationBuilder()
.setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
.addUrls(ClasspathHelper.forJavaClassPath())
.filterInputsBy(new FilterBuilder()
.include(FilterBuilder.prefix(basePackage))));
Set<Class<?>> subTypesOf = reflections.getSubTypesOf(Object.class);
search all not (word characters || space):
str.replace(/[^\w ]/, '')
Add android:contentDescription="@string/description"
(static or dynamic) to your ImageView.
Please do not ignore nor filter the message, because it is helpfull for people using alternative input methods because of their disability (Like TalkBack, Tecla Access Shield etc etc).
HTMLUNIT is the package if you're a java developer. http://htmlunit.sourceforge.net/apidocs/index.html
You can run this command for making a factory reset:
killall dropbear uhttpd; sleep 1; mtd -r erase rootfs_data
How about
map(list, zip(*l))
--> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
For python 3.x users can use
list(map(list, zip(*l))) # short circuits at shortest nested list if table is jagged
list(map(list, itertools.zip_longest(*l, fillvalue=None))) # discards no data if jagged and fills short nested lists with None
Explanation:
There are two things we need to know to understand what's going on:
zip(*iterables)
This means zip
expects an arbitrary number of arguments each of which must be iterable. E.g. zip([1, 2], [3, 4], [5, 6])
.args
, f(*args)
will call f
such that each element in args
is a separate positional argument of f
.itertools.zip_longest
does not discard any data if the number of elements of the nested lists are not the same (homogenous), and instead fills in the shorter nested lists then zips them up.Coming back to the input from the question l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
, zip(*l)
would be equivalent to zip([1, 2, 3], [4, 5, 6], [7, 8, 9])
. The rest is just making sure the result is a list of lists instead of a list of tuples.
There's no need to do this in two commits, you can add the file and mark it executable in a single commit:
C:\Temp\TestRepo>touch foo.sh
C:\Temp\TestRepo>git add foo.sh
C:\Temp\TestRepo>git ls-files --stage
100644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0 foo.sh
As you note, after adding, the mode is 0644 (ie, not executable). However, we can mark it as executable before committing:
C:\Temp\TestRepo>git update-index --chmod=+x foo.sh
C:\Temp\TestRepo>git ls-files --stage
100755 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 0 foo.sh
And now the file is mode 0755 (executable).
C:\Temp\TestRepo>git commit -m"Executable!"
[master (root-commit) 1f7a57a] Executable!
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100755 foo.sh
And now we have a single commit with a single executable file.
POSIX is a set of standards put forth by IEEE and The Open Group that describes how an ideal Unix would operate. Programmers, users, and administrators can all become familiar with the POSIX document, and expect a POSIX-complaint Unix to provide all of the standard facilities mentioned.
Since every Unix does things a little differently -- Solaris, Mac OS X, IRIX, BSD, and Linux all have their quirks -- POSIX is especially useful to those in the industry as it defines a standard environment to operate in. For example, most of the functions in the C library are based in POSIX; a programmer can, therefore, use one in his application and expect it to behave the same across most Unices.
However, the divergent areas of Unix are typically the focus, rather than the standard ones.
The great thing about POSIX is that you're welcome to read it yourself:
Issue 7 is known as POSIX.1-2008, and there are new things in there -- however, Google-fu for POSIX.1 and such will allow you to see the entire history behind what Unix is.
There is no such method as java.util.Random.getRandomDigits
.
To get a random number use nextInt:
return random.nextInt(10 ** num)
Also you should create the random object once when your application starts:
Random random = new Random()
You should not create a new random object every time you want a new random number. Doing this destroys the randomness.
Apache Commons has an IntegerValidator class which appears to do what you want. Java provides no in-built method for doing this.
See here for the groupid/artifactid.
So, I had the same issue and sadly just adding to the rules didn't work. I found out that accept: and extension: are not part of JQuery validate.js by default and it requires an additional-Methods.js plugin to make it work.
So for anyone else who followed this thread and it still didn't work, you can try adding additional-Methods.js to your tag in addition to the answer above and it should work.
This is very simple:
import numpy as np
list_of_lists = np.array(df)
And the requisite, non-jquery way, for followers, since google seems to send everyone here:
var select = document.getElementById("select_id");
for (var i = 0; i < select.length; i++){
var option = select.options[i];
// now have option.text, option.value
}
From Javascript: The Definitive Guide, it clarifies things. It notes that HTMLElement objects of a HTML doc define JS properties that correspond to all standard HTML attributes.
So you only need to use setAttribute
for non-standard attributes.
Example:
node.className = 'test'; // works
node.frameborder = '0'; // doesn't work - non standard attribute
node.setAttribute('frameborder', '0'); // works
Use .prop
instead (and clean up your selector string):
function disable(i){
$("#rbutton_"+i).prop("disabled",true);
}
generated HTML:
<button id="rbutton_1" onclick="disable(1)">Click me</button>
<!-- wrap your onclick in quotes -->
But the "best practices" approach is to use JavaScript event binding and this
instead:
$('.rbutton').on('click',function() {_x000D_
$(this).prop("disabled",true);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<button class="rbutton">Click me</button>
_x000D_
sudo sh -c "echo 127.0.0.1 localhost >> /etc/hosts"
this.setState({abc: {xyz: 'new value'}});
will NOT work, as state.abc
will be entirely overwritten, not merged.
This works for me:
this.setState((previousState) => {
previousState.abc.xyz = 'blurg';
return previousState;
});
Unless I'm reading the docs wrong, Facebook recommends the above format. https://facebook.github.io/react/docs/component-api.html
Additionally, I guess the most direct way without mutating state is to directly copy by using the ES6 spread/rest operator:
const newState = { ...this.state.abc }; // deconstruct state.abc into a new object-- effectively making a copy
newState.xyz = 'blurg';
this.setState(newState);
The main difference is with asynchronous programming, you don't stop execution otherwise. You can continue executing other code while the 'request' is being made.
If you have a dataset named daily_data
:
daily_data<-daily_data[order(as.Date(daily_data$date, format="%d/%m/%Y")),]
Or add styles inline:
<p style="font-size:18px">Paragraph 1</p>
<p style="font-size:16px">Paragraph 2</p>
Adapting @MOnsDaR answer for modern CMake syntax with imported targets, this would be:
find_package(Boost 1.40 COMPONENTS program_options REQUIRED)
add_executable(anyExecutable myMain.cpp)
target_link_libraries(anyExecutable Boost::program_options)
Note that it is not necessary to specify the include directories manually, since it is already taken care of through the imported target Boost::program_options
.
When you return value from server to jQuery's Ajax call you can also use the below code to indicate a server error:
return StatusCode(500, "My error");
Or
return StatusCode((int)HttpStatusCode.InternalServerError, "My error");
Or
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return Json(new { responseText = "my error" });
Codes other than Http Success codes (e.g. 200[OK]) will trigger the function in front of error:
in client side (ajax).
you can have ajax call like:
$.ajax({
type: "POST",
url: "/General/ContactRequestPartial",
data: {
HashId: id
},
success: function (response) {
console.log("Custom message : " + response.responseText);
}, //Is Called when Status Code is 200[OK] or other Http success code
error: function (jqXHR, textStatus, errorThrown) {
console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
}, //Is Called when Status Code is 500[InternalServerError] or other Http Error code
})
Additionally you can handle different HTTP errors from jQuery side like:
$.ajax({
type: "POST",
url: "/General/ContactRequestPartial",
data: {
HashId: id
},
statusCode: {
500: function (jqXHR, textStatus, errorThrown) {
console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
501: function (jqXHR, textStatus, errorThrown) {
console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
}
})
statusCode:
is useful when you want to call different functions for different status codes that you return from server.
You can see list of different Http Status codes here:Wikipedia
Additional resources:
Related answer to @nash11, here's how you would produce an array of checkbox values
AND
have a checkbox that also selectsAll the checkboxes:
https://stackblitz.com/edit/angular-checkbox-custom-value-with-selectall
From here what I understand DataFrames are:
DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects.
And Series are:
Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.).
Series have a name
attribute which can be accessed like so:
In [27]: s = pd.Series(np.random.randn(5), name='something')
In [28]: s
Out[28]:
0 0.541
1 -1.175
2 0.129
3 0.043
4 -0.429
Name: something, dtype: float64
In [29]: s.name
Out[29]: 'something'
EDIT: Based on OP's comments, I think OP was looking for something like:
>>> df = pd.DataFrame(...)
>>> df.name = 'df' # making a custom attribute that DataFrame doesn't intrinsically have
>>> print(df.name)
'df'
In addition to the answers above the command below will also work. I post it because it makes more sense to me. In each case it is 'using x-value-column: y-value-column'
plot 'ls.dat' using 1:2, 'ls.dat' using 1:3, 'ls.dat' using 1:4
note that the command above assumes that you have a file named ls.dat
with tab separated columns of data where column 1 is x, column 2 is y1, column 3 is y2 and column 4 is y3.
Let me add an example here:
I'm trying to build Alluxio
on windows platform and got the same issue, it's because the pom.xml
contains below step:
<plugin>
<artifactId>exec-maven-plugin</artifactId>
<groupId>org.codehaus.mojo</groupId>
<inherited>false</inherited>
<executions>
<execution>
<id>Check that there are no Windows line endings</id>
<phase>compile</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>${build.path}/style/check_no_windows_line_endings.sh</executable>
</configuration>
</execution>
</executions>
</plugin>
The .sh
file is not executable on windows so the error throws.
Comment it out if you do want build Alluxio
on windows.
I ran into this issue on GKE and the reason was no credentials for docker.
Running this resolved it:
gcloud auth configure-docker
I had the same problem while I was testing a project and it turned that running Fiddler was the cause for this error..!!
If you are using Fiddler to intercept the http request, shut it down ...
This is one of the many causes for such error.
To fix Fiddler you may need to Reset Fiddler Https Certificates.
The ErrorDocument
directive, when supplied a local URL path, expects the path to be fully qualified from the DocumentRoot
. In your case, this means that the actual path to the ErrorDocument
is
ErrorDocument 404 /hellothere/error/404page.html
Use the android:drawableLeft
property on the EditText.
<EditText
...
android:drawableLeft="@drawable/my_icon" />
A regex-less version which is easy on the eye:
const trim = (str, chars) => str.split(chars).filter(Boolean).join(chars);
For use cases where we're certain that there's no repetition of the chars off the edges.
At least for me, there was an easy answer (after much digging around) to changing a tab title at runtime:
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.getTabAt(MyTabPos).setText("My New Text");
I wanted a function that would return a boolean, I encountered problems related to closure and asynchronicity. I solved this way:
checkFileExistence= function (file){
result=false;
jQuery.ajaxSetup({async:false});
$.get(file)
.done(function() {
result=true;
})
.fail(function() {
result=false;
})
jQuery.ajaxSetup({async:true});
return(result);
},
Not sure if this is relevant to your question but it might be relevant to someone else in the future: I had a similar error. Turned out that the df was empty (had zero rows) and that is what was causing the error in my command.
Also set ${COMMAND}
to g++
on Linux
Under:
Replace:
${COMMAND} ${FLAGS} -E -P -v -dD "${INPUTS}"
with:
g++ -std=c++11 -E -P -v -dD "${INPUTS}"
If you don't do this, the Eclipse stdout shows:
Unable to find full path for "-E"
and logs under ${HOME}/eclipse-workspace/.metadata/.log
show:
!ENTRY org.eclipse.cdt.core 4 0 2020-04-23 20:17:07.288
!MESSAGE Error: Cannot run program "-E": Unknown reason
because ${COMMAND} ${FLAGS}
are empty, and so Eclipse tries to execute the -E
that comes next.
I wonder if we can properly define the COMMAND
and FLAGS
variables on the settings, but I tried to add them as build variables and it didn't work.
C version of the question: "Unresolved inclusion" error with Eclipse CDT for C standard library headers
Tested on Eclipse 2020-03 (4.15.0), Ubuntu 19.10, and this minimal Makefile project with existing sources.
The function that it returns has a call signature, but you told Typescript to completely ignore that by adding : any
in its signature.
This worked for me. Hope it helps someone. :)
SimpleAdapter adapter = (SimpleAdapter) getListAdapter();
this.resultsList.remove((int) info.id);
adapter.notifyDataSetChanged();
if you use apiLevel >= 19
, don't use
WindowManager.LayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
which gets the following error:
android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W@40ec8528 -- permission denied for this window type
Use this instead:
LayoutParams.TYPE_TOAST or TYPE_APPLICATION_PANEL
I know it's an old question, but for single line text setting display: inline-block
and then setting the height
has worked well for me to control the distance between a border and the text.
Have you googled about it - insert update delete access vb.net, there are lots of reference about this.
Insert Update Delete Navigation & Searching In Access Database Using VB.NET
what could be the easier way to connect and manipulate the DB?
Use OleDBConnection class to make connection with DB
is it by using MS ACCESS 2003 or MS ACCESS 2007?
you can use any you want to use or your client will use on their machine.
it seems that you want to find some example of opereations fo the database. Here is an example of Access 2010 for your reference:
Example code snippet:
Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class DBUtil
Private connectionString As String
Public Sub New()
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
Dim dbSource = "Data Source=d:\DB\Database11.accdb"
connectionString = dbProvider & dbSource
End Sub
Public Function GetCategories() As DataSet
Dim query As String = "SELECT * FROM Categories"
Dim cmd As New OleDbCommand(query)
Return FillDataSet(cmd, "Categories")
End Function
Public SubUpdateCategories(ByVal name As String)
Dim query As String = "update Categories set name = 'new2' where name = ?"
Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("Name", name)
Return FillDataSet(cmd, "Categories")
End Sub
Public Function GetItems() As DataSet
Dim query As String = "SELECT * FROM Items"
Dim cmd As New OleDbCommand(query)
Return FillDataSet(cmd, "Items")
End Function
Public Function GetItems(ByVal categoryID As Integer) As DataSet
'Create the command.
Dim query As String = "SELECT * FROM Items WHERE Category_ID=?"
Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("category_ID", categoryID)
'Fill the dataset.
Return FillDataSet(cmd, "Items")
End Function
Public Sub AddCategory(ByVal name As String)
Dim con As New OleDbConnection(connectionString)
'Create the command.
Dim insertSQL As String = "INSERT INTO Categories "
insertSQL &= "VALUES(?)"
Dim cmd As New OleDbCommand(insertSQL, con)
cmd.Parameters.AddWithValue("Name", name)
Try
con.Open()
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
End Sub
Public Sub AddItem(ByVal title As String, ByVal description As String, _
ByVal price As Decimal, ByVal categoryID As Integer)
Dim con As New OleDbConnection(connectionString)
'Create the command.
Dim insertSQL As String = "INSERT INTO Items "
insertSQL &= "(Title, Description, Price, Category_ID)"
insertSQL &= "VALUES (?, ?, ?, ?)"
Dim cmd As New OleDb.OleDbCommand(insertSQL, con)
cmd.Parameters.AddWithValue("Title", title)
cmd.Parameters.AddWithValue("Description", description)
cmd.Parameters.AddWithValue("Price", price)
cmd.Parameters.AddWithValue("CategoryID", categoryID)
Try
con.Open()
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
End Sub
Private Function FillDataSet(ByVal cmd As OleDbCommand, ByVal tableName As String) As DataSet
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
Dim dbSource = "Data Source=D:\DB\Database11.accdb"
connectionString = dbProvider & dbSource
con.ConnectionString = connectionString
cmd.Connection = con
Dim adapter As New OleDbDataAdapter(cmd)
Dim ds As New DataSet()
Try
con.Open()
adapter.Fill(ds, tableName)
Finally
con.Close()
End Try
Return ds
End Function
End Class
Refer these links:
Insert, Update, Delete & Search Values in MS Access 2003 with VB.NET 2005
INSERT, DELETE, UPDATE AND SELECT Data in MS-Access with VB 2008
How Add new record ,Update record,Delete Records using Vb.net Forms when Access as a back
You can use these functions to brutally remove everything Docker related:
removecontainers() {
docker stop $(docker ps -aq)
docker rm $(docker ps -aq)
}
armageddon() {
removecontainers
docker network prune -f
docker rmi -f $(docker images --filter dangling=true -qa)
docker volume rm $(docker volume ls --filter dangling=true -q)
docker rmi -f $(docker images -qa)
}
You can add those to your ~/Xrc
file, where X is your shell interpreter (~/.bashrc
if you're using bash) file and reload them via executing source ~/Xrc
. Also, you can just copy paste them to the console and afterwards (regardless the option you took before to get the functions ready) just run:
armageddon
It's also useful for just general Docker clean up. Have in mind that this will also remove your images, not only your containers (either running or not) and your volumes of any kind.
This works well for me:
WifiConfiguration apConfig = null;
Method method = wifimanager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
method.invoke(wifimanager, apConfig, true);
I can't think of a way with the styling, but you could just set the text of the checkbox to nothing, and put a TextView to the left of the checkbox with your desired text.
If you just need to know if there's a fix, then check for the last known location provided by the GPS receiver and check the .getTime() value to know how old is that. If it's recent enough (like... a few seconds) you have a fix.
LocationManager lm = (LocationManager)context.getSystemService(LOCATION_SERVICE);
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// Get the time of the last fix
long lastFixTimeMillis = loc.getTime();
... and finally compare that to current date time (In UTC!). If it's recent enough you have a fix.
I do that in my app and so far so good.
File myFile = new File(uri.toString());
myFile.getAbsolutePath()
should return u the correct path
EDIT
As @Tron suggested the working code is
File myFile = new File(uri.getPath());
myFile.getAbsolutePath()
Using iReport designer 5.6.0, if you wish to compile multiple jrxml files without previewing - go to Tools -> Massive Processing Tool. Select Elaboration Type as "Compile Files", select the folder where all your jrxml reports are stored, and compile them in a batch.
Here is a shorter solution by AbacusUtil
Stream.of(input).toMap(e -> e.getKey().substring(subLength),
e -> AttributeType.GetByName(e.getValue()));
What about something like this ?
class Configuration
{
private $config;
public function __construct($configIniFilePath)
{
$this->config = parse_ini_file($configIniFilePath, true);
}
/**
* Gets the value for the specified setting name.
*
* @param string $name the setting name
* @param string $section optional, the name of the section containing the
* setting
* @return string|null the value of the setting, or null if it doesn't exist
*/
public function getConfiguration($name, $section = null)
{
$configValue = null;
if ($section === null) {
if (array_key_exists($name, $this->config)) {
$configValue = $this->config[$name];
}
} else {
if (array_key_exists($section, $this->config)) {
$sectionSettings = $this->config[$section];
if (array_key_exists($name, $sectionSettings)) {
$configValue = $sectionSettings[$name];
}
}
}
return $configValue;
}
}
VB is not a language. VB is a program that hosts VBA, just as Office hosts VBA. VB is a set of App objects, just like Word and Excel have, and a forms package, just like in Office.
So you can only write VBA code in VB.
PS this info is on the INFO tab on the VB question page for VB.
From VBA Info
VBA 6, was shipped in 1998 and includes a myriad of licensed hosts, among them: Office 2000 - 2010, AutoCAD, PI Processbook, and the stand-alone Visual Basic 6.0
@xtrem's answer is good, but I think the toFixed
and the makePercentage
are common use. Define two functions, and we can use that at everywhere.
const R = require('ramda')
const RA = require('ramda-adjunct')
const fix = R.invoker(1, 'toFixed')(2)
const makePercentage = R.when(
RA.isNotNil,
R.compose(R.flip(R.concat)('%'), fix, R.multiply(100)),
)
let a = 0.9988
let b = null
makePercentage(b) // -> null
makePercentage(a) // -> ?????99.88%?????