You've pretty much nailed it, however Mustache templates can also be compiled.
Mustache is missing helpers and the more advanced blocks because it strives to be logicless. Handlebars' custom helpers can be very useful, but often end up introducing logic into your templates.
Mustache has many different compilers (JavaScript, Ruby, Python, C, etc.). Handlebars began in JavaScript, now there are projects like django-handlebars, handlebars.java, handlebars-ruby, lightncandy (PHP), and handlebars-objc.
FOR ANDROID:
You only need to enable “USB remote debugger” within your android device and plug with a USB cable. Then open your application in the device. Chrome will detect the remote browser and you can see the console in the same way than you see it when you use Chrome locally.
Use this link: chrome://inspect/#devices
in Chrome browser (you'll have to paste it into the nav bar).
If your app crashes in the device you only need to see the console’s log within your browser and see what happens. You also can add functionality, change variables, and override functions in the same way than we do it with our local browser.
Read this article for more information on the steps to take.
This will work ONLY with devices running Android 4.4+.
FOR iOS:
Use Safari for iOS, follow these steps:
1.In your iOS device go to Settings > Safari > Advanced > Web Inspector to enable Web Inspector
2.Open Safari on your iOS device.
3.Connect it to your computer via USB.
4.Open Safari on your computer.
5.In Safari’s menu, go to Develop and, look for your device’s name.
6.Select the tab you want to debug.
1 - Common Java setter idiom:
public void setFoo(int foo) {
this.foo = foo;
}
2 - When calling a function with this object as a parameter
notifier.addListener(this);
a.txt
this is line 1
this is line 2
code:
Python 3.4.0 (default, Mar 20 2014, 22:43:40)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']
I'm on Linux, but I guess you just use \r\n
on Windows and it would also work
Use Platform.runLater(...)
for quick and simple operations and Task
for complex and big operations .
Example: Why Can't we use Platform.runLater(...)
for long calculations (Taken from below reference).
Problem: Background thread which just counts from 0 to 1 million and update progress bar in UI.
Code using Platform.runLater(...)
:
final ProgressBar bar = new ProgressBar();
new Thread(new Runnable() {
@Override public void run() {
for (int i = 1; i <= 1000000; i++) {
final int counter = i;
Platform.runLater(new Runnable() {
@Override public void run() {
bar.setProgress(counter / 1000000.0);
}
});
}
}).start();
This is a hideous hunk of code, a crime against nature (and programming in general). First, you’ll lose brain cells just looking at this double nesting of Runnables. Second, it is going to swamp the event queue with little Runnables — a million of them in fact. Clearly, we needed some API to make it easier to write background workers which then communicate back with the UI.
Code using Task :
Task task = new Task<Void>() {
@Override public Void call() {
static final int max = 1000000;
for (int i = 1; i <= max; i++) {
updateProgress(i, max);
}
return null;
}
};
ProgressBar bar = new ProgressBar();
bar.progressProperty().bind(task.progressProperty());
new Thread(task).start();
it suffers from none of the flaws exhibited in the previous code
Reference : Worker Threading in JavaFX 2.0
start "" "%SystemRoot%\Notepad.exe"
Keep the ""
in between start and your application path.
Added explanation:
Normally when we launch a program from a batch file like below, we'll have the black windows at the background like OP said.
%SystemRoot%\Notepad.exe
This was cause by Notepad running in same command prompt (process). The command prompt will close AFTER notepad is closed. To avoid that, we can use the start
command to start a separate process like this.
start %SystemRoot%\Notepad.exe
This command is fine as long it doesn't has space in the path. To handle space in the path for just in case, we added the "
quotes like this.
start "%SystemRoot%\Notepad.exe"
However running this command would just start another blank command prompt. Why? If you lookup to the start /?
, the start
command will recognize the argument between the "
as the title of the new command prompt it is going to launch. So, to solve that, we have the command like this:
start "" "%SystemRoot%\Notepad.exe"
The first argument of ""
is to set the title (which we set as blank), and the second argument of
"%SystemRoot%\Notepad.exe"
is the target command to run (that support spaces in the path).
If you need to add parameters to the command, just append them quoted, i.e.:
start "" "%SystemRoot%\Notepad.exe" "<filename>"
Try to use the WEEKDAY()
function.
Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).
private bool IsValidPath(string path)
{
Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
if (!driveCheck.IsMatch(path.Substring(0, 3))) return false;
string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars());
strTheseAreInvalidFileNameChars += @":/?*" + "\"";
Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]");
if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
return false;
DirectoryInfo dir = new DirectoryInfo(Path.GetFullPath(path));
if (!dir.Exists)
dir.Create();
return true;
}
Based on nadeausoftware and Lambda Fairy's answer.
#include <stdio.h>
/**
* Determination a platform of an operation system
* Fully supported supported only GNU GCC/G++, partially on Clang/LLVM
*/
#if defined(_WIN32)
#define PLATFORM_NAME "windows" // Windows
#elif defined(_WIN64)
#define PLATFORM_NAME "windows" // Windows
#elif defined(__CYGWIN__) && !defined(_WIN32)
#define PLATFORM_NAME "windows" // Windows (Cygwin POSIX under Microsoft Window)
#elif defined(__ANDROID__)
#define PLATFORM_NAME "android" // Android (implies Linux, so it must come first)
#elif defined(__linux__)
#define PLATFORM_NAME "linux" // Debian, Ubuntu, Gentoo, Fedora, openSUSE, RedHat, Centos and other
#elif defined(__unix__) || !defined(__APPLE__) && defined(__MACH__)
#include <sys/param.h>
#if defined(BSD)
#define PLATFORM_NAME "bsd" // FreeBSD, NetBSD, OpenBSD, DragonFly BSD
#endif
#elif defined(__hpux)
#define PLATFORM_NAME "hp-ux" // HP-UX
#elif defined(_AIX)
#define PLATFORM_NAME "aix" // IBM AIX
#elif defined(__APPLE__) && defined(__MACH__) // Apple OSX and iOS (Darwin)
#include <TargetConditionals.h>
#if TARGET_IPHONE_SIMULATOR == 1
#define PLATFORM_NAME "ios" // Apple iOS
#elif TARGET_OS_IPHONE == 1
#define PLATFORM_NAME "ios" // Apple iOS
#elif TARGET_OS_MAC == 1
#define PLATFORM_NAME "osx" // Apple OSX
#endif
#elif defined(__sun) && defined(__SVR4)
#define PLATFORM_NAME "solaris" // Oracle Solaris, Open Indiana
#else
#define PLATFORM_NAME NULL
#endif
// Return a name of platform, if determined, otherwise - an empty string
const char *get_platform_name() {
return (PLATFORM_NAME == NULL) ? "" : PLATFORM_NAME;
}
int main(int argc, char *argv[]) {
puts(get_platform_name());
return 0;
}
Tested with GCC and clang on:
#import <Foundation/Foundation.h>
// clang -framework Foundation Siegfried.m
int
main() {
NSArray *arr = @[
@{@"1" : @"Fafner"},
@{@"1" : @"Fasolt"}
];
NSPredicate *p = [NSPredicate predicateWithFormat:
@"SELF['1'] CONTAINS 'e'"];
NSArray *res = [arr filteredArrayUsingPredicate:p];
NSLog(@"Siegfried %@", res);
return 0;
}
We had a similar situation, but in our case Infosec agreed to allow any to 1, so we didnt had to fix the slave port, rather fixing the master to high level JNLP port 49187 worked ("Configure Global Security" -> "TCP port for JNLP slave agents").
TCP
49187 - Fixed jnlp port
8080 - jenkins http port
Other ports needed to launch slave as a windows service
TCP
135
139
445
UDP
137
138
If you want to take advantage of the 60FPS smoothness that the "transform" property offers, you can combine the two:
@keyframes changewidth {
from {
transform: scaleX(1);
}
to {
transform: scaleX(2);
}
}
div {
animation-duration: 0.1s;
animation-name: changewidth;
animation-iteration-count: infinite;
animation-direction: alternate;
}
More explanation on why transform offers smoother transitions here: https://medium.com/outsystems-experts/how-to-achieve-60-fps-animations-with-css3-db7b98610108
You can do:
<script type="text/javascript">
if (window.location.protocol != "https:") {
window.location.protocol = "https";
}
</script>
skip[1]
will skip second line, not the first one.
(()=> {
var elem = document.querySelector('.elem');
(
(elem) ?
console.log(elem+' was found.') :
console.log('not found')
)
})();
If it exists, it spits out the specified element as a DOM object. With JQuery $('.elem')
it only tells you that it's an object if found but not which.
If you're okay with ES2017, await
is good:
const DEF_DELAY = 1000;
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms || DEF_DELAY));
}
await sleep(100);
Note that the await
part needs to be in an async function:
//IIAFE (immediately invoked async function expression)
(async()=>{
//Do some stuff
await sleep(100);
//Do some more stuff
})()
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
On my machine using Node.js, I ran the following:
console.log('Testing Array:');
console.time('using[]');
for(var i=0; i<200000000; i++){var arr = []};
console.timeEnd('using[]');
console.time('using new');
for(var i=0; i<200000000; i++){var arr = new Array};
console.timeEnd('using new');
console.log('Testing Object:');
console.time('using{}');
for(var i=0; i<200000000; i++){var obj = {}};
console.timeEnd('using{}');
console.time('using new');
for(var i=0; i<200000000; i++){var obj = new Object};
console.timeEnd('using new');
Note, this is an extension of what is found here: Why is arr = [] faster than arr = new Array?
my output was the following:
Testing Array:
using[]: 1091ms
using new: 2286ms
Testing Object:
using{}: 870ms
using new: 5637ms
so clearly {} and [] are faster than using new for creating empty objects/arrays.
You are right the urllib and urllib2 packages have been split into urllib.request , urllib.parse and urllib.error packages in Python 3.x. The latter packages do not exist in Python 2.x
From documentation -
The urllib module has been split into parts and renamed in Python 3 to urllib.request, urllib.parse, and urllib.error.
From urllib2 documentation -
The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error.
So I am pretty sure the code you downloaded has been written for Python 3.x , since they are using a library that is only present in Python 3.x .
There is a urllib package in python, but it does not have the request subpackage. Also, lets assume you do lots of work and somehow make request subpackage available in Python 2.x .
There is a very very high probability that you will run into more issues, there is lots of incompatibility between Python 2.x and Python 3.x , in the end you would most probably end up rewriting atleast half the code from github (and most probably reading and understanding the complete code from there).
Even then there may be other bugs arising from the fact that some of the implementation details changed between Python 2.x to Python 3.x (As an example - list comprehension got its own namespace in Python 3.x)
You are better off trying to download and use Python 3 , than trying to make code written for Python 3.x compatible with Python 2.x
The javadoc for File.delete()
public boolean delete()
Deletes the file or directory denoted by this abstract pathname. If this pathname >denotes a directory, then the directory must be empty in order to be deleted.
So a folder has to be empty or deleting it will fail. Your code currently fills the folder list with the top most folder first, followed by its sub folders. Since you iterrate through the list in the same way it will try to delete the top most folder before deleting its subfolders, this will fail.
Changing these line
for(String filePath : folderList) {
File tempFile = new File(filePath);
tempFile.delete();
}
to this
for(int i = folderList.size()-1;i>=0;i--) {
File tempFile = new File(folderList.get(i));
tempFile.delete();
}
should cause your code to delete the sub folders first.
The delete operation also returns false when it fails, so you can check this value to do some error handling if necessary.
You need to overload operator <<
for mystruct
class
Something like :-
friend ostream& operator << (ostream& os, const mystruct& m)
{
os << m.m_a <<" " << m.m_b << endl;
return os ;
}
See here
The AWS support pointed a simpler solution. It's basically the same idea proposed by @Vivek M. Chawla, with a more simple implementation.
AWS S3:
aws.example.com
Redirect all requests to another host name
and enter your URL:
https://myaccount.signin.aws.amazon.com/console/
AWS Route53:
Yes
. Click on Alias
Target
field and select the S3 bucket you created in the previous
step.Reference: How to redirect domains using Amazon Web Services
AWS official documentation: Is there a way to redirect a domain to another domain using Amazon Route 53?
JavaScript variable = PHP variable try follow:-
<script>
var a="Hello";
<?php
$variable='a';
?>
</script>
Note:-It run only when you do php code under script tag.I have a successfully initialise php variable.
Neither is good.
Behaviour should be configured independent of the actual markup. For instance, in jQuery you might do something like
$('#the-element').click(function () { /* perform action here */ });
in a separate <script>
block.
The advantage of this is that it
Furthermore, it degrades gracefully (but so would using the onclick
event) since you can provide the link tags with a href
in case the user doesn’t have JavaScript enabled.
Of course, these arguments still count if you’re not using jQuery or another JavaScript library (but why do that?).
(Update: August 2011)
As geofflane mentions in his answer, Java 7 now support named groups.
tchrist points out in the comment that the support is limited.
He details the limitations in his great answer "Java Regex Helper"
Java 7 regex named group support was presented back in September 2010 in Oracle's blog.
In the official release of Java 7, the constructs to support the named capturing group are:
(?<name>capturing text)
to define a named group "name"\k<name>
to backreference a named group "name"${name}
to reference to captured group in Matcher's replacement stringMatcher.group(String name)
to return the captured input subsequence by the given "named group".
Other alternatives for pre-Java 7 were:
(Original answer: Jan 2009, with the next two links now broken)
You can not refer to named group, unless you code your own version of Regex...
That is precisely what Gorbush2 did in this thread.
(limited implementation, as pointed out again by tchrist, as it looks only for ASCII identifiers. tchrist details the limitation as:
only being able to have one named group per same name (which you don’t always have control over!) and not being able to use them for in-regex recursion.
Note: You can find true regex recursion examples in Perl and PCRE regexes, as mentioned in Regexp Power, PCRE specs and Matching Strings with Balanced Parentheses slide)
Example:
String:
"TEST 123"
RegExp:
"(?<login>\\w+) (?<id>\\d+)"
Access
matcher.group(1) ==> TEST
matcher.group("login") ==> TEST
matcher.name(1) ==> login
Replace
matcher.replaceAll("aaaaa_$1_sssss_$2____") ==> aaaaa_TEST_sssss_123____
matcher.replaceAll("aaaaa_${login}_sssss_${id}____") ==> aaaaa_TEST_sssss_123____
(extract from the implementation)
public final class Pattern
implements java.io.Serializable
{
[...]
/**
* Parses a group and returns the head node of a set of nodes that process
* the group. Sometimes a double return system is used where the tail is
* returned in root.
*/
private Node group0() {
boolean capturingGroup = false;
Node head = null;
Node tail = null;
int save = flags;
root = null;
int ch = next();
if (ch == '?') {
ch = skip();
switch (ch) {
case '<': // (?<xxx) look behind or group name
ch = read();
int start = cursor;
[...]
// test forGroupName
int startChar = ch;
while(ASCII.isWord(ch) && ch != '>') ch=read();
if(ch == '>'){
// valid group name
int len = cursor-start;
int[] newtemp = new int[2*(len) + 2];
//System.arraycopy(temp, start, newtemp, 0, len);
StringBuilder name = new StringBuilder();
for(int i = start; i< cursor; i++){
name.append((char)temp[i-1]);
}
// create Named group
head = createGroup(false);
((GroupTail)root).name = name.toString();
capturingGroup = true;
tail = root;
head.next = expr(tail);
break;
}
Active record method or_where
is to be used:
$this->db->select("*")
->from("table_name")
->where("first", $first)
->or_where("second", $second);
In the old language, to delete the entry with key k
from the map represented by m
, one wrote the statement,
m[k] = value, false
This syntax was a peculiar special case, the only two-to-one assignment. It required passing a value (usually ignored) that is evaluated but discarded, plus a boolean that was nearly always the constant false. It did the job but was odd and a point of contention.
In Go 1, that syntax has gone; instead there is a new built-in function, delete
. The call
delete(m, k)
will delete the map entry retrieved by the expression m[k]
. There is no return value. Deleting a non-existent entry is a no-op.
Updating: Running go fix
will convert expressions of the form m[k] = value, false
into delete(m, k)
when it is clear that the ignored value can be safely discarded from the program and false
refers to the predefined boolean constant. The fix tool will flag other uses of the syntax for inspection by the programmer.
parameter?: type
is a shorthand for parameter: type | undefined
Try something like:
WHERE (column LIKE '%this%' OR column LIKE '%that%') AND something = else
U can use eclipse. but u need to download pydev addon for that.
SELECT created
FROM dba_objects
WHERE object_name = <<your table name>>
AND owner = <<owner of the table>>
AND object_type = 'TABLE'
will tell you when a table was created (if you don't have access to DBA_OBJECTS, you could use ALL_OBJECTS instead assuming you have SELECT privileges on the table).
The general answer to getting timestamps from a row, though, is that you can only get that data if you have added columns to track that information (assuming, of course, that your application populates the columns as well). There are various special cases, however. If the DML happened relatively recently (most likely in the last couple hours), you should be able to get the timestamps from a flashback query. If the DML happened in the last few days (or however long you keep your archived logs), you could use LogMiner to extract the timestamps but that is going to be a very expensive operation particularly if you're getting timestamps for many rows. If you build the table with ROWDEPENDENCIES enabled (not the default), you can use
SELECT scn_to_timestamp( ora_rowscn ) last_modified_date,
ora_rowscn last_modified_scn,
<<other columns>>
FROM <<your table>>
to get the last modification date and SCN (system change number) for the row. By default, though, without ROWDEPENDENCIES, the SCN is only at the block level. The SCN_TO_TIMESTAMP
function also isn't going to be able to map SCN's to timestamps forever.
dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;
Set border: 1px solid black
to make all sides equals and remove any kind of custom border (other than solid).
Also, set box-shadow: none
to remove any inset shadow applied to it.
Your Service may be getting shut down before it completes due to the device going to sleep after booting. You need to obtain a wake lock first. Luckily, the Support library gives us a class to do this:
public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// This is the Intent to deliver to our service.
Intent service = new Intent(context, SimpleWakefulService.class);
// Start the service, keeping the device awake while it is launching.
Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
startWakefulService(context, service);
}
}
then, in your Service, make sure to release the wake lock:
@Override
protected void onHandleIntent(Intent intent) {
// At this point SimpleWakefulReceiver is still holding a wake lock
// for us. We can do whatever we need to here and then tell it that
// it can release the wakelock.
...
Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
SimpleWakefulReceiver.completeWakefulIntent(intent);
}
Don't forget to add the WAKE_LOCK permission:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
Create an alias for gcc with your favorite includes.
alias mygcc='gcc -I /whatever/'
As it does not answer your question but searching vm arguments I stumbled on this page and there seem to be no other. So if you want to pass vm arguments its like so
{
"version": "0.2.0",
"configurations": [
{
"type": "java",
"name": "ddtBatch",
"request": "launch",
"mainClass": "com.something.MyApplication",
"projectName": "MyProject",
"args": "Hello",
"vmArgs": "-Dspring.config.location=./application.properties"
}
]
}
There are any number of ways to do this. For example:
double d = 5.0;
bool isInt = d == (int)d;
You can also use modulo.
double d = 5.0;
bool isInt = d % 1 == 0;
Try this instead in the end:
exec (@query)
If you do not have the brackets, SQL Server assumes the value of the variable to be a stored procedure name.
OR
EXECUTE sp_executesql @query
And it should not be because of FULL JOIN.
But I hope you have already created the temp tables: #TrafficFinal, #TrafficFinal2, #TrafficFinal3 before this.
Please note that there are performance considerations between using EXEC and sp_executesql. Because sp_executesql uses forced statement caching like an sp.
More details here.
On another note, is there a reason why you are using dynamic sql for this case, when you can use the query as is, considering you are not doing any query manipulations and executing it the way it is?
With Tooltip object Boostrap :
$(element).attr('data-original-title', 'New value');
$(element).data('bs.tooltip').tip().find('.tooltip-inner').text('New value');
I think using the matrix.at<type>(x,y)
is not the best way to iterate trough a Mat object!
If I recall correctly matrix.at<type>(x,y)
will iterate from the beginning of the matrix each time you call it(I might be wrong though).
I would suggest using cv::MatIterator_
cv::Mat someMat(1, 4, CV_64F, &someData);;
cv::MatIterator_<double> _it = someMat.begin<double>();
for(;_it!=someMat.end<double>(); _it++){
std::cout << *_it << std::endl;
}
There's actually a great Google API for this. It takes in a location and returns the timezone for that location. Should be simple enough to create a bash or python script to get the results for each address in a CSV file or database then save the timezone information.
https://developers.google.com/maps/documentation/timezone/start
Request Endpoint:
https://maps.googleapis.com/maps/api/timezone/json?location=38.908133,-77.047119×tamp=1458000000&key=YOUR_API_KEY
Response:
{
"dstOffset" : 3600,
"rawOffset" : -18000,
"status" : "OK",
"timeZoneId" : "America/New_York",
"timeZoneName" : "Eastern Daylight Time"
}
Nowadays, it's better to use queues than threads (for those who don't use Laravel there are tons of other implementations out there like this).
The basic idea is, your original PHP script puts tasks or jobs into a queue. Then you have queue job workers running elsewhere, taking jobs out of the queue and starts processing them independently of the original PHP.
The advantages are:
Place your script
inside the body tag
<body>
// Rest of html
<script>
function hideButton() {
$(".loading").hide();
}
function showButton() {
$(".loading").show();
}
</script>
< /body>
If you check this JSFIDDLE and click on javascript, you will see the load Type body
is selected
I suggest code bellow. You may work with exception, when convert error occured.
public static class Utils {
public static bool TryParse<Tin, Tout>(this Tin obj, Func<Tin, Tout> onConvert, Action<Tout> onFill, Action<Exception> onError) {
Tout value = default(Tout);
bool ret = true;
try {
value = onConvert(obj);
}
catch (Exception exc) {
onError(exc);
ret = false;
}
if (ret)
onFill(value);
return ret;
}
public static bool TryParse(this string str, Action<int?> onFill, Action<Exception> onError) {
return Utils.TryParse(str
, s => string.IsNullOrEmpty(s) ? null : (int?)int.Parse(s)
, onFill
, onError);
}
public static bool TryParse(this string str, Action<int> onFill, Action<Exception> onError) {
return Utils.TryParse(str
, s => int.Parse(s)
, onFill
, onError);
}
}
Use this extension method in code (fill int? Age property of a person class):
string ageStr = AgeTextBox.Text;
Utils.TryParse(ageStr, i => person.Age = i, exc => { MessageBox.Show(exc.Message); });
OR
AgeTextBox.Text.TryParse(i => person.Age = i, exc => { MessageBox.Show(exc.Message); });
The error you gave is due to the fact that in python, dictionary keys must be immutable types (if key can change, there will be problems), and list is a mutable type.
Your error says that you try to use a list as dictionary key, you'll have to change your list into tuples if you want to put them as keys in your dictionary.
According to the python doc :
The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key’s hash value to remain constant
Hi url should be calling a function which in return will give response
$.ajax({
url:'function to call url',
...
...
});
try using/calling API facebook method
A nice version that works under Linux, BSD and MacOS X. First tries to send SIGTERM, and if it doesn't succeed, kills the process after 10 seconds.
KillJobs() {
for job in $(jobs -p); do
kill -s SIGTERM $job > /dev/null 2>&1 || (sleep 10 && kill -9 $job > /dev/null 2>&1 &)
done
}
TrapQuit() {
# Whatever you need to clean here
KillJobs
}
trap TrapQuit EXIT
Please note that jobs does not include grand children processes.
You do not have to install something.
parseInt(req.params.year, 10);
should work properly.
console.log(typeof parseInt(req.params.year)); // returns 'number'
What is your output, if you use parseInt? is it still a string?
I also tried this answer but was not entirely happy with the result. I kept googling around and finally found a Nuget Package that helped me to manage the result I wanted, anno 2021. I would like to share it with the former developers of Stack Overflow.
I used this Nuget Package Gu.WPF.Geometry found via this Github Repository. All credits for develoment should go to Johan Larsson, the owner of this package.
How I used it? I wanted to have the commands as buttons below the zoombox, as shown here in MachineLayoutControl.xaml
.
<UserControl
x:Class="MyLib.MachineLayoutControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:csmachinelayoutdrawlib="clr-namespace:CSMachineLayoutDrawLib"
xmlns:effects="http://gu.se/Geometry">
<UserControl.Resources>
<ResourceDictionary Source="Resources/ResourceDictionaries/AllResourceDictionariesCombined.xaml" />
</UserControl.Resources>
<Grid Margin="0">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Border
Grid.Row="0"
Margin="0,0"
Padding="0"
BorderThickness="1"
Style="{StaticResource Border_Head}"
Visibility="Visible">
<effects:Zoombox
x:Name="ImageBox"
IsManipulationEnabled="True"
MaxZoom="10"
MinZoom="0.1"
Visibility="{Binding Zoombox_Visibility}">
<ContentControl Content="{Binding Viewing_Canvas}" />
</effects:Zoombox>
</Border>
<StackPanel
Grid.Column="1"
Margin="10"
HorizontalAlignment="Right"
Orientation="Horizontal">
<Button
Command="effects:ZoomCommands.Increase"
CommandParameter="2.0"
CommandTarget="{Binding ElementName=ImageBox}"
Content="Zoom In"
Style="{StaticResource StyleForResizeButtons}" />
<Button
Command="effects:ZoomCommands.Decrease"
CommandParameter="2.0"
CommandTarget="{Binding ElementName=ImageBox}"
Content="Zoom Out"
Style="{StaticResource StyleForResizeButtons}" />
<Button
Command="effects:ZoomCommands.Uniform"
CommandTarget="{Binding ElementName=ImageBox}"
Content="See Full Machine"
Style="{StaticResource StyleForResizeButtons}" />
<Button
Command="effects:ZoomCommands.UniformToFill"
CommandTarget="{Binding ElementName=ImageBox}"
Content="Zoom To Machine Width"
Style="{StaticResource StyleForResizeButtons}" />
</StackPanel>
</Grid>
</UserControl>
In the underlying Viewmodel, I had the following relevant code:
public Visibility Zoombox_Visibility { get => movZoombox_Visibility; set { movZoombox_Visibility = value; OnPropertyChanged(nameof(Zoombox_Visibility)); } }
public Canvas Viewing_Canvas { get => mdvViewing_Canvas; private set => mdvViewing_Canvas = value; }
Also, I wanted that immediately on loading, the Uniform to Fill Command was executed, this is something that I managed to do in the code-behind MachineLayoutControl.xaml.cs
. You see that I only set the Zoombox to visible if the command is executed, to avoid "flickering" when the usercontrol is loading.
public partial class MachineLayoutControl : UserControl
{
#region Constructors
public MachineLayoutControl()
{
InitializeComponent();
Loaded += MyWindow_Loaded;
}
#endregion Constructors
#region EventHandlers
private void MyWindow_Loaded(object sender, RoutedEventArgs e)
{
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.ApplicationIdle,
new Action(() =>
{
ZoomCommands.Uniform.Execute(null, ImageBox);
((MachineLayoutControlViewModel)DataContext).Zoombox_Visibility = Visibility.Visible;
}));
}
#endregion EventHandlers
}
For that you need reflection in C/C++ language, that doesn't exists. You need to have some meta data describing the structure of your classes (members, inherited base classes). For the moment C/C++ compilers doesn't provide automatically that information in built binaries.
I had the same idea in mind, and I used GCC XML project to get this information. It outputs XML data describing class structures. I have built a project and I'm explaining some key points in this page :
Serialization is easy, but we have to deal with complex data structure implementations (std::string, std::map for example) that play with allocated buffers. Deserialization is more complex and you need to rebuild your object with all its members, plus references to vtables ... a painful implementation.
For example you can serialize like that :
// Random class initialization
com::class1* aObject = new com::class1();
for (int i=0; i<10; i++){
aObject->setData(i,i);
}
aObject->pdata = new char[7];
for (int i=0; i<7; i++){
aObject->pdata[i] = 7-i;
}
// dictionary initialization
cjson::dictionary aDict("./data/dictionary.xml");
// json transformation
std::string aJson = aDict.toJson<com::class1>(aObject);
// print encoded class
cout << aJson << std::endl ;
To deserialize data it works like that:
// decode the object
com::class1* aDecodedObject = aDict.fromJson<com::class1>(aJson);
// modify data
aDecodedObject->setData(4,22);
// json transformation
aJson = aDict.toJson<com::class1>(aDecodedObject);
// print encoded class
cout << aJson << std::endl ;
Ouptuts:
>:~/cjson$ ./main
{"_index":54,"_inner": {"_ident":"test","pi":3.141593},"_name":"first","com::class0::_type":"type","com::class0::data":[0,1,2,3,4,5,6,7,8,9],"com::classb::_ref":"ref","com::classm1::_type":"typem1","com::classm1::pdata":[7,6,5,4,3,2,1]}
{"_index":54,"_inner":{"_ident":"test","pi":3.141593},"_name":"first","com::class0::_type":"type","com::class0::data":[0,1,2,3,22,5,6,7,8,9],"com::classb::_ref":"ref","com::classm1::_type":"typem1","com::classm1::pdata":[7,6,5,4,3,2,1]}
>:~/cjson$
Usually these implementations are compiler dependent (ABI Specification for example), and requires external description to work (GCCXML output), such are not really easy to integrate to projects.
Suppose you want to calculate the male–female ratios for various school clubs, but you discover that the following query fails and issues a divide-by-zero error when it tries to calculate ratio for the Lord of the Rings Club, which has no women:
SELECT club_id, males, females, males/females AS ratio
FROM school_clubs;
You can use the function NULLIF
to avoid division by zero. NULLIF
compares two expressions and returns null if they are equal or the first expression otherwise.
Rewrite the query as:
SELECT club_id, males, females, males/NULLIF(females, 0) AS ratio
FROM school_clubs;
Any number divided by NULL
gives NULL
, and no error is generated.
A bit late to the party but you can also use a context manager, if you're opening and closing your file multiple times, or logging data, statistics, etc.
from contextlib import contextmanager
import pandas as pd
@contextmanager
def open_file(path, mode):
file_to=open(path,mode)
yield file_to
file_to.close()
##later
saved_df=pd.DataFrame(data)
with open_file('yourcsv.csv','r') as infile:
saved_df.to_csv('yourcsv.csv',mode='a',header=False)`
I use this piece of code . works fine for me .copy it and run on your computer. you'll understand by yourself .
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <vector <int> > matrix;
size_t row=3 , col=3 ;
for(int i=0,cnt=1 ; i<row ; i++)
{
for(int j=0 ; j<col ; j++)
{
vector <int> colVector ;
matrix.push_back(colVector) ;
matrix.at(i).push_back(cnt++) ;
}
}
matrix.at(1).at(1) = 0; //matrix.at(columns).at(rows) = intValue
//printing all elements
for(int i=0,cnt=1 ; i<row ; i++)
{
for(int j=0 ; j<col ; j++)
{
cout<<matrix[i][j] <<" " ;
}
cout<<endl ;
}
}
You can create the radio buttons dynamically, ListBox
can help you do that, without converters, quite simple.
The concrete steps are below:
MyLovelyEnum
and binding the SelectedItem of the ListBox to the VeryLovelyEnum
property. <Window.Resources>
<ObjectDataProvider MethodName="GetValues"
ObjectType="{x:Type system:Enum}"
x:Key="MyLovelyEnum">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:MyLovelyEnum" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
Control Template
to populate each item inside as Radio button <ListBox ItemsSource="{Binding Source={StaticResource MyLovelyEnum}}" SelectedItem="{Binding VeryLovelyEnum, Mode=TwoWay}" >
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<RadioButton
Content="{TemplateBinding ContentPresenter.Content}"
IsChecked="{Binding Path=IsSelected,
RelativeSource={RelativeSource TemplatedParent},
Mode=TwoWay}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
</ListBox>
The advantage is: if someday your enum class changes, you do not need to update the GUI (XAML file).
References: https://brianlagunas.com/a-better-way-to-data-bind-enums-in-wpf/
employees.sort(key = lambda x:x[1])
employees.sort(key = lambda x:x[0])
We can also use .sort with lambda 2 times because python sort is in place and stable. This will first sort the list according to the second element, x[1]. Then, it will sort the first element, x[0] (highest priority).
employees[0] = Employee's Name
employees[1] = Employee's Salary
This is equivalent to doing the following: employees.sort(key = lambda x:(x[0], x[1]))
Transposing is inefficient for large DataFrames. Here is an alternative:
def duplicate_columns(frame):
groups = frame.columns.to_series().groupby(frame.dtypes).groups
dups = []
for t, v in groups.items():
dcols = frame[v].to_dict(orient="list")
vs = dcols.values()
ks = dcols.keys()
lvs = len(vs)
for i in range(lvs):
for j in range(i+1,lvs):
if vs[i] == vs[j]:
dups.append(ks[i])
break
return dups
Use it like this:
dups = duplicate_columns(frame)
frame = frame.drop(dups, axis=1)
Edit
A memory efficient version that treats nans like any other value:
from pandas.core.common import array_equivalent
def duplicate_columns(frame):
groups = frame.columns.to_series().groupby(frame.dtypes).groups
dups = []
for t, v in groups.items():
cs = frame[v].columns
vs = frame[v]
lcs = len(cs)
for i in range(lcs):
ia = vs.iloc[:,i].values
for j in range(i+1, lcs):
ja = vs.iloc[:,j].values
if array_equivalent(ia, ja):
dups.append(cs[i])
break
return dups
// Array of doubles
double[] array_doubles = {2.5, 6.2, 8.2, 4846.354, 9.6};
// First position
double firstNum = array_doubles[0]; // 2.5
// Last position
double lastNum = array_doubles[array_doubles.length - 1]; // 9.6
This is the same in any array.
Updated 2018
See if this example helps: http://bootply.com/mQh8DyRfWY
The brand is centered using..
.navbar-brand
{
position: absolute;
width: 100%;
left: 0;
top: 0;
text-align: center;
margin: auto;
}
Your markup is for Bootstrap 2, not 3. There is no longer a navbar-inner
.
EDIT - Another approach is using transform: translateX(-50%);
.navbar-brand {
transform: translateX(-50%);
left: 50%;
position: absolute;
}
http://www.bootply.com/V7vKDfk46G
In Bootstrap 4, mx-auto
or flexbox can be used to center the brand and other elements. See How to position navbar contents in Bootstrap 4 for an explanation.
Also see:
In the root path create a .htaccess file with
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/public/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /public/$1
#RewriteRule ^ index.php [L]
RewriteRule ^(/)?$ public/index.php [L]
</IfModule>
In public directory create a .htaccess file
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
if you have done any changes in public/index.php file correct them with the right path then your site will be live.
what will solve with this?
I'm using Borland code here is the code ti_hund gives me some times a negativnumber but timing is fairly good.
#include <dos.h>
void main()
{
struct time t;
int Hour,Min,Sec,Hun;
gettime(&t);
Hour=t.ti_hour;
Min=t.ti_min;
Sec=t.ti_sec;
Hun=t.ti_hund;
printf("Start time is: %2d:%02d:%02d.%02d\n",
t.ti_hour, t.ti_min, t.ti_sec, t.ti_hund);
....
your code to time
...
// read the time here remove Hours and min if the time is in sec
gettime(&t);
printf("\nTid Hour:%d Min:%d Sec:%d Hundreds:%d\n",t.ti_hour-Hour,
t.ti_min-Min,t.ti_sec-Sec,t.ti_hund-Hun);
printf("\n\nAlt Ferdig Press a Key\n\n");
getch();
} // end main
$('.submit').filter(':checked').each(function() {
//This is same as 'continue'
if(something){
return true;
}
//This is same as 'break'
if(something){
return false;
}
});
You can't use the elevation attribute before API 21 (Android Lollipop). You can however add the shadow programmatically, for example using a custom view placed below the Toolbar.
@layout/toolbar
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/blue"
android:minHeight="?attr/actionBarSize"
app:theme="@style/ThemeOverlay.AppCompat.ActionBar" />
<View
android:id="@+id/toolbar_shadow"
android:layout_width="match_parent"
android:layout_height="3dp"
android:background="@drawable/toolbar_dropshadow" />
@drawable/toolbar_dropshadow
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<gradient
android:startColor="@android:color/transparent"
android:endColor="#88333333"
android:angle="90"/> </shape>
in your activity layout
<include layout="@layout/toolbar" />
To check an ajax request you can use if (Request::ajax())
Note: If you are using laravel 5, then in the controller replace
use Illuminate\Http\Request;
with
use Request;
I hope it'll work.
Probably the only choice is to read it on the client side and transfer it manually to the server (GET/POST/AJAX). Regards Artur
You may see also how to play with back button and browser history at Malcan
time.clock()
Deprecated since version 3.3: The behavior of this function depends on the platform: use perf_counter() or process_time() instead, depending on your requirements, to have a well-defined behavior.
time.perf_counter()
Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide.
time.process_time()
Return the value (in fractional seconds) of the sum of the system and user CPU time of the current process. It does not include time elapsed during sleep.
start = time.process_time()
... do something
elapsed = (time.process_time() - start)
Use convert
from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)
To get the value of the selected Radio Button, Use RadioButtonName and the Form Id containing the RadioButton.
$('input[name=radioName]:checked', '#myForm').val()
OR by only
$('form input[type=radio]:checked').val();
Quoting the iPhone OS Technology Overview:
iPhone OS provides support for full-screen video playback through the Media Player framework (MediaPlayer.framework). This framework supports the playback of movie files with the .mov, .mp4, .m4v, and .3gp filename extensions and using the following compression standards:
- H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second, Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
- H.264 video, up to 768 Kbps, 320 by 240 pixels, 30 frames per second, Baseline Profile up to Level 1.3 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
- MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
- Numerous audio formats, including the ones listed in “Audio Technologies”
For information about the classes of the Media Player framework, see Media Player Framework Reference.
Trailing whitespace:
It is extra spaces (and tabs) at the end of line
^^^^^ here
Strip them:
#!/usr/bin/env python2
"""\
strip trailing whitespace from file
usage: stripspace.py <file>
"""
import sys
if len(sys.argv[1:]) != 1:
sys.exit(__doc__)
content = ''
outsize = 0
inp = outp = sys.argv[1]
with open(inp, 'rb') as infile:
content = infile.read()
with open(outp, 'wb') as output:
for line in content.splitlines():
newline = line.rstrip(" \t")
outsize += len(newline) + 1
output.write(newline + '\n')
print("Done. Stripped %s bytes." % (len(content)-outsize))
Try Project Euler:
Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.
The problem is:
Add all the natural numbers below 1000 that are multiples of 3 or 5.
This question will probably introduce you to Python for-loops and the range() builtin function in the least. It might lead you to discover list comprehensions, or generator expressions and the sum() builtin function.
A canvas has 2 sizes, the dimension of the pixels in the canvas (it's backingstore or drawingBuffer) and the display size. The number of pixels is set using the the canvas attributes. In HTML
<canvas width="400" height="300"></canvas>
Or in JavaScript
someCanvasElement.width = 400;
someCanvasElement.height = 300;
Separate from that are the canvas's CSS style width and height
In CSS
canvas { /* or some other selector */
width: 500px;
height: 400px;
}
Or in JavaScript
canvas.style.width = "500px";
canvas.style.height = "400px";
The arguably best way to make a canvas 1x1 pixels is to ALWAYS USE CSS to choose the size then write a tiny bit of JavaScript to make the number of pixels match that size.
function resizeCanvasToDisplaySize(canvas) {
// look up the size the canvas is being displayed
const width = canvas.clientWidth;
const height = canvas.clientHeight;
// If it's resolution does not match change it
if (canvas.width !== width || canvas.height !== height) {
canvas.width = width;
canvas.height = height;
return true;
}
return false;
}
Why is this the best way? Because it works in most cases without having to change any code.
const ctx = document.querySelector("#c").getContext("2d");_x000D_
_x000D_
function render(time) {_x000D_
time *= 0.001;_x000D_
resizeCanvasToDisplaySize(ctx.canvas);_x000D_
_x000D_
ctx.fillStyle = "#DDE";_x000D_
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_
ctx.save();_x000D_
_x000D_
const spacing = 64;_x000D_
const size = 48;_x000D_
const across = ctx.canvas.width / spacing + 1;_x000D_
const down = ctx.canvas.height / spacing + 1;_x000D_
const s = Math.sin(time);_x000D_
const c = Math.cos(time);_x000D_
for (let y = 0; y < down; ++y) {_x000D_
for (let x = 0; x < across; ++x) {_x000D_
ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
}_x000D_
}_x000D_
_x000D_
ctx.restore();_x000D_
_x000D_
requestAnimationFrame(render);_x000D_
}_x000D_
requestAnimationFrame(render);_x000D_
_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
// look up the size the canvas is being displayed_x000D_
const width = canvas.clientWidth;_x000D_
const height = canvas.clientHeight;_x000D_
_x000D_
// If it's resolution does not match change it_x000D_
if (canvas.width !== width || canvas.height !== height) {_x000D_
canvas.width = width;_x000D_
canvas.height = height;_x000D_
return true;_x000D_
}_x000D_
_x000D_
return false;_x000D_
}
_x000D_
body { margin: 0; }_x000D_
canvas { display: block; width: 100vw; height: 100vh; }
_x000D_
<canvas id="c"></canvas>
_x000D_
const ctx = document.querySelector("#c").getContext("2d");_x000D_
_x000D_
function render(time) {_x000D_
time *= 0.001;_x000D_
resizeCanvasToDisplaySize(ctx.canvas);_x000D_
_x000D_
ctx.fillStyle = "#DDE";_x000D_
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_
ctx.save();_x000D_
_x000D_
const spacing = 64;_x000D_
const size = 48;_x000D_
const across = ctx.canvas.width / spacing + 1;_x000D_
const down = ctx.canvas.height / spacing + 1;_x000D_
const s = Math.sin(time);_x000D_
const c = Math.cos(time);_x000D_
for (let y = 0; y <= down; ++y) {_x000D_
for (let x = 0; x <= across; ++x) {_x000D_
ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
}_x000D_
}_x000D_
_x000D_
ctx.restore();_x000D_
_x000D_
requestAnimationFrame(render);_x000D_
}_x000D_
requestAnimationFrame(render);_x000D_
_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
// look up the size the canvas is being displayed_x000D_
const width = canvas.clientWidth;_x000D_
const height = canvas.clientHeight;_x000D_
_x000D_
// If it's resolution does not match change it_x000D_
if (canvas.width !== width || canvas.height !== height) {_x000D_
canvas.width = width;_x000D_
canvas.height = height;_x000D_
return true;_x000D_
}_x000D_
_x000D_
return false;_x000D_
}
_x000D_
span { _x000D_
width: 250px; _x000D_
height: 100px; _x000D_
float: left; _x000D_
padding: 1em 1em 1em 0;_x000D_
display: inline-block;_x000D_
}_x000D_
canvas {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}
_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent cursus venenatis metus. Mauris ac nibh at odio scelerisque scelerisque. Donec ut enim <span class="diagram"><canvas id="c"></canvas></span>_x000D_
vel urna gravida imperdiet id ac odio. Aenean congue hendrerit eros id facilisis. In vitae leo ullamcorper, aliquet leo a, vehicula magna. Proin sollicitudin vestibulum aliquet. Sed et varius justo._x000D_
<br/><br/>_x000D_
Quisque tempor metus in porttitor placerat. Nulla vehicula sem nec ipsum commodo, at tincidunt orci porttitor. Duis porttitor egestas dui eu viverra. Sed et ipsum eget odio pharetra semper. Integer tempor orci quam, eget aliquet velit consectetur sit amet. Maecenas maximus placerat arcu in varius. Morbi semper, quam a ullamcorper interdum, augue nisl sagittis urna, sed pharetra lectus ex nec elit. Nullam viverra lacinia tellus, bibendum maximus nisl dictum id. Phasellus mauris quam, rutrum ut congue non, hendrerit sollicitudin urna._x000D_
</p>
_x000D_
const ctx = document.querySelector("#c").getContext("2d");_x000D_
_x000D_
function render(time) {_x000D_
time *= 0.001;_x000D_
resizeCanvasToDisplaySize(ctx.canvas);_x000D_
_x000D_
ctx.fillStyle = "#DDE";_x000D_
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_
ctx.save();_x000D_
_x000D_
const spacing = 64;_x000D_
const size = 48;_x000D_
const across = ctx.canvas.width / spacing + 1;_x000D_
const down = ctx.canvas.height / spacing + 1;_x000D_
const s = Math.sin(time);_x000D_
const c = Math.cos(time);_x000D_
for (let y = 0; y < down; ++y) {_x000D_
for (let x = 0; x < across; ++x) {_x000D_
ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
}_x000D_
}_x000D_
_x000D_
ctx.restore();_x000D_
_x000D_
requestAnimationFrame(render);_x000D_
}_x000D_
requestAnimationFrame(render);_x000D_
_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
// look up the size the canvas is being displayed_x000D_
const width = canvas.clientWidth;_x000D_
const height = canvas.clientHeight;_x000D_
_x000D_
// If it's resolution does not match change it_x000D_
if (canvas.width !== width || canvas.height !== height) {_x000D_
canvas.width = width;_x000D_
canvas.height = height;_x000D_
return true;_x000D_
}_x000D_
_x000D_
return false;_x000D_
}_x000D_
_x000D_
// ----- the code above related to the canvas does not change ----_x000D_
// ---- the code below is related to the slider ----_x000D_
const $ = document.querySelector.bind(document);_x000D_
const left = $(".left");_x000D_
const slider = $(".slider");_x000D_
let dragging;_x000D_
let lastX;_x000D_
let startWidth;_x000D_
_x000D_
slider.addEventListener('mousedown', e => {_x000D_
lastX = e.pageX;_x000D_
dragging = true;_x000D_
});_x000D_
_x000D_
window.addEventListener('mouseup', e => {_x000D_
dragging = false;_x000D_
});_x000D_
_x000D_
window.addEventListener('mousemove', e => {_x000D_
if (dragging) {_x000D_
const deltaX = e.pageX - lastX;_x000D_
left.style.width = left.clientWidth + deltaX + "px";_x000D_
lastX = e.pageX;_x000D_
}_x000D_
});
_x000D_
body { _x000D_
margin: 0;_x000D_
}_x000D_
.frame {_x000D_
display: flex;_x000D_
align-items: space-between;_x000D_
height: 100vh;_x000D_
}_x000D_
.left {_x000D_
width: 70%;_x000D_
left: 0;_x000D_
top: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
} _x000D_
canvas {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}_x000D_
pre {_x000D_
padding: 1em;_x000D_
}_x000D_
.slider {_x000D_
width: 10px;_x000D_
background: #000;_x000D_
}_x000D_
.right {_x000D_
flex 1 1 auto;_x000D_
}
_x000D_
<div class="frame">_x000D_
<div class="left">_x000D_
<canvas id="c"></canvas>_x000D_
</div>_x000D_
<div class="slider">_x000D_
_x000D_
</div>_x000D_
<div class="right">_x000D_
<pre>_x000D_
* controls_x000D_
* go _x000D_
* here_x000D_
_x000D_
<- drag this_x000D_
</pre>_x000D_
</div>_x000D_
</div>
_x000D_
const ctx = document.querySelector("#c").getContext("2d");_x000D_
_x000D_
function render(time) {_x000D_
time *= 0.001;_x000D_
resizeCanvasToDisplaySize(ctx.canvas);_x000D_
_x000D_
ctx.fillStyle = "#DDE";_x000D_
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_
ctx.save();_x000D_
_x000D_
const spacing = 64;_x000D_
const size = 48;_x000D_
const across = ctx.canvas.width / spacing + 1;_x000D_
const down = ctx.canvas.height / spacing + 1;_x000D_
const s = Math.sin(time);_x000D_
const c = Math.cos(time);_x000D_
for (let y = 0; y < down; ++y) {_x000D_
for (let x = 0; x < across; ++x) {_x000D_
ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
}_x000D_
}_x000D_
_x000D_
ctx.restore();_x000D_
_x000D_
requestAnimationFrame(render);_x000D_
}_x000D_
requestAnimationFrame(render);_x000D_
_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
// look up the size the canvas is being displayed_x000D_
const width = canvas.clientWidth;_x000D_
const height = canvas.clientHeight;_x000D_
_x000D_
// If it's resolution does not match change it_x000D_
if (canvas.width !== width || canvas.height !== height) {_x000D_
canvas.width = width;_x000D_
canvas.height = height;_x000D_
return true;_x000D_
}_x000D_
_x000D_
return false;_x000D_
}
_x000D_
body { margin: 0; }_x000D_
canvas { _x000D_
display: block; _x000D_
width: 100vw; _x000D_
height: 100vh; _x000D_
position: fixed;_x000D_
}_x000D_
#content {_x000D_
position: absolute;_x000D_
margin: 0 1em;_x000D_
font-size: xx-large;_x000D_
font-family: sans-serif;_x000D_
font-weight: bold;_x000D_
text-shadow: 2px 2px 0 #FFF, _x000D_
-2px -2px 0 #FFF,_x000D_
-2px 2px 0 #FFF,_x000D_
2px -2px 0 #FFF;_x000D_
}
_x000D_
<canvas id="c"></canvas>_x000D_
<div id="content">_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent cursus venenatis metus. Mauris ac nibh at odio scelerisque scelerisque. Donec ut enim vel urna gravida imperdiet id ac odio. Aenean congue hendrerit eros id facilisis. In vitae leo ullamcorper, aliquet leo a, vehicula magna. Proin sollicitudin vestibulum aliquet. Sed et varius justo._x000D_
</p>_x000D_
<p>_x000D_
Quisque tempor metus in porttitor placerat. Nulla vehicula sem nec ipsum commodo, at tincidunt orci porttitor. Duis porttitor egestas dui eu viverra. Sed et ipsum eget odio pharetra semper. Integer tempor orci quam, eget aliquet velit consectetur sit amet. Maecenas maximus placerat arcu in varius. Morbi semper, quam a ullamcorper interdum, augue nisl sagittis urna, sed pharetra lectus ex nec elit. Nullam viverra lacinia tellus, bibendum maximus nisl dictum id. Phasellus mauris quam, rutrum ut congue non, hendrerit sollicitudin urna._x000D_
</p>_x000D_
</div>
_x000D_
Because I didn't set the attributes the only thing that changed in each sample is the CSS (as far as the canvas is concerned)
Notes:
Add the below lines in .gitignore and place the file inside ur project folder
/target/
/.classpath
/*.project
/.settings
/*.springBeans
<asp:TemplateField HeaderText="ExEmp" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"
FooterStyle-BackColor="BurlyWood" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:TextBox ID="txtNoOfExEmp" runat="server" CssClass="form-control input-sm m-bot15"
Font-Bold="true" onkeypress="return isNumberKey(event)" Text='<%#Bind("ExEmp") %>'></asp:TextBox>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" Width="50px" />
<FooterTemplate>
<asp:Label ID="lblTotNoOfExEmp" Font-Bold="true" runat="server" Text="0" CssClass="form-label"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
private void TotalExEmpOFMonth()
{
Label lbl_TotNoOfExEmp = (Label)GrdPFRecord.FooterRow.FindControl("lblTotNoOfExEmp");
/*Sum of the Total Amount Of month*/
foreach (GridViewRow gvr in GrdPFRecord.Rows)
{
TextBox txt_NoOfExEmp = (TextBox)gvr.FindControl("txtNoOfExEmp");
lbl_TotNoOfExEmp.Text = (Convert.ToDouble(txt_NoOfExEmp.Text) + Convert.ToDouble(lbl_TotNoOfExEmp.Text)).ToString();
lbl_TotNoOfExEmp.Text = string.Format("{0:F0}", Decimal.Parse(lbl_TotNoOfExEmp.Text));
}
}
Here is a simple approach:
#!/bin/bash
USE_IP='-o StrictHostKeyChecking=no [email protected]'
FILE_NAME=/home/user/file.txt
SSH_PASS='sshpass -p password-for-remote-machine'
if $SSH_PASS ssh $USE_IP stat $FILE_NAME \> /dev/null 2\>\&1
then
echo "File exists"
else
echo "File does not exist"
fi
You need to install sshpass on your machine to work it.
Even using this won't work. I think the best solution is Browserify:
module.exports = {
func1: function () {
console.log("I am function 1");
},
func2: function () {
console.log("I am function 2");
}
};
-getFunc1.js-
var common = require('./common');
common.func1();
A solution using mutate_all
from dplyr
in case you want to add that to your dplyr
pipeline:
library(dplyr)
df %>%
mutate_all(funs(ifelse(is.na(.), 0, .)))
Result:
A B C
1 0 0 0
2 1 0 0
3 2 0 2
4 3 0 5
5 0 0 2
6 0 0 1
7 1 0 1
8 2 0 5
9 3 0 2
10 0 0 4
11 0 0 3
12 1 0 5
13 2 0 5
14 3 0 0
15 0 0 1
If in any case you only want to replace the NA's in numeric columns, which I assume it might be the case in modeling, you can use mutate_if
:
library(dplyr)
df %>%
mutate_if(is.numeric, funs(ifelse(is.na(.), 0, .)))
or in base R:
replace(is.na(df), 0)
Result:
A B C
1 0 0 0
2 1 <NA> 0
3 2 0 2
4 3 <NA> 5
5 0 0 2
6 0 <NA> 1
7 1 0 1
8 2 <NA> 5
9 3 0 2
10 0 <NA> 4
11 0 0 3
12 1 <NA> 5
13 2 0 5
14 3 <NA> 0
15 0 0 1
with dplyr 1.0.0
, across
is introduced:
library(dplyr)
# Replace `NA` for all columns
df %>%
mutate(across(everything(), ~ ifelse(is.na(.), 0, .)))
# Replace `NA` for numeric columns
df %>%
mutate(across(where(is.numeric), ~ ifelse(is.na(.), 0, .)))
Data:
set.seed(123)
df <- data.frame(A=rep(c(0:3, NA), 3),
B=rep(c("0", NA), length.out = 15),
C=sample(c(0:5, NA), 15, replace = TRUE))
Here is a helper function:
def append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,
truncate_sheet=False,
**to_excel_kwargs):
"""
Append a DataFrame [df] to existing Excel file [filename]
into [sheet_name] Sheet.
If [filename] doesn't exist, then this function will create it.
Parameters:
filename : File path or existing ExcelWriter
(Example: '/path/to/file.xlsx')
df : dataframe to save to workbook
sheet_name : Name of sheet which will contain DataFrame.
(default: 'Sheet1')
startrow : upper left cell row to dump data frame.
Per default (startrow=None) calculate the last row
in the existing DF and write to the next row...
truncate_sheet : truncate (remove and recreate) [sheet_name]
before writing DataFrame to Excel file
to_excel_kwargs : arguments which will be passed to `DataFrame.to_excel()`
[can be dictionary]
Returns: None
(c) [MaxU](https://stackoverflow.com/users/5741205/maxu?tab=profile)
"""
from openpyxl import load_workbook
# ignore [engine] parameter if it was passed
if 'engine' in to_excel_kwargs:
to_excel_kwargs.pop('engine')
writer = pd.ExcelWriter(filename, engine='openpyxl')
# Python 2.x: define [FileNotFoundError] exception if it doesn't exist
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
try:
# try to open an existing workbook
writer.book = load_workbook(filename)
# get the last row in the existing Excel sheet
# if it was not specified explicitly
if startrow is None and sheet_name in writer.book.sheetnames:
startrow = writer.book[sheet_name].max_row
# truncate sheet
if truncate_sheet and sheet_name in writer.book.sheetnames:
# index of [sheet_name] sheet
idx = writer.book.sheetnames.index(sheet_name)
# remove [sheet_name]
writer.book.remove(writer.book.worksheets[idx])
# create an empty sheet [sheet_name] using old index
writer.book.create_sheet(sheet_name, idx)
# copy existing sheets
writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
except FileNotFoundError:
# file does not exist yet, we will create it
pass
if startrow is None:
startrow = 0
# write out the new sheet
df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs)
# save the workbook
writer.save()
NOTE: for Pandas < 0.21.0, replace sheet_name
with sheetname
!
Usage examples:
append_df_to_excel('d:/temp/test.xlsx', df)
append_df_to_excel('d:/temp/test.xlsx', df, header=None, index=False)
append_df_to_excel('d:/temp/test.xlsx', df, sheet_name='Sheet2', index=False)
append_df_to_excel('d:/temp/test.xlsx', df, sheet_name='Sheet2', index=False, startrow=25)
The question itself has already been addressed above. Just adding part of the default values.
As per http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/jrdocs/refman/optionX.html
The default value of Xmx will depend on platform and amount of memory available in the system.
This will detect any version of Firefox:
var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
more specifically:
if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1){
// Do Firefox-related activities
}
You may want to consider using feature-detection ala Modernizr, or a related tool, to accomplish what you need.
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/', ['as' => 'home', 'uses' => 'BaseController@index']);
Route::group(['namespace' => 'User', 'prefix' => 'user'], function(){
Route::get('{nickname}/settings', ['as' => 'user.settings', 'uses' => 'SettingsController@index']);
Route::get('{nickname}/profile', ['as' => 'user.profile', 'uses' => 'ProfileController@index']);
});
});
You need to open TCP port 8787 in the ec2 Security Group. Also need to open the same port on the EC2 instance's firewall.
The explanations given here are correct. I just wanted to add that this problem might be because you copied the code from somewhere, from a website or a pdf file due to which there are some invalid characters in the code.
Try to find those invalid characters, or just retype the code if you can't. It will definitely compile then.
Source: stray error reason
Something has deleted your ibdata1 file where InnoDB keeps the dictionary. Definitely it's not MySQL who does it.
UPDATE: I made a tutorial on how to fix the error - https://youtu.be/014KbCYayuE
I know it's an old question, but if someone is looking here again... see https://python-sounddevice.readthedocs.io/en/0.4.1/index.html .
It has a nice example "Input to Ouput Pass-Through" here https://python-sounddevice.readthedocs.io/en/0.4.1/examples.html#input-to-output-pass-through .
... and a lot of other examples as well ...
You could use a sub query...
WHERE t1.field3 = (SELECT MAX(st1.field3) FROM table1 AS st1)
But I would actually move this out of the where clause and into the join statement, as an AND for the ON clause.
short answer, specific to OAuth2,
A[A==NDV]=numpy.nan
A==NDV will produce a boolean array that can be used as an index for A
I guess you probably are running the preview of VS2013 Ultimate, because it is not present in my professional preview. But looking online I found that the feature is called Code Information Indicators
or CodeLens
, and can be located under
Tools ? Options ? Text Editor ? All Languages ? CodeLens
(for RC/final version)
or
Tools ? Options ? Text Editor ? All Languages ? Code Information Indicators
(for preview version)
That was according to this link. It seems to be pretty well hidden.
In Visual Studio 2013 RTM, you can also get to the CodeLens options by right clicking the indicators themselves in the editor:
documented in the Q&A section of the msdn CodeLens documentation
I wouldn't go so far as @Femi to change the existing address property. You can add new services to the definitions section easily.
<wsdl:service name="serviceMethodName_2">
<wsdl:port binding="tns:serviceMethodNameSoapBinding" name="serviceMethodName">
<soap:address location="http://new_end_point_adress"/>
</wsdl:port>
</wsdl:service>
This doesn't require a recompile of the WSDL to Java and making updates isn't any more difficult than if you used the BindingProvider option (which didn't work for me btw).
Re: craigts's response, for anyone having trouble with using either False or None parameters for index_col, such as in cases where you're trying to get rid of a range index, you can instead use an integer to specify the column you want to use as the index. For example:
df = pd.read_csv('file.csv', index_col=0)
The above will set the first column as the index (and not add a range index in my "common case").
Given the popularity of this answer, I thought i'd add some context/ a demo:
# Setting up the dummy data
In [1]: df = pd.DataFrame({"A":[1, 2, 3], "B":[4, 5, 6]})
In [2]: df
Out[2]:
A B
0 1 4
1 2 5
2 3 6
In [3]: df.to_csv('file.csv', index=None)
File[3]:
A B
1 4
2 5
3 6
Reading without index_col or with None/False will all result in a range index:
In [4]: pd.read_csv('file.csv')
Out[4]:
A B
0 1 4
1 2 5
2 3 6
# Note that this is the default behavior, so the same as In [4]
In [5]: pd.read_csv('file.csv', index_col=None)
Out[5]:
A B
0 1 4
1 2 5
2 3 6
In [6]: pd.read_csv('file.csv', index_col=False)
Out[6]:
A B
0 1 4
1 2 5
2 3 6
However, if we specify that "A" (the 0th column) is actually the index, we can avoid the range index:
In [7]: pd.read_csv('file.csv', index_col=0)
Out[7]:
B
A
1 4
2 5
3 6
I added a check that makes it work...
if (_form.Handle.ToInt32() > 0)
{
_form.Invoke(method, args);
}
it is always true, but the form throws an error without it. BTW, my handle is around 4.9 million
What about System.getProperty("user.dir")
? It'll give you the working directory from where your program was launched.
See System Properties from the Java Tutorial for an overview of Java's System Properties.
I would include all functions of one case in an include
file, and the others in another include
.
For instance simple.inc
would contain function boofoo() { simple }
and really.inc
would contain function boofoo() { really }
It helps the readability / maintenance of your program, having all functions of the same kind in the same inc
.
Then at the top of your main module
if ($_GET['foolevel'] == 10) {
include "really.inc";
}
else {
include "simple.inc";
}
For a quick fix or test, I find it handy just adding #define _CRT_SECURE_NO_WARNINGS
to the top of the file before all #include
#define _CRT_SECURE_NO_WARNINGS
#include ...
int main(){
//...
}
Just add them in one line command 2>> error 1>> output
However, note that >>
is for appending if the file already has data. Whereas, >
will overwrite any existing data in the file.
So, command 2> error 1> output
if you do not want to append.
Just for completion's sake, you can write 1>
as just >
since the default file descriptor is the output. so 1>
and >
is the same thing.
So, command 2> error 1> output
becomes, command 2> error > output
Run it on a single command line like so:
powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile
-WindowStyle Hidden -Command "Get-AppLockerFileInformation -Directory <folderpath>
-Recurse -FileType <type>"
Deleting duplicates from a huge(several millions of records) table might take long time . I suggest that you do a bulk insert into a temp table of the selected rows rather than deleting.
--REWRITING YOUR CODE(TAKE NOTE OF THE 3RD LINE) WITH CTE AS(SELECT NAME,ROW_NUMBER()
OVER (PARTITION BY NAME ORDER BY NAME) ID FROM @TB) SELECT * INTO #unique_records FROM
CTE WHERE ID =1;
VMDK/VMX are VMWare file formats but you can use it with VirtualBox:
Remove javascript:
from onclick="..
, onsubmit="..
declarations
javascript:
prefix is used only in href=""
or similar attributes (not events related)
Here is the general solution if you really only want the first key's value
Object firstKey = myHashMap.keySet().toArray()[0];
Object valueForFirstKey = myHashMap.get(firstKey);
You could create a function who consumes an list of int, transforms in string to concatenate and cast do int again, something like this:
import random
def generate_random_number(length):
return int(''.join([str(random.randint(0,10)) for _ in range(length)]))
It seems Google have updated their docs since all these answers, so hopefully this will help someone else in future :) Just came across this question myself, while creating a new (new new) project.
TL;DR: drawables may be stripped out as part of dp-specific resource optimisation. Mipmaps will not be stripped.
Different home screen launcher apps on different devices show app launcher icons at various resolutions. When app resource optimization techniques remove resources for unused screen densities, launcher icons can wind up looking fuzzy because the launcher app has to upscale a lower-resolution icon for display. To avoid these display issues, apps should use the
mipmap/
resource folders for launcher icons. The Android system preserves these resources regardless of density stripping, and ensures that launcher apps can pick icons with the best resolution for display.
(from http://developer.android.com/tools/projects/index.html#mipmap)
The first line of every source file of your project must be the following:
#include <stdafx.h>
Visit here to understand Precompiled Headers
Try this:
Calendar calendar = Calendar.getInstance();
calendar.setTime(yourdate);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);
Edit:
hours, minutes, seconds
above will be the hours, minutes and seconds after converting yourdate
to System Timezone!
Ideally, a hashtable is O(1)
. The problem is if two keys are not equal, however they result in the same hash.
For example, imagine the strings "it was the best of times it was the worst of times" and "Green Eggs and Ham" both resulted in a hash value of 123
.
When the first string is inserted, it's put in bucket 123. When the second string is inserted, it would see that a value already exists for bucket 123
. It would then compare the new value to the existing value, and see they are not equal. In this case, an array or linked list is created for that key. At this point, retrieving this value becomes O(n)
as the hashtable needs to iterate through each value in that bucket to find the desired one.
For this reason, when using a hash table, it's important to use a key with a really good hash function that's both fast and doesn't often result in duplicate values for different objects.
Make sense?
ddd is a graphical front-end to gdb that is pretty nice. One of the down sides is a classic X interface, but I seem to recall it being pretty intuitive.
If the icon is from Font Awesome (https://fontawesome.com/icons/) then you could tap into the color css property to change it's background.
fb-icon{
color:none;
}
fb-icon:hover{
color:#0000ff;
}
This is irrespective of the color it had. So you could use an entirely different color in its usual state and define another in its active state.
this is what worked for me as seen here.
Just use it or add it to a static class helper and just call it from anywher in your project.
/**
Current Activity instance will go through its lifecycle to onDestroy() and a new instance then created after it.
*/
@SuppressLint("NewApi")
public static final void recreateActivityCompat(final Activity a) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
a.recreate();
} else {
final Intent intent = a.getIntent();
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
a.finish();
a.overridePendingTransition(0, 0);
a.startActivity(intent);
a.overridePendingTransition(0, 0);
}
}
I think the simplest way to do this is to create a loop to compare the each value to the next. As long as there is a break in the "chain" then it would return false. If the first is equal to the second, the second equal to the third and so on, then we can conclude that all elements of the array are equal to each other.
given an array data[], then you can use:
for(x=0;x<data.length - 1;x++){
if (data[x] != data[x+1]){
isEqual = false;
}
}
alert("All elements are equal is " + isEqual);
Internally, Chrome maintains a stack, where $0 is the selected element, $1 is the element that was last selected, $2 would be the one that was selected before $1 and so on.
Here are some of its applications:
This is documented behavior. From ?as.Date
:
format: A character string. If not specified, it will try '"%Y-%m-%d"' then '"%Y/%m/%d"' on the first non-'NA' element, and give an error if neither works.
as.Date("01 Jan 2000")
yields an error because the format isn't one of the two listed above. as.Date("01/01/2000")
yields an incorrect answer because the date isn't in one of the two formats listed above.
I take "standard unambiguous" to mean "ISO-8601" (even though as.Date
isn't that strict, as "%m/%d/%Y" isn't ISO-8601).
If you receive this error, the solution is to specify the format your date (or datetimes) are in, using the formats described in ?strptime
. Be sure to use particular care if your data contain day/month names and/or abbreviations, as the conversion will depend on your locale (see the examples in ?strptime
and read ?LC_TIME
).
I found this to be a better solution
$(".alert-dismissible").fadeTo(2000, 500).slideUp(500, function(){
$(".alert-dismissible").alert('close');
});
I see a lot of answers that repeat the old idiom:
If it looks like a duck and quacks like a duck, it's a duck
and then dive into an explanation of what you can do with duck typing, or an example which seems to obfuscate the concept further.
I don't find that much help.
This is the best attempt at a plain english answer about duck typing that I have found:
Duck Typing means that an object is defined by what it can do, not by what it is.
This means that we are less concerned with the class/type of an object and more concerned with what methods can be called on it and what operations can be performed on it. We don't care about it's type, we care about what it can do.
If you use file_put_contents you don't need to do a fopen -> fwrite -> fclose, the file_put_contents does all that for you. You should also check if the webserver has write rights in the directory where you are trying to write your "data.txt" file.
Depending on your PHP version (if it's old) you might not have the file_get/put_contents functions. Check your webserver log to see if any error appeared when you executed the script.
As of Swift 4 (Xcode 9), the Swift standard
library provides methods to convert between Swift string ranges
(Range<String.Index>
) and NSString
ranges (NSRange
).
Example:
let str = "abc"
let r1 = str.range(of: "")!
// String range to NSRange:
let n1 = NSRange(r1, in: str)
print((str as NSString).substring(with: n1)) //
// NSRange back to String range:
let r2 = Range(n1, in: str)!
print(str[r2]) //
Therefore the text replacement in the text field delegate method can now be done as
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
if let oldString = textField.text {
let newString = oldString.replacingCharacters(in: Range(range, in: oldString)!,
with: string)
// ...
}
// ...
}
(Older answers for Swift 3 and earlier:)
As of Swift 1.2, String.Index
has an initializer
init?(_ utf16Index: UTF16Index, within characters: String)
which can be used to convert NSRange
to Range<String.Index>
correctly
(including all cases of Emojis, Regional Indicators or other extended
grapheme clusters) without intermediate conversion to an NSString
:
extension String {
func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
let from16 = advance(utf16.startIndex, nsRange.location, utf16.endIndex)
let to16 = advance(from16, nsRange.length, utf16.endIndex)
if let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self) {
return from ..< to
}
return nil
}
}
This method returns an optional string range because not all NSRange
s
are valid for a given Swift string.
The UITextFieldDelegate
delegate method can then be written as
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if let swRange = textField.text.rangeFromNSRange(range) {
let newString = textField.text.stringByReplacingCharactersInRange(swRange, withString: string)
// ...
}
return true
}
The inverse conversion is
extension String {
func NSRangeFromRange(range : Range<String.Index>) -> NSRange {
let utf16view = self.utf16
let from = String.UTF16View.Index(range.startIndex, within: utf16view)
let to = String.UTF16View.Index(range.endIndex, within: utf16view)
return NSMakeRange(from - utf16view.startIndex, to - from)
}
}
A simple test:
let str = "abc"
let r1 = str.rangeOfString("")!
// String range to NSRange:
let n1 = str.NSRangeFromRange(r1)
println((str as NSString).substringWithRange(n1)) //
// NSRange back to String range:
let r2 = str.rangeFromNSRange(n1)!
println(str.substringWithRange(r2)) //
Update for Swift 2:
The Swift 2 version of rangeFromNSRange()
was already given
by Serhii Yakovenko in this answer, I am including it
here for completeness:
extension String {
func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
let from16 = utf16.startIndex.advancedBy(nsRange.location, limit: utf16.endIndex)
let to16 = from16.advancedBy(nsRange.length, limit: utf16.endIndex)
if let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self) {
return from ..< to
}
return nil
}
}
The Swift 2 version of NSRangeFromRange()
is
extension String {
func NSRangeFromRange(range : Range<String.Index>) -> NSRange {
let utf16view = self.utf16
let from = String.UTF16View.Index(range.startIndex, within: utf16view)
let to = String.UTF16View.Index(range.endIndex, within: utf16view)
return NSMakeRange(utf16view.startIndex.distanceTo(from), from.distanceTo(to))
}
}
Update for Swift 3 (Xcode 8):
extension String {
func nsRange(from range: Range<String.Index>) -> NSRange {
let from = range.lowerBound.samePosition(in: utf16)
let to = range.upperBound.samePosition(in: utf16)
return NSRange(location: utf16.distance(from: utf16.startIndex, to: from),
length: utf16.distance(from: from, to: to))
}
}
extension String {
func range(from nsRange: NSRange) -> Range<String.Index>? {
guard
let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
let to16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location + nsRange.length, limitedBy: utf16.endIndex),
let from = from16.samePosition(in: self),
let to = to16.samePosition(in: self)
else { return nil }
return from ..< to
}
}
Example:
let str = "abc"
let r1 = str.range(of: "")!
// String range to NSRange:
let n1 = str.nsRange(from: r1)
print((str as NSString).substring(with: n1)) //
// NSRange back to String range:
let r2 = str.range(from: n1)!
print(str.substring(with: r2)) //
While I agree with everyone, this is no-nice behavior, here is code:
[DllImport("User32.dll")]
public static extern Int32 SetForegroundWindow(int hWnd);
SetForegroundWindow(Handle.ToInt32());
Update
David is completely right, for completeness I include the list of conditions that must apply for this to work (+1 for David!):
@The Thunder Chimp You can split text in such a way that some sections are affected by super(or sub) script and others aren't through the use of *. For your example, with splitting the word "moment" from "4th" -
plot(rnorm(30), xlab = expression('4'^th*'moment'))
git clean -d -f -i
is the best way to do it.
This will help to clean in a more controlled manner.
-i
stands for interactive.
String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']/div[1]/span));
kk.getText().toString();
System.out.println(+kk.getText().toString());
I found this the quick and easy way:
Used: org.json.XML
class from java-json.jar
if (statusCode == 200 && inputStream != null) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = bufferedReader.readLine()) != null) {
responseStrBuilder.append(inputStr);
}
jsonObject = XML.toJSONObject(responseStrBuilder.toString());
}
That depends on what you mean. If you just want to get rid of them, do this:
(Update: Apparently you want to keep digits as well, use the second lines in that case)
String alphaOnly = input.replaceAll("[^a-zA-Z]+","");
String alphaAndDigits = input.replaceAll("[^a-zA-Z0-9]+","");
or the equivalent:
String alphaOnly = input.replaceAll("[^\\p{Alpha}]+","");
String alphaAndDigits = input.replaceAll("[^\\p{Alpha}\\p{Digit}]+","");
(All of these can be significantly improved by precompiling the regex pattern and storing it in a constant)
Or, with Guava:
private static final CharMatcher ALNUM =
CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z'))
.or(CharMatcher.inRange('0', '9')).precomputed();
// ...
String alphaAndDigits = ALNUM.retainFrom(input);
But if you want to turn accented characters into something sensible that's still ascii, look at these questions:
Here is your article for doing it with code
private void Form1_Load(object sender, System.EventArgs e)
{
// Create the ToolTip and associate with the Form container.
ToolTip toolTip1 = new ToolTip();
// Set up the delays for the ToolTip.
toolTip1.AutoPopDelay = 5000;
toolTip1.InitialDelay = 1000;
toolTip1.ReshowDelay = 500;
// Force the ToolTip text to be displayed whether or not the form is active.
toolTip1.ShowAlways = true;
// Set up the ToolTip text for the Button and Checkbox.
toolTip1.SetToolTip(this.button1, "My button1");
toolTip1.SetToolTip(this.checkBox1, "My checkBox1");
}
You could use vcsjones's solution, but this might cause problems with further ping/tracert commands, since the result is an array of addresses and you need only one.
To select the proper address, Send
an ICMP echo request and read the Address
property of the echo reply:
$ping = New-Object System.Net.NetworkInformation.Ping
$ip = $($ping.Send("yourhosthere").Address).IPAddressToString
Though the remarks from the documentation say:
The
Address
returned by any of theSend
overloads can originate from a malicious remote computer. Do not connect to the remote computer using this address. Use DNS to determine the IP address of the machine to which you want to connect.
you can use String format to include variables within strings
i use this code to include 2 variable in string:
String myString = String.format("this is my string %s %2d", variable1Name, variable2Name);
in my case i always put these stuffs in a p tag like
<p>
name : < input type=text />
</p>
and so on and then applying the css like
p {
text-align:left;
}
p input {
float:right;
}
You need to specify the width of the p tag.because the input tags will float all the way right.
This css will also affect the submit button. You need to override the rule for this tag.
Reason for the error: In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column. Source:MSDN
Actual Code which I faced error:
Before changed the code:
if( ds.Tables[0].Rows[0][0] == null ) // Which is not working
{
seqno = 1;
}
else
{
seqno = Convert.ToInt16(ds.Tables[0].Rows[0][0]) + 1;
}
After changed the code:
if( ds.Tables[0].Rows[0][0] == DBNull.Value ) //which is working properly
{
seqno = 1;
}
else
{
seqno = Convert.ToInt16(ds.Tables[0].Rows[0][0]) + 1;
}
Conclusion: when the database value return the null value, we recommend to use the DBNull class instead of just specifying as a null like in C# language.
Not sure if it will work with AngularJS v1.2.0-rc.2 with ui-router v0.2.0. I have tested this solution on AngularJS v1.3.14 with ui-router v0.2.13.
I just realize that is not necessary to pass the parameter in the URL as gwhn recommends.
Just add your parameters with a default value on your state definition. Your state can still have an Url value.
$stateProvider.state('state1', {
url : '/url',
templateUrl : "new.html",
controller : 'TestController',
params: {new_param: null}
});
and add the param to $state.go()
$state.go('state1',{new_param: "Going places!"});
While dbenham's answer is pretty good, relying on IF DEFINED
can get you in loads of trouble if the variable you're checking isn't an environment variable. Script variables don't get this special treatment.
While this might seem like some ludicrous undocumented BS, doing a simple shell query of IF
with IF /?
reveals that,
The DEFINED conditional works just like EXIST except it takes an environment variable name and returns true if the environment variable is defined.
In regards to answering this question, is there a reason to not just use a simple flag after a series of evaluations? That seems the most flexible OR
check to me, both in regards to underlying logic and readability. For example:
Set Evaluated_True=false
IF %condition_1%==true (Set Evaluated_True=true)
IF %some_string%=="desired result" (Set Evaluated_True=true)
IF %set_numerical_variable% EQ %desired_numerical_value% (Set Evaluated_True=true)
IF %Evaluated_True%==true (echo This is where you do your passing logic) ELSE (echo This is where you do your failing logic)
Obviously, they can be any sort of conditional evaluation, but I'm just sharing a few examples.
If you wanted to have it all on one line, written-wise, you could just chain them together with &&
like:
Set Evaluated_True=false
IF %condition_1%==true (Set Evaluated_True=true) && IF %some_string%=="desired result" (Set Evaluated_True=true) && IF %set_numerical_variable% EQ %desired_numerical_value% (Set Evaluated_True=true)
IF %Evaluated_True%==true (echo This is where you do your passing logic) ELSE (echo This is where you do your failing logic)
The line-continuation will fail if you have whitespace (spaces or tab characters[1]) after the backslash and before the newline. With no such whitespace, your example works fine for me:
$ cat test.sh
if ! fab --fabfile=.deploy/fabfile.py \
--forward-agent \
--disable-known-hosts deploy:$target; then
echo failed
else
echo succeeded
fi
$ alias fab=true; . ./test.sh
succeeded
$ alias fab=false; . ./test.sh
failed
Some detail promoted from the comments: the line-continuation backslash in the shell is not really a special case; it is simply an instance of the general rule that a backslash "quotes" the immediately-following character, preventing any special treatment it would normally be subject to. In this case, the next character is a newline, and the special treatment being prevented is terminating the command. Normally, a quoted character winds up included literally in the command; a backslashed newline is instead deleted entirely. But otherwise, the mechanism is the same. Most importantly, the backslash only quotes the immediately-following character; if that character is a space or tab, you just get a literal space or tab, and any subsequent newline remains unquoted.
[1] or carriage returns, for that matter, as Czechnology points out. Bash does not get along with Windows-formatted text files, not even in WSL. Or Cygwin, but at least their Bash port has added a set -o igncr
option that you can set to make it carriage-return-tolerant.
It's easier with the enumitem package:
\documentclass{article}
\usepackage{enumitem}
\begin{document}
Less space:
\begin{itemize}[noitemsep]
\item foo
\item bar
\item baz
\end{itemize}
Even more compact:
\begin{itemize}[noitemsep,nolistsep]
\item foo
\item bar
\item baz
\end{itemize}
\end{document}
The enumitem package provides a lot of features to customize bullets, numbering and lengths.
The paralist package provides very compact lists: compactitem, compactenum and even lists within paragraphs like inparaenum and inparaitem.
It’s because you tried to update a table without a WHERE that uses a KEY column.
The quick fix is to add SET SQL_SAFE_UPDATES=0; before your query :
SET SQL_SAFE_UPDATES=0;
Or
close the safe update mode. Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) .
BTW you can use TRUNCATE TABLE tablename;
to delete all the records .
the first step
netstat -vanp tcp | grep 8888
example
tcp4 0 0 127.0.0.1.8888 *.* LISTEN 131072 131072 76061 0
tcp46 0 0 *.8888 *.* LISTEN 131072 131072 50523 0
the second step: find your PIDs and kill them
in my case
sudo kill -9 76061 50523
Made a sample code implementing the same with slide effects from left, right, top and bottom. (For those who dont want to make all those anim xml files :) )
Checkout out the code on github
I think the quickest/neatest way to do this:
For each class have string[] obj.ToListViewItem()
method and then do this:
foreach(var item in personList)
{
listView1.Items.Add(new ListViewItem(item.ToListViewItem()));
}
Here is an example definition
public class Person
{
public string Name { get; set; }
public string Address { get; set; }
public DateTime DOB { get; set; }
public uint ID { get; set; }
public string[] ToListViewItem()
{
return new string[] {
ID.ToString("000000"),
Name,
Address,
DOB.ToShortDateString()
};
}
}
As an added bonus you can have a static
method that returns ColumnHeader[]
list for setting up the listview columns with
listView1.Columns.AddRange(Person.ListViewHeaders());
Use $dirty
flag to show the error only after user interacted with the input:
<div>
<input type="email" name="email" ng-model="user.email" required />
<span ng-show="form.email.$dirty && form.email.$error.required">Email is required</span>
</div>
If you want to trigger the errors only after the user has submitted the form than you may use a separate flag variable as in:
<form ng-submit="submit()" name="form" ng-controller="MyCtrl">
<div>
<input type="email" name="email" ng-model="user.email" required />
<span ng-show="(form.email.$dirty || submitted) && form.email.$error.required">
Email is required
</span>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
function MyCtrl($scope){
$scope.submit = function(){
// Set the 'submitted' flag to true
$scope.submitted = true;
// Send the form to server
// $http.post ...
}
};
Then, if all that JS inside ng-show
expression looks too much for you, you can abstract it into a separate method:
function MyCtrl($scope){
$scope.submit = function(){
// Set the 'submitted' flag to true
$scope.submitted = true;
// Send the form to server
// $http.post ...
}
$scope.hasError = function(field, validation){
if(validation){
return ($scope.form[field].$dirty && $scope.form[field].$error[validation]) || ($scope.submitted && $scope.form[field].$error[validation]);
}
return ($scope.form[field].$dirty && $scope.form[field].$invalid) || ($scope.submitted && $scope.form[field].$invalid);
};
};
<form ng-submit="submit()" name="form">
<div>
<input type="email" name="email" ng-model="user.email" required />
<span ng-show="hasError('email', 'required')">required</span>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
For the first question I think answer would be:
<your DataFrame>.rename(columns={'count':'Total_Numbers'})
or
<your DataFrame>.columns = ['ID', 'Region', 'Total_Numbers']
As for second one I'd say the answer would be no. It's possible to use it like 'df.ID' because of python datamodel:
Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.dict["x"]
I am using like this in my code and it's working fine
using System.Web.Script.Serialization;
JavaScriptSerializer oJS = new JavaScriptSerializer();
RootObject oRootObject = new RootObject();
oRootObject = oJS.Deserialize<RootObject>(Your JSon String);
There is a method that is designed for this. Check out process.hrtime(); .
So, I basically put this at the top of my app.
var start = process.hrtime();
var elapsed_time = function(note){
var precision = 3; // 3 decimal places
var elapsed = process.hrtime(start)[1] / 1000000; // divide by a million to get nano to milli
console.log(process.hrtime(start)[0] + " s, " + elapsed.toFixed(precision) + " ms - " + note); // print message + time
start = process.hrtime(); // reset the timer
}
Then I use it to see how long functions take. Here's a basic example that prints the contents of a text file called "output.txt":
var debug = true;
http.createServer(function(request, response) {
if(debug) console.log("----------------------------------");
if(debug) elapsed_time("recieved request");
var send_html = function(err, contents) {
if(debug) elapsed_time("start send_html()");
response.writeHead(200, {'Content-Type': 'text/html' } );
response.end(contents);
if(debug) elapsed_time("end send_html()");
}
if(debug) elapsed_time("start readFile()");
fs.readFile('output.txt', send_html);
if(debug) elapsed_time("end readFile()");
}).listen(8080);
Here's a quick test you can run in a terminal (BASH shell):
for i in {1..100}; do echo $i; curl http://localhost:8080/; done
I have added a distribution to the Python Package Index which makes the match_hostname()
function from the Python 3.2 ssl
package available on previous versions of Python.
http://pypi.python.org/pypi/backports.ssl_match_hostname/
You can install it with:
pip install backports.ssl_match_hostname
Or you can make it a dependency listed in your project's setup.py
. Either way, it can be used like this:
from backports.ssl_match_hostname import match_hostname, CertificateError
...
sslsock = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_SSLv3,
cert_reqs=ssl.CERT_REQUIRED, ca_certs=...)
try:
match_hostname(sslsock.getpeercert(), hostname)
except CertificateError, ce:
...
This can also be caused if you include bootstrap.js
before jquery.js
.
Others might have the same problem I did.
Include jQuery
before bootstrap
.
I meant in the template()
call..
You just need to pass the results as an object. So instead of calling
var html = template(data);
do
var html = template({apidata: data});
and use {{#each apidata}}
in your template code
demo at http://jsfiddle.net/KPCh4/4/
(removed some leftover if
code that crashed)
Allow only 2 ip , all other will block
Order Deny,Allow
Deny from all
Allow from 173.11.227.73 108.222.245.179
The agg
function will do this for you. Pass the columns and function as a dict with column, output:
df.groupby(['Country', 'Item_Code']).agg({'Y1961': np.sum, 'Y1962': [np.sum, np.mean]}) # Added example for two output columns from a single input column
This will display only the group by columns, and the specified aggregate columns. In this example I included two agg functions applied to 'Y1962'.
To get exactly what you hoped to see, included the other columns in the group by, and apply sums to the Y variables in the frame:
df.groupby(['Code', 'Country', 'Item_Code', 'Item', 'Ele_Code', 'Unit']).agg({'Y1961': np.sum, 'Y1962': np.sum, 'Y1963': np.sum})
Why not try find /usr/include/X11 -name Xlib.h
If there is a hit, you have Xlib.h
If not install it using sudo apt-get install libx11-dev
and you are good to go :)
getActivity()
is a child of Context so that should work for you
This code is to find the whole current week. It is written in Swift 2.0 :
var i = 2
var weekday: [String] = []
var weekdate: [String] = []
var weekmonth: [String] = []
@IBAction func buttonaction(sender: AnyObject) {
let currentDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM-dd-yyyy"
let dayOfWeekStrings = dateFormatter.stringFromDate(currentDate)
let weekdays = getDayOfWeek(dayOfWeekStrings)
let calendar = NSCalendar.currentCalendar()
while((weekdays - weekdays) + i < 9)
{
let weekFirstDate = calendar.dateByAddingUnit(.Day, value: (-weekdays+i), toDate: NSDate(), options: [])
let dayFormatter = NSDateFormatter()
dayFormatter.dateFormat = "EEEE"
let dayOfWeekString = dayFormatter.stringFromDate(weekFirstDate!)
weekday.append(dayOfWeekString)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd"
let dateOfWeekString = dateFormatter.stringFromDate(weekFirstDate!)
weekdate.append(dateOfWeekString)
let monthFormatter = NSDateFormatter()
monthFormatter.dateFormat = "MMMM"
let monthOfWeekString = monthFormatter.stringFromDate(weekFirstDate!)
weekmonth.append(monthOfWeekString)
i++
}
for(var j = 0; j<7 ; j++)
{
let day = weekday[j]
let date = weekdate[j]
let month = weekmonth[j]
var wholeweek = date + "-" + month + "(" + day + ")"
print(wholeweek)
}
}
func getDayOfWeek(today:String)->Int {
let formatter = NSDateFormatter()
formatter.dateFormat = "MMM-dd-yyyy"
let todayDate = formatter.dateFromString(today)!
let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let myComponents = myCalendar.components(.Weekday, fromDate: todayDate)
let daynumber = myComponents.weekday
return daynumber
}
The output will be like this:
14March(Monday) 15March(Tuesday) 16March(Wednesday) 17March(Thursday) 18March(Friday) 19March(Saturday) 20March(Sunday)
When encoding query values, either form, plus or percent-20, is valid; however, since the bandwidth of the internet isn't infinite, you should use plus, since it's two fewer bytes.
Here is the example:
SQL> set define off;
SQL> select * from dual where dummy='&var';
no rows selected
SQL> set define on
SQL> /
Enter value for var: X
old 1: select * from dual where dummy='&var'
new 1: select * from dual where dummy='X'
D
-
X
With set define off
, it took a row with &var
value, prompted a user to enter a value for it and replaced &var
with the entered value (in this case, X
).
It is already a list
type(my_set)
>>> <type 'list'>
Do you want something like
my_set = set([1,2,3,4])
my_list = list(my_set)
print my_list
>> [1, 2, 3, 4]
EDIT : Output of your last comment
>>> my_list = [1,2,3,4]
>>> my_set = set(my_list)
>>> my_new_list = list(my_set)
>>> print my_new_list
[1, 2, 3, 4]
I'm wondering if you did something like this :
>>> set=set()
>>> set([1,2])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'set' object is not callable
I need to select character to split urls in string, so I decided to create list of characters which could not be found in URL by myself:
>>> allowed = "-_.~!*'();:@&=+$,/?%#[]?@ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
>>> from string import printable
>>> ''.join(set(printable).difference(set(allowed)))
'`" <\x0b\n\r\x0c\\\t{^}|>'
So, the possible choices are the newline, tab, space, backslash and "<>{}^|
. I guess I'll go with the space or newline. :)
My solution:
String.prototype.toCapital = function () {
return this.toLowerCase().split(' ').map(function (i) {
if (i.length > 2) {
return i.charAt(0).toUpperCase() + i.substr(1);
}
return i;
}).join(' ');
};
Example:
'álL riGht'.toCapital();
// Returns 'Áll Right'
you can test a color by writing the CSS inline like <div style="color:red";>...</div>
Try editing your eclipse.ini file and add the following at the top
-vm
/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home
Of course the path may be slightly different, looks like I have an older version...
I'm not sure if it will add itself automatically. If not go into
Preferences --> Java --> Installed JREs
Click Add and follow the instructions there to add it
This code helps to change the background of the title bar programmatically in Android. Change the color to any color you want.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#1c2833")));
}
You must use Rect.width()
and Rect.Height()
which returned from getTextBounds()
instead. That works for me.
If you just want to use AWT, then use Graphics.getFontMetrics
(optionally specifying the font, for a non-default one) to get a FontMetrics
and then FontMetrics.stringWidth
to find the width for the specified string.
For example, if you have a Graphics
variable called g
, you'd use:
int width = g.getFontMetrics().stringWidth(text);
For other toolkits, you'll need to give us more information - it's always going to be toolkit-dependent.
Anonymous types can implement interfaces via a dynamic proxy.
I wrote an extension method on GitHub and a blog post http://wblo.gs/feE to support this scenario.
The method can be used like this:
class Program
{
static void Main(string[] args)
{
var developer = new { Name = "Jason Bowers" };
PrintDeveloperName(developer.DuckCast<IDeveloper>());
Console.ReadKey();
}
private static void PrintDeveloperName(IDeveloper developer)
{
Console.WriteLine(developer.Name);
}
}
public interface IDeveloper
{
string Name { get; }
}
Now find tag and change it to < Directory "C:/xampp/htdocs/myproject/web" >
Restart Your Apache
Whenever I'm testing something with PHP/Curl, I try it from the command line first, figure out what works, and then port my options to PHP.
This functionality is available from C# 4.0 - it was introduced in Visual Studio 2010. And you can use it in project for .NET 3.5. So there is no need to upgrade old projects in .NET 3.5 to .NET 4.0.
You have to just use Visual Studio 2010, but remember that it should compile to default language version (set it in project Properties->Buid->Advanced...)
This MSDN page has more information about optional parameters in VS 2010.
Handlebars partials take a second parameter which becomes the context for the partial:
{{> person this}}
In versions v2.0.0 alpha and later, you can also pass a hash of named parameters:
{{> person headline='Headline'}}
You can see the tests for these scenarios: https://github.com/wycats/handlebars.js/blob/ce74c36118ffed1779889d97e6a2a1028ae61510/spec/qunit_spec.js#L456-L462 https://github.com/wycats/handlebars.js/blob/e290ec24f131f89ddf2c6aeb707a4884d41c3c6d/spec/partials.js#L26-L32
Oh well, I looked up for scrollable table with fixed column to understand the need of this specific requirement and your question was one of it with no close answers..
I answered this question Large dynamically sized html table with a fixed scroll row and fixed scroll column which inspired to showcase my work as a plugin https://github.com/meetselva/fixed-table-rows-cols
The plugin basically converts a well formatted HTML table to a scrollable table with fixed table header and columns.
The usage is as below,
$('#myTable').fxdHdrCol({
fixedCols : 3, /* 3 fixed columns */
width : "100%", /* set the width of the container (fixed or percentage)*/
height : 500 /* set the height of the container */
});
You can check the demo and documentation here
If in .net ( I'm not sure if it works for all windows services)
Unless I'm changing the service's public interface, I often deploy upgraded versions of my services without even unistalling/reinstalling... ALl I do is stop the service, replace the files and restart the service again...
Swift
You should always use the system defaults and not hard coding the font name because the default font could be changed by Apple at any time.
There are a couple of system default fonts(normal, bold, italic) with different sizes(label, button, others):
let font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
let font2 = UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)
let font3 = UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)
beaware that the default font size depends on the target view (label, button, others)
Examples:
let labelFont = UIFont.systemFont(ofSize: UIFont.labelFontSize)
let buttonFont = UIFont.systemFont(ofSize: UIFont.buttonFontSize)
let textFieldFont = UIFont.systemFont(ofSize: UIFont.systemFontSize)
we can add attribute width directly to th
eg:
<ng-container matColumnDef="position" >
<th mat-header-cell *matHeaderCellDef width ="20%"> No. </th>
<td mat-cell *matCellDef="let element"> {{element.position}} </td>
</ng-container>
I think you mean to put the rolling of the random a,b,c, etc within the loop:
a = None # initialise
while not (a in winning_numbers):
# keep rolling an a until you get one not in winning_numbers
a = random.randint(1,30)
winning_numbers.append(a)
Otherwise, a
will be generated just once, and if it is in winning_numbers
already, it won't be added. Since the generation of a
is outside the while
(in your code), if a
is already in winning_numbers
then too bad, it won't be re-rolled, and you'll have one less winning number.
That could be what causes your error in if guess[i] == winning_numbers[i]
. (Your winning_numbers
isn't always of length 5).
If you are using startActivityForResult()
in your previous activities, just override OnActivityResult()
and call the finish();
method inside it in all activities.. This will do the job...
As mentioned in this tutorial, it's as simple as:
To install
brew install gradle
To upgrade
brew upgrade gradle
(using Homebrew of course)
Also see (finally) updated docs.
Cheers :)!
For those who are trying to use 3.1.0 but after installing python says "cv2 module not found".
You likely have python but not python-dev.
sudo apt-get install python-dev
then reinstall 3.1.0 and it'll work.
Why hasn't anyone thought it was worth mentioning Scanner?
Scanner input = new Scanner(new File("foo.txt"));
while (input.hasNextLine())
{
System.out.println(input.nextLine());
}
I have another way to do this if you're using Nuget to manage your dependencies. I've discovered that sometimes VS and Nuget don't match up and Nuget is unable to recognize that your projects are out of sync. The packages.config will say one thing but the path shown in References - Properties will indicate something else.
If you're willing to update your dependencies, do the following:
From Solution Explorer, right click the Project and click 'Manage Nuget Packages'
Select 'Installed packages' tab in left pane Record your installed packages You may want to copy your packages.config to your desktop first if you have a lot, so you can cross check it with Google to see what Nuget pkgs are installed
Uninstall your packages. Its OK, we're going to add them right back.
Immediately install the packages you need. What Nuget will do is not only get you the latest version, but will alter your references, and also add the binding redirects for you.
Do this for all of your projects.
At the solution level, do a Clean and Rebuild.
You may want to start with the lower projects and work your way to the higher level ones, and rebuild each project as you go along.
If you don't want to update your dependencies, then you can use the package manager console, and use the syntax Update-Package -ProjectName [yourProjectName] [packageName] -Version [versionNumber]
Only use WOFF2, or if you need legacy support, WOFF. Do not use any other format
(svg
and eot
are dead formats, ttf
and otf
are full system fonts, and should not be used for web purposes)
In short, font-face is very old, but only recently has been supported by more than IE.
eot
is needed for Internet Explorers that are older than IE9 - they invented the spec, but eot was a proprietary solution.
ttf
and otf
are normal old fonts, so some people got annoyed that this meant anyone could download expensive-to-license fonts for free.
Time passes, SVG 1.1 adds a "fonts" chapter that explains how to model a font purely using SVG markup, and people start to use it. More time passes and it turns out that they are absolutely terrible compared to just a normal font format, and SVG 2 wisely removes the entire chapter again.
Then, woff
gets invented by people with quite a bit of domain knowledge, which makes it possible to host fonts in a way that throws away bits that are critically important for system installation, but irrelevant for the web (making people worried about piracy happy) and allows for internal compression to better suit the needs of the web (making users and hosts happy). This becomes the preferred format.
2019 edit A few years later, woff2
gets drafted and accepted, which improves the compression, leading to even smaller files, along with the ability to load a single font "in parts" so that a font that supports 20 scripts can be stored as "chunks" on disk instead, with browsers automatically able to load the font "in parts" as needed, rather than needing to transfer the entire font up front, further improving the typesetting experience.
If you don't want to support IE 8 and lower, and iOS 4 and lower, and android 4.3 or earlier, then you can just use WOFF (and WOFF2, a more highly compressed WOFF, for the newest browsers that support it.)
@font-face {
font-family: 'MyWebFont';
src: url('myfont.woff2') format('woff2'),
url('myfont.woff') format('woff');
}
Support for woff
can be checked at http://caniuse.com/woff
Support for woff2
can be checked at http://caniuse.com/woff2
If you put set -e
in a script, the script will terminate as soon as any command inside it fails (i.e. as soon as any command returns a nonzero status). This doesn't let you write your own message, but often the failing command's own messages are enough.
The advantage of this approach is that it's automatic: you don't run the risk of forgetting to deal with an error case.
Commands whose status is tested by a conditional (such as if
, &&
or ||
) do not terminate the script (otherwise the conditional would be pointless). An idiom for the occasional command whose failure doesn't matter is command-that-may-fail || true
. You can also turn set -e
off for a part of the script with set +e
.
There is no standard Unix command, AFAIK. I haven't used Sun OS, but on Linux, you can use this:
cat /proc/cpuinfo
Sorry that it is Linux, not Sun OS. There is probably something similar though for Sun OS.
I've been playing with this code for a while now and I have something that works well for me. Log files are numbered with leading '0' but retain their file extension. And I know everyone likes to make functions for everything but I started to remove functions that performed 1 simple task. Why use many word when few do trick? Will likely remove other functions and perhaps create functions out of other blocks. I keep the logger script in a central share and make a local copy if it has changed, or load it from the central location if needed.
First I import the logger:
#Change directory to the script root
cd $PSScriptRoot
#Make a local copy if changed then Import logger
if(test-path "D:\Scripts\logger.ps1"){
if (Test-Path "\\<server>\share\DCS\Scripts\logger.ps1") {
if((Get-FileHash "\\<server>\share\DCS\Scripts\logger.ps1").Hash -ne (Get-FileHash "D:\Scripts\logger.ps1").Hash){
rename-Item -path "..\logger.ps1" -newname "logger$(Get-Date -format 'yyyyMMdd-HH.mm.ss').ps1" -force
Copy-Item "\\<server>\share\DCS\Scripts\logger.ps1" -destination "..\" -Force
}
}
}else{
Copy-Item "\\<server>\share\DCS\Scripts\logger.ps1" -destination "..\" -Force
}
. "..\logger.ps1"
Define the log file:
$logfile = (get-location).path + "\Log\" + $QProfile.replace(" ","_") + "-$metricEnv-$ScriptName.log"
What I log depends on debug levels that I created:
if ($Debug -ge 1){
$message = "<$pid>Debug:$Debug`-Adding tag `"MetricClass:temp`" to $host_name`:$metric_name"
Write-Log $message $logfile "DEBUG"
}
I would probably consider myself a bit of a "hack" when it comes to coding so this might not be the prettiest but here is my version of logger.ps1
:
# all logging settins are here on top
param(
[Parameter(Mandatory=$false)]
[string]$logFile = "$(gc env:computername).log",
[Parameter(Mandatory=$false)]
[string]$logLevel = "DEBUG", # ("DEBUG","INFO","WARN","ERROR","FATAL")
[Parameter(Mandatory=$false)]
[int64]$logSize = 10mb,
[Parameter(Mandatory=$false)]
[int]$logCount = 25
)
# end of settings
function Write-Log-Line ($line, $logFile) {
$logFile | %{
If (Test-Path -Path $_) { Get-Item $_ }
Else { New-Item -Path $_ -Force }
} | Add-Content -Value $Line -erroraction SilentlyCOntinue
}
function Roll-logFile
{
#function checks to see if file in question is larger than the paramater specified if it is it will roll a log and delete the oldes log if there are more than x logs.
param(
[string]$fileName = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")+".log",
[int64]$maxSize = $logSize,
[int]$maxCount = $logCount
)
$logRollStatus = $true
if(test-path $filename) {
$file = Get-ChildItem $filename
# Start the log-roll if the file is big enough
#Write-Log-Line "$Stamp INFO Log file size is $($file.length), max size $maxSize" $logFile
#Write-Host "$Stamp INFO Log file size is $('{0:N0}' -f $file.length), max size $('{0:N0}' -f $maxSize)"
if($file.length -ge $maxSize) {
Write-Log-Line "$Stamp INFO Log file size $('{0:N0}' -f $file.length) is larger than max size $('{0:N0}' -f $maxSize). Rolling log file!" $logFile
#Write-Host "$Stamp INFO Log file size $('{0:N0}' -f $file.length) is larger than max size $('{0:N0}' -f $maxSize). Rolling log file!"
$fileDir = $file.Directory
$fbase = $file.BaseName
$fext = $file.Extension
$fn = $file.name #this gets the name of the file we started with
function refresh-log-files {
Get-ChildItem $filedir | ?{ $_.Extension -match "$fext" -and $_.name -like "$fbase*"} | Sort-Object lastwritetime
}
function fileByIndex($index) {
$fileByIndex = $files | ?{($_.Name).split("-")[-1].trim("$fext") -eq $($index | % tostring 00)}
#Write-Log-Line "LOGGER: fileByIndex = $fileByIndex" $logFile
$fileByIndex
}
function getNumberOfFile($theFile) {
$NumberOfFile = $theFile.Name.split("-")[-1].trim("$fext")
if ($NumberOfFile -match '[a-z]'){
$NumberOfFile = "01"
}
#Write-Log-Line "LOGGER: GetNumberOfFile = $NumberOfFile" $logFile
$NumberOfFile
}
refresh-log-files | %{
[int32]$num = getNumberOfFile $_
Write-Log-Line "LOGGER: checking log file number $num" $logFile
if ([int32]$($num | % tostring 00) -ge $maxCount) {
write-host "Deleting files above log max count $maxCount : $_"
Write-Log-Line "LOGGER: Deleting files above log max count $maxCount : $_" $logFile
Remove-Item $_.fullName
}
}
$files = @(refresh-log-files)
# Now there should be at most $maxCount files, and the highest number is one less than count, unless there are badly named files, eg non-numbers
for ($i = $files.count; $i -gt 0; $i--) {
$newfilename = "$fbase-$($i | % tostring 00)$fext"
#$newfilename = getFileNameByNumber ($i | % tostring 00)
if($i -gt 1) {
$fileToMove = fileByIndex($i-1)
} else {
$fileToMove = $file
}
if (Test-Path $fileToMove.PSPath) { # If there are holes in sequence, file by index might not exist. The 'hole' will shift to next number, as files below hole are moved to fill it
write-host "moving '$fileToMove' => '$newfilename'"
#Write-Log-Line "LOGGER: moving $fileToMove => $newfilename" $logFile
# $fileToMove is a System.IO.FileInfo, but $newfilename is a string. Move-Item takes a string, so we need full path
Move-Item ($fileToMove.FullName) -Destination $fileDir\$newfilename -Force
}
}
} else {
$logRollStatus = $false
}
} else {
$logrollStatus = $false
}
$LogRollStatus
}
Function Write-Log {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True)]
[string]
$Message,
[Parameter(Mandatory=$False)]
[String]
$logFile = "log-$(gc env:computername).log",
[Parameter(Mandatory=$False)]
[String]
$Level = "INFO"
)
#Write-Host $logFile
$levels = ("DEBUG","INFO","WARN","ERROR","FATAL")
$logLevelPos = [array]::IndexOf($levels, $logLevel)
$levelPos = [array]::IndexOf($levels, $Level)
$Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss:fff")
# First roll the log if needed to null to avoid output
$Null = @(
Roll-logFile -fileName $logFile -filesize $logSize -logcount $logCount
)
if ($logLevelPos -lt 0){
Write-Log-Line "$Stamp ERROR Wrong logLevel configuration [$logLevel]" $logFile
}
if ($levelPos -lt 0){
Write-Log-Line "$Stamp ERROR Wrong log level parameter [$Level]" $logFile
}
# if level parameter is wrong or configuration is wrong I still want to see the
# message in log
if ($levelPos -lt $logLevelPos -and $levelPos -ge 0 -and $logLevelPos -ge 0){
return
}
$Line = "$Stamp $Level $Message"
Write-Log-Line $Line $logFile
}
In case the data is not in the same character set you might consider this snippet from http://dev.mysql.com/doc/refman/5.0/en/charset-conversion.html
If the column has a nonbinary data type (CHAR, VARCHAR, TEXT), its contents should be encoded in the column character set, not some other character set. If the contents are encoded in a different character set, you can convert the column to use a binary data type first, and then to a nonbinary column with the desired character set.
Here is an example:
ALTER TABLE t1 CHANGE c1 c1 BLOB;
ALTER TABLE t1 CHANGE c1 c1 VARCHAR(100) CHARACTER SET utf8;
Make sure to choose the right collation, or you might get unique key conflicts. e.g. Éleanore and Eleanore might be considered the same in some collations.
Aside:
I had a situation where certain characters "broke" in emails even though they were stored as UTF-8 in the database. If you are sending emails using utf8 data, you might want to also convert your emails to send in UTF8.
In PHPMailer, just update this line: public $CharSet = 'utf-8';
//Add a list of BBDD
var item = myEntities.getList().ToList();
//Insert a new object of type in a position of the list
item.Insert(0,(new Model.getList_Result { id = 0, name = "Coca Cola" }));
//List assigned to DataGridView
dgList.DataSource = item;
Okay, just to clarify things that have already been posted.
You should have the directory com
, containing the directory company
, containing the directory example
, containing the file MyClass.java
.
From the folder containing com
, run:
$ javac com\company\example\MyClass.java
Then:
$ java com.company.example.MyClass Hello from MyClass!
These must both be done from the root of the source tree. Otherwise, javac
and java
won't be able to find any other packages (in fact, java
wouldn't even be able to run MyClass
).
I created the folders "testpackage" and "testpackage2". Inside testpackage, I created TestPackageClass.java containing the following code:
package testpackage;
import testpackage2.MyClass;
public class TestPackageClass {
public static void main(String[] args) {
System.out.println("Hello from testpackage.TestPackageClass!");
System.out.println("Now accessing " + MyClass.NAME);
}
}
Inside testpackage2, I created MyClass.java containing the following code:
package testpackage2;
public class MyClass {
public static String NAME = "testpackage2.MyClass";
}
From the directory containing the two new folders, I ran:
C:\examples>javac testpackage\*.java C:\examples>javac testpackage2\*.java
Then:
C:\examples>java testpackage.TestPackageClass Hello from testpackage.TestPackageClass! Now accessing testpackage2.MyClass
Does that make things any clearer?
You don't need jquery for this, in plain javascript, the following will work!
var intervalId = window.setInterval(function(){
/// call your function here
}, 5000);
To stop the loop you can use
clearInterval(intervalId)
You also can use graceful restart the apache server with service apache2 reload
or apachectl -k graceful
.
As the apache doc says:
The USR1 or graceful signal causes the parent process to advise the children to exit after their current request (or to exit immediately if they're not serving anything). The parent re-reads its configuration files and re-opens its log files. As each child dies off the parent replaces it with a child from the new generation of the configuration, which begins serving new requests immediately.
Here is a code snippet which might help:
String input = "ABC_DEF";
StringBuilder sb = new StringBuilder();
for( String oneString : input.toLowerCase().split("_") )
{
sb.append( oneString.substring(0,1).toUpperCase() );
sb.append( oneString.substring(1) );
}
// sb now holds your desired String
Try to change the loop like this:
for line in $(cat filename); do
read input
echo $input;
done
Unit test:
for line in $(cat /etc/passwd); do
read input
echo $input;
echo "[$line]"
done
Never use md5() for securing your password, even with salt, it is always dangerous!!
Make your password secured with latest hashing algorithms as below.
<?php
// Your original Password
$password = '121@121';
//PASSWORD_BCRYPT or PASSWORD_DEFAULT use any in the 2nd parameter
/*
PASSWORD_BCRYPT always results 60 characters long string.
PASSWORD_DEFAULT capacity is beyond 60 characters
*/
$password_encrypted = password_hash($password, PASSWORD_BCRYPT);
For matching with database's encrypted password and user inputted password use the below function.
<?php
if (password_verify($password_inputted_by_user, $password_encrypted)) {
// Success!
echo 'Password Matches';
}else {
// Invalid credentials
echo 'Password Mismatch';
}
If you want to use your own salt, use your custom generated function for the same, just follow below, but I not recommend this as It is found deprecated in latest versions of PHP.
Read about password_hash() before using below code.
<?php
$options = [
'salt' => your_custom_function_for_salt(),
//write your own code to generate a suitable & secured salt
'cost' => 12 // the default cost is 10
];
$hash = password_hash($your_password, PASSWORD_DEFAULT, $options);
It depends on the class you are using.
Dictionary<(Of <(TKey, TValue>)>) Class For Example Support This
The Dictionary<(Of <(TKey, TValue>)>) generic class provides a mapping from a set of keys to a set of values.
For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair<(Of <(TKey, TValue>)>) structure representing a value and its key. The order in which the items are returned is undefined.
foreach (KeyValuePair kvp in myDictionary) {...}
For me, and other newbies who has just contacted with Javascript,
I think that the Closeure Solution
is a little kind of too confusing.
While I found that, you can easilly pass as many parameters as you want to every ajax callback using jquery.
Here are two easier solutions.
First one, which @zeroasterisk has mentioned above, example:
var $items = $('.some_class');
$.each($items, function(key, item){
var url = 'http://request_with_params' + $(item).html();
$.ajax({
selfDom : $(item),
selfData : 'here is my self defined data',
url : url,
dataType : 'json',
success : function(data, code, jqXHR){
// in $.ajax callbacks,
// [this] keyword references to the options you gived to $.ajax
// if you had not specified the context of $.ajax callbacks.
// see http://api.jquery.com/jquery.ajax/#jQuery-ajax-settings context
var $item = this.selfDom;
var selfdata = this.selfData;
$item.html( selfdata );
...
}
});
});
Second one, pass self-defined-datas by adding them into the XHR object
which exists in the whole ajax-request-response life span.
var $items = $('.some_class');
$.each($items, function(key, item){
var url = 'http://request_with_params' + $(item).html();
$.ajax({
url : url,
dataType : 'json',
beforeSend : function(XHR) {
// ??????,???? jquery??????? XHR
XHR.selfDom = $(item);
XHR.selfData = 'here is my self defined data';
},
success : function(data, code, jqXHR){
// jqXHR is a superset of the browser's native XHR object
var $item = jqXHR.selfDom;
var selfdata = jqXHR.selfData;
$item.html( selfdata );
...
}
});
});
As you can see these two solutions has a drawback that : you need write a little more code every time than just write:
$.get/post (url, data, successHandler);
Read more about $.ajax : http://api.jquery.com/jquery.ajax/
There is collection of Func<...>
classes - Func that is probably what you are looking for:
void MyMethod(Func<int> param1 = null)
This defines method that have parameter param1
with default value null
(similar to AS), and a function that returns int
. Unlike AS in C# you need to specify type of the function's arguments.
So if you AS usage was
MyMethod(function(intArg, stringArg) { return true; })
Than in C# it would require param1
to be of type Func<int, siring, bool>
and usage like
MyMethod( (intArg, stringArg) => { return true;} );
You are just outside the directory which you are working. Enter into the directory which your project is there and run command ng g c name
.
The best option now is to install the Microsoft Visual Studio add on called Productivity Power Tools.
With this comes "Solution Navigator" (alternative to Solution Explorer, with a lot of benefits) - which then you can use to filter the files to only show "Open". You can even filter files to show "Edited" and "Unsaved".
Simple way if new table does not exist and you want to make a copy of old table with everything then following works in SQL Server.
SELECT * INTO NewTable FROM OldTable
I would use git submodules
.
have a look here Git repository in a Git repository
As per February2019, I would suggest Monorepos
You can also add labels that are tied to your radio buttons with the same ID, which then allows the user to click the radio button or label to select that item. I'm using constants here for "Male", "Female" and "Unknown", but obviously these could be strings in your model.
<%: Html.RadioButtonFor(m => m.Gender, "Male",
new Dictionary<string, object> { { "checked", "checked" }, { "id", "Male" } }) %>
<%: Html.Label("Male") %>
<%: Html.RadioButtonFor(m => m.Gender, "Female",
new Dictionary<string, object> { { "id", "Female" } }) %>
<%: Html.Label("Female")%>
<%: Html.RadioButtonFor(m => m.Gender, "Unknown",
new Dictionary<string, object> { { "id", "Unknown" } }) %>
<%: Html.Label("Unknown")%>
All the answers are great here, I tried a couple of solutions mentioned above by Ryan, Chris and couldn't resolve the issue, so had to follow a quick and dirty way.
rm -rf <project dir>
(or mv <project dir> <backup projct dir>
if you want to keep a backup)git clone <project git url>
Nothing novel here, but it makes life easier!
Here is another use case which worked well for me.
Code: Swift 5.3
// Assuming you have a view named "targeView"
scrollView.scroll(to: CGPoint(x:targeView.frame.minX, y:targeView.frame.minY), animated: true)
As you can guess if you want to scroll to make a bottom part of your target view visible then use maxX and minY.
I think a simple if
statement can accomplish this. Once I saw mkelement0's response that the last exit status is stored in $?, I put the following together:
# Set the first command to a variable
$a=somecommand
# Temporary variable to store exit status of the last command (since we can't write to "$?")
$test=$?
# Run the test
if ($test=$true) { 2nd-command }
So for the OP's example, it would be:
a=(csc /t:exe /out:a.exe SomeFile.cs); $test = $?; if ($test=$true) { a.exe }
Try with below logic
driver.get("http://www.labmultis.info/jpecka.portal-exdrazby/index.php?c1=2&a=s&aa=&ta=1");
List<WebElement> allElements=driver.findElements(By.cssSelector(".list.list-categories li"));
for(WebElement ele :allElements) {
System.out.println("Name + Number===>"+ele.getText());
String s=ele.getText();
s=s.substring(s.indexOf("(")+1, s.indexOf(")"));
System.out.println("Number==>"+s);
}
====Output======
Name + Number===>Vše (950)
Number==>950
Name + Number===>Byty (181)
Number==>181
Name + Number===>Domy (512)
Number==>512
Name + Number===>Pozemky (172)
Number==>172
Name + Number===>Chaty (28)
Number==>28
Name + Number===>Zemedelské objekty (5)
Number==>5
Name + Number===>Komercní objekty (30)
Number==>30
Name + Number===>Ostatní (22)
Number==>22
You could merge two queries together:
$merged = $query_one->merge($query_two);
An working demo is here-
.floating-box {_x000D_
display:-moz-inline-stack;_x000D_
display: inline-block;_x000D_
_x000D_
width: fit-content; _x000D_
height: fit-content;_x000D_
_x000D_
width: 150px;_x000D_
height: 75px;_x000D_
margin: 10px;_x000D_
border: 3px solid #73AD21; _x000D_
}
_x000D_
<h2>The Way is using inline-block</h2>_x000D_
_x000D_
Supporting elements are also added in CSS._x000D_
_x000D_
<div>_x000D_
<div class="floating-box">Floating box</div>_x000D_
<div class="floating-box">Floating box</div>_x000D_
<div class="floating-box">Floating box</div>_x000D_
<div class="floating-box">Floating box</div>_x000D_
<div class="floating-box">Floating box</div>_x000D_
<div class="floating-box">Floating box</div>_x000D_
<div class="floating-box">Floating box</div>_x000D_
<div class="floating-box">Floating box</div>_x000D_
</div>
_x000D_
This would be the lines you need in your vimrc for this purpose:
set clipboard+=unnamed " use the clipboards of vim and win
set paste " Paste from a windows or from vim
set go+=a " Visual selection automatically copied to the clipboard
Another possibility is using tidyr::expand
:
library(dplyr)
library(tidyr)
df %>% group_by_at(vars(-freq)) %>% expand(temp = 1:freq) %>% select(-temp)
#> # A tibble: 6 x 2
#> # Groups: var1, var2 [3]
#> var1 var2
#> <fct> <fct>
#> 1 a d
#> 2 b e
#> 3 b e
#> 4 c f
#> 5 c f
#> 6 c f
One-liner version of vonjd's answer:
library(data.table)
setDT(df)[ ,list(freq=rep(1,freq)),by=c("var1","var2")][ ,freq := NULL][]
#> var1 var2
#> 1: a d
#> 2: b e
#> 3: b e
#> 4: c f
#> 5: c f
#> 6: c f
Created on 2019-05-21 by the reprex package (v0.2.1)
A static library is just an archive of .o
object files. Extract them with ar
(assuming Unix) and pack them back into one big library.