If someone is searching for a complete solution for changing default charset for all database tables and converting the data, this could be one:
DELIMITER $$
CREATE PROCEDURE `exec_query`(IN sql_text VARCHAR(255))
BEGIN
SET @tquery = `sql_text`;
PREPARE `stmt` FROM @tquery;
EXECUTE `stmt`;
DEALLOCATE PREPARE `stmt`;
END$$
CREATE PROCEDURE `change_character_set`(IN `charset` VARCHAR(64), IN `collation` VARCHAR(64))
BEGIN
DECLARE `done` BOOLEAN DEFAULT FALSE;
DECLARE `tab_name` VARCHAR(64);
DECLARE `charset_cursor` CURSOR FOR
SELECT `table_name` FROM `information_schema`.`tables`
WHERE `table_schema` = DATABASE() AND `table_type` = 'BASE TABLE';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET `done` = TRUE;
SET foreign_key_checks = 0;
OPEN `charset_cursor`;
`change_loop`: LOOP
FETCH `charset_cursor` INTO `tab_name`;
IF `done` THEN
LEAVE `change_loop`;
END IF;
CALL `exec_query`(CONCAT(
'ALTER TABLE `',
tab_name,
'` CONVERT TO CHARACTER SET ',
QUOTE(charset),
' COLLATE ',
QUOTE(collation),
';'
));
CALL `exec_query`(CONCAT('REPAIR TABLE `', tab_name, '`;'));
CALL `exec_query`(CONCAT('OPTIMIZE TABLE `', tab_name, '`;'));
END LOOP `change_loop`;
CLOSE `charset_cursor`;
SET foreign_key_checks = 1;
END$$
DELIMITER ;
You can place this code inside the file e.g. chg_char_set.sql
and execute it e.g. by calling it from MySQL terminal:
SOURCE ~/path-to-the-file/chg_char_set.sql
Then call defined procedure with desired input parameters e.g.
CALL change_character_set('utf8mb4', 'utf8mb4_bin');
Once you've tested the results, you can drop those stored procedures:
DROP PROCEDURE `change_character_set`;
DROP PROCEDURE `exec_query`;
To perform case-insensitive operations, supply re.IGNORECASE
>>> import re
>>> test = 'UPPER TEXT, lower text, Mixed Text'
>>> re.findall('text', test, flags=re.IGNORECASE)
['TEXT', 'text', 'Text']
and if we want to replace text matching the case...
>>> def matchcase(word):
def replace(m):
text = m.group()
if text.isupper():
return word.upper()
elif text.islower():
return word.lower()
elif text[0].isupper():
return word.capitalize()
else:
return word
return replace
>>> re.sub('text', matchcase('word'), test, flags=re.IGNORECASE)
'UPPER WORD, lower word, Mixed Word'
ALTER TABLE users CHANGE id int( 30 ) NOT NULL AUTO_INCREMENT
the integer parameter is based on my default sql setting have a nice day
For posterity, also check server logs to see if the resource being requested is returning a 200.
I ran into a similar issue, where all of the proper headers were being returned in the pre-flight ajax request, but the browser reported the actual request was blocked due to bad CORS headers.
Turns out, the page being requested was returning a 500 error due to bad code, but only when it was fetched via CORS. The browser (both Chrome and Firefox) mistakenly reported that the Access-Control-Allow-Origin header was missing instead of saying the page returned a 500.
This is an example for a RelativeLayout:
RelativeLayout relativeLayout=(RelativeLayout)vi.findViewById(R.id.RelativeLayoutLeft);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)relativeLayout.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
relativeLayout.setLayoutParams(params);
With another kind of layout (example LinearLayout) you just simply has to change RelativeLayout for LinearLayout.
You can find out something like this in C#.
This is what I used in JUnit - Selenium
WebDriverWait wait = new WebDriverWait(driver, 100);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));
Do import related packages.
If you want to use an npm package, wrench is pretty good.
var wrench = require("wrench");
var files = wrench.readdirSyncRecursive("directory");
wrench.readdirRecursive("directory", function (error, files) {
// live your dreams
});
EDIT (2018):
Anyone reading through in recent time: The author deprecated this package in 2015:
wrench.js is deprecated, and hasn't been updated in quite some time. I heavily recommend using fs-extra to do any extra filesystem operations.
The difference is pretty subtle and if you dont pay much attention then you will keep it using in a wrong way.
Best way to understand the difference between orElse()
and orElseGet()
is that orElse()
will always be executed if the Optional<T>
is null or not, But orElseGet()
will only be executed when Optional<T>
is null.
The dictionary meaning of orElse is :- execute the part when something is not present, but here it contradicts, see the below example:
Optional<String> nonEmptyOptional = Optional.of("Vishwa Ratna");
String value = nonEmptyOptional.orElse(iAmStillExecuted());
public static String iAmStillExecuted(){
System.out.println("nonEmptyOptional is not NULL,still I am being executed");
return "I got executed";
}
Output: nonEmptyOptional is not NULL,still I am being executed
Optional<String> emptyOptional = Optional.ofNullable(null);
String value = emptyOptional.orElse(iAmStillExecuted());
public static String iAmStillExecuted(){
System.out.println("emptyOptional is NULL, I am being executed, it is normal as
per dictionary");
return "I got executed";
}
Output: emptyOptional is NULL, I am being executed, it is normal as per dictionary
For
orElseGet()
, The method goes as per dictionary meaning, TheorElseGet()
part will be executed only when the Optional is null.
Benchmarks:
+--------------------+------+-----+------------+-------------+-------+
| Benchmark | Mode | Cnt | Score | Error | Units |
+--------------------+------+-----+------------+-------------+-------+
| orElseBenchmark | avgt | 20 | 60934.425 | ± 15115.599 | ns/op |
+--------------------+------+-----+------------+-------------+-------+
| orElseGetBenchmark | avgt | 20 | 3.798 | ± 0.030 | ns/op |
+--------------------+------+-----+------------+-------------+-------+
Remarks:
orElseGet()
has clearly outperformedorElse()
for our particular example.
Hope it clears the doubts of people like me who wants the very basic ground example :)
Using pretty much the same approach as used by Burnash, for the final result you can use ...
=regexextract(A1,"[0-9]+")+A2
where A1 houses the string with text and number and A2 houses the date of interest
This looks like a behavior difference in the handling of \s
between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).
Note:
GNU grep 2.5.4
echo "foo bar" | grep "\s"
(doesn't match)
whereas
GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar
Probably less trouble (as \s
is not documented):
Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar
My advice is to avoid using \s
... use [ \t]*
or [[:space:]]
or something like it instead.
Use this code to click:
$("#gift-close").click();
Try enclosing your date into a character string.
select *
from dbo.March2010 A
where A.Date >= '2010-04-01';
I'll use Java as an example. Let's say we have a class that looks like this:
public class ABC
{
public void doDiskAccess() {...}
}
When I call the class, I'll need to do something like this:
ABC abc = new ABC();
abc. doDiskAccess();
So far, so good. Now let's say I have another class that looks like this:
public class XYZ
{
public void doNetworkAccess() {...}
}
It looks exactly the same as ABC, but let's say it works over the network instead of on disk. So now let's write a program like this:
if(config.isNetwork()) new XYZ().doNetworkAccess();
else new ABC().doDiskAccess();
That works, but it's a bit unwieldy. I could simplify this with an interface like this:
public interface Runnable
{
public void run();
}
public class ABC implements Runnable
{
public void run() {...}
}
public class XYZ implements Runnable
{
public void run() {...}
}
Now my code can look like this:
Runnable obj = config.isNetwork() ? new XYZ() : new ABC();
obj.run();
See how much cleaner and simpler to understand that is? We've just understood the first basic tenet of loose coupling: abstraction. The key from here is to ensure that ABC and XYZ do not depend on any methods or variables of the classes that call them. That allows ABC and XYZ to be completely independent APIs. Or in other words, they are "decoupled" or "loosely coupled" from the parent classes.
But what if we need communication between the two? Well, then we can use further abstractions like an Event Model to ensure that the parent code never needs to couple with the APIs you have created.
Answer for Question #1 - You could simply have your if statement stop being TRUE
$project.PropertyGroup | Foreach {
if(($_.GetAttribute('Condition').Trim() -eq $propertyGroupConditionName.Trim()) -and !$FinishLoop) {
$a = $project.RemoveChild($_);
Write-Host $_.GetAttribute('Condition')"has been removed.";
$FinishLoop = $true
}
};
I'd create the array and then append the object literals to it.
var myColumnDefs = [];
for ( var i=0 ; i < oFullResponse.results.length; i++) {
console.log(oFullResponse.results[i].label);
myColumnDefs[myColumnDefs.length] = {key:oFullResponse.results[i].label, sortable:true, resizeable:true};
}
Typically you see this error after you have already done a redirect and then try to output some more data to the output stream. In the cases where I have seen this in the past, it is often one of the filters that is trying to redirect the page, and then still forwards through to the servlet. I cannot see anything immediately wrong with the servlet, so you might want to try having a look at any filters that you have in place as well.
Edit: Some more help in diagnosing the problem…
The first step to diagnosing this problem is to ascertain exactly where the exception is being thrown. We are assuming that it is being thrown by the line
getServletConfig().getServletContext()
.getRequestDispatcher("/GroupCopiedUpdt.jsp")
.forward(request, response);
But you might find that it is being thrown later in the code, where you are trying to output to the output stream after you have tried to do the forward. If it is coming from the above line, then it means that somewhere before this line you have either:
Good luck!
You can use like that:
data
is DataTable
data.DefaultView.ToTable(true, "Id", "Name", "Role", "DC1", "DC2", "DC3", "DC4", "DC5", "DC6", "DC7");
but performance will be down. try to use below code:
data.AsEnumerable().Distinct(System.Data.DataRowComparer.Default).ToList();
For Performance ; http://onerkaya.blogspot.com/2013/01/distinct-dataviewtotable-vs-linq.html
What about this?
java.sql.Timestamp timestamp = java.sql.Timestamp.valueOf("2007-09-23 10:10:10.0");
After installing Docker, do the following:
[mdesales@pppdc9prd1vq ~]$ sudo HTTP_PROXY=http://proxy02.ie.xyz.net:80 ./docker -d &
[2] 20880
Then, you can pull or do anything:
mdesales@pppdc9prd1vq ~]$ sudo docker pull base
2014/04/11 00:46:02 POST /v1.10/images/create?fromImage=base&tag=
[/var/lib/docker|aa088847] +job pull(base, )
Pulling repository base
b750fe79269d: Download complete
27cf78414709: Download complete
[/var/lib/docker|aa088847] -job pull(base, ) = OK (0)
Using individual regular expressions to test the different parts would be considerably easier than trying to get one single regular expression to cover all of them. It also makes it easier to add or remove validation criteria.
Note, also, that your usage of .filter()
was incorrect; it will always return a jQuery object (which is considered truthy in JavaScript). Personally, I'd use an .each()
loop to iterate over all of the inputs, and report individual pass/fail statuses. Something like the below:
$(".buttonClick").click(function () {
$("input[type=text]").each(function () {
var validated = true;
if(this.value.length < 8)
validated = false;
if(!/\d/.test(this.value))
validated = false;
if(!/[a-z]/.test(this.value))
validated = false;
if(!/[A-Z]/.test(this.value))
validated = false;
if(/[^0-9a-zA-Z]/.test(this.value))
validated = false;
$('div').text(validated ? "pass" : "fail");
// use DOM traversal to select the correct div for this input above
});
});
Code evolves. private
is great for when you need data member protection. Eventually all classes should be sort of "miniprograms" that have a well-defined interface that you can't just screw with the internals of.
That said, software development isn't about setting down that final version of the class as if you're pressing some cast iron statue on the first try. While you're working with it, code is more like clay. It evolves as you develop it and learn more about the problem domain you are solving. During development classes may interact with each other than they should (dependency you plan to factor out), merge together, or split apart. So I think the debate boils down to people not wanting to religiously write
int getVar() const { return var ; }
So you have:
doSomething( obj->getVar() ) ;
Instead of
doSomething( obj->var ) ;
Not only is getVar()
visually noisy, it gives this illusion that gettingVar()
is somehow a more complex process than it really is. How you (as the class writer) regard the sanctity of var
is particularly confusing to a user of your class if it has a passthru setter -- then it looks like you're putting up these gates to "protect" something you insist is valuable, (the sanctity of var
) but yet even you concede var
's protection isn't worth much by the ability for anyone to just come in and set
var
to whatever value they want, without you even peeking at what they are doing.
So I program as follows (assuming an "agile" type approach -- ie when I write code not knowing exactly what it will be doing/don't have time or experience to plan an elaborate waterfall style interface set):
1) Start with all public members for basic objects with data and behavior. This is why in all my C++ "example" code you'll notice me using struct
instead of class
everywhere.
2) When an object's internal behavior for a data member becomes complex enough, (for example, it likes to keep an internal std::list
in some kind of order), accessor type functions are written. Because I'm programming by myself, I don't always set the member private
right away, but somewhere down the evolution of the class the member will be "promoted" to either protected
or private
.
3) Classes that are fully fleshed out and have strict rules about their internals (ie they know exactly what they are doing, and you are not to "fuck" (technical term) with its internals) are given the class
designation, default private members, and only a select few members are allowed to be public
.
I find this approach allows me to avoid sitting there and religiously writing getter/setters when a lot of data members get migrated out, shifted around, etc. during the early stages of a class's evolution.
if you are creating in specific module go to that path and run ng g c componentname
else create module first ng g module modulename
cd arc/app/modulename go to modulename path and create the component
Had the same issue installing angular material CDK:
npm install --save @angular/material @angular/cdk @angular/animations
Adding -dev
like below worked for me:
npm install --save-dev @angular/material @angular/cdk @angular/animations
The code you have for the two columns looks ok. Look for any other datetime columns on that mapping class. Also, enable logging on the datacontext to see the query and parameters.
dc.Log = Console.Out;
DateTime is initialized to c#'s 0 - which is 0001-01-01. This is transmitted by linqtosql to the database via sql string literal : '0001-01-01'. Sql cannot parse a T-Sql datetime from this date.
There's a couple ways to deal with this:
Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:
open(filename, 'w').close()
The problem is the indexing subplot
is using. Subplots are counted starting with 1!
Your code thus needs to read
fig=plt.figure(figsize=(15, 6),facecolor='w', edgecolor='k')
for i in range(10):
#this part is just arranging the data for contourf
ind2 = py.find(zz==i+1)
sfr_mass_mat = np.reshape(sfr_mass[ind2],(pixmax_x,pixmax_y))
sfr_mass_sub = sfr_mass[ind2]
zi = griddata(massloclist, sfrloclist, sfr_mass_sub,xi,yi,interp='nn')
temp = 251+i # this is to index the position of the subplot
ax=plt.subplot(temp)
ax.contourf(xi,yi,zi,5,cmap=plt.cm.Oranges)
plt.subplots_adjust(hspace = .5,wspace=.001)
#just annotating where each contour plot is being placed
ax.set_title(str(temp))
Note the change in the line where you calculate temp
The solution above does not work in all InputBox-Cancel cases. Most notably, it does not work if you have to InputBox a Range.
For example, try the following InputBox for defining a custom range ('sRange', type:=8, requires Set + Application.InputBox) and you will get an error upon pressing Cancel:
Sub Cancel_Handler_WRONG()
Set sRange = Application.InputBox("Input custom range", _
"Cancel-press test", Selection.Address, Type:=8)
If StrPtr(sRange) = 0 Then 'I also tried with sRange.address and vbNullString
MsgBox ("Cancel pressed!")
Exit Sub
End If
MsgBox ("Your custom range is " & sRange.Address)
End Sub
The only thing that works, in this case, is an "On Error GoTo ErrorHandler" statement before the InputBox + ErrorHandler at the end:
Sub Cancel_Handler_OK()
On Error GoTo ErrorHandler
Set sRange = Application.InputBox("Input custom range", _
"Cancel-press test", Selection.Address, Type:=8)
MsgBox ("Your custom range is " & sRange.Address)
Exit Sub
ErrorHandler:
MsgBox ("Cancel pressed")
End Sub
So, the question is how to detect either an error or StrPtr()=0 with an If statement?
This is a small example that will convert 'image.png' to 'image.jpg' at 70% image quality:
<?php
$image = imagecreatefrompng('image.png');
imagejpeg($image, 'image.jpg', 70);
imagedestroy($image);
?>
Hope that helps
The easiest and better way that worked for me was to apply height constraint to label and set the priority to low, i.e., (250) in storyboard.
So you need not worry about calculating the height and width programmatically, thanks to storyboard.
$(document).ready(function(){
var response;
$.validator.addMethod(
"uniqueUserName",
function(value, element) {
$.ajax({
type: "POST",
url: "http://"+location.host+"/checkUser.php",
data: "checkUsername="+value,
dataType:"html",
success: function(msg)
{
//If username exists, set response to true
response = ( msg == 'true' ) ? true : false;
}
});
return response;
},
"Username is Already Taken"
);
$("#regFormPart1").validate({
username: {
required: true,
minlength: 8,
uniqueUserName: true
},
messages: {
username: {
required: "Username is required",
minlength: "Username must be at least 8 characters",
uniqueUserName: "This Username is taken already"
}
}
});
});
One another point to note down is in MaxLength attribute you can only provide max required range not a min required range. While in StringLength you can provide both.
Too late but it could be helpful :
Go to Window Menu > Preferences > General > Appearance > Colors and Fonts
then go to Java > Java Editor Text Font > Edit
I fix my problem with javascript + HTML. First i check selected options and save its in a hidden field of my form:
for(i=0; i < form.select.options.length; i++)
if (form.select.options[i].selected)
form.hidden.value += form.select.options[i].value;
Next, i get by post that field and get all the string ;-) I hope it'll be work for somebody more. Thanks to all.
def isPrime(num,div=2):
if(num==div):
return True
elif(num % div == 0):
return False
else:
return isPrime(num,div+1)
==============================================
EDITED
def is_prime(num, div = 2):
if num == div: return True
elif num % div == 0: return False
elif num == 1: return False
else: return is_prime(num, div + 1)
Other than the given answers, in the case that you have something like this:
<div id="test">
<input type="file" name="file0" onchange="changed()">
</div>
<script type="text/javascript">
var isAllowed = true;
function changed()
{
if (isAllowed)
{
var tmpHTML = $('#test').html();
tmpHTML += "<input type=\"file\" name=\"file1\" onchange=\"changed()\">";
$('#test').html(tmpHTML);
isAllowed = false;
}
}
</script>
meaning that you want to automatically add one more file upload if any files were uploaded, the mentioned code will not work, because after the file is uploaded, the first file-upload element will be recreated and therefore the uploaded file will be wiped from it. You should use .append() instead:
function changed()
{
if (isAllowed)
{
var tmpHTML = "<input type=\"file\" name=\"file1\" onchange=\"changed()\">";
$('#test').append(tmpHTML);
isAllowed = false;
}
}
You could try a subquery:
SELECT DISTINCT TEST.* FROM (
SELECT rsc.RadioServiceCodeId,
rsc.RadioServiceCode + ' - ' + rsc.RadioService as RadioService
FROM sbi_l_radioservicecodes rsc
INNER JOIN sbi_l_radioservicecodegroups rscg ON rsc.radioservicecodeid = rscg.radioservicecodeid
WHERE rscg.radioservicegroupid IN
(select val from dbo.fnParseArray(@RadioServiceGroup,','))
OR @RadioServiceGroup IS NULL
ORDER BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService
) as TEST
In macOS try to restart postgresql database through the console using the command:
brew services restart postgresql
this error usually shows if the name of your struct is different from the initialization of your struct in the code, so normally, c will find the name of the struct you put and if the original struct is not found, this would usually appear, or if you point a pointer pointed into that pointer, the error will show up.
It is not necessary to change java as a String parameter. You have to change the c code to receive a String without a pointer and in its code:
Bool DmgrGetVersion (String szVersion);
Char NewszVersion [200];
Strcpy (NewszVersion, szVersion.t_str ());
.t_str () applies to builder c ++ 2010
No above answer resolve my issue. When i download xml it apppends <xml
to my xml. I simply
xml = parser.getXmlFromUrl(url);
xml = xml.substring(3);// it remove first three character from string,
now it is running accurately.
I get the same error in Chrome after pasting code copied from jsfiddle.
If you select all the code from a panel in jsfiddle and paste it into the free text editor Notepad++, you should be able to see the problem character as a question mark "?" at the very end of your code. Delete this question mark, then copy and paste the code from Notepad++ and the problem will be gone.
We can create a [debounce] directive which overwrites ngModel's default viewToModelUpdate function with an empty one.
Directive Code
@Directive({ selector: '[debounce]' })
export class MyDebounce implements OnInit {
@Input() delay: number = 300;
constructor(private elementRef: ElementRef, private model: NgModel) {
}
ngOnInit(): void {
const eventStream = Observable.fromEvent(this.elementRef.nativeElement, 'keyup')
.map(() => {
return this.model.value;
})
.debounceTime(this.delay);
this.model.viewToModelUpdate = () => {};
eventStream.subscribe(input => {
this.model.viewModel = input;
this.model.update.emit(input);
});
}
}
How to use it
<div class="ui input">
<input debounce [delay]=500 [(ngModel)]="myData" type="text">
</div>
insertion or shell sort!
You can't use text as a background image, but you can use the :before
or :after
pseudo classes to place a text character where you want it, without having to add all kinds of messy extra mark-up.
Be sure to set position:relative
on your actual text wrapper for the positioning to work.
.mytextwithicon {
position:relative;
}
.mytextwithicon:before {
content: "\25AE"; /* this is your text. You can also use UTF-8 character codes as I do here */
font-family: FontAwesome;
left:-5px;
position:absolute;
top:0;
}
EDIT:
Font Awesome v5 uses other font names than older versions:
font-family: "Font Awesome 5 Free"
font-family: "Font Awesome 5 Pro"
Note that you should set the same font-weight property, too (seems to be 900).
Another way to find the font name is to right click on a sample font awesome icon on your page and get the font name (same way the utf-8 icon code can be found, but note that you can find it out on :before
).
Like others have already said, it's not immediately obvious what you're asking. I'm going to assume that you want to start a process and then perform another action when the process "is ready".
Of course, the "is ready" is the tricky bit. Depending on what you're needs are, you may find that simply waiting is sufficient. However, if you need a more robust solution, you can consider using a named Mutex to control the control flow between your two processes.
For example, in your main process, you might create a named mutex and start a thread or task which will wait. Then, you can start the 2nd process. When that process decides that "it is ready", it can open the named mutex (you have to use the same name, of course) and signal to the first process.
You see the two empty -D
entries in the g++
command line? They're causing the problem. You must have values in the -D
items e.g. -DWIN32
if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:
SYSTEM ?= generic
ENVIRONMENT ?= generic
in the makefile which gives them default values.
Your output looks to be missing the all important output:
<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers
just to clarify, what actually got sent to g++
was -D -DWindows_NT
, i.e. define a preprocessor macro called -DWindows_NT
; which is of course not a valid identifier (similarly for -D -I.
)
Basic validation can be performed by choosing the type attribute of input elements. For example:
<input type="email" />
<input type="URL" />
<input type="number" />
using pattern attribute like:
<input type="text" pattern="[1-4]{5}" />
required attribute
<input type="text" required />
maxlength:
<input type="text" maxlength="20" />
min & max:
<input type="number" min="1" max="4" />
On (mostly) old processors, multiplying by 31 can be relatively cheap. On an ARM, for instance, it is only one instruction:
RSB r1, r0, r0, ASL #5 ; r1 := - r0 + (r0<<5)
Most other processors would require a separate shift and subtract instruction. However, if your multiplier is slow this is still a win. Modern processors tend to have fast multipliers so it doesn't make much difference, so long as 32 goes on the correct side.
It's not a great hash algorithm, but it's good enough and better than the 1.0 code (and very much better than the 1.0 spec!).
found it on this site, it works on me. Modify /res/values/styles.xml from:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
</style>
to:
<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
</style>
Service references deal with endpoints and bindings, which are completely configurable. They let you point your client proxy to a WCF via any transport protocol (HTTP, TCP, Shared Memory, etc)
They are designed to work with WCF.
If you use a WebProxy, you are pretty much binding yourself to using WCF over HTTP
You can refer below example for getting a comma separated string array from list.
Example:
List<string> testList= new List<string>();
testList.Add("Apple"); // Add string 1
testList.Add("Banana"); // 2
testList.Add("Mango"); // 3
testList.Add("Blue Berry"); // 4
testList.Add("Water Melon"); // 5
string JoinDataString = string.Join(",", testList.ToArray());
I use @Thiho answer but i get this error:
'git' is not recognized as an internal or external command
For solving that i use this steps:
I add the following paths to PATH:
C:\Program Files\Git\bin\
C:\Program Files\Git\cmd\
In windows 7:
Finally close and re-open your console.
if you just run the main.py
under the app
, just import like
from mymodule import myclass
if you want to call main.py
on other folder, use:
from .mymodule import myclass
for example:
+-- app
¦ +-- __init__.py
¦ +-- main.py
¦ +-- mymodule.py
+-- __init__.py
+-- run.py
main.py
from .mymodule import myclass
run.py
from app import main
print(main.myclass)
So I think the main question of you is how to call app.main
.
Uri.IsFile doesn't work with http urls. It only works for "file://". From MSDN : "The IsFile property is true when the Scheme property equals UriSchemeFile." So you can't depend on that.
Uri uri = new Uri(hreflink);
string filename = System.IO.Path.GetFileName(uri.LocalPath);
I tried changing year
to a different term, and it worked.
public_methods : {
get: function() {
return this._year;
},
set: function(newValue) {
if(newValue > this.originYear) {
this._year = newValue;
this.edition += newValue - this.originYear;
}
}
}
There is no need to use AS
, just use:
SELECT table1.price Table1 Price, table2.price Table2 Price, .....
I made a bash script, that given a number of parts as input, split a file
#!/bin/sh
parts_total="$2";
input="$1";
parts=$((parts_total))
for i in $(seq 0 $((parts_total-2))); do
lines=$(wc -l "$input" | cut -f 1 -d" ")
#n is rounded, 1.3 to 2, 1.6 to 2, 1 to 1
n=$(awk -v lines=$lines -v parts=$parts 'BEGIN {
n = lines/parts;
rounded = sprintf("%.0f", n);
if(n>rounded){
print rounded + 1;
}else{
print rounded;
}
}');
head -$n "$input" > split${i}
tail -$((lines-n)) "$input" > .tmp${i}
input=".tmp${i}"
parts=$((parts-1));
done
mv .tmp$((parts_total-2)) split$((parts_total-1))
rm .tmp*
I used head
and tail
commands, and store in tmp files, for split the files
#10 means 10 parts
sh mysplitXparts.sh input_file 10
or with awk, where 0.1 is 10% => 10 parts, or 0.334 is 3 parts
awk -v size=$(wc -l < input) -v perc=0.1 '{
nfile = int(NR/(size*perc));
if(nfile >= 1/perc){
nfile--;
}
print > "split_"nfile
}' input
You can use length to see if your selector matched anything.
if ($('#MyId').length) {
// do your stuff
}
I just wrote a simple zippy/collapsable using Angular using ng-show, ng-click and ng-init. Its implemented to one level but can be expanded to multiple levels easily.
Assign a boolean variable to ng-show and toggle it on click of header.
Check it out here
MySQL implicitly closed the database connection because the connection has been inactive for too long (34,247,052 milliseconds ˜ 9.5 hours).
If your program then fetches a bad connection from the connection-pool that causes the MySQLNonTransientConnectionException: No operations allowed after connection closed
.
MySQL suggests:
You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property
autoReconnect=true
to avoid this problem.
For me the following explanatory snippet worked. Perhaps you shouldn't use '
for header name?
{
headers: {
Authorization: "Basic " + getAuthDigest(),
Accept: "text/plain"
}
}
I'm using $http.ajax()
, though I wouldn't expect that to be a game changer.
For background images, make sure to use url()
node.backgroundImage = 'url(' + e.target.result + ')';
''.join([a, b]) is better solution than +.
Because Code should be written in a way that does not disadvantage other implementations of Python (PyPy, Jython, IronPython, Cython, Psyco, and such)
form a += b or a = a + b is fragile even in CPython and isn't present at all in implementations that don't use refcounting (reference counting is a technique of storing the number of references, pointers, or handles to a resource such as an object, block of memory, disk space or other resource)
https://www.python.org/dev/peps/pep-0008/#programming-recommendations
And if you just want to get the directory name and no need for the filename coming with it, then you can do that in the following conventional way using os
Python module.
>>> import os
>>> f = open('/Users/Desktop/febROSTER2012.xls')
>>> os.path.dirname(f.name)
>>> '/Users/Desktop/'
This way you can get hold of the directory structure.
You can get the favicon URL from the website's HTML.
Here is the favicon
element:
<link rel="icon" type="image/png" href="/someimage.png" />
You should use a regular expression here. If no tag found, look for favicon.ico
in the site root directory. If nothing found, the site does not have a favicon.
Everyone else's method doesn't account for whitespaces. Obviously nobody really considers a whitespace a special character.
Use this method to detect special characters not including whitespaces:
import re
def detect_special_characer(pass_string):
regex= re.compile('[@_!#$%^&*()<>?/\|}{~:]')
if(regex.search(pass_string) == None):
res = False
else:
res = True
return(res)
in Swift 3.0 or Later
passwordTextField.isSecureTextEntry = true
Since NumPy version 1.16, for more details see GitHub ticket 12251.
from sys import maxsize
from numpy import set_printoptions
set_printoptions(threshold=maxsize)
My favorite way to do this is with an extension function called 'Map':
public static void Map<T>(this IEnumerable<T> source, Action<T> func)
{
foreach (T i in source)
func(i);
}
Then you can add all the rows like so:
X.Map(item => this.dataGridView1.Rows.Add(item.ID, item.Name));
They're faster; unless you're loading the entire flat file into memory, a database will allow faster access in almost all cases.
They're safer; databases are easier to safely backup; they have mechanisms to check for file corruption, which flat files do not. Once corruption in your flat file migrates to your backups, you're done, and you might not even know it yet.
They have more features; databases can allow many users to read/write at the same time.
They're much less complex to work with, once they're setup.
The language itself doesn't support this, but sometimes this is still a useful requirement. Besides the Bunch recipe, you can also write a little method which can access a dictionary using a dotted string:
def get_var(input_dict, accessor_string):
"""Gets data from a dictionary using a dotted accessor-string"""
current_data = input_dict
for chunk in accessor_string.split('.'):
current_data = current_data.get(chunk, {})
return current_data
which would support something like this:
>> test_dict = {'thing': {'spam': 12, 'foo': {'cheeze': 'bar'}}}
>> output = get_var(test_dict, 'thing.spam.foo.cheeze')
>> print output
'bar'
>>
angular.module('myApp').controller('myCtrl', function($scope, $rootScope) {
var a = //something in the scope
//put it in the root scope
$rootScope.test = "TEST";
});
angular.module('myApp').controller('myCtrl2', function($scope, $rootScope) {
var b = //get var a from root scope somehow
//use var b
$scope.value = $rootScope.test;
alert($scope.value);
// var b = $rootScope.test;
// alert(b);
});
If you're interested in the physical RAM, use the command dmidecode
. It gives you a lot more information than just that, but depending on your use case, you might also want to know if the 8G in the system come from 2x4GB sticks or 4x2GB sticks.
Using LINQ to xml if you are using framework 3.5:
using System.Xml.Linq;
XDocument xmlFile = XDocument.Load("books.xml");
var query = from c in xmlFile.Elements("catalog").Elements("book")
select c;
foreach (XElement book in query)
{
book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");
JNDI needs to be approached with the understanding that it is a service locator. When the desired service is hosted on the same server/node as the application, then your use of InitialContext may work.
What makes it more complicated is that defining a Data Source in Web Sphere (at least back in 4.0) allowed you to define the visibility to various degrees. Basically it adds namespaces to the environment and clients have to know where the resource is hosted.
javax.naming.InitialContext ctx = new javax.naming.InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/DataSourceAlias");
Here is IBM's reference page.
If you are trying to reference a data source from an app that is NOT in the J2EE container, you'll need a slightly different approach starting with needing some J2EE client jars in your classpath. http://www.coderanch.com/t/75386/Websphere/lookup-datasources-JNDI-outside-EE
Be sure to include the Key
in the imports...
const {Builder, By, logging, until, Key} = require('selenium-webdriver');
searchInput.sendKeys(Key.ENTER)
worked great for me
Other answers already pointed out that the representation of floating numbers is a thorny issue, to say the least.
Since you don't give enough context in your question, I cannot know if the decimal module can be useful for your needs:
http://docs.python.org/library/decimal.html
Among other things you can explicitly specify the precision that you wish to obtain (from the docs):
>>> getcontext().prec = 6
>>> Decimal('3.0')
Decimal('3.0')
>>> Decimal('3.1415926535')
Decimal('3.1415926535')
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987')
>>> getcontext().rounding = ROUND_UP
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85988')
A simple example from my prompt (python 2.6):
>>> import decimal
>>> a = decimal.Decimal('10.000000001')
>>> a
Decimal('10.000000001')
>>> print a
10.000000001
>>> b = decimal.Decimal('10.00000000000000000000000000900000002')
>>> print b
10.00000000000000000000000000900000002
>>> print str(b)
10.00000000000000000000000000900000002
>>> len(str(b/decimal.Decimal('3.0')))
29
Maybe this can help? decimal is in python stdlib since 2.4, with additions in python 2.6.
Hope this helps, Francesco
You could also add listener from XML layout: android:onClick="onRadioButtonClicked"
in your <RadioButton/>
tag.
<RadioButton android:id="@+id/radio_pirates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/pirates"
android:onClick="onRadioButtonClicked"/>
See Android developer SDK- Radio Buttons for details.
select distinct owner
from dba_segments
where owner in (select username from dba_users where default_tablespace not in ('SYSTEM','SYSAUX'));
public MainWindow()
{
// This button needs to exist on your form.
myButton.Click += myButton_Click;
}
void myButton_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Message here");
this.Close();
}
Only two Semicolons are allowed to be used in for
loop.
If you have do initialization of multiple variables or manipulation of multiple variables, you can achieve it by separating them with comma(,).
for(int i=0, j=5; i < 5; i++, j--)
NOTE: Multiple conditions separated by comma are NOT allowed.
for(int i=0, j=5; i < 5, j > 5; i++, j--) // This is NOT allowed.
In the RatingBar
tag, add these two lines
style="@style/Widget.AppCompat.RatingBar.Small"
android:isIndicator="false"
You might looking for the placeholder
attribute which will display a grey text in the input field while empty.
From Mozilla Developer Network:
A hint to the user of what can be entered in the control . The placeholder text must not contain carriage returns or line-feeds. This attribute applies when the value of the type attribute is text, search, tel, url or email; otherwise it is ignored.
However as it's a fairly 'new' tag (from the HTML5 specification afaik) you might want to to browser testing to make sure your target audience is fine with this solution.
(If not tell tell them to upgrade browser 'cause this tag works like a charm ;o) )
And finally a mini-fiddle to see it directly in action: http://jsfiddle.net/LnU9t/
Edit: Here is a plain jQuery solution which will also clear the input field if an escape keystroke is detected: http://jsfiddle.net/3GLwE/
I actually got fed up by the lack of standard MIME sniffing methods in PHP. Install fileinfo... Use deprecated functions... Oh these work, but only for images! I got fed up of it, so I did some research and found the WHATWG Mimesniffing spec - I believe this is still a draft spec though.
Anyway, using this specification, I was able to implement a mimesniffer in PHP. Performance is not an issue. In fact on my humble machine, I was able to open and sniff thousands of files before PHP timed out.
Here is the MimeReader class.
require_once("MimeReader.php");
$mime = new MimeReader(<YOUR FILE PATH>);
$mime_type_string = $mime->getType(); // "image/jpeg" etc.
the only thing that worked for me was to run pod deintegrate
and pod install
SELECT * FROM items WHERE `items.xml` LIKE '%123456%'
The %
operator in LIKE
means "anything can be here".
Maven way
If you use Maven, you can run the following command to run all your test cases:
mvn clean test
Or you can run a particular test as below
mvn clean test -Dtest=your.package.TestClassName
mvn clean test -Dtest=your.package.TestClassName#particularMethod
If you would like to see the stack trace (if any) in the console instead of report files in the target\surefire-reports folder, set the user property surefire.useFile to false. For example:
mvn clean test -Dtest=your.package.TestClassName -Dsurefire.useFile=false
Gradle way
If you use Gradle, you can run the following command to run all your test cases:
gradle test
Or you can run a particular test as below
gradle test --tests your.package.TestClassName
gradle test --tests your.package.TestClassName.particularMethod
If you would like more information, you can consider options such as --stacktrace, or --info, or --debug.
For example, when you run Gradle with the info logging level --info, it will show you the result of each test while they are running. If there is any exception, it will show you the stack trace, pointing out what the problem is.
gradle test --info
If you would like to see the overall test results, you can open the report in the browser, for example (Open it using Google Chrome in Ubuntu):
google-chrome build/reports/tests/index.html
Ant way
Once you set up your Ant build file build.xml, you can run your JUnit test cases from the command line as below:
ant -f build.xml <Your JUnit test target name>
You can follow the link below to read more about how to configure JUnit tests in the Ant build file: https://ant.apache.org/manual/Tasks/junit.html
Normal way
If you do not use Maven, or Gradle or Ant, you can follow the following way:
First of all, you need to compile your test cases. For example (in Linux):
javac -d /absolute/path/for/compiled/classes -cp /absolute/path/to/junit-4.12.jar /absolute/path/to/TestClassName.java
Then run your test cases. For example:
java -cp /absolute/path/for/compiled/classes:/absolute/path/to/junit-4.12.jar:/absolute/path/to/hamcrest-core-1.3.jar org.junit.runner.JUnitCore your.package.TestClassName
Using CROSS APPLY
:
SELECT ID, Col1, Col2, Col3, MinValue
FROM YourTable
CROSS APPLY (SELECT MIN(d) AS MinValue FROM (VALUES (Col1), (Col2), (Col3)) AS a(d)) A
Tried in Hive and got the below output
table1
1,wqe,chennai,india
2,stu,salem,india
3,mia,bangalore,india
4,yepie,newyork,USA
table2
1,wqe,chennai,india
2,stu,salem,india
3,mia,bangalore,india
5,chapie,Los angels,USA
Inner Join
SELECT * FROM table1 INNER JOIN table2 ON (table1.id = table2.id);
1 wqe chennai india 1 wqe chennai india
2 stu salem india 2 stu salem india
3 mia bangalore india 3 mia bangalore india
Left Join
SELECT * FROM table1 LEFT JOIN table2 ON (table1.id = table2.id);
1 wqe chennai india 1 wqe chennai india
2 stu salem india 2 stu salem india
3 mia bangalore india 3 mia bangalore india
4 yepie newyork USA NULL NULL NULL NULL
Left Semi Join
SELECT * FROM table1 LEFT SEMI JOIN table2 ON (table1.id = table2.id);
1 wqe chennai india
2 stu salem india
3 mia bangalore india
note: Only records in left table are displayed whereas for Left Join both the table records displayed
danorton solution didn't work for me. I had some really weird problems where webkit wouldn't draw some elements at all; where text in inputs wasn't updated until onblur; and changing className would not result in a redraw.
My solution, I accidentally discovered, was to add a empty style element to the body, after the script.
<body>
...
<script>doSomethingThatWebkitWillMessUp();</script>
<style></style>
...
That fixed it. How weird is that? Hope this is helpful for someone.
You can pass any command-line argument without additional plugins using --env
since webpack 2:
webpack --config webpack.config.js --env.foo=bar
Using the variable in webpack.config.js:
module.exports = function(env) {
if (env.foo === 'bar') {
// do something
}
}
If you are using JPA to hibernate make sure the Entity has the correct data type for a field defined against a date column like use java.util.Date instead of String.
You can make your code simpler and more readable like this
bad_words = ['bad', 'naughty']
with open('oldfile.txt') as oldfile, open('newfile.txt', 'w') as newfile:
for line in oldfile:
if not any(bad_word in line for bad_word in bad_words):
newfile.write(line)
using a Context Manager and any.
File Path Seems to be an issue here please make sure that file exists in the correct directory or give the absolute path to make sure that you are pointing to a correct file. Please log the file.getAbsolutePath() to verify that file is correct.
Try this one,
{
"address": "colombo",
"username": "hesh",
"password": "123",
"registetedDate": "2015-4-3",
"firstname": "hesh",
"contactNo": "07762",
"accountNo": "16161",
"lastName": "jay",
"skill":[1436517454492,1436517476993]
}
You can use the JSON stringify
method.
JSON.stringify({x: 5, y: 6}); // '{"x":5,"y":6}' or '{"y":6,"x":5}'
There is pretty good support for this across the board when it comes to browsers, as shown on http://caniuse.com/#search=JSON. You will note, however, that versions of IE earlier than 8 do not support this functionality natively.
If you wish to cater to those users as well you will need a shim. Douglas Crockford has provided his own JSON Parser on github.
CREATE TABLE `table2` LIKE `table1`;
INSERT INTO `table2` SELECT * FROM `table1`;
the first query will create the structure from table1
to table2
and second query will put the data from table1
to table2
You have different line endings in the example texts in Debuggex. What is especially interesting is that Debuggex seems to have identified which line ending style you used first, and it converts all additional line endings entered to that style.
I used Notepad++ to paste sample text in Unix and Windows format into Debuggex, and whichever I pasted first is what that session of Debuggex stuck with.
So, you should wash your text through your text editor before pasting it into Debuggex. Ensure that you're pasting the style you want. Debuggex defaults to Unix style (\n).
Also, NEL (\u0085) is something different entirely: https://en.wikipedia.org/wiki/Newline#Unicode
(\r?\n)
will cover Unix and Windows. You'll need something more complex, like (\r\n|\r|\n)
, if you want to match old Mac too.
The most accepted answers don't work when zooming in Google Chrome on Android. In combination with Dan's answer, to account for Chrome on Android, visualViewport must be used. The following example only takes the vertical check into account and uses jQuery for the window height:
var Rect = YOUR_ELEMENT.getBoundingClientRect();
var ElTop = Rect.top, ElBottom = Rect.bottom;
var WindowHeight = $(window).height();
if(window.visualViewport) {
ElTop -= window.visualViewport.offsetTop;
ElBottom -= window.visualViewport.offsetTop;
WindowHeight = window.visualViewport.height;
}
var WithinScreen = (ElTop >= 0 && ElBottom <= WindowHeight);
There is a more concise and intuitive way to add days to php date. Don't get me wrong, those php expressions are great, but you always have to google how to treat them. I miss auto-completion facility for that.
Here is how I like to handle those cases:
(new Future(
new DateTimeFromISO8601String('2014-11-21T06:04:31.321987+00:00'),
new OneDay()
))
->value();
For me, it's way more intuitive and autocompletion works out of the box. No need to google for the solution each time.
As a nice bonus, you don't have to worry about formatting the resulting value, it's already is ISO8601 format.
This is meringue library, there are more examples here.
Verified the following on Virtualbox-5.0.24, Android_x86-4.4-r5. You get a screen similar to an 8" table. You can play around with the xxx in DPI=xxx, to change the resolution. xxx=100 makes it really small to match a real table exactly, but it may be too small when working with android in Virtualbox.
VBoxManage setextradata <VmName> "CustomVideoMode1" "440x680x16"
With the following appended to android kernel cmd:
UVESA_MODE=440x680 DPI=120
change this {% if loop.counter == 1 %}
to {% if forloop.counter == 1 %} {#your code here#} {%endfor%}
and this from {{ user }} {{loop.counter}}
to {{ user }} {{forloop.counter}}
Hello to everybody I did this and it worked well
var canvas, ctx;_x000D_
_x000D_
function init() {_x000D_
canvas = document.getElementById('color');_x000D_
ctx = canvas.getContext('2d');_x000D_
_x000D_
ctx.save();_x000D_
ctx.fillStyle = '#bfbfbf'; // #00843D // 118846_x000D_
ctx.fillRect(0, 0, 490, 490);_x000D_
ctx.restore();_x000D_
}
_x000D_
section{_x000D_
height: 400px;_x000D_
background: url(https://images.pexels.com/photos/265087/pexels-photo-265087.jpeg?w=1260&h=750&auto=compress&cs=tinysrgb);_x000D_
background-repeat: no-repeat;_x000D_
background-position: center;_x000D_
background-size: cover;_x000D_
position: relative;_x000D_
_x000D_
}_x000D_
_x000D_
canvas {_x000D_
width: 100%;_x000D_
height: 400px;_x000D_
opacity: 0.9;_x000D_
_x000D_
}_x000D_
_x000D_
#text {_x000D_
position: absolute;_x000D_
top: 10%;_x000D_
left: 0;_x000D_
width: 100%;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
_x000D_
.middle{_x000D_
text-align: center;_x000D_
_x000D_
}_x000D_
_x000D_
section small{_x000D_
background-color: #262626;_x000D_
padding: 12px;_x000D_
color: whitesmoke;_x000D_
letter-spacing: 1.5px;_x000D_
_x000D_
}_x000D_
_x000D_
section i{_x000D_
color: white;_x000D_
background-color: grey;_x000D_
}_x000D_
_x000D_
section h1{_x000D_
opacity: 0.8;_x000D_
}
_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<title>Metrics</title>_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"> _x000D_
</head> _x000D_
_x000D_
<body onload="init();">_x000D_
<section>_x000D_
<canvas id="color"></canvas>_x000D_
_x000D_
<div class="w3-container middle" id="text">_x000D_
<i class="material-icons w3-highway-blue" style="font-size:60px;">assessment</i>_x000D_
<h1>Medimos las acciones de tus ventas y disenamos en la WEB tu Marca.</h1>_x000D_
<small>Metrics & WEB</small>_x000D_
</div>_x000D_
</section>
_x000D_
Try using dynamic SQL:
create procedure sp_First @columnname varchar
AS
begin
declare @sql nvarchar(4000);
set @sql='select ['+@columnname+'] from Table_1';
exec sp_executesql @sql
end
go
exec sp_First 'sname'
go
I would prefere
if (!myStr.empty())
{
//do something
}
Also you don't have to write std::string a = "";
. You can just write std::string a;
- it will be empty by default
To prevent the records with Empty
or Null
value in SQL result
we can simply add ..... WHERE Column_name != '' or 'null'
Object.create(Constructor.prototype)
is the part of new Constructor
new Constructor
implementation// 1. define constructor function
function myConstructor(name, age) {
this.name = name;
this.age = age;
}
myConstructor.prototype.greet = function(){
console.log(this.name, this.age)
};
// 2. new operator implementation
let newOperatorWithConstructor = function(name, age) {
const newInstance = new Object(); // empty object
Object.setPrototypeOf(newInstance, myConstructor.prototype); // set prototype
const bindedConstructor = myConstructor.bind(newInstance); // this binding
bindedConstructor(name, age); // execute binded constructor function
return newInstance; // return instance
};
// 3. produce new instance
const instance = new myConstructor("jun", 28);
const instance2 = newOperatorWithConstructor("jun", 28);
console.log(instance);
console.log(instance2);
new Constructor
implementation contains Object.create
method newOperatorWithConstructor = function(name, age) {
const newInstance = Object.create(myConstructor.prototype); // empty object, prototype chaining
const bindedConstructor = myConstructor.bind(newInstance); // this binding
bindedConstructor(name, age); // execute binded constructor function
return newInstance; // return instance
};
console.log(newOperatorWithConstructor("jun", 28));
Django has some documentation about that on their website, see: Saving changes to objects. To summarize:
.. to save changes to an object that's already in the database, use
save()
.
My situation was that I did not have a main function.
This will do it in SQL Server:
DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+',' ,'') + Convert(nvarchar(8),DepartmentId)
FROM Table
SELECT @listStr
A quick googling on "perl high resolution timers" gave a reference to Time::HiRes. Maybe that it what you want.
I had the same issue when I copy-pasted
the command. Instead, when I typed-in the entire command, it worked!
Good Luck...
It's already 2019, I can't believe still no easiest and conveniencest way to convert the most popular Micro$oft Word document to Adobe PDF format in Java world.
I almost tried every method the above answers mentioned, and I found the best and the only way can satisfy my requirement is by using OpenOffice or LibreOffice. Actually I am not exactly know the difference between them, seems both of them provide soffice
command line.
My requirement is:
First thing came in mind is doc-to-pdf-converter
, but it lacks of maintenance, last update happened 4 years ago, I will not use a nobody-maintain-solution. Xdocreport
seems a promising choice, but it can only convert docx
, but not doc
binary file which is mandatory for me. Using Java to call OpenOffice API seems good, but too complicated for such a simple requirement.
Finally I found the best solution: use OpenOffice command line to finish the job:
Runtime.getRuntime().exec("soffice --convert-to pdf -outdir . /path/some.doc");
I always believe the shortest code is the best code (of course it should be understandable), that's it.
I found a faster way of embedding:
The declaration and initialization
char *array = "One good thing about music";
declares a pointer array
and make it point to a constant array of 31 characters.
The declaration and initialization
char array[] = "One, good, thing, about, music";
declares an array of characters, containing 31 characters.
And yes, the size of the arrays is 31, as it includes the terminating '\0'
character.
Laid out in memory, it will be something like this for the first:
+-------+ +------------------------------+ | array | --> | "One good thing about music" | +-------+ +------------------------------+
And like this for the second:
+------------------------------+ | "One good thing about music" | +------------------------------+
Arrays decays to pointers to the first element of an array. If you have an array like
char array[] = "One, good, thing, about, music";
then using plain array
when a pointer is expected, it's the same as &array[0]
.
That mean that when you, for example, pass an array as an argument to a function it will be passed as a pointer.
Pointers and arrays are almost interchangeable. You can not, for example, use sizeof(pointer)
because that returns the size of the actual pointer and not what it points to. Also when you do e.g. &pointer
you get the address of the pointer, but &array
returns a pointer to the array. It should be noted that &array
is very different from array
(or its equivalent &array[0]
). While both &array
and &array[0]
point to the same location, the types are different. Using the arrat above, &array
is of type char (*)[31]
, while &array[0]
is of type char *
.
For more fun: As many knows, it's possible to use array indexing when accessing a pointer. But because arrays decays to pointers it's possible to use some pointer arithmetic with arrays.
For example:
char array[] = "Foobar"; /* Declare an array of 7 characters */
With the above, you can access the fourth element (the 'b
' character) using either
array[3]
or
*(array + 3)
And because addition is commutative, the last can also be expressed as
*(3 + array)
which leads to the fun syntax
3[array]
You're almost all the way there.
Your first few lines, comparing the last name, are right on track. The compareTo() method on string will return a negative number for a string in alphabetical order before, and a positive number for one in alphabetical order after.
Now, you just need to do the same thing for your first name and score.
In other words, if Last Name 1 == Last Name 2, go on a check your first name next. If the first name is the same, check your score next. (Think about nesting your if/then blocks.)
import React from 'react';
class RentalHome extends React.Component{
constructor(){
super();
this.state = {
rentals:[{
_id: 1,
title: "Nice Shahghouse Biryani",
city: "Hyderabad",
category: "condo",
image: "http://via.placeholder.com/350x250",
numOfRooms: 4,
shared: true,
description: "Very nice apartment in center of the city.",
dailyPrice: 43
},
{
_id: 2,
title: "Modern apartment in center",
city: "Bangalore",
category: "apartment",
image: "http://via.placeholder.com/350x250",
numOfRooms: 1,
shared: false,
description: "Very nice apartment in center of the city.",
dailyPrice: 11
},
{
_id: 3,
title: "Old house in nature",
city: "Patna",
category: "house",
image: "http://via.placeholder.com/350x250",
numOfRooms: 5,
shared: true,
description: "Very nice apartment in center of the city.",
dailyPrice: 23
}]
}
}
render(){
const {rentals} = this.state;
return(
<div className="card-list">
<div className="container">
<h1 className="page-title">Your Home All Around the World</h1>
<div className="row">
{
rentals.map((rental)=>{
return(
<div key={rental._id} className="col-md-3">
<div className="card bwm-card">
<img
className="card-img-top"
src={rental.image}
alt={rental.title} />
<div className="card-body">
<h6 className="card-subtitle mb-0 text-muted">
{rental.shared} {rental.category} {rental.city}
</h6>
<h5 className="card-title big-font">
{rental.title}
</h5>
<p className="card-text">
${rental.dailyPrice} per Night · Free Cancelation
</p>
</div>
</div>
</div>
)
})
}
</div>
</div>
</div>
)
}
}
export default RentalHome;
While applying the new profile to the user,you should also check for resource limits are "turned on" for the database as a whole i.e.RESOURCE_LIMIT = TRUE
Let check the parameter value.
If in Case it is :
SQL> show parameter resource_limit
NAME TYPE VALUE
------------------------------------ ----------- ---------
resource_limit boolean FALSE
Its mean resource limit is off,we ist have to enable it.
Use the ALTER SYSTEM statement to turn on resource limits.
SQL> ALTER SYSTEM SET RESOURCE_LIMIT = TRUE;
System altered.
I prefer NumPy because of speed.
import numpy as np
# Find all prime numbers using Sieve of Eratosthenes
def get_primes1(n):
m = int(np.sqrt(n))
is_prime = np.ones(n, dtype=bool)
is_prime[:2] = False # 0 and 1 are not primes
for i in range(2, m):
if is_prime[i] == False:
continue
is_prime[i*i::i] = False
return np.nonzero(is_prime)[0]
# Find all prime numbers using brute-force.
def isprime(n):
''' Check if integer n is a prime '''
n = abs(int(n)) # n is a positive integer
if n < 2: # 0 and 1 are not primes
return False
if n == 2: # 2 is the only even prime number
return True
if not n & 1: # all other even numbers are not primes
return False
# Range starts with 3 and only needs to go up the square root
# of n for all odd numbers
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
# To apply a function to a numpy array, one have to vectorize the function
def get_primes2(n):
vectorized_isprime = np.vectorize(isprime)
a = np.arange(n)
return a[vectorized_isprime(a)]
Check the output:
n = 100
print(get_primes1(n))
print(get_primes2(n))
[ 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97]
[ 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97]
Compare the speed of Sieve of Eratosthenes and brute-force on Jupyter Notebook. Sieve of Eratosthenes in 539 times faster than brute-force for million elements.
%timeit get_primes1(1000000)
%timeit get_primes2(1000000)
4.79 ms ± 90.3 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.58 s ± 31.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
word
is on the stack and goes out of scope as soon as getStr()
returns. You are invoking undefined behavior.
Here's this exact same question elsewhere, that includes a more robust equals
, hash
that maerics alludes to:
That discussion goes on to mirror the maerics vs ColinD approaches of "should I re-use a class Tuple with an unspecific name, or make a new class with specific names each time I encounter this situation". Years ago I was in the latter camp; I've evolved into supporting the former.
Those are Java varargs. They let you pass any number of objects of a specific type (in this case they are of type JID).
In your example, the following function calls would be valid:
MessageBuilder msgBuilder; //There should probably be a call to a constructor here ;)
MessageBuilder msgBuilder2;
msgBuilder.withRecipientJids(jid1, jid2);
msgBuilder2.withRecipientJids(jid1, jid2, jid78_a, someOtherJid);
See more here: http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html
The results of the test and source code are below (you can set the number of iterations in the app). The time is in milliseconds, and each entry is an average result of running the test 5-10 times. I found that generally it is accurate to 2-3 significant digits and after that it would vary with each run. That gives a margin of error of less than 1%. The test was running on an iPhone 3G as that's the target platform I was interested in.
numberOfItems NSArray (ms) C Array (ms) Ratio
100 0.39 0.0025 156
191 0.61 0.0028 218
3,256 12.5 0.026 481
4,789 16 0.037 432
6,794 21 0.050 420
10,919 36 0.081 444
19,731 64 0.15 427
22,030 75 0.162 463
32,758 109 0.24 454
77,969 258 0.57 453
100,000 390 0.73 534
The classes provided by Cocoa for handling data sets (NSDictionary, NSArray, NSSet etc.) provide a very nice interface for managing information, without having to worry about the bureaucracy of memory management, reallocation etc. Of course this does come at a cost though. I think it's pretty obvious that say using an NSArray of NSNumbers is going to be slower than a C Array of floats for simple iterations, so I decided to do some tests, and the results were pretty shocking! I wasn't expecting it to be this bad. Note: these tests are conducted on an iPhone 3G as that's the target platform I was interested in.
In this test I do a very simple random access performance comparison between a C float* and NSArray of NSNumbers
I create a simple loop to sum up the contents of each array and time them using mach_absolute_time(). The NSMutableArray takes on average 400 times longer!! (not 400 percent, just 400 times longer! thats 40,000% longer!).
Header:
// Array_Speed_TestViewController.h
// Array Speed Test
// Created by Mehmet Akten on 05/02/2009.
// Copyright MSA Visuals Ltd. 2009. All rights reserved.
#import <UIKit/UIKit.h>
@interface Array_Speed_TestViewController : UIViewController {
int numberOfItems; // number of items in array
float *cArray; // normal c array
NSMutableArray *nsArray; // ns array
double machTimerMillisMult; // multiplier to convert mach_absolute_time() to milliseconds
IBOutlet UISlider *sliderCount;
IBOutlet UILabel *labelCount;
IBOutlet UILabel *labelResults;
}
-(IBAction) doNSArray:(id)sender;
-(IBAction) doCArray:(id)sender;
-(IBAction) sliderChanged:(id)sender;
@end
Implementation:
// Array_Speed_TestViewController.m
// Array Speed Test
// Created by Mehmet Akten on 05/02/2009.
// Copyright MSA Visuals Ltd. 2009. All rights reserved.
#import "Array_Speed_TestViewController.h"
#include <mach/mach.h>
#include <mach/mach_time.h>
@implementation Array_Speed_TestViewController
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
NSLog(@"viewDidLoad");
[super viewDidLoad];
cArray = NULL;
nsArray = NULL;
// read initial slider value setup accordingly
[self sliderChanged:sliderCount];
// get mach timer unit size and calculater millisecond factor
mach_timebase_info_data_t info;
mach_timebase_info(&info);
machTimerMillisMult = (double)info.numer / ((double)info.denom * 1000000.0);
NSLog(@"machTimerMillisMult = %f", machTimerMillisMult);
}
// pass in results of mach_absolute_time()
// this converts to milliseconds and outputs to the label
-(void)displayResult:(uint64_t)duration {
double millis = duration * machTimerMillisMult;
NSLog(@"displayResult: %f milliseconds", millis);
NSString *str = [[NSString alloc] initWithFormat:@"%f milliseconds", millis];
[labelResults setText:str];
[str release];
}
// process using NSArray
-(IBAction) doNSArray:(id)sender {
NSLog(@"doNSArray: %@", sender);
uint64_t startTime = mach_absolute_time();
float total = 0;
for(int i=0; i<numberOfItems; i++) {
total += [[nsArray objectAtIndex:i] floatValue];
}
[self displayResult:mach_absolute_time() - startTime];
}
// process using C Array
-(IBAction) doCArray:(id)sender {
NSLog(@"doCArray: %@", sender);
uint64_t start = mach_absolute_time();
float total = 0;
for(int i=0; i<numberOfItems; i++) {
total += cArray[i];
}
[self displayResult:mach_absolute_time() - start];
}
// allocate NSArray and C Array
-(void) allocateArrays {
NSLog(@"allocateArrays");
// allocate c array
if(cArray) delete cArray;
cArray = new float[numberOfItems];
// allocate NSArray
[nsArray release];
nsArray = [[NSMutableArray alloc] initWithCapacity:numberOfItems];
// fill with random values
for(int i=0; i<numberOfItems; i++) {
// add number to c array
cArray[i] = random() * 1.0f/(RAND_MAX+1);
// add number to NSArray
NSNumber *number = [[NSNumber alloc] initWithFloat:cArray[i]];
[nsArray addObject:number];
[number release];
}
}
// callback for when slider is changed
-(IBAction) sliderChanged:(id)sender {
numberOfItems = sliderCount.value;
NSLog(@"sliderChanged: %@, %i", sender, numberOfItems);
NSString *str = [[NSString alloc] initWithFormat:@"%i items", numberOfItems];
[labelCount setText:str];
[str release];
[self allocateArrays];
}
//cleanup
- (void)dealloc {
[nsArray release];
if(cArray) delete cArray;
[super dealloc];
}
@end
From : memo.tv
////////////////////
Available since the introduction of blocks, this allows to iterate an array with blocks. Its syntax isn't as nice as fast enumeration, but there is one very interesting feature: concurrent enumeration. If enumeration order is not important and the jobs can be done in parallel without locking, this can provide a considerable speedup on a multi-core system. More about that in the concurrent enumeration section.
[myArray enumerateObjectsUsingBlock:^(id object, NSUInteger index, BOOL *stop) {
[self doSomethingWith:object];
}];
[myArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[self doSomethingWith:object];
}];
/////////// NSFastEnumerator
The idea behind fast enumeration is to use fast C array access to optimize iteration. Not only is it supposed to be faster than traditional NSEnumerator, but Objective-C 2.0 also provides a very concise syntax.
id object;
for (object in myArray) {
[self doSomethingWith:object];
}
/////////////////
NSEnumerator
This is a form of external iteration: [myArray objectEnumerator] returns an object. This object has a method nextObject that we can call in a loop until it returns nil
NSEnumerator *enumerator = [myArray objectEnumerator];
id object;
while (object = [enumerator nextObject]) {
[self doSomethingWith:object];
}
/////////////////
objectAtIndex: enumeration
Using a for loop which increases an integer and querying the object using [myArray objectAtIndex:index] is the most basic form of enumeration.
NSUInteger count = [myArray count];
for (NSUInteger index = 0; index < count ; index++) {
[self doSomethingWith:[myArray objectAtIndex:index]];
}
////////////// From : darkdust.net
Try this > Bootstrap 3
Brilliant exacly what I was looking for, however I had some clashes with the javascript and the bootstrap modal, this fixed it.
$(function() {
$('.navbar-nav').on('click', function(){
if($('.navbar-header .navbar-toggle').css('display') !='none'){
$(".navbar-header .navbar-toggle").trigger( "click" );
}
});
});
Hope this helps.
You dont need absolute positioning Use
p {
text-align: center;
line-height: 100px;
}
And adjust at will...
If text exceeds width and goes more than one line
In that case the adjust you can do is to include the display property in your rules as follows;
(I added a background for a better view of the example)
div
{
width:300px;
height:100px;
display: table;
background:#ccddcc;
}
p {
text-align:center;
vertical-align: middle;
display: table-cell;
}
Play with it in this JBin
simply used the +
operator. Javascript concats strings with +
Just some examples on usage of array_split
, split
, hsplit
and vsplit
:
n [9]: a = np.random.randint(0,10,[4,4])
In [10]: a
Out[10]:
array([[2, 2, 7, 1],
[5, 0, 3, 1],
[2, 9, 8, 8],
[5, 7, 7, 6]])
Some examples on using array_split
:
If you give an array or list as second argument you basically give the indices (before) which to 'cut'
# split rows into 0|1 2|3
In [4]: np.array_split(a, [1,3])
Out[4]:
[array([[2, 2, 7, 1]]),
array([[5, 0, 3, 1],
[2, 9, 8, 8]]),
array([[5, 7, 7, 6]])]
# split columns into 0| 1 2 3
In [5]: np.array_split(a, [1], axis=1)
Out[5]:
[array([[2],
[5],
[2],
[5]]),
array([[2, 7, 1],
[0, 3, 1],
[9, 8, 8],
[7, 7, 6]])]
An integer as second arg. specifies the number of equal chunks:
In [6]: np.array_split(a, 2, axis=1)
Out[6]:
[array([[2, 2],
[5, 0],
[2, 9],
[5, 7]]),
array([[7, 1],
[3, 1],
[8, 8],
[7, 6]])]
split
works the same but raises an exception if an equal split is not possible
In addition to array_split
you can use shortcuts vsplit
and hsplit
.
vsplit
and hsplit
are pretty much self-explanatry:
In [11]: np.vsplit(a, 2)
Out[11]:
[array([[2, 2, 7, 1],
[5, 0, 3, 1]]),
array([[2, 9, 8, 8],
[5, 7, 7, 6]])]
In [12]: np.hsplit(a, 2)
Out[12]:
[array([[2, 2],
[5, 0],
[2, 9],
[5, 7]]),
array([[7, 1],
[3, 1],
[8, 8],
[7, 6]])]
You need to use ScriptManager.RegisterStartupScript for Ajax.
protected void ButtonPP_Click(object sender, EventArgs e) { if (radioBtnACO.SelectedIndex < 0) { string csname1 = "PopupScript"; var cstext1 = new StringBuilder(); cstext1.Append("alert('Please Select Criteria!')"); ScriptManager.RegisterStartupScript(this, GetType(), csname1, cstext1.ToString(), true); } }
Assuming you are using VSTS run vsts-npm-auth -config .npmrc
to generate new .npmrc file with the auth token
For those, who faced
stat: unrecognized option: format
when executed the line from Heppo's answer (find $1 -type f -exec stat --format '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head
)
Please try the -c
key to replace --format
and finally the call will be:
find $1 -type f -exec stat -c '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head
That worked for me inside of some Docker containers, where stat
was not able to use --format
option.
I was trying to find the meaning of GRANT USAGE on *.* TO
and found here. I can clarify that GRANT USAGE on *.* TO user IDENTIFIED BY PASSWORD password
will be granted when you create the user with the following command (CREATE
):
CREATE USER 'user'@'localhost' IDENTIFIED BY 'password';
When you grant privilege with GRANT
, new privilege s will be added on top of it.
A combined solution from different answers is:
new Handler().postDelayed(() -> {
myViewPager.setCurrentItem(position, true);
myTabLayout.setScrollPosition(position, 0f, true);
},
100);
Try
mySelect.innerHTML = `<option selected value="whatever">text</option>`
function setOne() {
console.log({mySelect});
mySelect.innerHTML = `<option selected value="whatever">text</option>`;
}
_x000D_
<button onclick="setOne()" >set one</button>
<Select id="mySelect" size="9">
<option value="1">old1</option>
<option value="2">old2</option>
<option value="3">old3</option>
</Select>
_x000D_
If using .NET Core or .NET Standard
use:
Manage NuGet Packages..
instead of:
Add Reference...
Here is some resource you can read about pseudo-random number generator.
https://en.wikipedia.org/wiki/Pseudorandom_number_generator
Basically, random numbers in computer need a seed (this number can be the current system time).
Replace
std::default_random_engine generator;
By
std::default_random_engine generator(<some seed number>);
I believe you are looking for setInterval()
You may also want to look at rsync if you're doing a lot of files.
If you're going to making a lot of changes and want to keep your directories and files in sync, you may want to use a version control system like Subversion or Git. See http://xoa.petdance.com/How_to:_Keep_your_home_directory_in_Subversion
Instead of setting absolute widths and heights, you can use percentages:
#mydiv img {
height: 100%;
width: 100%;
}
Already answered, but to generalize to help other readers:
//Here: NSData * fileData;
uint8_t * bytePtr = (uint8_t * )[fileData bytes];
// Here, For getting individual bytes from fileData, uint8_t is used.
// You may choose any other data type per your need, eg. uint16, int32, char, uchar, ... .
// Make sure, fileData has atleast number of bytes that a single byte chunk would need. eg. for int32, fileData length must be > 4 bytes. Makes sense ?
// Now, if you want to access whole data (fileData) as an array of uint8_t
NSInteger totalData = [fileData length] / sizeof(uint8_t);
for (int i = 0 ; i < totalData; i ++)
{
NSLog(@"data byte chunk : %x", bytePtr[i]);
}
awk '$3 ~ /snow/ { print }' dummy_file
On Visual Studio 2015 Update 3, and with Git extension updated as of today (2016-10-24), the .gitignore generated by Visual Studio is:
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
[Xx]64/
[Xx]86/
[Bb]uild/
bld/
[Bb]in/
[Oo]bj/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Un-comment the next line if you do not want to checkin
# your web deploy settings because they may include unencrypted
# passwords
#*.pubxml
*.publishproj
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Microsoft Azure ApplicationInsights config file
ApplicationInsights.config
# Windows Store app package directory
AppPackages/
BundleArtifacts/
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# LightSwitch generated files
GeneratedArtifacts/
ModelManifest.xml
# Paket dependency manager
.paket/paket.exe
# FAKE - F# Make
.fake/
Give the parent z-index: -1, or opacity: 0.99
I was receiving the same error some time back. The issue was that my XLS file contained more than 65531 records(500 thousand to be precise). I was attempting to read a range of cells.
Excel.Range rng = (Excel.Range) myExcelWorkbookObj.UsedRange.Rows[i];
The exception was thrown while trying to read the range of cells when my counter, i.e. 'i', exceeded this limit of 65531 records.
From menu, Code -> Comment with Line Commment. So simple.
genrsa
has been replaced by genpkey
& when run manually in a terminal it will prompt for a password:
openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096
However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell
script:
get_passwd() {
local passwd=
echo -ne "Enter passwd for private key: ? "; read -s passwd
openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}
There is no unmarshal(String)
method. You should use a Reader
:
Person person = (Person) unmarshaller.unmarshal(new StringReader("xml string"));
But usually you are getting that string from somewhere, for example a file. If that's the case, better pass the FileReader
itself.
You can always do something shell-scripty like:
#!/usr/bin/node
var header = "Content-type: text/plain\n";
var hi = "Hello World from nodetest!";
console.log(header);
console.log(hi);
exit;
the name you (optionally) give the struct is called the tag name and, as has been noted, is not a type in itself. To get to the type requires the struct prefix.
GTK+ aside, I'm not sure the tagname is used anything like as commonly as a typedef to the struct type, so in C++ that is recognised and you can omit the struct keyword and use the tagname as the type name too:
struct MyStruct
{
int i;
};
// The following is legal in C++:
MyStruct obj;
obj.i = 7;
After trying some ways to load the file with no success, I remembered I could use FileInputStream
, which worked perfectly.
InputStream is = new FileInputStream("file.txt");
This is another way to read a file into an InputStream
, it reads the file from the currently running folder.
This should work for you. It just passes {:value => params[:pid] }
to the html_options variable.
<%= f.select :project_id, @project_select, {}, {:value => params[:pid] } %>
If you want all the ancestors rather than just the immediate ones, use inspect.getmro:
import inspect
print inspect.getmro(cls)
Usefully, this gives you all ancestor classes in the "method resolution order" -- i.e. the order in which the ancestors will be checked when resolving a method (or, actually, any other attribute -- methods and other attributes live in the same namespace in Python, after all;-).
You can now use string interpolation and expression bodied properties in C# 6.
private decimal _amount;
public string FormattedAmount => $"{_amount:C}";
To get Ant running on your Mac in 5 minutes, follow these steps.
Open up your terminal.
Perform these commands in order:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew install ant
If you don't have Java installed yet, you will get the following error: "Error: An unsatisfied requirement failed this build."
Run this command next: brew cask install java
to fix this.
The installation will resume.
Check your version of by running this command:
ant -version
And you're ready to go!
On windows use the name of the table in quotes:
TABLE "user";
or SELECT * FROM "user";
I think should be enough to map a boolean
In code this is:
boolean isEmpty = anyCollection.stream()
.filter(p -> someFilter(p)) // Add my filter
.map(p -> Boolean.TRUE) // For each element after filter, map to a TRUE
.findAny() // Get any TRUE
.orElse(Boolean.FALSE); // If there is no match return false
Please follow the way like below:
.selectParent {_x000D_
width:120px;_x000D_
overflow:hidden; _x000D_
}_x000D_
.selectParent select { _x000D_
display: block;_x000D_
width: 100%;_x000D_
padding: 2px 25px 2px 2px; _x000D_
border: none; _x000D_
background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
appearance: none; _x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
direction: rtl;_x000D_
padding: 2px 2px 2px 25px;_x000D_
background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
<select>_x000D_
<option value="1">Option 1</option>_x000D_
<option value="2">Option 2</option> _x000D_
</select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
<select>_x000D_
<option value="1">Option 1</option>_x000D_
<option value="2">Option 2</option> _x000D_
</select>_x000D_
</div>
_x000D_
You can also use array_reduce()
if you prefer a more functional approach
For instance:
$userNames = array_reduce($users, function ($carry, $user) {
array_push($carry, $user['name']);
return $carry;
}, []);
Or if you like to be fancy,
$userNames = [];
array_map(function ($user) use (&$userNames){
$userNames[]=$user['name'];
}, $users);
This and all the methods above do loop behind the scenes though ;)
You can accomplish the task by simply adding the following 'meta' element into your 'head':
<meta name="viewport" content="user-scalable=no">
Adding all the attributes like 'width','initial-scale', 'maximum-width', 'maximum-scale' might not work. Therefore, just add the above element.
Had to debug a site for native Android browser and came here. So I tried weinre on an OS X 10.9 (as weinre server) with Firefox 30.0 (weinre client) and an Android 4.1.2 (target). I'm really, really surprised of the result.
sudo npm -g install weinre
weinre --boundHost YOUR.IP.ADDRESS.HERE
http://YOUR.IP.ADRESS.HERE:8080
<script src="http://YOUR.IP.ADDRESS.HERE:8080/target/target-script-min.js"></script>
Maybe 8080 isn't your default port. Then in step 4 you have to call weinre --httpPort YOURPORT --boundHost YOUR.IP.ADRESS.HERE
.
And I don't remember exactly when it was, maybe somewhere after step 5, I had to accept incoming connections prompt, of course.
Happy debugging
P.S. I'm still overwhelmed how good that works. Even elements-highlighting work
SELinux prevents Apache (and therefore all Apache modules) from making remote connections by default.
# setsebool -P httpd_can_network_connect=1
As mentioned, you can use:
=Format(Fields!Price.Value, "C")
A digit after the "C" will specify precision:
=Format(Fields!Price.Value, "C0")
=Format(Fields!Price.Value, "C1")
You can also use Excel-style masks like this:
=Format(Fields!Price.Value, "#,##0.00")
Haven't tested the last one, but there's the idea. Also works with dates:
=Format(Fields!Date.Value, "yyyy-MM-dd")
If unwanted files were added to the staging area but not yet committed, then a simple reset will do the job:
$ git reset HEAD file
# Or everything
$ git reset HEAD .
To only remove unstaged changes in the current working directory, use:
git checkout -- .
You could also just put the first SELECT in a subquery. Since most optimizers will fold it into a constant anyway, there should not be a performance hit on this.
Incidentally, since you are using a predicate like this:
CONVERT(...) = CONVERT(...)
that predicate expression cannot be optimized properly or use indexes on the columns reference by the CONVERT() function.
Here is one way to make the original query somewhat better:
DECLARE @ooDate datetime
SELECT @ooDate = OO.Date FROM OLAP.OutageHours AS OO where OO.OutageID = 1
SELECT
COUNT(FF.HALID)
FROM
Outages.FaultsInOutages AS OFIO
INNER JOIN Faults.Faults as FF ON
FF.HALID = OFIO.HALID
WHERE
FF.FaultDate >= @ooDate AND
FF.FaultDate < DATEADD(day, 1, @ooDate) AND
OFIO.OutageID = 1
This version could leverage in index that involved FaultDate, and achieves the same goal.
Here it is, rewritten to use a subquery to avoid the variable declaration and subsequent SELECT.
SELECT
COUNT(FF.HALID)
FROM
Outages.FaultsInOutages AS OFIO
INNER JOIN Faults.Faults as FF ON
FF.HALID = OFIO.HALID
WHERE
CONVERT(varchar(10), FF.FaultDate, 126) = (SELECT CONVERT(varchar(10), OO.Date, 126) FROM OLAP.OutageHours AS OO where OO.OutageID = 1) AND
OFIO.OutageID = 1
Note that this approach has the same index usage issue as the original, because of the use of CONVERT() on FF.FaultDate. This could be remedied by adding the subquery twice, but you would be better served with the variable approach in this case. This last version is only for demonstration.
Regards.
input
fields can be styled as you wish. So instead of zoom, you could have
input[type="checkbox"]{
width: 30px; /*Desired width*/
height: 30px; /*Desired height*/
}
EDIT:
You would have to add extra rules like this:
input[type="checkbox"]{
width: 30px; /*Desired width*/
height: 30px; /*Desired height*/
cursor: pointer;
-webkit-appearance: none;
appearance: none;
}
Check this fiddle http://jsfiddle.net/p36tqqyq/1/
Basically the scope of workspace(s) is divided in two points.
First point (and primary) is the eclipse it self and is related with the settings and metadata configurations (plugin ctr). Each time you create a project, eclipse collects all the configurations and stores them on that workspace and if somehow in the same workspace a conflicting project is present you might loose some functionality or even stability of eclipse it self.
And second (secondary) the point of development strategy one can adopt. Once the primary scope is met (and mastered) and there's need for further adjustments regarding project relations (as libraries, perspectives ctr) then initiate separate workspace(s) could be appropriate based on development habits or possible language/frameworks "behaviors". DLTK for examples is a beast that should be contained in a separate cage. Lots of complains at forums for it stopped working (properly or not at all) and suggested solution was to clean the settings of the equivalent plugin from the current workspace.
Personally, I found myself lean more to language distinction when it comes to separate workspaces which is relevant to known issues that comes with the current state of the plugins are used. Preferably I keep them in the minimum numbers as this is leads to less frustration when the projects are become... plenty and version control is not the only version you keep your projects. Finally, loading speed and performance is an issue that might come up if lots of (unnecessary) plugins are loaded due to presents of irrelevant projects. Bottom line; there is no one solution to every one, no master blue print that solves the issue. It's something that grows with experience, Less is more though!
Configure the pivot table so that it is like this:
Your code can simply work on range("B1") now and the pivot table will be filtered to you required SavedFamilyCode
Sub FilterPivotTable()
Application.ScreenUpdating = False
ActiveSheet.Range("B1") = "K123224"
Application.ScreenUpdating = True
End Sub
Using GNU sed
:
sed "/cdef/aline1\nline2\nline3\nline4" input.txt
If you started with:
abcd
accd
cdef
line
web
this would produce:
abcd
accd
cdef
line1
line2
line3
line4
line
web
If you want to save the changes to the file in-place, say:
sed -i "/cdef/aline1\nline2\nline3\nline4" input.txt
In Angular2:
(keyup.enter)="doSomething()"
If you don't want some visual feedback in the button, it's a good design to not reference the button but rather directly invoke the controller.
Also, the id isn't needed - another NG2 way of separating between the view and the model.
Answer below the dotted line below is the original that's now outdated.
Here is the latest information ( Thank you @deadfish ):
add &hl=<language>
like &hl=pl
or &hl=en
example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl
All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en
......................................................................
To change the actual local market:
Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html
To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720
public class MyExceptionClass : Exception
{
public MyExceptionClass(string message,
Exception innerException): base(message, innerException)
{
//other stuff here
}
}
You can pass inner exception to one of the constructors.
I do not know if your still looking for the answer to this problem but today I happened the same problem and solved it. You need to specify in the HTML code,
**<Div class = "navbar"**>
div class = "container">
<Div class = "navbar-header">
or
**<Div class = "navbar navbar-default">**
div class = "container">
<Div class = "navbar-header">
You got that place in your CSS
.navbar-default-toggle .navbar .icon-bar {
background-color: # 0000ff;
}
and what I did was add above
.navbar .navbar-toggle .icon-bar {
background-color: # ff0000;
}
Because my html code is
**<Div class = "navbar">**
div class = "container">
<Div class = "navbar-header">
and if you associate a file less / css
search this section and also here placed the color you want to change, otherwise it will self-correct the css file to the state it was before
// Toggle Navbar
@ Navbar-default-toggle-hover-bg: #ddd;
**@ Navbar-default-toggle-icon-bar-bg: # 888;**
@ Navbar-default-toggle-border-color: #ddd;
if your html code is like mine and is not navbar-default, add it as you did with the css.
// Toggle Navbar
@ Navbar-default-toggle-hover-bg: #ddd;
**@ Navbar-toggle-icon-bar-bg : #888;**
@ Navbar-default-toggle-icon-bar-bg: # 888;
@ Navbar-default-toggle-border-color: #ddd;
good luck
public void callingMethod(Class neededClass) {
//Cast the class to the class you need
//and call your method in the class
((ClassBeingCalled)neededClass).methodOfClass();
}
To call the method, you call it this way:
callingMethod(ClassBeingCalled.class);
In addition to answer of @gjha:
inline std::string ltrim_copy(const std::string& str)
{
auto it = std::find_if(str.cbegin(), str.cend(),
[](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
return std::string(it, str.cend());
}
inline std::string rtrim_copy(const std::string& str)
{
auto it = std::find_if(str.crbegin(), str.crend(),
[](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
return it == str.crend() ? std::string() : std::string(str.cbegin(), ++it.base());
}
inline std::string trim_copy(const std::string& str)
{
auto it1 = std::find_if(str.cbegin(), str.cend(),
[](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
if (it1 == str.cend()) {
return std::string();
}
auto it2 = std::find_if(str.crbegin(), str.crend(),
[](char ch) { return !std::isspace<char>(ch, std::locale::classic()); });
return it2 == str.crend() ? std::string(it1, str.cend()) : std::string(it1, ++it2.base());
}
In Powershell 3.0 and above there is both a Invoke-WebRequest and Invoke-RestMethod. Curl is actually an alias of Invoke-WebRequest in PoSH. I think using native Powershell would be much more appropriate than curl, but it's up to you :).
Invoke-WebRequest MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849901.aspx?f=255&MSPPError=-2147217396
Invoke-RestMethod MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849971.aspx?f=255&MSPPError=-2147217396
internal
members are visible to all code in the assembly they are declared in.
(And to other assemblies referenced using the [InternalsVisibleTo]
attribute)
private
members are visible only to the declaring class. (including nested classes)
An outer (non-nested) class cannot be declared private
, as there is no containing scope to make it private to.
To answer the question you forgot to ask, protected
members are like private
members, but are also visible in all classes that inherit the declaring type. (But only on an expression of at least the type of the current class)
How to use an IF statement in the MySQL "select list":
select if (1>2, 2, 3); //returns 3
select if(1<2,'yes','no'); //returns yes
SELECT IF(STRCMP('test','test1'),'no','yes'); //returns no
How to use an IF statement in the MySQL where clause search condition list:
create table penguins (id int primary key auto_increment, name varchar(100))
insert into penguins (name) values ('rico')
insert into penguins (name) values ('kowalski')
insert into penguins (name) values ('skipper')
select * from penguins where 3 = id
-->3 skipper
select * from penguins where (if (true, 2, 3)) = id
-->2 kowalski
How to use an IF statement in the MySQL "having clause search conditions":
select * from penguins
where 1=1
having (if (true, 2, 3)) = id
-->1 rico
Use an IF statement with a column used in the select list to make a decision:
select (if (id = 2, -1, 1)) item
from penguins
where 1=1
--> 1
--> -1
--> 1
If statements embedded in SQL queries is a bad "code smell". Bad code has high "WTF's per minute" during code review. This is one of those things. If I see this in production with your name on it, I'm going to automatically not like you.
For me it was important to delete the "php.executablePath" path from the VS code settings and leave only the path to PHP in the Path variable.
When I had the Path variable together with php.executablePath, an irritating error still occurred (despite the fact that the path to php was correct).
I have created a realtively small (4.89 KB) javascript library for this exact functionality.
Found on my GitHub here: https://github.com/thelevicole/youtube-to-html5-loader/
It's as simple as:
<video data-yt2html5="https://www.youtube.com/watch?v=ScMzIvxBSi4"></video>
<script src="https://cdn.jsdelivr.net/gh/thelevicole/[email protected]/dist/YouTubeToHtml5.js"></script>
<script>new YouTubeToHtml5();</script>
Working example here: https://jsfiddle.net/thelevicole/5g6dbpx3/1/
What the library does is extract the video ID from the data attribute and makes a request to the https://www.youtube.com/get_video_info?video_id=
. It decodes the response which includes streaming information we can use to add a source to the <video>
tag.
Assuming that your implementation meaningfully supports SEEK_END:
fseek(f, 0, SEEK_END); // seek to end of file
size = ftell(f); // get current file pointer
fseek(f, 0, SEEK_SET); // seek back to beginning of file
// proceed with allocating memory and reading the file
You can use stat
(if you know the filename), or fstat
(if you have the file descriptor).
Here is an example for stat:
#include <sys/stat.h>
struct stat st;
stat(filename, &st);
size = st.st_size;
You can use GetFileSize or GetFileSizeEx.
I use this for my npm Process
#!/bin/bash
for (( ; ; ))
do
date +"%T"
echo Start Process
cd /toFolder
sudo process
date +"%T"
echo Crash
sleep 1
done
I had a list of lists of equal length. Even then Ignacio Vazquez-Abrams
's answer didn't work out for me. I got a 1-D numpy array whose elements are lists. If you faced the same problem, you can use the below method
Use numpy.vstack
import numpy as np
np_array = np.empty((0,4), dtype='float')
for i in range(10)
row_data = ... # get row_data as list
np_array = np.vstack((np_array, np.array(row_data)))
I would recommend a combination of PatIndex and Left. Carefully constructed, you can write a query that always works, no matter what your data looks like.
Ex:
Declare @Temp Table(Data VarChar(20))
Insert Into @Temp Values('BTA200')
Insert Into @Temp Values('BTA50')
Insert Into @Temp Values('BTA030')
Insert Into @Temp Values('BTA')
Insert Into @Temp Values('123')
Insert Into @Temp Values('X999')
Select Data, Left(Data, PatIndex('%[0-9]%', Data + '1') - 1)
From @Temp
PatIndex will look for the first character that falls in the range of 0-9, and return it's character position, which you can use with the LEFT function to extract the correct data. Note that PatIndex is actually using Data + '1'. This protects us from data where there are no numbers found. If there are no numbers, PatIndex would return 0. In this case, the LEFT function would error because we are using Left(Data, PatIndex - 1). When PatIndex returns 0, we would end up with Left(Data, -1) which returns an error.
There are still ways this can fail. For a full explanation, I encourage you to read:
Extracting numbers with SQL Server
That article shows how to get numbers out of a string. In your case, you want to get alpha characters instead. However, the process is similar enough that you can probably learn something useful out of it.
To clarify, a database created under SQL Server 2008 R2 was being opened in an instance of SQL Server 2008 (the version prior to R2). The solution for me was to simply perform an upgrade installation of SQL Server 2008 R2. I can only speak for the Express edition, but it worked.
Oddly, though, the Web Platform Installer indicated that I had Express R2 installed. The better way to tell is to ask the database server itself:
SELECT @@VERSION
Try CTR + M it will work like before.
Confirming I was able to use the answer posted by MadBoy and edited by Otiel on both MS SQL Server 2012 and 2014 in addition to the versions previously listed using varbinary(MAX) columns.
If you are wondering why you cannot "Filestream" (noted in a separate answer) as a datatype in the SQL Server table designer or why you cannot set a column's datatype to "Filestream" using T-SQL, it is because FILESTREAM is a storage attribute of the varbinary(MAX) datatype. It is not a datatype on its own.
See these articles on setting up and enabling FILESTREAM on a database: https://msdn.microsoft.com/en-us/library/cc645923(v=sql.120).aspx
http://www.kodyaz.com/t-sql/default-filestream-filegroup-is-not-available-in-database.aspx
Once configured, a filestream enabled varbinary(max) column can be added as so:
ALTER TABLE TableName
ADD ColumnName varbinary(max) FILESTREAM NULL
GO
The CSS class that can be changed to add a image to the JQuery slider handle is called ".ui-slider-horizontal .ui-slider-handle".
The following code shows a demo:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" href="http://jqueryui.com/latest/themes/base/ui.all.css" rel="stylesheet" />
<script type="text/javascript" src="http://jqueryui.com/latest/jquery-1.3.2.js"></script>
<script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.core.js"></script>
<script type="text/javascript" src="http://jqueryui.com/latest/ui/ui.slider.js"></script>
<style type="text/css">
.ui-slider-horizontal .ui-state-default {background: white url(http://stackoverflow.com/content/img/so/vote-arrow-down.png) no-repeat scroll 50% 50%;}
</style>
<script type="text/javascript">
$(document).ready(function(){
$("#slider").slider();
});
</script>
</head>
<body>
<div id="slider"></div>
</body>
</html>
I think registering a handle option was the old way of doing it and no longer supported in JQuery-ui 1.7.2?
One quick solution that came to mind :-
<input type="checkbox" id="markitem" name="markitem" value="1" onchange="GetMarkedItems(1)">
<label for="markitem" style="position:absolute; top:1px; left:165px;"> </label>
<!-- Fire the below javascript everytime the page reloads -->
<script type=text/javascript>
document.getElementById("markitem").checked = false;
</script>
<!-- Tested on Latest FF, Chrome, Opera and IE. -->
I know this is an old question, however for intersted developers Multi line literals gonna be in #Java12
http://mail.openjdk.java.net/pipermail/amber-dev/2018-July/003254.html
This takes Arany's answer and makes it work if the modal is taller than the height of the screen:
function centerModal() {
$(this).css('display', 'block');
var $dialog = $(this).find(".modal-dialog");
var offset = ($(window).height() - $dialog.height()) / 2;
//Make sure you don't hide the top part of the modal w/ a negative margin if it's longer than the screen height, and keep the margin equal to the bottom margin of the modal
var bottomMargin = $dialog.css('marginBottom');
bottomMargin = parseInt(bottomMargin);
if(offset < bottomMargin) offset = bottomMargin;
$dialog.css("margin-top", offset);
}
$('.modal').on('show.bs.modal', centerModal);
$(window).on("resize", function () {
$('.modal:visible').each(centerModal);
});
basename() has a bug when processing Asian characters like Chinese.
I use this:
function get_basename($filename)
{
return preg_replace('/^.+[\\\\\\/]/', '', $filename);
}
Wouldn't this
"d+|D+"
do the job instead of the cumbersome:
"(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"
?
Solution tested, works on iOS 12.x
This is problem I was encountering :
<body> <!-- the whole body can be scroll vertically -->
<article>
<my_gallery> <!-- some picture gallery, can be scroll horizontally -->
</my_gallery>
</article>
</body>
While I scrolling my gallery, the body always scrolling itself (human swipe aren't really horizontal), that makes my gallery useless.
Here's what I did while my gallery start scrolling
var html=jQuery('html');
html.css('overflow-y', 'hidden');
//above code works on mobile Chrome/Edge/Firefox
document.ontouchmove=function(e){e.preventDefault();} //Add this only for mobile Safari
And when my gallery end its scrolling...
var html=jQuery('html');
html.css('overflow-y', 'scroll');
document.ontouchmove=function(e){return true;}
Hope this helps~
If can't rely on the process name like python scripts which will always have python.exe as process name. If found this method very handy
import psutil
psutil.pid_exists(pid)
check docs for further info http://psutil.readthedocs.io/en/latest/#psutil.pid_exists
STR_TO_DATE('12/31/2011', '%m/%d/%Y')
Something like this could work...
mydf.loc['newindex'] = myseries
Here is an example where I used it...
stats = df[['bp_prob', 'ICD9_prob', 'meds_prob', 'regex_prob']].describe()
stats
Out[32]:
bp_prob ICD9_prob meds_prob regex_prob
count 171.000000 171.000000 171.000000 171.000000
mean 0.179946 0.059071 0.067020 0.126812
std 0.271546 0.142681 0.152560 0.207014
min 0.000000 0.000000 0.000000 0.000000
25% 0.000000 0.000000 0.000000 0.000000
50% 0.000000 0.000000 0.000000 0.013116
75% 0.309019 0.065248 0.066667 0.192954
max 1.000000 1.000000 1.000000 1.000000
medians = df[['bp_prob', 'ICD9_prob', 'meds_prob', 'regex_prob']].median()
stats.loc['median'] = medians
stats
Out[36]:
bp_prob ICD9_prob meds_prob regex_prob
count 171.000000 171.000000 171.000000 171.000000
mean 0.179946 0.059071 0.067020 0.126812
std 0.271546 0.142681 0.152560 0.207014
min 0.000000 0.000000 0.000000 0.000000
25% 0.000000 0.000000 0.000000 0.000000
50% 0.000000 0.000000 0.000000 0.013116
75% 0.309019 0.065248 0.066667 0.192954
max 1.000000 1.000000 1.000000 1.000000
median 0.000000 0.000000 0.000000 0.013116
On windows in a corporate environment where certificates are distributed from a single source, I found this answer solved the issue: https://stackoverflow.com/a/48212753/761755
Here is an overview in a table format in order to show the differences between Pool.apply
, Pool.apply_async
, Pool.map
and Pool.map_async
. When choosing one, you have to take multi-args, concurrency, blocking, and ordering into account:
| Multi-args Concurrence Blocking Ordered-results
---------------------------------------------------------------------
Pool.map | no yes yes yes
Pool.map_async | no yes no yes
Pool.apply | yes no yes no
Pool.apply_async | yes yes no no
Pool.starmap | yes yes yes yes
Pool.starmap_async| yes yes no no
Pool.imap
and Pool.imap_async
– lazier version of map and map_async.
Pool.starmap
method, very much similar to map method besides it acceptance of multiple arguments.
Async
methods submit all the processes at once and retrieve the results once they are finished. Use get method to obtain the results.
Pool.map
(or Pool.apply
)methods are very much similar to Python built-in map(or apply). They block the main process until all the processes complete and return the result.
Is called for a list of jobs in one time
results = pool.map(func, [1, 2, 3])
Can only be called for one job
for x, y in [[1, 1], [2, 2]]:
results.append(pool.apply(func, (x, y)))
def collect_result(result):
results.append(result)
Is called for a list of jobs in one time
pool.map_async(func, jobs, callback=collect_result)
Can only be called for one job and executes a job in the background in parallel
for x, y in [[1, 1], [2, 2]]:
pool.apply_async(worker, (x, y), callback=collect_result)
Is a variant of pool.map
which support multiple arguments
pool.starmap(func, [(1, 1), (2, 1), (3, 1)])
A combination of starmap() and map_async() that iterates over iterable of iterables and calls func with the iterables unpacked. Returns a result object.
pool.starmap_async(calculate_worker, [(1, 1), (2, 1), (3, 1)], callback=collect_result)
Find complete documentation here: https://docs.python.org/3/library/multiprocessing.html
If you want to combine two files where one overlays the other (example: document A is a template and document B has the text you want to put on the template), this works:
after creating "doc", you want to write your template (templateFile) on top of that -
PDDocument watermarkDoc = PDDocument.load(getServletContext()
.getRealPath(templateFile));
Overlay overlay = new Overlay();
overlay.overlay(watermarkDoc, doc);
Also you can use
dirname(__DIR__, $level)
for access any folding level without traversing