You can use DataFrame.values
to get an numpy array of the data and then use NumPy functions such as argsort()
to get the most correlated pairs.
But if you want to do this in pandas, you can unstack
and sort the DataFrame:
import pandas as pd
import numpy as np
shape = (50, 4460)
data = np.random.normal(size=shape)
data[:, 1000] += data[:, 2000]
df = pd.DataFrame(data)
c = df.corr().abs()
s = c.unstack()
so = s.sort_values(kind="quicksort")
print so[-4470:-4460]
Here is the output:
2192 1522 0.636198
1522 2192 0.636198
3677 2027 0.641817
2027 3677 0.641817
242 130 0.646760
130 242 0.646760
1171 2733 0.670048
2733 1171 0.670048
1000 2000 0.742340
2000 1000 0.742340
dtype: float64
I think below explanation will help to you..
differentiation between those:
Correlated subquery
is an inner query referenced by main query (outer query) such that inner query considered as being excuted repeatedly.
non-correlated subquery
is a sub query that is an independent of the outer query and it can executed on it's own without relying on main outer query.
plain subquery
is not dependent on the outer query,
One option is to put the subquery in a LEFT JOIN
:
select sum ( t.graduates ) - t1.summedGraduates
from table as t
left join
(
select sum ( graduates ) summedGraduates, id
from table
where group_code not in ('total', 'others' )
group by id
) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates
Perhaps a better option would be to use SUM
with CASE
:
select sum(case when group_code = 'total' then graduates end) -
sum(case when group_code not in ('total','others') then graduates end)
from yourtable
Necromancing:
It's relativiely simple to emulate a COUNT DISTINCT over PARTITION BY with MAX via DENSE_RANK:
;WITH baseTable AS
(
SELECT 'RM1' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM1' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR2' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR2' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR3' AS ADR
UNION ALL SELECT 'RM3' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM2' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM3' AS RM, 'ADR1' AS ADR
UNION ALL SELECT 'RM3' AS RM, 'ADR2' AS ADR
)
,CTE AS
(
SELECT RM, ADR, DENSE_RANK() OVER(PARTITION BY RM ORDER BY ADR) AS dr
FROM baseTable
)
SELECT
RM
,ADR
,COUNT(CTE.ADR) OVER (PARTITION BY CTE.RM ORDER BY ADR) AS cnt1
,COUNT(CTE.ADR) OVER (PARTITION BY CTE.RM) AS cnt2
-- Not supported
--,COUNT(DISTINCT CTE.ADR) OVER (PARTITION BY CTE.RM ORDER BY CTE.ADR) AS cntDist
,MAX(CTE.dr) OVER (PARTITION BY CTE.RM ORDER BY CTE.RM) AS cntDistEmu
FROM CTE
Note:
This assumes the fields in question are NON-nullable fields.
If there is one or more NULL-entries in the fields, you need to subtract 1.
The package broom
comes in handy here (it uses the "tidy" format).
tidy(mg)
will give a nicely formated data.frame with coefficients, t statistics etc. Works also for other models (e.g. plm, ...).
Example from broom
's github repo:
lmfit <- lm(mpg ~ wt, mtcars)
require(broom)
tidy(lmfit)
term estimate std.error statistic p.value
1 (Intercept) 37.285 1.8776 19.858 8.242e-19
2 wt -5.344 0.5591 -9.559 1.294e-10
is.data.frame(tidy(lmfit))
[1] TRUE
Let's assume you want to concatenate string and integer in a situation like this:
for i in range(1,11):
string="string"+i
and you are getting type or concatenation error
The best way to go about it is to do something like this:
for i in range(1,11):
print("string",i)
This will give you concatenated results like string 1, string 2, string 3 ...etc
ALTER TABLE Employee ADD DEFAULT 'SANDNES' FOR CityBorn
If you need a one off solution, you can try: https://addresstolatlong.com/
I've used it for a long time and it has worked pretty well for me.
You can always use an alias:
alias next='printf "blah_%02d" $count;count=$((count+1))'
You can use the <datalist>
tag instead of the <select>
tag.
<input list="browsers" name="browser" id="browser">
<datalist id="browsers">
<option value="Edge">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
31-DEC-95
isn't a string, nor is 20-JUN-94
. They're numbers with some extra stuff added on the end. This should be '31-DEC-95'
or '20-JUN-94'
- note the single quote, '
. This will enable you to do a string comparison.
However, you're not doing a string comparison; you're doing a date comparison. You should transform your string into a date. Either by using the built-in TO_DATE()
function, or a date literal.
select employee_id
from employee
where employee_date_hired > to_date('31-DEC-95','DD-MON-YY')
This method has a few unnecessary pitfalls
DEC
, doesn't necessarily mean December. It depends on your NLS_DATE_LANGUAGE
and NLS_DATE_FORMAT
settings. To ensure that your comparison with work in any locale you can use the datetime format model MM
instead select employee_id
from employee
where employee_date_hired > to_date('31-12-1995','DD-MM-YYYY')
A date literal is part of the ANSI standard, which means you don't have to use an Oracle specific function. When using a literal you must specify your date in the format YYYY-MM-DD
and you cannot include a time element.
select employee_id
from employee
where employee_date_hired > date '1995-12-31'
Remember that the Oracle date datatype includes a time elemement, so the date without a time portion is equivalent to 1995-12-31 00:00:00
.
If you want to include a time portion then you'd have to use a timestamp literal, which takes the format YYYY-MM-DD HH24:MI:SS[.FF0-9]
select employee_id
from employee
where employee_date_hired > timestamp '1995-12-31 12:31:02'
NLS_DATE_LANGUAGE
is derived from NLS_LANGUAGE
and NLS_DATE_FORMAT
is derived from NLS_TERRITORY
. These are set when you initially created the database but they can be altered by changing your inialization parameters file - only if really required - or at the session level by using the ALTER SESSION
syntax. For instance:
alter session set nls_date_format = 'DD.MM.YYYY HH24:MI:SS';
This means:
DD
numeric day of the month, 1 - 31MM
numeric month of the year, 01 - 12 ( January is 01 )YYYY
4 digit year - in my opinion this is always better than a 2 digit year YY
as there is no confusion with what century you're referring to.HH24
hour of the day, 0 - 23MI
minute of the hour, 0 - 59SS
second of the minute, 0-59You can find out your current language and date language settings by querying V$NLS_PARAMETERSs
and the full gamut of valid values by querying V$NLS_VALID_VALUES
.
Incidentally, if you want the count(*)
you need to group by employee_id
select employee_id, count(*)
from employee
where employee_date_hired > date '1995-12-31'
group by employee_id
This gives you the count per employee_id
.
Use px-0
on the container
and no-gutters
on the row
to remove the paddings.
Quoting from Bootstrap 4 - Grid system:
Rows are wrappers for columns. Each column has horizontal padding (called a gutter) for controlling the space between them. This padding is then counteracted on the rows with negative margins. This way, all the content in your columns is visually aligned down the left side.
Columns have horizontal padding to create the gutters between individual columns, however, you can remove the margin from rows and padding from columns with
.no-gutters
on the.row
.
Following is a live demo:
h1 {
background-color: tomato;
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" />
<div class="container-fluid" id="div1">
<div class="row">
<div class="col">
<h1>With padding : (</h1>
</div>
</div>
</div>
<div class="container-fluid px-0" id="div1">
<div class="row no-gutters">
<div class="col">
<h1>No padding : > </h1>
</div>
</div>
</div>
_x000D_
The reason this works is that container-fluid
and col
both have following padding:
padding-right: 15px;
padding-left: 15px;
px-0
can remove the horizontal padding from container-fluid
and no-gutters
can remove the padding from col
.
Apple's implementation of @synchronized is open source and it can be found here. Mike ash wrote two really interesting post about this subject:
In a nutshell it has a table that maps object pointers (using their memory addresses as keys) to pthread_mutex_t
locks, which are locked and unlocked as needed.
One way to get this error is trying to add a usercontrol to a form while the project is set to compile as x64. Visual Studio throws the unhelpful: "Failed to load toolbox item . It will be removed from the toolbox."
Workaround is to design with "Any CPU" and compile to x64 as necessary.
Could use sprintf
to accomplish this:
awk '{str = sprintf("%s %s", $1, $2)} END {print str}' file
If you are using gradle,
```
def gitHash = new ByteArrayOutputStream()
project.exec {
commandLine 'git', 'rev-parse', '--short', 'HEAD'
standardOutput = gitHash
}
def gitBranch = new ByteArrayOutputStream()
project.exec {
def gitCmd = "git symbolic-ref --short -q HEAD || git branch -rq --contains "+getGitHash()+" | sed -e '2,\$d' -e 's/\\(.*\\)\\/\\(.*\\)\$/\\2/' || echo 'master'"
commandLine "bash", "-c", "${gitCmd}"
standardOutput = gitBranch
}
```
The clearest explanation for LSP I found so far has been "The Liskov Substitution Principle says that the object of a derived class should be able to replace an object of the base class without bringing any errors in the system or modifying the behavior of the base class" from here. The article gives code example for violating LSP and fixing it.
Use encodeURI()
in client JS and use URLDecoder.decode()
in server Java side works.
Example:
Javascript:
$.getJSON(
url,
{
"user": encodeURI(JSON.stringify(user))
},
onSuccess
);
Java:
java.net.URLDecoder.decode(params.user, "UTF-8");
You can add UIButton,UIlable and UITextfield programmatically in this way.
UIButton code
// var button = UIButton.buttonWithType(UIButtonType.System) as UIButton
let button = UIButton(type: .System) // let preferred over var here
button.frame = CGRectMake(100, 100, 100, 50)
button.backgroundColor = UIColor.greenColor()
button.setTitle("Button", forState: UIControlState.Normal)
button.addTarget(self, action: "Action:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(button)
UILabel Code
var label: UILabel = UILabel()
label.frame = CGRectMake(50, 50, 200, 21)
label.backgroundColor = UIColor.blackColor()
label.textColor = UIColor.whiteColor()
label.textAlignment = NSTextAlignment.Center
label.text = "test label"
self.view.addSubview(label)
UITextField code
var txtField: UITextField = UITextField()
txtField.frame = CGRectMake(50, 70, 200, 30)
txtField.backgroundColor = UIColor.grayColor()
self.view.addSubview(txtField)
Hope this is helpful for you.
This seems to work fine for intel Mac 10.7:
#include <time.h>
time_t start = time(NULL);
//Do your work
time_t end = time(NULL);
std::cout<<"Execution Time: "<< (double)(end-start)<<" Seconds"<<std::endl;
Try this one, this function allows alphanumeric and spaces:
function alpha(e) {
var k;
document.all ? k = e.keyCode : k = e.which;
return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
}
in your html:
<input type="text" name="name" onkeypress="return alpha(event)"/>
And the missing awk solution is:
$ awk '(FNR==1){print ">> " FILENAME " <<"}1' *
VisualHG is a Mercurial Source control plugin that drives TortoiseHG from VS. I'm a big fan of Mercurial & DVCS. VisualHG makes it nice n integrated. Git fans - I'm not asking for a flame war. Hg is just my brand.
You can now use Modern ECMAScript syntax thanks to V8 Runtime.
You can use includes():
var grade = itemResponse.getResponse();
if(grade.includes("9th")){do something}
If you are just concatenating paths you can use Ruby's own File.join method.
source = File.join(ROOT_DIR, project, 'App.config')
You may be checking an object null by comparing it with a null value but when you try to check an empty object then you need to string typecast. Below the code, you get the idea.
if(obj == null || (string) obj == string.Empty)
{
//Obj is null or empty
}
In my opinion this is the simplest solution
$orderby = 'name';
$order = 'asc';
$hide_empty = false ;
$cat_args = array(
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
);
$product_categories = get_terms( 'product_cat', $cat_args );
if( !empty($product_categories) ){
echo '
<ul>';
foreach ($product_categories as $key => $category) {
echo '
<li>';
echo '<a href="'.get_term_link($category).'" >';
echo $category->name;
echo '</a>';
echo '</li>';
}
echo '</ul>
';
}
In my case the problem was I had forgotten to add the switch -m before the quoted comment. It may be a common error too, and the error message received is exactly the same
String.compareTo
might or might not be what you need.
Take a look at this link if you need localized ordering of strings.
It's not necessary, as interfaces are by default abstract as all the methods in an interface are abstract.
var myArr1 = [AnyObject]()
can store any object
var myArr2 = [String]()
can store only string
class Foo {
const BAR = 'baz';
}
echo Foo::BAR;
This is the only way to make class constants. These constants are always globally accessible via Foo::BAR
, but they're not accessible via just BAR
.
To achieve a syntax like Foo::baz()->BAR
, you would need to return an object from the function baz()
of class Foo
that has a property BAR
. That's not a constant though. Any constant you define is always globally accessible from anywhere and can't be restricted to function call results.
The reason enums work easily with == is because each defined instance is also a singleton. So identity comparison using == will always work.
But using == because it works with enums means all your code is tightly coupled with usage of that enum.
For example: Enums can implement an interface. Suppose you are currently using an enum which implements Interface1. If later on, someone changes it or introduces a new class Impl1 as an implementation of same interface. Then, if you start using instances of Impl1, you'll have a lot of code to change and test because of previous usage of ==.
Hence, it's best to follow what is deemed a good practice unless there is any justifiable gain.
Seems very similar to this question. From there it seems that this should do the trick:
table {
display: block; /* important */
height: 600px;
overflow-y: scroll;
}
Update:
Often people want the most recent version of gcc, and devtoolset is being kept up-to-date, so maybe you want devtoolset-N where N={4,5,6,7...}, check yum for the latest available on your system). Updated the cmds below for N=7.
There is a package for gcc-7.2.1 for devtoolset-7 as an example. First you need to enable the Software Collections, then it's available in devtoolset-7:
sudo yum install centos-release-scl
sudo yum install devtoolset-7-gcc*
scl enable devtoolset-7 bash
which gcc
gcc --version
as the error says 'No installed build tools found' it means that
1 : It really really really did not found build tools
2 : To make him find build tools you need to define these paths correctly
PATH IS SAME FOR UBUNTU(.bashrc) AND MAC(.bash_profile)
export ANDROID_HOME=/Users/vijay/Software/android-sdk-macosx
export PATH=${PATH}:/Users/vijay/Software/android-sdk-macosx/tools
export PATH=${PATH}:/Users/vijay/Software/android-sdk-macosx/platform-tools
3 : IMPORTANT IMPORTANT as soon as you set environmental variables you need to reload evnironmental variables.
//For ubuntu
$source .bashrc
//For macos
$source .bash_profile
4 : Then check in terminal
$printenv ANDROID_HOME
$printenv PATH
Note : if you did not find your changes in printenv then restart the pc and try again printenv PATH, printenv ANDROID_HOME .There is also command to reload environmental variables .
4 : then open terminal and write HALF TEXT '$and' and hit tab. On hitting tab you should see full '$android' name.this verifys all paths are correct
5 : write $android in terminal and hit enter
Try this:
BitmapImage image = new BitmapImage(new Uri("/MyProject;component/Images/down.png", UriKind.Relative));
Is there a way to set the session timeout programatically
There are basically three ways to set the session timeout value:
session-timeout
in the standard web.xml
file ~or~session-timeout
value (and thus configuring it at the server level) ~or~HttpSession. setMaxInactiveInterval(int seconds)
method in your Servlet or JSP. But note that the later option sets the timeout value for the current session, this is not a global setting.
You should be able to install m2e (maven project for eclipse) using the Help -> Install New Software dialog. On that dialog open the Juno site (http://download.eclipse.org/releases/juno) and expand the Collaboration group (or type m2e into the filter). Select the two m2e options and follow the installation dialog
Kindall's answer in Python3
class ThreadWithReturnValue(Thread):
def __init__(self, group=None, target=None, name=None,
args=(), kwargs={}, *, daemon=None):
Thread.__init__(self, group, target, name, args, kwargs, daemon)
self._return = None
def run(self):
try:
if self._target:
self._return = self._target(*self._args, **self._kwargs)
finally:
del self._target, self._args, self._kwargs
def join(self,timeout=None):
Thread.join(self,timeout)
return self._return
I was getting this one on this case
...
.then((error: any, response: any) => {
console.info('document error: ', error);
console.info('documenr response: ', response);
return new MyModel();
})
...
on this case making parameters optional would make ts stop complaining
.then((error?: any, response?: any) => {
AFAIK you can not remove attribute at runtime, but only change their values (ie: readonly true/false) look here for something similar . As another way of doing what you want without messing with attributes I will go with a ViewModel for your specific action so you can insert all the logic without breaking the logic needed by other controllers. If you try to obtain some sort of wizard (a multi steps form) you can instead serialize the already compiled fields and with TempData bring them along your steps. (for help in serialize deserialize you can use MVC futures)
Keeping it simple :
a = 0
The code above gives a global scope variable
var a = 0;
This code will give a variable to be used in the current scope, and under it
window.a = 0;
This generally is same as the global variable.
By checking the source code of glob.glob
you see that it internally calls os.listdir
, described here:
http://docs.python.org/library/os.html?highlight=os.listdir#os.listdir
Key sentence: os.listdir(path) Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.
Arbitrary order. :)
If you are into optimization, and assuming the input is always one of the four characters, the function below might be worth a try as a replacement for the map:
char map(const char in)
{ return ((in & 2) ? '\x8a' - in : '\x95' - in); }
It works based on the fact that you are dealing with two symmetric pairs. The conditional works to tell apart the A/T pair from the G/C one ('G' and 'C' happen to have the second-least-significant bit in common). The remaining arithmetics performs the symmetric mapping. It's based on the fact that a = (a + b) - b is true for any a,b.
Just call componentsSeparatedByString
method on your fullName
import Foundation
var fullName: String = "First Last"
let fullNameArr = fullName.componentsSeparatedByString(" ")
var firstName: String = fullNameArr[0]
var lastName: String = fullNameArr[1]
Update for Swift 3+
import Foundation
let fullName = "First Last"
let fullNameArr = fullName.components(separatedBy: " ")
let name = fullNameArr[0]
let surname = fullNameArr[1]
I'm sure someone can do better, but this works:
sapply(as.character(q.data$string), function(x, letter = "a"){
sum(unlist(strsplit(x, split = "")) == letter)
})
greatgreat magic not
2 1 0
or in a function:
countLetter <- function(charvec, letter){
sapply(charvec, function(x, letter){
sum(unlist(strsplit(x, split = "")) == letter)
}, letter = letter)
}
countLetter(as.character(q.data$string),"a")
Using ...
search = (^.*import )(.*)(\(.*\):)
replace = $1$2
...replaces ...
from checks import checklist(_list):
...with...
from checks import checklist
Blocks in regex are delineated by parenthesis (which are not preceded by a "\")
(^.*import ) finds "from checks import " and loads it to $1 (eclipse starts counting at 1)
(.*) find the next "everything" until the next encountered "(" and loads it to $2. $2 stops at the "(" because of the next part (see next line below)
(\(.*\):) says "at the first encountered "(" after starting block $2...stop block $2 and start $3. $3 gets loaded with the "('any text'):" or, in the example, the "(_list):"
Then in the replace, just put the $1$2 to replace all three blocks with just the first two.
Choose which DI to inject stuff into Jersey:
Spring 4:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring4</artifactId>
</dependency>
Spring 3:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
</dependency>
HK2:
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
</dependency>
I agree with @arcy, the problem is on client side, on my case it was because of nginx, let me elaborate
I am using nginx as the frontend (so I can distribute load, ssl, etc ...) and using proxy_pass http://127.0.0.1:8080
to forward the appropiate requests to tomcat.
There is a default value for the nginx variable proxy_read_timeout
of 60s that should be enough, but on some peak moments my setup would error with the java.io.IOException: Broken pipe changing the value will help until the root cause (60s should be enough) can be fixed.
NOTE: I made a new answer so I could expand a bit more with my case (it was the only mention I found about this error on internet after looking quite a lot)
if(A && B){ }
The difference between the commands is that one provides you with a tag message while the other doesn't. An annotated tag has a message that can be displayed with git-show(1), while a tag without annotations is just a named pointer to a commit.
According to the documentation: "To create a lightweight tag, don’t supply any of the -a, -s, or -m options, just provide a tag name". There are also some different options to write a message on annotated tags:
git tag <tagname>
, Git will create a tag at the current revision but will not prompt you for an annotation. It will be tagged without a message (this is a lightweight tag).git tag -a <tagname>
, Git will prompt you for an annotation unless you have also used the -m flag to provide a message.git tag -a -m <msg> <tagname>
, Git will tag the commit and annotate it with the provided message.git tag -m <msg> <tagname>
, Git will behave as if you passed the -a flag for annotation and use the provided message.Basically, it just amounts to whether you want the tag to have an annotation and some other information associated with it or not.
Draggable div not possible only with CSS
, if you want draggable div you must need to use javascript.
Because (
is special in regex, you should escape it \(
when matching. However, depending on what language you are using, you can easily match (
with string methods like index()
or other methods that enable you to find at what position the (
is in. Sometimes, there's no need to use regex.
None of these solutions worked for me since I wanted to find peaks in the center of repeating values as well. for example, in
ar = np.array([0,1,2,2,2,1,3,3,3,2,5,0])
the answer should be
array([ 3, 7, 10], dtype=int64)
I did this using a loop. I know it's not super clean, but it gets the job done.
def findLocalMaxima(ar):
# find local maxima of array, including centers of repeating elements
maxInd = np.zeros_like(ar)
peakVar = -np.inf
i = -1
while i < len(ar)-1:
#for i in range(len(ar)):
i += 1
if peakVar < ar[i]:
peakVar = ar[i]
for j in range(i,len(ar)):
if peakVar < ar[j]:
break
elif peakVar == ar[j]:
continue
elif peakVar > ar[j]:
peakInd = i + np.floor(abs(i-j)/2)
maxInd[peakInd.astype(int)] = 1
i = j
break
peakVar = ar[i]
maxInd = np.where(maxInd)[0]
return maxInd
The problem is that you are attempting to define the elements in lists to multiple lists (not multiple ints as is defined). You should be defining lists like this.
int[,] list = new int[4,4] {
{1,2,3,4},
{5,6,7,8},
{1,3,2,1},
{5,4,3,2}};
You could also do
int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };
int[,] lists = new int[4,4] {
{list1[0],list1[1],list1[2],list1[3]},
{list2[0],list2[1],list2[2],list2[3]},
etc...};
Three ways to pass model data to partial view (there may be more)
This is view page
Method One Populate at view
@{
PartialViewTestSOl.Models.CountryModel ctry1 = new PartialViewTestSOl.Models.CountryModel();
ctry1.CountryName="India";
ctry1.ID=1;
PartialViewTestSOl.Models.CountryModel ctry2 = new PartialViewTestSOl.Models.CountryModel();
ctry2.CountryName="Africa";
ctry2.ID=2;
List<PartialViewTestSOl.Models.CountryModel> CountryList = new List<PartialViewTestSOl.Models.CountryModel>();
CountryList.Add(ctry1);
CountryList.Add(ctry2);
}
@{
Html.RenderPartial("~/Views/PartialViewTest.cshtml",CountryList );
}
Method Two Pass Through ViewBag
@{
var country = (List<PartialViewTestSOl.Models.CountryModel>)ViewBag.CountryList;
Html.RenderPartial("~/Views/PartialViewTest.cshtml",country );
}
Method Three pass through model
@{
Html.RenderPartial("~/Views/PartialViewTest.cshtml",Model.country );
}
Page -- Takes the specified XAML file, and compiles into BAML, and embeds that output into the managed resource stream for your assembly (specifically AssemblyName.g.resources), Additionally, if you have the appropriate attributes on the root XAML element in the file, it will create a blah.g.cs file, which will contain a partial class of the "codebehind" for that page; this basically involves a call to the BAML goop to re-hydrate the file into memory, and to set any of the member variables of your class to the now-created items (e.g. if you put x:Name="foo" on an item, you'll be able to do this.foo.Background = Purple; or similar.
ApplicationDefinition -- similar to Page, except it goes onestep furthur, and defines the entry point for your application that will instantiate your app object, call run on it, which will then instantiate the type set by the StartupUri property, and will give your mainwindow.
Also, to be clear, this question overall is infinate in it's results set; anyone can define additional BuildActions just by building an MSBuild Task. If you look in the %systemroot%\Microsoft.net\framework\v{version}\ directory, and look at the Microsoft.Common.targets file, you should be able to decipher many more (example, with VS Pro and above, there is a "Shadow" action that allows you generate private accessors to help with unit testing private classes.
Result :
Try something like this :
final int MAX_COLUMN = gridView.getColumnCount(); //5
final int MAX_ROW = gridView.getRowCount(); //7
final int itemsCount = MAX_ROW * MAX_COLUMN; //35
int row = 0, column = 0;
for (int i = 0; i < itemsCount; i++) {
ImageView view = new ImageView(this);
//Just to provide alternate colors
if (i % 2 == 0) {
view.setBackgroundColor(Color.RED);
} else {
view.setBackgroundColor(Color.GREEN);
}
GridLayout.LayoutParams params = new GridLayout.LayoutParams(GridLayout.spec(row, 1F), GridLayout.spec(column, 1F));
view.setLayoutParams(params);
gridView.addView(view);
column++;
if (column >= MAX_COLUMN) {
column = 0;
row++;
}
}
If you want specific width and height for your cells, then use :
params.width = 100; // Your width
params.height = 100; //your height
personally i'd rather go with tcpdf which is an ehnanced and mantained version of fpdf.
You can use substring
method
s = s.substring(0, s.length - 1) //removes last character
another alternative is slice
method
For me, fny answers really got it all. since fetch is not throwing error, we need to throw/handle the error ourselves. Posting my solution with async/await. I think it's more strait forward and readable
Solution 1: Not throwing an error, handle the error ourselves
async _fetch(request) {
const fetchResult = await fetch(request); //Making the req
const result = await fetchResult.json(); // parsing the response
if (fetchResult.ok) {
return result; // return success object
}
const responseError = {
type: 'Error',
message: result.message || 'Something went wrong',
data: result.data || '',
code: result.code || '',
};
const error = new Error();
error.info = responseError;
return (error);
}
Here if we getting an error, we are building an error object, plain JS object and returning it, the con is that we need to handle it outside. How to use:
const userSaved = await apiCall(data); // calling fetch
if (userSaved instanceof Error) {
debug.log('Failed saving user', userSaved); // handle error
return;
}
debug.log('Success saving user', userSaved); // handle success
Solution 2: Throwing an error, using try/catch
async _fetch(request) {
const fetchResult = await fetch(request);
const result = await fetchResult.json();
if (fetchResult.ok) {
return result;
}
const responseError = {
type: 'Error',
message: result.message || 'Something went wrong',
data: result.data || '',
code: result.code || '',
};
let error = new Error();
error = { ...error, ...responseError };
throw (error);
}
Here we are throwing and error that we created, since Error ctor approve only string, Im creating the plain Error js object, and the use will be:
try {
const userSaved = await apiCall(data); // calling fetch
debug.log('Success saving user', userSaved); // handle success
} catch (e) {
debug.log('Failed saving user', userSaved); // handle error
}
Solution 3: Using customer error
async _fetch(request) {
const fetchResult = await fetch(request);
const result = await fetchResult.json();
if (fetchResult.ok) {
return result;
}
throw new ClassError(result.message, result.data, result.code);
}
And:
class ClassError extends Error {
constructor(message = 'Something went wrong', data = '', code = '') {
super();
this.message = message;
this.data = data;
this.code = code;
}
}
Hope it helped.
From the ReactDOM.render() documentation:
If the optional callback is provided, it will be executed after the component is rendered or updated.
There is a circumstance where you're required to declare it final --otherwise it will result in compile error--, namely passing them through into anonymous classes. Basic example:
public FileFilter createFileExtensionFilter(final String extension) {
FileFilter fileFilter = new FileFilter() {
public boolean accept(File pathname) {
return pathname.getName().endsWith(extension);
}
};
// What would happen when it's allowed to change extension here?
// extension = "foo";
return fileFilter;
}
Removing the final
modifier would result in compile error, because it isn't guaranteed anymore that the value is a runtime constant. Changing the value from outside the anonymous class would namely cause the anonymous class instance to behave different after the moment of creation.
Here is a "concrete" (and possibly useful) example of how, why, and when to use these handy, yet unsightly constructs...
Xcode uses a "global" "user default" to decide which XCTestObserver
class spews it's heart out to the beleaguered console.
In this example... when I implicitly load this psuedo-library, let's call it... libdemure.a
, via a flag in my test target á la..
OTHER_LDFLAGS = -ldemure
I want to..
At load (ie. when XCTest
loads my test bundle), override the "default" XCTest
"observer" class... (via the constructor
function) PS: As far as I can tell.. anything done here could be done with equivalent effect inside my class' + (void) load { ... }
method.
run my tests.... in this case, with less inane verbosity in the logs (implementation upon request)
Return the "global" XCTestObserver
class to it's pristine state.. so as not to foul up other XCTest
runs which haven't gotten on the bandwagon (aka. linked to libdemure.a
). I guess this historically was done in dealloc
.. but I'm not about to start messing with that old hag.
So...
#define USER_DEFS NSUserDefaults.standardUserDefaults
@interface DemureTestObserver : XCTestObserver @end
@implementation DemureTestObserver
__attribute__((constructor)) static void hijack_observer() {
/*! here I totally hijack the default logging, but you CAN
use multiple observers, just CSV them,
i.e. "@"DemureTestObserverm,XCTestLog"
*/
[USER_DEFS setObject:@"DemureTestObserver"
forKey:@"XCTestObserverClass"];
[USER_DEFS synchronize];
}
__attribute__((destructor)) static void reset_observer() {
// Clean up, and it's as if we had never been here.
[USER_DEFS setObject:@"XCTestLog"
forKey:@"XCTestObserverClass"];
[USER_DEFS synchronize];
}
...
@end
Without the linker flag... (Fashion-police swarm Cupertino demanding retribution, yet Apple's default prevails, as is desired, here)
WITH the -ldemure.a
linker flag... (Comprehensible results, gasp... "thanks constructor
/destructor
"... Crowd cheers)
/*
** Bit set, clear, and test operations
**
** public domain snippet by Bob Stout
*/
typedef enum {ERROR = -1, FALSE, TRUE} LOGICAL;
#define BOOL(x) (!(!(x)))
#define BitSet(arg,posn) ((arg) | (1L << (posn)))
#define BitClr(arg,posn) ((arg) & ~(1L << (posn)))
#define BitTst(arg,posn) BOOL((arg) & (1L << (posn)))
#define BitFlp(arg,posn) ((arg) ^ (1L << (posn)))
OK, let's analyze things...
The common expression that you seem to be having problems with in all of these is "(1L << (posn))". All this does is create a mask with a single bit on and which will work with any integer type. The "posn" argument specifies the position where you want the bit. If posn==0, then this expression will evaluate to:
0000 0000 0000 0000 0000 0000 0000 0001 binary.
If posn==8, it will evaluate to:
0000 0000 0000 0000 0000 0001 0000 0000 binary.
In other words, it simply creates a field of 0's with a 1 at the specified position. The only tricky part is in the BitClr() macro where we need to set a single 0 bit in a field of 1's. This is accomplished by using the 1's complement of the same expression as denoted by the tilde (~) operator.
Once the mask is created it's applied to the argument just as you suggest, by use of the bitwise and (&), or (|), and xor (^) operators. Since the mask is of type long, the macros will work just as well on char's, short's, int's, or long's.
The bottom line is that this is a general solution to an entire class of problems. It is, of course, possible and even appropriate to rewrite the equivalent of any of these macros with explicit mask values every time you need one, but why do it? Remember, the macro substitution occurs in the preprocessor and so the generated code will reflect the fact that the values are considered constant by the compiler - i.e. it's just as efficient to use the generalized macros as to "reinvent the wheel" every time you need to do bit manipulation.
Unconvinced? Here's some test code - I used Watcom C with full optimization and without using _cdecl so the resulting disassembly would be as clean as possible:
----[ TEST.C ]----------------------------------------------------------------
#define BOOL(x) (!(!(x)))
#define BitSet(arg,posn) ((arg) | (1L << (posn)))
#define BitClr(arg,posn) ((arg) & ~(1L << (posn)))
#define BitTst(arg,posn) BOOL((arg) & (1L << (posn)))
#define BitFlp(arg,posn) ((arg) ^ (1L << (posn)))
int bitmanip(int word)
{
word = BitSet(word, 2);
word = BitSet(word, 7);
word = BitClr(word, 3);
word = BitFlp(word, 9);
return word;
}
----[ TEST.OUT (disassembled) ]-----------------------------------------------
Module: C:\BINK\tst.c
Group: 'DGROUP' CONST,CONST2,_DATA,_BSS
Segment: _TEXT BYTE 00000008 bytes
0000 0c 84 bitmanip_ or al,84H ; set bits 2 and 7
0002 80 f4 02 xor ah,02H ; flip bit 9 of EAX (bit 1 of AH)
0005 24 f7 and al,0f7H
0007 c3 ret
No disassembly errors
----[ finis ]-----------------------------------------------------------------
SQLite is database engine, .sqlite
or .db
should be a database. If you don't need to program anything, you can use a GUI like sqlitebrowser or anything like that to view the database contents.
There is also spatialite, https://www.gaia-gis.it/fossil/spatialite_gui/index
I would go with 422 Unprocessable Entity
, which is used when a request is invalid but the issue is not in syntax or authentication.
As an argument against other answers, to use any non-4xx
error code would imply it's not a client error, and it obviously is. To use a non-4xx
error code to represent a client error just makes no sense at all.
It seems that 409 Conflict
is the most common answer here, but, according to the spec, that implies that the resource already exists and the new data you are applying to it is incompatible with its current state. If you are sending a POST
request, with, for example, a username that is already taken, it's not actually conflicting with the target resource, as the target resource (the resource you're trying to create) has not yet been posted. It's an error specifically for version control, when there is a conflict between the version of the resource stored and the version of the resource requested. It's very useful for that purpose, for example when the client has cached an old version of the resource and sends a request based on that incorrect version which would no longer be conditionally valid. "In this case, the response representation would likely contain information useful for merging the differences based on the revision history." The request to create another user with that username is just unprocessable, having nothing to do with version control.
For the record, 422 is also the status code GitHub uses when you try to create a repository by a name already in use.
you can use unlink in the folder where you have created your symlink
Disadvantages: Technically, design and initial development of SPA is complex and can be avoided. Other reasons for not using this SPA can be:
Apart from above, other architectural limitations are Navigational Data loss, No log of Navigational History in browser and difficulty in Automated Functional Testing with selenium.
This link explain Single Page Application's Advantages and Disadvantages.
git branch -D <branch-name>
git fetch <remote> <branch-name>
git checkout -b <branch-name> --track <remote>/<branch-name>
Get path work with all OS
var filename = $('input[type=file]').val().replace(/.*(\/|\\)/, '');
Example
C:\fakepath\filename.doc
/var/fakepath/filename.doc
Both return
filename.doc
filename.doc
If you're using Spring framework then reading ClassPathResource
into a String
is pretty simple using Spring framework's FileCopyUtils
:
String data = "";
ClassPathResource cpr = new ClassPathResource("static/file.txt");
try {
byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream());
data = new String(bdata, StandardCharsets.UTF_8);
} catch (IOException e) {
LOG.warn("IOException", e);
}
As of Pandas 0.17 there is now a styling system which essentially provides formatted views of a DataFrame using Python format strings:
import pandas as pd
import numpy as np
constants = pd.DataFrame([('pi',np.pi),('e',np.e)],
columns=['name','value'])
C = constants.style.format({'name': '~~ {} ~~', 'value':'--> {:15.10f} <--'})
C
which displays
This is a view object; the DataFrame itself does not change formatting, but updates in the DataFrame are reflected in the view:
constants.name = ['pie','eek']
C
However it appears to have some limitations:
Adding new rows and/or columns in-place seems to cause inconsistency in the styled view (doesn't add row/column labels):
constants.loc[2] = dict(name='bogus', value=123.456)
constants['comment'] = ['fee','fie','fo']
constants
which looks ok but:
C
Formatting works only for values, not index entries:
constants = pd.DataFrame([('pi',np.pi),('e',np.e)],
columns=['name','value'])
constants.set_index('name',inplace=True)
C = constants.style.format({'name': '~~ {} ~~', 'value':'--> {:15.10f} <--'})
C
here is anaother way to limit your filter on html, for example I want to display 3 list at time than i will use limitTo:3
<li ng-repeat="phone in phones | limitTo:3">
<p>Phone Name: {{phone.name}}</p>
</li>
I have added code for onclick event value pass to the method in two ways . 1 . using bind method 2. using arrow(=>) method . see the methods handlesort1 and handlesort
var HeaderRows = React.createClass({
getInitialState : function() {
return ({
defaultColumns : ["col1","col2","col2","col3","col4","col5" ],
externalColumns : ["ecol1","ecol2","ecol2","ecol3","ecol4","ecol5" ],
})
},
handleSort: function(column,that) {
console.log(column);
alert(""+JSON.stringify(column));
},
handleSort1: function(column) {
console.log(column);
alert(""+JSON.stringify(column));
},
render: function () {
var that = this;
return(
<div>
<div>Using bind method</div>
{this.state.defaultColumns.map(function (column) {
return (
<div value={column} style={{height : '40' }}onClick={that.handleSort.bind(that,column)} >{column}</div>
);
})}
<div>Using Arrow method</div>
{this.state.defaultColumns.map(function (column) {
return (
<div value={column} style={{height : 40}} onClick={() => that.handleSort1(column)} >{column}</div>
);
})}
{this.state.externalColumns.map(function (column) {
// Multi dimension array - 0 is column name
var externalColumnName = column;
return (<div><span>{externalColumnName}</span></div>
);
})}
</div>);
}
});
This works great for me:
function listenForShiftKey(e){
var evt = e || window.event;
if (evt.shiftKey) {
shiftKeyDown = true;
} else {
shiftKeyDown = false;
}
}
First thing, define a type or interface for your object, it will make things much more readable:
type Product = { productId: number; price: number; discount: number };
You used a tuple of size one instead of array, it should look like this:
let myarray: Product[];
let priceListMap : Map<number, Product[]> = new Map<number, Product[]>();
So now this works fine:
myarray.push({productId : 1 , price : 100 , discount : 10});
myarray.push({productId : 2 , price : 200 , discount : 20});
myarray.push({productId : 3 , price : 300 , discount : 30});
priceListMap.set(1 , this.myarray);
myarray = null;
str
- Creates a new string object from the given object.
repr
- Returns the canonical string representation of the object.
The differences:
str():
repr():
I faced a similar situation:
I was trying to read raw response in case of an HTTP error consuming a SOAP service, using BasicHTTPBinding.
However, when reading the response using GetResponseStream()
, got the error:
Stream not readable
So, this code worked for me:
try
{
response = basicHTTPBindingClient.CallOperation(request);
}
catch (ProtocolException exception)
{
var webException = exception.InnerException as WebException;
var rawResponse = string.Empty;
var alreadyClosedStream = webException.Response.GetResponseStream() as MemoryStream;
using (var brandNewStream = new MemoryStream(alreadyClosedStream.ToArray()))
using (var reader = new StreamReader(brandNewStream))
rawResponse = reader.ReadToEnd();
}
If you don't want to have to buy CKFinder, like I didn't want to buy CKFinder, then I wrote a very reliable uploader for CKEditor 4. It consists of a second form, placed immediately above your textarea form, and utilizes the iframe hack, which, in spite of its name, is seamless and unobtrusive.
After the image is successfully uploaded, it will appear in your CKEditor window, along with whatever content is already there.
editor.php (the form page):
<?php
set_time_limit ( 3600 )
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Content Editor</title>
<link href="jquery-ui-1.10.2/themes/vader/ui.dialog.css" rel="stylesheet" media="screen" id="dialog_ui" />
<link href="jquery-ui-1.10.2/themes/vader/jquery-ui.css" rel="stylesheet" media="screen" id="dialog_ui" />
<script src="jquery-ui-1.10.2/jquery-1.9.1.js"></script>
<script src="jquery-ui-1.10.2/jquery.form.js"></script>
<script src="jquery-ui-1.10.2/ui/jquery-ui.js"></script>
<script src="ckeditor/ckeditor.js"></script>
<script src="ckeditor/config.js"></script>
<script src="ckeditor/adapters/jquery.js"></script>
<script src="ckeditor/plugin2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#editor').ckeditor({ height: 400, width:600});
});
function placePic(){
function ImageExist(url){
var img = new Image();
img.src = url;
return img.height != 0;
}
var filename = document.forms['uploader']['uploadedfile'].value;
document.forms['uploader']['filename'].value = filename;
var url = 'http://www.mydomain.com/external/images/cms/'+filename;
document.getElementById('uploader').submit();
var string = CKEDITOR.instances.editor.getData();
var t = setInterval(function(){
var exists = ImageExist(url);
if(exists === true){
if(document.getElementById('loader')){
document.getElementById('loader').parentNode.removeChild(document.getElementById('loader'));
}
CKEDITOR.instances.editor.setData(string + "<img src=\""+url+"\" />");
clearInterval(t);
}
else{
if(! document.getElementById("loader")){
var loader = document.createElement("div");
loader.setAttribute("id","loader");
loader.setAttribute("style","position:absolute;margin:-300px auto 0px 240px;width:113px;height:63px;text-align:center;z-index:10;");
document.getElementById('formBox').appendChild(loader);
var loaderGif = document.createElement("img");
loaderGif.setAttribute("id","loaderGif");
loaderGif.setAttribute("style","width:113px;height:63px;text-align:center;");
loaderGif.src = "external/images/cms/2dumbfish.gif";
document.getElementById('loader').appendChild(loaderGif);
}
}
},100);
}
function loadContent(){
if(document.forms['editorform']['site'].value !== "" && document.forms['editorform']['page'].value !== ""){
var site = document.forms['editorform']['site'].value;
var page = document.forms['editorform']['page'].value;
var url = site+"/"+page+".html";
$.ajax({
type: "GET",
url: url,
dataType: 'html',
success: function (html) {
CKEDITOR.instances.editor.setData(html);
}
});
}
}
</script>
<style>
button{
width: 93px;
height: 28px;
border:none;
padding: 0 4px 8px 0;
font-weight:bold
}
#formBox{
width:50%;
margin:10px auto 0px auto;
font-family:Tahoma, Geneva, sans-serif;
font-size:12px;
}
#field{
position:absolute;
top:10px;
margin-left:300px;
margin-bottom:20px;
}
#target{
position:absolute;
top:100px;
left:100px;
width:400px;
height:100px;
display:none;
}
.textField{
padding-left: 1px;
border-style: solid;
border-color: black;
border-width: 1px;
font-family: helvetica, arial, sans serif;
padding-left: 1px;
}
#report{
float:left;
margin-left:20px;
margin-top:10px;
font-family: helvetica, arial, sans serif;
font-size:12px;
color:#900;
}
</style>
</head>
<body>
<?php
if(isset($_GET['r'])){ ?><div id="report">
<?php echo $_GET['r']; ?> is changed.
</div><?php
}
?>
<div id="formBox">
<form id="uploader" name="uploader" action="editaction.php" method="post" target="target" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="50000000" />
<input type="hidden" name="filename" value="" />
Insert image: <input name="uploadedfile" type="file" class="textField" onchange="placePic();return false;" />
</form>
<form name="editorform" id="editorform" method="post" action="editaction.php" >
<div id="field" >Site: <select name="site" class="textField" onchange="loadContent();return false;">
<option value=""></option>
<option value="scubatortuga">scubatortuga</option>
<option value="drytortugascharters">drytortugascharters</option>
<option value="keyscombo">keyscombo</option>
<option value="keywesttreasurehunters">keywesttreasurehunters</option>
<option value="spearfishkeywest">spearfishkeywest</option>
</select>
Page: <select name="page" class="textField" onchange="loadContent();return false;">
<option value=""></option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
<option value="four">4</option>
</select>
</div><br />
<textarea name="editor" id="editor"></textarea><br />
<input type="submit" name="submit" value="Submit" />
</form>
</div>
<iframe name="target" id="target"></iframe>
</body>
</html>
And here is the action page, editaction.php, which does the actual file upload:
<?php
//editaction.php
foreach($_POST as $k => $v){
${"$k"} = $v;
}
//fileuploader.php
if($_FILES){
$target_path = "external/images/cms/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(! file_exists("$target_path$filename")){
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path);
}
}
else{
$string = stripslashes($editor);
$filename = "$site/$page.html";
$handle = fopen($filename,"w");
fwrite($handle,$string,strlen($string));
fclose($handle);
header("location: editor.php?r=$filename");
}
?>
Make sure python is installed on your machine, Python is required for node-sass.
Adding another "Same symptoms, but different solution" response, just in case somebody is having the same problem, but none of the common solutions are working.
In my case, I had an app that started development prior to the instruction of asset catalogs and the flexibility in icon naming conventions, but was first submitted to the store after the transition. To resolve the issue I had to:
-ErrorAction Stop
is changing things for you. Try adding this and see what you get:
Catch [System.Management.Automation.ActionPreferenceStopException] {
"caught a StopExecution Exception"
$error[0]
}
Instead of using overflow:hidden
, which is a kind of hack, why not simply setting a fixed height, e.g. height:500px
, to the parent division?
I had the same problem, I was trying to listen the change on some select and actually the problem was I was using the event instead of the event.target which is the select object.
INCORRECT :
$(document).on('change', $("select"), function(el) {
console.log($(el).val());
});
CORRECT :
$(document).on('change', $("select"), function(el) {
console.log($(el.target).val());
});
If I'm correct, this is a bug in webkit (according to this). I'm not sure if there is much you can do, sorry for the weak answer.
There is, however, a work around which you can use. If you add the title
attribute to your image (e.g. title="Image Not Found"
) it'll work.
Using freegate as agent in China. Run Freegate,latest version. Run SDK Manager, Tools -> Options, Proxy Server 127.0.0.1, Port 8580. I hope it will help you.
See: Multiple-line-syntax
It also support variables in multiline string, for example:
String name="zzg";
String lines = ""/**~!{
SELECT *
FROM user
WHERE name="$name"
}*/;
System.out.println(lines);
Output:
SELECT *
FROM user
WHERE name="zzg"
var string = string.split(",");
You can follow the .selectedIndex strategy of danielrmt, but determine the index based on the text within the option tags like this:
$('#dropdown')[0].selectedIndex = $('#dropdown option').toArray().map(jQuery.text).indexOf('B');
This works on the original HTML without using value attributes.
Sorry not sure what was going on this worked in the end:
<VirtualHost *>
ServerName example.com
DocumentRoot /var/www/html/mjp
Alias /ncn "/var/www/html/ncn"
<Directory "/var/www/html/ncn">
Options None
AllowOverride None
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
I have also been through this problem,
First i tried setting my password of root to blank using command :
SET PASSWORD FOR root@localhost=PASSWORD('');
But don't be happy , PHPMYADMIN uses 127.0.0.1 not localhost , i know you would say both are same but that is not the case , use the command mentioned underneath and you are done.
SET PASSWORD FOR [email protected]=PASSWORD('');
Just replace localhost with 127.0.0.1 and you are done .
The two answers are good. And I also suggest you a similar method:
<% @images.each.with_index do |page, index| %>
<% end %>
You might not see the difference between this and the accepted answer. Let me direct your eyes to these method calls: .each.with_index
see how it's .each
and then .with_index
.
to perform a GET request using the fetch api I worked on this solution that doesn't require the installation of packages.
this is an example of a call to the google's map api
// encode to scape spaces
const esc = encodeURIComponent;
const url = 'https://maps.googleapis.com/maps/api/geocode/json?';
const params = {
key: "asdkfñlaskdGE",
address: "evergreen avenue",
city: "New York"
};
// this line takes the params object and builds the query string
const query = Object.keys(params).map(k => `${esc(k)}=${esc(params[k])}`).join('&')
const res = await fetch(url+query);
const googleResponse = await res.json()
feel free to copy this code and paste it on the console to see how it works!!
the generated url is something like:
https://maps.googleapis.com/maps/api/geocode/json?key=asdkf%C3%B1laskdGE&address=evergreen%20avenue&city=New%20York
this is what I was looking before I decided to write this, enjoy :D
You could implement a JavaScript block which contains a function with your needs.
<div style="position: absolute; left: 10px; top: 40px;">
<img src="logg.png" width="114" height="38" onclick="DoSomething();" />
</div>
I wanted to use JavaScript to change a form's action, so I could have different submit inputs within the same form linking to different pages.
I also had the added complication of using Apache rewrite to change example.com/page-name
into example.com/index.pl?page=page-name
. I found that changing the form's action caused example.com/index.pl
(with no page parameter) to be rendered, even though the expected URL (example.com/page-name
) was displayed in the address bar.
To get around this, I used JavaScript to insert a hidden field to set the page parameter. I still changed the form's action, just so the address bar displayed the correct URL.
function setAction (element, page)
{
if(checkCondition(page))
{
/* Insert a hidden input into the form to set the page as a parameter.
*/
var input = document.createElement("input");
input.setAttribute("type","hidden");
input.setAttribute("name","page");
input.setAttribute("value",page);
element.form.appendChild(input);
/* Change the form's action. This doesn't chage which page is displayed,
* it just make the URL look right.
*/
element.form.action = '/' + page;
element.form.submit();
}
}
In the form:
<input type="submit" onclick='setAction(this,"my-page")' value="Click Me!" />
Here are my Apache rewrite rules:
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule ^/(.*)$ %{DOCUMENT_ROOT}/index.pl?page=$1&%{QUERY_STRING}
I'd be interested in any explanation as to why just setting the action didn't work.
The answer from @Emiliano is excellent. You can also pass named parameters like so:
powershell.exe -Command 'G:\Karan\PowerShell_Scripts\START_DEV.ps1' -NamedParam1 "SomeDataA" -NamedParam2 "SomeData2"
Note the parameters are outside the command call, and you'll use:
[parameter(Mandatory=$false)]
[string]$NamedParam1,
[parameter(Mandatory=$false)]
[string]$NamedParam2
JAXB is part of JDK standard edition version 1.6+. So it is FREE
and no extra libraries to download and manage.
A simple example can be found here
XStream seems to be dead. Last update was on Dec 6 2008.
Simple
seems as easy and simpler as JAXB but I could not find any licensing information to evaluate it for enterprise use.
vector<char> vec;
//fill the vector;
std::string s(vec.begin(), vec.end());
Use the following code:
if(processing == success) {
header("Location:filename");
exit();
}
And you are good to go.
While I don't know myself, I would certainly hope that #2 is incorrect...I'd like to think that Windows isn't going to AUTOMATICALLY give out my login information (least of all my password!) to any machine, let alone one that isn't part of my trust.
Regardless, have you explored the impersonation architecture? Your code is going to look similar to this:
using (System.Security.Principal.WindowsImpersonationContext context = System.Security.Principal.WindowsIdentity.Impersonate(token))
{
// Do network operations here
context.Undo();
}
In this case, the token
variable is an IntPtr. In order to get a value for this variable, you'll have to call the unmanaged LogonUser Windows API function. A quick trip to pinvoke.net gives us the following signature:
[System.Runtime.InteropServices.DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(
string lpszUsername,
string lpszDomain,
string lpszPassword,
int dwLogonType,
int dwLogonProvider,
out IntPtr phToken
);
Username, domain, and password should seem fairly obvious. Have a look at the various values that can be passed to dwLogonType and dwLogonProvider to determine the one that best suits your needs.
This code hasn't been tested, as I don't have a second domain here where I can verify, but this should hopefully put you on the right track.
If you want to backup your data or restore data from a backup, you can run the following commands:
To create backup of your data, go to your postgres \bin\ directory like C:\programfiles\postgres\10\bin\
and then type the following command:
pg_dump -FC -U ngb -d ngb -p 5432 >C:\BACK_UP\ngb.090718_after_readUpload.backup
To restore data from a backup, go to your postgres \bin\ directory like C:\programfiles\postgres\10\bin\
and then type below command:
C:\programFiles\postgres\10\bin> pg_restore -Fc -U ngb -d ngb -p 5432 <C:\ngb.130918.backup
Please make sure that the backup file exists.
Not sure if it's really a problem, but I see you have the same name for your binding configuration ().
I usually try to call my endpoints something like "UserServiceBasicHttp" or something similar (the "Binding" really doesn't have anything to do here), and I try to call my binding configurations something with "....Configuration", e.g. "UserServiceDefaultBinding", to avoid any potential name clashes.
Marc
IMHO this answer here solve issue in the most elegant way..
Developer should create a style,
<style name="noAnimTheme" parent="android:Theme">
<item name="android:windowAnimationStyle">@null</item>
</style>
then in manifest set it as theme for activity or whole application.
<activity android:name=".ui.ArticlesActivity" android:theme="@style/noAnimTheme">
</activity>
Voila! Nice and easy..
even adding a return statement brings up this exception, for which only solution is this code:
if(!response.isCommitted())
// Place another redirection
Didn't wan to mess with carbon. So here's my solution
$start = new \DateTime('now');
$start->modify('first day of this month');
$end = new \DateTime('now');
$end->modify('last day of this month');
$new_releases = Game::whereBetween('release', array($start, $end))->get();
Hash is a default vue-router mode setting, it is set because with hash, application doesn't need to connect server to serve the url. To change it you should configure your server and set the mode to HTML5 History API mode.
For server configuration this is the link to help you set up Apache, Nginx and Node.js servers:
https://router.vuejs.org/guide/essentials/history-mode.html
Then you should make sure, that vue router mode is set like following:
vue-router version 2.x
const router = new VueRouter({
mode: 'history',
routes: [...]
})
To be clear, these are all vue-router modes you can choose: "hash" | "history" | "abstract".
Try this
<a target="_self" href="mysite.com/uploads/ahlem.pdf" download="foo.pdf">
and visit this site it could be helpful for you :)
Onchange
is only fired when user enters something by keyboard. A possible workarround could be to first focus the textfield and then change it.
But why not fetch the event when the user clicks on a date? There already must be some javascript.
Found an XML transform stylesheet here (wayback machine link, site itself is in german)
The stylesheet added here could be helpful:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="iso-8859-1"/>
<xsl:strip-space elements="*" />
<xsl:template match="/*/child::*">
<xsl:for-each select="child::*">
<xsl:if test="position() != last()">"<xsl:value-of select="normalize-space(.)"/>", </xsl:if>
<xsl:if test="position() = last()">"<xsl:value-of select="normalize-space(.)"/>"<xsl:text>
</xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Perhaps you want to remove the quotes inside the xsl:if tags so it doesn't put your values into quotes, depending on where you want to use the CSV file.
Here some basic explanation of hibernate cache...
First level cache is associated with “session” object.
The scope of cache objects is of session. Once session is closed, cached objects are gone forever.
First level cache is enabled by default and you can not disable it.
When we query an entity first time, it is retrieved from database and stored in first level cache associated with hibernate session.
If we query same object again with same session object, it will be loaded from cache and no sql query will be executed.
The loaded entity can be removed from session using evict()
method. The next loading of this entity will again make a database call if it has been removed using evict()
method.
The whole session cache can be removed using clear()
method. It will remove all the entities stored in cache.
Second level cache is apart from first level cache which is available to be used globally in session factory scope.
second level cache is created in session factory scope and is available to be used in all sessions which are created using that particular session factory.
It also means that once session factory is closed, all cache associated with it die and cache manager also closed down.
Whenever hibernate session try to load an entity, the very first place it look for cached copy of entity in first level cache (associated with particular hibernate session).
If cached copy of entity is present in first level cache, it is returned as result of load method.
If there is no cached entity in first level cache, then second level cache is looked up for cached entity.
If second level cache has cached entity, it is returned as result of load method. But, before returning the entity, it is stored in first level cache also so that next invocation to load method for entity will return the entity from first level cache itself, and there will not be need to go to second level cache again.
If entity is not found in first level cache and second level cache also, then database query is executed and entity is stored in both cache levels, before returning as response of load()
method.
First: Even the unique IDs generated by java UUID.randomUUID or .net GUID are not 100% unique. Especialy UUID.randomUUID is "only" a 128 bit (secure) random value. So if you reduce it to 64 bit, 32 bit, 16 bit (or even 1 bit) then it becomes simply less unique.
So it is at least a risk based decisions, how long your uuid must be.
Second: I assume that when you talk about "only 8 characters" you mean a String of 8 normal printable characters.
If you want a unique string with length 8 printable characters you could use a base64 encoding. This means 6bit per char, so you get 48bit in total (possible not very unique - but maybe it is ok for you application)
So the way is simple: create a 6 byte random array
SecureRandom rand;
// ...
byte[] randomBytes = new byte[16];
rand.nextBytes(randomBytes);
And then transform it to a Base64 String, for example by org.apache.commons.codec.binary.Base64
BTW: it depends on your application if there is a better way to create "uuid" then by random. (If you create a the UUIDs only once per second, then it is a good idea to add a time stamp) (By the way: if you combine (xor) two random values, the result is always at least as random as the most random of the both).
It prints 47.48000 if you use another MathContext:
BigDecimal b = new BigDecimal(d, MathContext.DECIMAL64);
Just pick the context you need.
From the official documentation:
As of PHP 5.2.2, DateTime objects can be compared using comparison operators.
$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");
var_dump($date1 == $date2); // false
var_dump($date1 < $date2); // true
var_dump($date1 > $date2); // false
For PHP versions before 5.2.2 (actually for any version), you can use diff.
$datetime1 = new DateTime('2009-10-11'); // 11 October 2013
$datetime2 = new DateTime('2009-10-13'); // 13 October 2013
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days'); // +2 days
I'm guessing that either the class name is wrong - be sure to use the fully-resolved class name, with all packages - or it's not in the CLASSPATH so javap can't find it.
SSH Key - Still asking for password and passphrase
If on Windows and using PuTTY as the SSH key generator, this quick & easy solution turned out to be the only working solution for me using a plain windows command line:
pageant.exe
and plink.exe
.ppk
extension"full\path\to\your\pageant.exe" "full\path\to\your\key.ppk"
(must be quoted). This will execute the pageant
service and register your key (after entering the password).GIT_SSH=full\path\to\plink.exe
(must not be quoted). This will redirect git ssh-communication-related commands to plink
that will use the pageant
service for authentication without asking for the password again.Done!
Note1: This documentation warns about some peculiarities when working with the GIT_SHH
environment variable settings. I can push
, pull
, fetch
with any number of additional parameters to the command and everything works just fine for me (without any need to write an extra script as suggested therein).
Note2: Path to PuTTY
instalation is usually in PATH
so may be omitted. Anyway, I prefer specifying the full paths.
Automation:
The following batch file can be run before using git from command line. It illustrates the usage of the settings:
git-init.bat
@ECHO OFF
:: Use start since the call is blocking
START "%ProgramFiles%\PuTTY\pageant.exe" "%HOMEDRIVE%%HOMEPATH%\.ssh\id_ed00000.ppk"
SET GIT_SSH=%ProgramFiles%\PuTTY\plink.exe
Anyway, I have the GIT_SSH
variable set in SystemPropertiesAdvanced.exe > Environment variables
and the pageant.exe
added as the Run
registry key (*).
(*) Steps to add a Run
registry key>
regedit.exe
HKEY_CURRENT_USER > Software > Microsoft > Windows > CurrentVersion > Run
Edit > New > String Value
Edit > Modify...
(or double-click)pageant.exe
and public key
, e.g., "C:\Program Files\PuTTY\pageant.exe" "C:\Users\username\.ssh\id_ed00000.ppk"
(notice that %ProgramFiles%
etc. variables do not work in here unless choosing Expandable string value
in place of the String value
in step 3.).Apparently, org.json.simple.JSONArray
implements a raw Iterator. This means that each element is considered to be an Object
. You can try to cast:
for(Object o: arr){
if ( o instanceof JSONObject ) {
parse((JSONObject)o);
}
}
This is how things were done back in Java 1.4 and earlier.
Issue because connection establishment or communication with a client failed to complete within the allotted time interval. This may be a result of network or system delays.
Check the thread status by calling Thread.isAlive
.
If you have a non-printing character at the front of the string try this
Option Explicit
Sub DoTrim()
Dim cell As Range
Dim str As String
Dim nAscii As Integer
For Each cell In Selection.Cells
If cell.HasFormula = False Then
str = Trim(CStr(cell))
If Len(str) > 0 Then
nAscii = Asc(Left(str, 1))
If nAscii < 33 Or nAscii = 160 Then
If Len(str) > 1 Then
str = Right(str, Len(str) - 1)
Else
strl = ""
End If
End If
End If
cell=str
End If
Next
End Sub
"I understand both are server cluster management software."
This statement isn't entirely true. Kubernetes doesn't manage server clusters, it orchestrates containers such that they work together with minimal hassle and exposure. Kubernetes allows you to define parts of your application as "pods" (one or more containers) that are delivered by "deployments" or "daemon sets" (and a few others) and exposed to the outside world via services. However, Kubernetes doesn't manage the cluster itself (there are tools that can provision, configure and scale clusters for you, but those are not part of Kubernetes itself).
Mesos on the other hand comes closer to "cluster management" in that it can control what's running where, but not just in terms of scheduling containers. Mesos also manages standalone software running on the cluster servers. Even though it's mostly used as an alternative to Kubernetes, Mesos can easily work with Kubernetes as while the functionality overlaps in many areas, Mesos can do more (but on the overlapping parts Kubernetes tends to be better).
Try using Math.abs:
variableAbs = Math.abs(variable);
For square root use:
variableSqRt = Math.sqrt(variable);
You probably need to use a TableModel
(Oracle's tutorial here)
How implements your own TableModel
public class FootballClubTableModel extends AbstractTableModel {
private List<FootballClub> clubs ;
private String[] columns ;
public FootBallClubTableModel(List<FootballClub> aClubList){
super();
clubs = aClubList ;
columns = new String[]{"Pos","Team","P", "W", "L", "D", "MP", "GF", "GA", "GD"};
}
// Number of column of your table
public int getColumnCount() {
return columns.length ;
}
// Number of row of your table
public int getRowsCount() {
return clubs.size();
}
// The object to render in a cell
public Object getValueAt(int row, int col) {
FootballClub club = clubs.get(row);
switch(col) {
case 0: return club.getPosition();
// to complete here...
default: return null;
}
}
// Optional, the name of your column
public String getColumnName(int col) {
return columns[col] ;
}
}
You maybe need to override anothers methods of TableModel
, depends on what you want to do, but here is the essential methods to understand and implements :)
Use it like this
List<FootballClub> clubs = getFootballClub();
TableModel model = new FootballClubTableModel(clubs);
JTable table = new JTable(model);
Hope it help !
For the Single line and double line break here are the following codes.
Single break: %0D0A
Double break: %0D0A%0D0A
Mr. Alien's answer is perfect, but anyway I don't recommend to use <div class="clear"></div>
because it just a hack which makes your markup dirty. This is useless empty div
in terms of bad structure and semantic, this also makes your code not flexible. In some browsers this div causes additional height and you have to add height: 0;
which even worse. But real troubles begin when you want to add background or border around your floated elements - it just will collapse because web was designed badly. I do recommend to wrap floated elements into container which has clearfix CSS rule. This is hack as well, but beautiful, more flexible to use and readable for human and SEO robots.
Though this pseudo-element was in drafts of CSS Selectors Level 3, it was removed during the Candidate Recommendation phase, as it appeared that its behavior was under-specified, especially with nested elements, and interoperability wasn't achieved.
It's being discussed in How ::selection works on nested elements.
Despite it is being implemented in browsers, you can make an illusion of text not being selected by using the same color and background color on selection as of the tab design (in your case).
p { color: white; background: black; }
p::-moz-selection { color: white; background: black; }
p::selection { color: white; background: black; }
Disallowing users to select the text will raise usability issues.
For Python 2.7 and Pandas 0.24.2 and using Psycopg2
Psycopg2 Connection Module
def dbConnect (db_parm, username_parm, host_parm, pw_parm):
# Parse in connection information
credentials = {'host': host_parm, 'database': db_parm, 'user': username_parm, 'password': pw_parm}
conn = psycopg2.connect(**credentials)
conn.autocommit = True # auto-commit each entry to the database
conn.cursor_factory = RealDictCursor
cur = conn.cursor()
print ("Connected Successfully to DB: " + str(db_parm) + "@" + str(host_parm))
return conn, cur
Connect to the database
conn, cur = dbConnect(databaseName, dbUser, dbHost, dbPwd)
Assuming dataframe to be present already as df
output = io.BytesIO() # For Python3 use StringIO
df.to_csv(output, sep='\t', header=True, index=False)
output.seek(0) # Required for rewinding the String object
copy_query = "COPY mem_info FROM STDOUT csv DELIMITER '\t' NULL '' ESCAPE '\\' HEADER " # Replace your table name in place of mem_info
cur.copy_expert(copy_query, output)
conn.commit()
The correct statement should be :
SELECT
student.firstname,
student.lastname,
exam.name,
exam.date,
grade.grade
FROM grade
INNER JOIN student
ON student.studentId = grade.fk_studentId
INNER JOIN exam
ON exam.examId = grade.fk_examId
ORDER BY exam.date
A table is refered to other on the basis of the foreign key relationship defined. You should refer the ids properly if you wish the data to show as queried. So you should refer the id's to the proper foreign keys in the table rather than just on the id which doesn't define a proper relation
An updated answer for @m.kocikowski that works on recent iOS versions.
-(NSString *) stringByStrippingHTMLFromString:(NSString *)str {
NSRange range;
while ((range = [str rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
str = [str stringByReplacingCharactersInRange:range withString:@""];
return str;
}
SASS has a built-in rgba() function to evaluate values.
rgba($color, $alpha)
E.g.
rgba(#00aaff, 0.5) => rgba(0, 170, 255, 0.5)
An example using your own variables:
$my-color: #00aaff;
$my-opacity: 0.5;
.my-element {
color: rgba($my-color, $my-opacity);
}
Outputs:
.my-element {
color: rgba(0, 170, 255, 0.5);
}
In one of my machine, delimiting the word with "\b
" (without the quotes) did not work. The solution was to use "\<
" for starting delimiter and "\>
" for ending delimiter.
To explain with Joakim Lundberg's example:
$ echo "bar embarassment" | sed "s/\<bar\>/no bar/g"
no bar embarassment
Follow these steps to fix this it looks too long but trust me it won't take more than 5 minutes:
Step-1: Create two ssh key pairs:
ssh-keygen -t rsa -C "[email protected]"
Step-2: It will create two ssh keys here:
~/.ssh/id_rsa_account1
~/.ssh/id_rsa_account2
Step-3: Now we need to add these keys:
ssh-add ~/.ssh/id_rsa_account2
ssh-add ~/.ssh/id_rsa_account1
- You can see the added keys list by using this command:
ssh-add -l
- You can remove old cached keys by this command:
ssh-add -D
Step-4: Modify the ssh config
cd ~/.ssh/
touch config
subl -a config
or code config
or nano config
Step-5: Add this to config file:
#Github account1
Host github.com-account1
HostName github.com
User account1
IdentityFile ~/.ssh/id_rsa_account1
#Github account2
Host github.com-account2
HostName github.com
User account2
IdentityFile ~/.ssh/id_rsa_account2
Step-6: Update your .git/config
file:
Step-6.1: Navigate to account1's project and update host:
[remote "origin"]
url = [email protected]:account1/gfs.git
If you are invited by some other user in their git Repository. Then you need to update the host like this:
[remote "origin"]
url = [email protected]:invitedByUserName/gfs.git
Step-6.2: Navigate to account2's project and update host:
[remote "origin"]
url = [email protected]:account2/gfs.git
Step-7: Update user name and email for each repository separately if required this is not an amendatory step:
Navigate to account1 project and run these:
git config user.name "account1"
git config user.email "[email protected]"
Navigate to account2 project and run these:
git config user.name "account2"
git config user.email "[email protected]"
Here is detailed example with multiple permission requests:-
The app needs 2 permissions at startup . SEND_SMS and ACCESS_FINE_LOCATION (both are mentioned in manifest.xml).
I am using Support Library v4 which is prepared to handle Android pre-Marshmallow and so no need to check build versions.
As soon as the app starts up, it asks for multiple permissions together. If both permissions are granted the normal flow goes.
public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(checkAndRequestPermissions()) {
// carry on the normal flow, as the case of permissions granted.
}
}
private boolean checkAndRequestPermissions() {
int permissionSendMessage = ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS);
int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
List<String> listPermissionsNeeded = new ArrayList<>();
if (locationPermission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.SEND_SMS);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
ContextCompat.checkSelfPermission(), ActivityCompat.requestPermissions(), ActivityCompat.shouldShowRequestPermissionRationale() are part of support library.
In case one or more permissions are not granted, ActivityCompat.requestPermissions() will request permissions and the control goes to onRequestPermissionsResult() callback method.
You should check the value of shouldShowRequestPermissionRationale() flag in onRequestPermissionsResult() callback method.
There are only two cases:--
Case 1:-Any time user clicks Deny permissions (including the very first time), it will return true. So when the user denies, we can show more explanation and keep asking again
Case 2:-Only if user select “never asks again” it will return false. In this case, we can continue with limited functionality and guide user to activate the permissions from settings for more functionalities, or we can finish the setup, if the permissions are trivial for the app.
CASE -1
CASE-2
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
Log.d(TAG, "Permission callback called-------");
switch (requestCode) {
case REQUEST_ID_MULTIPLE_PERMISSIONS: {
Map<String, Integer> perms = new HashMap<>();
// Initialize the map with both permissions
perms.put(Manifest.permission.SEND_SMS, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
// Fill with actual results from user
if (grantResults.length > 0) {
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for both permissions
if (perms.get(Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "sms & location services permission granted");
// process the normal flow
//else any one or both the permissions are not granted
} else {
Log.d(TAG, "Some permissions are not granted ask again ");
//permission is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permission
// // shouldShowRequestPermissionRationale will return true
//show the dialog or snackbar saying its necessary and try again otherwise proceed with setup.
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.SEND_SMS) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
showDialogOK("SMS and Location Services Permission required for this app",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
checkAndRequestPermissions();
break;
case DialogInterface.BUTTON_NEGATIVE:
// proceed with logic by disabling the related features or quit the app.
break;
}
}
});
}
//permission is denied (and never ask again is checked)
//shouldShowRequestPermissionRationale will return false
else {
Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG)
.show();
// //proceed with logic by disabling the related features or quit the app.
}
}
}
}
}
}
private void showDialogOK(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", okListener)
.create()
.show();
}
Use printf
command to have 0
padding:
printf "%02d\n" $num
Your for loop will be like this:
for (( num=1; num<=5; num++ )); do printf "%02d\n" $num; done
01
02
03
04
05
A dict (really, a defaultdict) gives you a pretty easy way to do this trick:
from collections import defaultdict
bool_mapping = defaultdict(bool) # Will give you False for non-found values
for val in ['True', 'yes', ...]:
bool_mapping[val] = True
print(bool_mapping['True']) # True
print(bool_mapping['kitten']) # False
It's really easy to tailor this method to the exact conversion behavior you want -- you can fill it with allowed Truthy and Falsy values and let it raise an exception (or return None) when a value isn't found, or default to True, or default to False, or whatever you want.
This is the simplest way
class YourSingletoneClass {
private static instance: YourSingletoneClass;
private constructor(public ifYouHaveAnyParams: string) {
}
static getInstance() {
if(!YourSingletoneClass.instance) {
YourSingletoneClass.instance = new YourSingletoneClass('If you have any params');
}
return YourSingletoneClass.instance;
}
}
So I was looking all over for a way to remove all files in a directory except for some directories, and files, I wanted to keep around. After much searching I devised a way to do it using find.
find -E . -regex './(dir1|dir2|dir3)' -and -type d -prune -o -print -exec rm -rf {} \;
Essentially it uses regex to select the directories to exclude from the results then removes the remaining files. Just wanted to put it out here in case someone else needed it.
I just had to update an .edmx model. The model/Run Custom Tool option was not refreshing the fields for me, but once I had the graphical designer open, I was able to manually rename the fields.
To resolve external dependencies within project. below things are important..
1. The compiler should know that where are header '.h' files located in workspace.
2. The linker able to find all specified all '.lib' files & there names for current project.
So, Developer has to specify external dependencies for Project as below..
1. Select Project in Solution explorer.
2 . Project Properties -> Configuration Properties -> C/C++ -> General
specify all header files in "Additional Include Directories".
3. Project Properties -> Configuration Properties -> Linker -> General
specify relative path for all lib files in "Additional Library Directories".
Yes the culprit is definitely word-wrapping. When I tested your two programs, NetBeans IDE 8.2 gave me the following result.
Looking at your code closely you have used a line break at the end of first loop. But you didn't use any line break in second loop. So you are going to print a word with 1000 characters in the second loop. That causes a word-wrapping problem. If we use a non-word character " " after B, it takes only 5.35 seconds to compile the program. And If we use a line break in the second loop after passing 100 values or 50 values, it takes only 8.56 seconds and 7.05 seconds respectively.
Random r = new Random();
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if(r.nextInt(4) == 0) {
System.out.print("O");
} else {
System.out.print("B");
}
if(j%100==0){ //Adding a line break in second loop
System.out.println();
}
}
System.out.println("");
}
Another advice is that to change settings of NetBeans IDE. First of all, go to NetBeans Tools and click Options. After that click Editor and go to Formatting tab. Then select Anywhere in Line Wrap Option. It will take almost 6.24% less time to compile the program.
Some practical examples, somewhat connected to large scale development where Gerrit is used for review and delivery integration:
I merge when I uplift my feature branch to a fresh remote master. This gives minimal uplift work and it's easy to follow the history of the feature development in for example gitk.
git fetch
git checkout origin/my_feature
git merge origin/master
git commit
git push origin HEAD:refs/for/my_feature
I merge when I prepare a delivery commit.
git fetch
git checkout origin/master
git merge --squash origin/my_feature
git commit
git push origin HEAD:refs/for/master
I rebase when my delivery commit fails integration for whatever reason, and I need to update it towards a fresh remote master.
git fetch
git fetch <gerrit link>
git checkout FETCH_HEAD
git rebase origin/master
git push origin HEAD:refs/for/master
The help for copy
explains that wildcards can be used to concatenate multiple files into one.
For example, to copy all .txt files in the current folder that start with "abc" into a single file named xyz.txt:
copy abc*.txt xyz.txt
I think you're confused because you haven't declared a TimeSpan
you've declared a TimeSpan?
which is a nullable TimeSpan
. Either remove the question mark if you don't need it to be nullable or use variable.Value.TotalHours
.
It's not clear to me at all what the OP is actually after, given the follow-up comments. It's possible they are actually looking for a way to write the data to file.
But let's assume that we're really after a way to cbind
multiple data frames of differing lengths.
cbind
will eventually call data.frame
, whose help files says:
Objects passed to data.frame should have the same number of rows, but atomic vectors, factors and character vectors protected by I will be recycled a whole number of times if necessary (including as from R 2.9.0, elements of list arguments).
so in the OP's actual example, there shouldn't be an error, as R ought to recycle the shorter vectors to be of length 50. Indeed, when I run the following:
set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(10),e = runif(10))
cbind(dat1,dat2)
I get no errors and the shorter data frame is recycled as expected. However, when I run this:
set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(9), e = runif(9))
cbind(dat1,dat2)
I get the following error:
Error in data.frame(..., check.names = FALSE) :
arguments imply differing number of rows: 50, 9
But the wonderful thing about R is that you can make it do almost anything you want, even if you shouldn't. For example, here's a simple function that will cbind
data frames of uneven length and automatically pad the shorter ones with NA
s:
cbindPad <- function(...){
args <- list(...)
n <- sapply(args,nrow)
mx <- max(n)
pad <- function(x, mx){
if (nrow(x) < mx){
nms <- colnames(x)
padTemp <- matrix(NA, mx - nrow(x), ncol(x))
colnames(padTemp) <- nms
if (ncol(x)==0) {
return(padTemp)
} else {
return(rbind(x,padTemp))
}
}
else{
return(x)
}
}
rs <- lapply(args,pad,mx)
return(do.call(cbind,rs))
}
which can be used like this:
set.seed(1)
a <- runif(50)
b <- 1:50
c <- rep(LETTERS[1:5],length.out = 50)
dat1 <- data.frame(a,b,c)
dat2 <- data.frame(d = runif(10),e = runif(10))
dat3 <- data.frame(d = runif(9), e = runif(9))
cbindPad(dat1,dat2,dat3)
I make no guarantees that this function works in all cases; it is meant as an example only.
EDIT
If the primary goal is to create a csv or text file, all you need to do it alter the function to pad using ""
rather than NA
and then do something like this:
dat <- cbindPad(dat1,dat2,dat3)
rs <- as.data.frame(apply(dat,1,function(x){paste(as.character(x),collapse=",")}))
and then use write.table
on rs
.
Just paste the below code in activity onCreate()
.
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
It will ignore URI exposure.
Happy coding :-)
Built upon rsplak's answer. It uses jQuery's newer .on() instead of the deprecated .bind(). In addition to input, it will also work for select and other html elements. It will also disable the submit button if one of the fields becomes blank again.
var fields = "#user_input, #pass_input, #v_pass_input, #email";
$(fields).on('change', function() {
if (allFilled()) {
$('#register').removeAttr('disabled');
} else {
$('#register').attr('disabled', 'disabled');
}
});
function allFilled() {
var filled = true;
$(fields).each(function() {
if ($(this).val() == '') {
filled = false;
}
});
return filled;
}
Demo: JSFiddle
In order of activity, demos/examples available, and simplicity:
Related:
Try putting this HTML snippet into your served document:
<img id="ItemPreview" src="">
Then, on JavaScript side, you can dynamically modify image's src
attribute with so-called Data URL.
document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;
Alternatively, using jQuery:
$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);
This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..."
part) in the URL accordingly.
Similar Questions:
If you have python version 3.6 or higher you can use f strings
>>> string = "John"
>>> f"{string:<15}"
'John '
Or if you'd like it to the left
>>> f"{string:>15}"
' John'
Centered
>>> f"{string:^15}"
' John '
For more variations, feel free to check out the docs: https://docs.python.org/3/library/string.html#format-string-syntax
If the file is placed under target/classes after compiling, then it is already in a directory that is part of the build path. The directory src/main/resources is the Maven default directory for such resources, and it is automatically placed to the build path by the Eclipse Maven plugin (M2E). So, there is no need to move your properties file.
The other topic is, how to retrieve such resources. Resources in the build path are automatically in the class path of the running Java program. Considering this, you should always load such resources with a class loader. Example code:
String resourceName = "myconf.properties"; // could also be a constant
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Properties props = new Properties();
try(InputStream resourceStream = loader.getResourceAsStream(resourceName)) {
props.load(resourceStream);
}
// use props here ...
You have stumbled over the general problem with encodings: How can I tell in which encoding a file is?
Answer: You can't unless the file format provides for this. XML, for example, begins with:
<?xml encoding="utf-8"?>
This header was carefully chosen so that it can be read no matter the encoding. In your case, there is no such hint, hence neither your editor nor Python has any idea what is going on. Therefore, you must use the codecs
module and use codecs.open(path,mode,encoding)
which provides the missing bit in Python.
As for your editor, you must check if it offers some way to set the encoding of a file.
The point of UTF-8 is to be able to encode 21-bit characters (Unicode) as an 8-bit data stream (because that's the only thing all computers in the world can handle). But since most OSs predate the Unicode era, they don't have suitable tools to attach the encoding information to files on the hard disk.
The next issue is the representation in Python. This is explained perfectly in the comment by heikogerlach. You must understand that your console can only display ASCII. In order to display Unicode or anything >= charcode 128, it must use some means of escaping. In your editor, you must not type the escaped display string but what the string means (in this case, you must enter the umlaut and save the file).
That said, you can use the Python function eval() to turn an escaped string into a string:
>>> x = eval("'Capit\\xc3\\xa1n\\n'")
>>> x
'Capit\xc3\xa1n\n'
>>> x[5]
'\xc3'
>>> len(x[5])
1
As you can see, the string "\xc3" has been turned into a single character. This is now an 8-bit string, UTF-8 encoded. To get Unicode:
>>> x.decode('utf-8')
u'Capit\xe1n\n'
Gregg Lind asked: I think there are some pieces missing here: the file f2 contains: hex:
0000000: 4361 7069 745c 7863 335c 7861 316e Capit\xc3\xa1n
codecs.open('f2','rb', 'utf-8')
, for example, reads them all in a separate chars (expected) Is there any way to write to a file in ASCII that would work?
Answer: That depends on what you mean. ASCII can't represent characters > 127. So you need some way to say "the next few characters mean something special" which is what the sequence "\x" does. It says: The next two characters are the code of a single character. "\u" does the same using four characters to encode Unicode up to 0xFFFF (65535).
So you can't directly write Unicode to ASCII (because ASCII simply doesn't contain the same characters). You can write it as string escapes (as in f2); in this case, the file can be represented as ASCII. Or you can write it as UTF-8, in which case, you need an 8-bit safe stream.
Your solution using decode('string-escape')
does work, but you must be aware how much memory you use: Three times the amount of using codecs.open()
.
Remember that a file is just a sequence of bytes with 8 bits. Neither the bits nor the bytes have a meaning. It's you who says "65 means 'A'". Since \xc3\xa1
should become "à" but the computer has no means to know, you must tell it by specifying the encoding which was used when writing the file.
Although it might look out of topic nobody bothered to check the ERRORLEVEL. When I used your suggestions I tried to check for errors straight after the MSI installation. I made it fail on purpose and noticed that on the command line all works beautifully whilst in a batch file msiexec dosn't seem to set errors. Tried different things there like
Nothing works and what mostly annoys me it's the fact that it works in the command line.
You can also use bellow code for pass data using ajax.
var dataString = "album" + title;
$.ajax({
type: 'POST',
url: 'test.php',
data: dataString,
success: function(response) {
content.html(response);
}
});
you should just remove the 'boolean' in front of your boolean variable.
Do it like this:
boolean isLeapYear = true;
System.out.println(isLeapYear);
or
boolean isLeapYear = true;
System.out.println(isLeapYear?"yes":"no");
The other thing ist hat you seems not to call the method at all! The method and the variable are both not static, thus, you have to create an instance of your class first. Or you just make both static and than simply call your method directly from your maim method.
Thus there are a couple of mistakes in the code. May be you shoud start with a more simple example and than rework it until it does what you want.
Example:
import java.util.Scanner;
public class booleanfun {
static boolean isLeapYear;
public static void main(String[] args)
{
System.out.println("Enter a year to determine if it is a leap year or not: ");
Scanner kboard = new Scanner(System.in);
int year = kboard.nextInt();
isLeapYear(year);
}
public static boolean isLeapYear(int year) {
if (year % 4 != 0)
isLeapYear = false;
else if ((year % 4 == 0) && (year % 100 == 0))
isLeapYear = false;
else if ((year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0))
isLeapYear = true;
else
isLeapYear = false;
System.out.println(isLeapYear);
return isLeapYear;
}
}
There is an easy way to check socket connection state via poll
call. First, you need to poll socket, whether it has POLLIN
event.
read
will return more than zero.POLLIN
will be set to 0 in revents
POLLIN
flag will be set to one and read will return 0.Here is small code snippet:
int client_socket_1, client_socket_2;
if ((client_socket_1 = accept(listen_socket, NULL, NULL)) < 0)
{
perror("Unable to accept s1");
abort();
}
if ((client_socket_2 = accept(listen_socket, NULL, NULL)) < 0)
{
perror("Unable to accept s2");
abort();
}
pollfd pfd[]={{client_socket_1,POLLIN,0},{client_socket_2,POLLIN,0}};
char sock_buf[1024];
while (true)
{
poll(pfd,2,5);
if (pfd[0].revents & POLLIN)
{
int sock_readden = read(client_socket_1, sock_buf, sizeof(sock_buf));
if (sock_readden == 0)
break;
if (sock_readden > 0)
write(client_socket_2, sock_buf, sock_readden);
}
if (pfd[1].revents & POLLIN)
{
int sock_readden = read(client_socket_2, sock_buf, sizeof(sock_buf));
if (sock_readden == 0)
break;
if (sock_readden > 0)
write(client_socket_1, sock_buf, sock_readden);
}
}
We use ClosedXML in rather large systems.
Matlab and Scilab languages offer a simpler and more elegant syntax than Python for the question you're asking, so I think the best you can do is to mimic Matlab/Scilab by using the Numpy package in Python. By doing this the solution to your problem is very concise and elegant:
from numpy import *
property_a = array([545., 656., 5.4, 33.])
property_b = array([ 1.2, 1.3, 2.3, 0.3])
good_objects = [True, False, False, True]
good_indices = [0, 3]
property_asel = property_a[good_objects]
property_bsel = property_b[good_indices]
Numpy tries to mimic Matlab/Scilab but it comes at a cost: you need to declare every list with the keyword "array", something which will overload your script (this problem doesn't exist with Matlab/Scilab). Note that this solution is restricted to arrays of number, which is the case in your example.
If you are using Pipenv
, you may need to add this to your Pipfile
:
[packages]
python-dateutil = "*"
In mixed Java/Kotlin projects also consider Kotlin's Map.withDefault.
If your DataGridView's RightToLeft
set to Yes
then your data copy reversely. So you should use the below code to copy the data correctly.
private void copyAlltoClipboard()
{
dgvItems.RightToLeft = RightToLeft.No;
dgvItems.SelectAll();
DataObject dataObj = dgvItems.GetClipboardContent();
if (dataObj != null)
Clipboard.SetDataObject(dataObj);
dgvItems.RightToLeft = RightToLeft.Yes;
}
this can also be tried...
SELECT l.ip, tbl2.ip as ip2, tbl2.hostname
FROM login_log l
LEFT JOIN (SELECT ip_location.ip, ip_location.hostname
FROM ip_location
WHERE ip_location.ip is null)tbl2
<html>
<title>Practice Session</title>
<body>
<form name="RegForm" onsubmit="return validate()" method="post">
<p>Name: <input type="text" name="Name"> </p><br>
<p>Contact: <input type="text" name="Telephone"> </p><br>
<p><input type="submit" value="send" name="Submit"></p>
</form>
</body>
<script>
function validate()
{
var name = document.forms["RegForm"]["Name"];
var phone = document.forms["RegForm"]["Telephone"];
if (name.value == "")
{
window.alert("Please enter your name.");
name.focus();
return false;
}
else if(isNaN(name.value) /*"%d[10]"*/)
{
alert("name confirmed");
}
else{
window.alert("please enter character");
}
if (phone.value == "")
{
window.alert("Please enter your telephone number.");
phone.focus();
return false;
}
else if(!isNaN(phone.value) /*phone.value == isNaN(phone.value)*/)
{
alert("number confirmed");
}
else{
window.alert("please enter numbers only");
}
}
</script>
</html>
For windows: Best is to use pre-compiled package available from this site: http://www.lfd.uci.edu/%7Egohlke/pythonlibs/#scipy
"+" not "."
But be careful with String concatenation. Here's a link introducing some thoughts from IBM DeveloperWorks.
add semi-colon the line before:
$total_pages = ceil($total_result / $per_page);
For Windows and Python 3.x, my two cents contribution about renaming the file on download :
pip install wget
import wget
wget.download('Url', 'C:\\PathToMyDownloadFolder\\NewFileName.extension')
Truely working command line example :
python -c "import wget; wget.download(""https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-4.17.2.tar.xz"", ""C:\\Users\\TestName.TestExtension"")"
Note : 'C:\\PathToMyDownloadFolder\\NewFileName.extension' is not mandatory. By default, the file is not renamed, and the download folder is your local path.
This is very possible; you define the URI scheme in your AndroidManifest.xml, using the <data>
element. You setup an intent filter with the <data>
element filled out, and you'll be able to create your own scheme. (More on intent filters and intent resolution here.)
Here's a short example:
<activity android:name=".MyUriActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="myapp" android:host="path" />
</intent-filter>
</activity>
As per how implicit intents work, you need to define at least one action and one category as well; here I picked VIEW as the action (though it could be anything), and made sure to add the DEFAULT category (as this is required for all implicit intents). Also notice how I added the category BROWSABLE - this is not necessary, but it will allow your URIs to be openable from the browser (a nifty feature).
You can achieve this using Lodash _.merge
function.
var json1 = [{id:1, name: 'xxx'}];_x000D_
var json2 = [{id:2, name: 'xyz'}];_x000D_
var merged = _.merge(_.keyBy(json1, 'id'), _.keyBy(json2, 'id'));_x000D_
var finalObj = _.values(merged);_x000D_
_x000D_
console.log(finalObj);
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
1752 was the year of Britain switching from the Julian to the Gregorian calendar. I believe two weeks in September 1752 never happened as a result, which has implications for dates in that general area.
An explanation: http://uneasysilence.com/archive/2007/08/12008/ (Internet Archive version)
You can use a separate class to represent the JSON object and use @SerializedName
annotations to specify the field name to grab for each data member:
public class Response {
@SerializedName("data")
private Data data;
private static class Data {
@SerializedName("translations")
public Translation[] translations;
}
private static class Translation {
@SerializedName("translatedText")
public String translatedText;
}
public String getTranslatedText() {
return data.translations[0].translatedText;
}
}
Then you can do the parsing in your parse() method using a Gson
object:
Gson gson = new Gson();
Response response = gson.fromJson(jsonLine, Response.class);
System.out.println("Translated text: " + response.getTranslatedText());
With this approach, you can reuse the Response
class to add any other additional fields to pick up other data members you might want to extract from JSON -- in case you want to make changes to get results for, say, multiple translations in one call, or to get an additional string for the detected source language.
For Oracle SQL Developer I was able to calculate the difference in years using the below line of SQL. This was to get Years that were within 0 to 10 years difference. You can do a case like shown in some of the other responses to handle your ifs as well. Happy Coding!
TRUNC((MONTHS_BETWEEN(<DATE_ONE>, <DATE_TWO>) * 31) / 365) > 0 and TRUNC((MONTHS_BETWEEN(<DATE_ONE>, <DATE_TWO>) * 31) / 365) < 10
Kotlin Solution :
private fun locationEnabled() : Boolean {
val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
}
Link statically to libstdc++ with -static-libstdc++
gcc option.
Here is a slightly improved version:
urls = [
"http://stackoverflow.com:8080/some/folder?test=/questions/9626535/get-domain-name-from-url",
"Stackoverflow.com:8080/some/folder?test=/questions/9626535/get-domain-name-from-url",
"http://stackoverflow.com/some/folder?test=/questions/9626535/get-domain-name-from-url",
"https://StackOverflow.com:8080?test=/questions/9626535/get-domain-name-from-url",
"stackoverflow.com?test=questions&v=get-domain-name-from-url"]
for url in urls:
spltAr = url.split("://");
i = (0,1)[len(spltAr)>1];
dm = spltAr[i].split("?")[0].split('/')[0].split(':')[0].lower();
print dm
Output
stackoverflow.com
stackoverflow.com
stackoverflow.com
stackoverflow.com
stackoverflow.com
Fiddle: https://pyfiddle.io/fiddle/23e4976e-88d2-4757-993e-532aa41b7bf0/?i=true
When you cherry-pick, it creates a new commit with a new SHA. If you do:
git cherry-pick -x <sha>
then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.
you can do it using eloquent easily like this
$sum = Model::sum('sum_field');
its will return a sum of fields, if apply condition on it that is also simple
$sum = Model::where('status', 'paid')->sum('sum_field');
You might want to check out RFC 6570. This URI Template spec shows many examples of how urls can contain parameters.
select t.data_type
from user_tab_columns t
where t.TABLE_NAME = 'xxx'
and t.COLUMN_NAME='aaa'
I had trouble getting the answer back from the dialog box but eventually came up with a solution by combining the answer from this other question display-yes-and-no-buttons-instead-of-ok-and-cancel-in-confirm-box with part of the code from the modal-confirmation dialog
This is what was suggested for the other question:
Create your own confirm box:
<div id="confirmBox">
<div class="message"></div>
<span class="yes">Yes</span>
<span class="no">No</span>
</div>
Create your own confirm()
method:
function doConfirm(msg, yesFn, noFn)
{
var confirmBox = $("#confirmBox");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes,.no").unbind().click(function()
{
confirmBox.hide();
});
confirmBox.find(".yes").click(yesFn);
confirmBox.find(".no").click(noFn);
confirmBox.show();
}
Call it by your code:
doConfirm("Are you sure?", function yes()
{
form.submit();
}, function no()
{
// do nothing
});
MY CHANGES
I have tweaked the above so that instead of calling confirmBox.show()
I used confirmBox.dialog({...})
like this
confirmBox.dialog
({
autoOpen: true,
modal: true,
buttons:
{
'Yes': function () {
$(this).dialog('close');
$(this).find(".yes").click();
},
'No': function () {
$(this).dialog('close');
$(this).find(".no").click();
}
}
});
The other change I made was to create the confirmBox div within the doConfirm function, like ThulasiRam did in his answer.
Here are a couple good sites to check out for that,
http://www.tripwiremagazine.com/2011/10/css-menu-and-navigation.html (Lots of examples)
http://webdesignerwall.com/tutorials/css3-dropdown-menu (1 example more tutorial like)
Hope this is helpful information!
In addition to the answers posted here, make sure you read this article:
It is located on the Android Studio
folder itself, on where you installed it.
Should we include a little JS? Because CSS was not basically created for this job. CSS was just a style sheet to add styles to the HTML, but its pseudo classes can do something that the basic CSS can't do. For example button:active
active is pseudo.
Reference:
http://css-tricks.com/pseudo-class-selectors/ You can learn more about pseudo here!
Your code:
The code that you're having the basic but helpfull. And yes :active
will only occur once the click event is triggered.
button {
font-size: 18px;
border: 2px solid gray;
border-radius: 100px;
width: 100px;
height: 100px;
}
button:active {
font-size: 18px;
border: 2px solid red;
border-radius: 100px;
width: 100px;
height: 100px;
}
This is what CSS would do, what rlemon suggested is good, but that would as he suggested would require a
tag.
How to use CSS:
You can use :focus
too. :focus
would work once the click is made and would stay untill you click somewhere else, this was the CSS, you were trying to use CSS, so use :focus
to make the buttons change.
What JS would do:
The JavaScript's jQuery library is going to help us for this code. Here is the example:
$('button').click(function () {
$(this).css('border', '1px solid red');
}
This will make sure that the button stays red even if the click gets out. To change the focus type (to change the color of red to other) you can use this:
$('button').click(function () {
$(this).css('border', '1px solid red');
// find any other button with a specific id, and change it back to white like
$('button#red').css('border', '1px solid white');
}
This way, you will create a navigation menu. Which will automatically change the color of the tabs as you click on them. :)
Hope you get the answer. Good luck! Cheers.
There are three possibilities:
1) If you are referring old DLL then it cant be used. So you have refer new DLL
2) If you are using it in different namespace and trying to use the other namespace's dll then it wont refer this method.
3) You may need to rebuild the project
I think third option might be the cause for you. Please post more information in order to understand exact problem of yours.
I came to this post by way of better understanding the inference of the infamous quote from Mac Lane's Category Theory For the Working Mathematician.
In describing what something is, it's often equally useful to describe what it's not.
The fact that Mac Lane uses the description to describe a Monad, one might imply that it describes something unique to monads. Bear with me. To develop a broader understanding of the statement, I believe it needs to be made clear that he is not describing something that is unique to monads; the statement equally describes Applicative and Arrows among others. For the same reason we can have two monoids on Int (Sum and Product), we can have several monoids on X in the category of endofunctors. But there is even more to the similarities.
Both Monad and Applicative meet the criteria:
(e.g., in day to day Tree a -> List b
, but in Category Tree -> List
)
Tree -> List
, only List -> List
. The statement uses "Category of..." This defines the scope of the statement. As an example, the Functor Category describes the scope of f * -> g *
, i.e., Any functor -> Any functor
, e.g., Tree * -> List *
or Tree * -> Tree *
.
What a Categorical statement does not specify describes where anything and everything is permitted.
In this case, inside the functors, * -> *
aka a -> b
is not specified which means Anything -> Anything including Anything else
. As my imagination jumps to Int -> String, it also includes Integer -> Maybe Int
, or even Maybe Double -> Either String Int
where a :: Maybe Double; b :: Either String Int
.
So the statement comes together as follows:
:: f a -> g b
(i.e., any parameterized type to any parameterized type):: f a -> f b
(i.e., any one parameterized type to the same parameterized type) ... said differently,So, where is the power of this construct? To appreciate the full dynamics, I needed to see that the typical drawings of a monoid (single object with what looks like an identity arrow, :: single object -> single object
), fails to illustrate that I'm permitted to use an arrow parameterized with any number of monoid values, from the one type object permitted in Monoid. The endo, ~ identity arrow definition of equivalence ignores the functor's type value and both the type and value of the most inner, "payload" layer. Thus, equivalence returns true
in any situation where the functorial types match (e.g., Nothing -> Just * -> Nothing
is equivalent to Just * -> Just * -> Just *
because they are both Maybe -> Maybe -> Maybe
).
Sidebar: ~ outside is conceptual, but is the left most symbol in f a
. It also describes what "Haskell" reads-in first (big picture); so Type is "outside" in relation to a Type Value. The relationship between layers (a chain of references) in programming is not easy to relate in Category. The Category of Set is used to describe Types (Int, Strings, Maybe Int etc.) which includes the Category of Functor (parameterized Types). The reference chain: Functor Type, Functor values (elements of that Functor's set, e.g., Nothing, Just), and in turn, everything else each functor value points to. In Category the relationship is described differently, e.g., return :: a -> m a
is considered a natural transformation from one Functor to another Functor, different from anything mentioned thus far.
Back to the main thread, all in all, for any defined tensor product and a neutral value, the statement ends up describing an amazingly powerful computational construct born from its paradoxical structure:
:: List
); staticfold
that says nothing about the payload)In Haskell, clarifying the applicability of the statement is important. The power and versatility of this construct, has absolutely nothing to do with a monad per se. In other words, the construct does not rely on what makes a monad unique.
When trying to figure out whether to build code with a shared context to support computations that depend on each other, versus computations that can be run in parallel, this infamous statement, with as much as it describes, is not a contrast between the choice of Applicative, Arrows and Monads, but rather is a description of how much they are the same. For the decision at hand, the statement is moot.
This is often misunderstood. The statement goes on to describe join :: m (m a) -> m a
as the tensor product for the monoidal endofunctor. However, it does not articulate how, in the context of this statement, (<*>)
could also have also been chosen. It truly is a an example of six/half dozen. The logic for combining values are exactly alike; same input generates the same output from each (unlike the Sum and Product monoids for Int because they generate different results when combining Ints).
So, to recap: A monoid in the category of endofunctors describes:
~t :: m * -> m * -> m *
and a neutral value for m *
(<*>)
and (>>=)
both provide simultaneous access to the two m
values in order to compute the the single return value. The logic used to compute the return value is exactly the same. If it were not for the different shapes of the functions they parameterize (f :: a -> b
versus k :: a -> m b
) and the position of the parameter with the same return type of the computation (i.e., a -> b -> b
versus b -> a -> b
for each respectively), I suspect we could have parameterized the monoidal logic, the tensor product, for reuse in both definitions. As an exercise to make the point, try and implement ~t
, and you end up with (<*>)
and (>>=)
depending on how you decide to define it forall a b
.
If my last point is at minimum conceptually true, it then explains the precise, and only computational difference between Applicative and Monad: the functions they parameterize. In other words, the difference is external to the implementation of these type classes.
In conclusion, in my own experience, Mac Lane's infamous quote provided a great "goto" meme, a guidepost for me to reference while navigating my way through Category to better understand the idioms used in Haskell. It succeeds at capturing the scope of a powerful computing capacity made wonderfully accessible in Haskell.
However, there is irony in how I first misunderstood the statement's applicability outside of the monad, and what I hope conveyed here. Everything that it describes turns out to be what is similar between Applicative and Monads (and Arrows among others). What it doesn't say is precisely the small but useful distinction between them.
- E
believe there should be a way in accessing file system.
Include node.d.ts
using npm i @types/node
. And then create a new tsconfig.json
file (npx tsc --init
) and create a .ts
file as followed:
import fs from 'fs';
fs.readFileSync('foo.txt','utf8');
You can use other functions in fs
as well : https://nodejs.org/api/fs.html
Node quick start : https://basarat.gitbooks.io/typescript/content/docs/node/nodejs.html
@cmaster made the best elaborated answer. In brief:
git checkout master #
git pull # update local master from remote master
git checkout <your_branch>
git merge master # solve merge conflicts if you have`
You should not rewrite branch history instead keep them in actual state for future references. While merging to master, it creates one extra commit but that is cheap. Commits does not cost.
First you to add a class then remove id
<script type="text/javascript">
$(document).ready(function(){
$("#page_navigation1").addClass("page_navigation");
$("#add").click(function(){
$(".page_navigation").attr("id","page_navigation1");
});
$("#remove").click(function(){
$(".page_navigation").removeAttr("id");
});
});
</script>
A rather separable way of doing this is to use
import tensorflow as tf
from keras import backend as K
num_cores = 4
if GPU:
num_GPU = 1
num_CPU = 1
if CPU:
num_CPU = 1
num_GPU = 0
config = tf.ConfigProto(intra_op_parallelism_threads=num_cores,
inter_op_parallelism_threads=num_cores,
allow_soft_placement=True,
device_count = {'CPU' : num_CPU,
'GPU' : num_GPU}
)
session = tf.Session(config=config)
K.set_session(session)
Here, with booleans
GPU
and CPU
, we indicate whether we would like to run our code with the GPU or CPU by rigidly defining the number of GPUs and CPUs the Tensorflow session is allowed to access. The variables num_GPU
and num_CPU
define this value. num_cores
then sets the number of CPU cores available for usage via intra_op_parallelism_threads
and inter_op_parallelism_threads
.
The intra_op_parallelism_threads
variable dictates the number of threads a parallel operation in a single node in the computation graph is allowed to use (intra). While the inter_ops_parallelism_threads
variable defines the number of threads accessible for parallel operations across the nodes of the computation graph (inter).
allow_soft_placement
allows for operations to be run on the CPU if any of the following criterion are met:
there is no GPU implementation for the operation
there are no GPU devices known or registered
there is a need to co-locate with other inputs from the CPU
All of this is executed in the constructor of my class before any other operations, and is completely separable from any model or other code I use.
Note: This requires tensorflow-gpu
and cuda
/cudnn
to be installed because the option is given to use a GPU.
Refs:
split takes regex as a parameter.|
has special meaning in regex.. use \\|
instead of |
to escape it.
In this LIVE DEMO i've achieved this by using the :before css selector which seems to work quite nicely.
.myDiv {_x000D_
position: relative; /*Parent MUST be relative*/_x000D_
z-index: 9;_x000D_
background: green;_x000D_
_x000D_
/*Set width/height of the div in 'parent'*/ _x000D_
width:100px;_x000D_
height:100px;_x000D_
}_x000D_
_x000D_
_x000D_
.myDiv:before {_x000D_
content: "";_x000D_
position: absolute;/*set 'child' to be absolute*/_x000D_
z-index: -1; /*Make this lower so text appears in front*/_x000D_
_x000D_
_x000D_
/*You can choose to align it left, right, top or bottom here*/_x000D_
top: 0; _x000D_
right:0;_x000D_
bottom: 60%;_x000D_
left: 0;_x000D_
_x000D_
_x000D_
background: red;_x000D_
}
_x000D_
<div class="myDiv">this is my div with multiple colours. It work's with text too!</div>
_x000D_
I thought i would add this as I feel it could work quite well for a percentage bar/visual level of something.
It also means you're not creating multiple divs if you don't have to, and keeps this page up-to-date
Adding an answer that exclusively uses the pandas library to read in a .csv file and save as a .xlsx file. This example makes use of pandas.read_csv
(Link to docs) and pandas.dataframe.to_excel
(Link to docs).
The fully reproducible example uses numpy to generate random numbers only, and this can be removed if you would like to use your own .csv file.
import pandas as pd
import numpy as np
# Creating a dataframe and saving as test.csv in current directory
df = pd.DataFrame(np.random.randn(100000, 3), columns=list('ABC'))
df.to_csv('test.csv', index = False)
# Reading in test.csv and saving as test.xlsx
df_new = pd.read_csv('test.csv')
writer = pd.ExcelWriter('test.xlsx')
df_new.to_excel(writer, index = False)
writer.save()
You have to specify project_id
:
reverse('edit_project', kwargs={'project_id':4})
Doc here
You can use CREATE SYNONYM to remote object.
The OP is asking about whether it is possible to add an Attribute to an Entity class for a Unique Key. The short answer is that it IS possible, but not an out-of-the-box feature from the EF Core Team. If you'd like to use an Attribute to add Unique Keys to your Entity Framework Core entity classes, you can do what I've posted here
public class Company
{
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid CompanyId { get; set; }
[Required]
[UniqueKey(groupId: "1", order: 0)]
[StringLength(100, MinimumLength = 1)]
public string CompanyName { get; set; }
[Required]
[UniqueKey(groupId: "1", order: 1)]
[StringLength(100, MinimumLength = 1)]
public string CompanyLocation { get; set; }
}
I am new to python.
I fixed this issue by changing the project interpreter path.
File -> Settings -> Project -> Project Interpreter
Using standard java libs, I suggest looking at the HttpUrlConnection class http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html
It can handle most of what curl can do with setting up the connection. What you do with the stream is up to you.
Late to the game, I know but there seems to be a very simple way to do this:
const str = "72 tocirah sneab";_x000D_
const arr = str.split(/ (.*)/);_x000D_
console.log(arr);
_x000D_
This will leave arr[0]
with "72"
and arr[1]
with "tocirah sneab"
. Note that arr[2] will be empty, but you can just ignore it.
For reference:
The following approach worked in Angular 5 CLI.
For sake of simplicity, I used similar d3gauge.js demo created and provided by oliverbinns - which you may easily find on Github.
So first, I simply created a new folder named externalJS on same level as the assets folder. I then copied the 2 following .js files.
I then made sure to declare both linked directives in main index.html
<script src="./externalJS/d3.v3.min.js"></script>
<script src="./externalJS/d3gauge.js"></script>
I then added a similar code in a gauge.component.ts component as followed:
import { Component, OnInit } from '@angular/core';
declare var d3gauge:any; <----- !
declare var drawGauge: any; <-----!
@Component({
selector: 'app-gauge',
templateUrl: './gauge.component.html'
})
export class GaugeComponent implements OnInit {
constructor() { }
ngOnInit() {
this.createD3Gauge();
}
createD3Gauge() {
let gauges = []
document.addEventListener("DOMContentLoaded", function (event) {
let opt = {
gaugeRadius: 160,
minVal: 0,
maxVal: 100,
needleVal: Math.round(30),
tickSpaceMinVal: 1,
tickSpaceMajVal: 10,
divID: "gaugeBox",
gaugeUnits: "%"
}
gauges[0] = new drawGauge(opt);
});
}
}
and finally, I simply added a div in corresponding gauge.component.html
<div id="gaugeBox"></div>
et voilà ! :)
Another option would be to suppress the PHP undefined index notice with the @
symbol in front of the GET variable like so:
$s = @$_GET['s'];
This will disable the notice. It is better to check if the variable has been set and act accordingly.
But this also works.
As in this answer Custom HTTP Header for a specific file you can use <File>
to enable CORS for a single file with this code:
<Files "index.php">
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
</Files>
When you just remove a map, it destroys the div id reference, so, after remove() you need to build again the div where the map will be displayed, in order to avoid the "Uncaught Error: Map container not found".
if(map != undefined || map != null){
map.remove();
$("#map").html("");
$("#preMap").empty();
$( "<div id=\"map\" style=\"height: 500px;\"></div>" ).appendTo("#preMap");
}
You simply need to make cab
a string:
cab = '6176'
As the error message states, you cannot do <int> in <string>
:
>>> 1 in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
>>>
because integers and strings are two totally different things and Python does not embrace implicit type conversion ("Explicit is better than implicit.").
In fact, Python only allows you to use the in
operator with a right operand of type string if the left operand is also of type string:
>>> '1' in '123' # Works!
True
>>>
>>> [] in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>>
>>> 1.0 in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not float
>>>
>>> {} in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not dict
>>>
You can simulate a readonly select box using the CSS pointer-events property:
select[readonly]
{
pointer-events: none;
}
The HTML tabindex property will also prevent it from being selected by keyboard tabbing:
<select tabindex="-1">
select[readonly]_x000D_
{_x000D_
pointer-events: none;_x000D_
}_x000D_
_x000D_
_x000D_
/* irrelevent styling */_x000D_
_x000D_
*_x000D_
{_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
*[readonly]_x000D_
{_x000D_
background: #fafafa;_x000D_
border: 1px solid #ccc;_x000D_
color: #555;_x000D_
}_x000D_
_x000D_
input, select_x000D_
{_x000D_
display:block;_x000D_
width: 20rem;_x000D_
padding: 0.5rem;_x000D_
margin-bottom: 1rem;_x000D_
}
_x000D_
<form>_x000D_
<input type="text" value="this is a normal text box">_x000D_
<input type="text" readonly value="this is a readonly text box">_x000D_
<select readonly tabindex="-1">_x000D_
<option>This is a readonly select box</option>_x000D_
<option>Option 2</option>_x000D_
</select>_x000D_
<select>_x000D_
<option>This is a normal select box</option>_x000D_
<option>Option 2</option>_x000D_
</select>_x000D_
</form>
_x000D_