try this:
var c=document.getElementById("alpha");
var d=c.toDataURL("image/png");
var w=window.open('about:blank','image from canvas');
w.document.write("<img src='"+d+"' alt='from canvas'/>");
This shows image from canvas on new page, but if you have open popup in new tab
setting it shows about:blank
in address bar.
EDIT:- though window.open("<img src='"+ c.toDataURL('image/png') +"'/>")
does not work in FF or Chrome, following works though rendering is somewhat different from what is shown on canvas, I think transparency is the issue:
window.open(c.toDataURL('image/png'));
They serve the actual image inside CSS so there will be less HTTP requests per page.
The compiler will generate code for each template instantiation when you use a template during the compilation step. In the compilation and linking process .cpp files are converted to pure object or machine code which in them contains references or undefined symbols because the .h files that are included in your main.cpp have no implementation YET. These are ready to be linked with another object file that defines an implementation for your template and thus you have a full a.out executable.
However since templates need to be processed in the compilation step in order to generate code for each template instantiation that you define, so simply compiling a template separate from it's header file won't work because they always go hand and hand, for the very reason that each template instantiation is a whole new class literally. In a regular class you can separate .h and .cpp because .h is a blueprint of that class and the .cpp is the raw implementation so any implementation files can be compiled and linked regularly, however using templates .h is a blueprint of how the class should look not how the object should look meaning a template .cpp file isn't a raw regular implementation of a class, it's simply a blueprint for a class, so any implementation of a .h template file can't be compiled because you need something concrete to compile, templates are abstract in that sense.
Therefore templates are never separately compiled and are only compiled wherever you have a concrete instantiation in some other source file. However, the concrete instantiation needs to know the implementation of the template file, because simply modifying the typename T
using a concrete type in the .h file is not going to do the job because what .cpp is there to link, I can't find it later on because remember templates are abstract and can't be compiled, so I'm forced to give the implementation right now so I know what to compile and link, and now that I have the implementation it gets linked into the enclosing source file. Basically, the moment I instantiate a template I need to create a whole new class, and I can't do that if I don't know how that class should look like when using the type I provide unless I make notice to the compiler of the template implementation, so now the compiler can replace T
with my type and create a concrete class that's ready to be compiled and linked.
To sum up, templates are blueprints for how classes should look, classes are blueprints for how an object should look. I can't compile templates separate from their concrete instantiation because the compiler only compiles concrete types, in other words, templates at least in C++, is pure language abstraction. We have to de-abstract templates so to speak, and we do so by giving them a concrete type to deal with so that our template abstraction can transform into a regular class file and in turn, it can be compiled normally. Separating the template .h file and the template .cpp file is meaningless. It is nonsensical because the separation of .cpp and .h only is only where the .cpp can be compiled individually and linked individually, with templates since we can't compile them separately, because templates are an abstraction, therefore we are always forced to put the abstraction always together with the concrete instantiation where the concrete instantiation always has to know about the type being used.
Meaning typename T
get's replaced during the compilation step not the linking step so if I try to compile a template without T
being replaced as a concrete value type that is completely meaningless to the compiler and as a result object code can't be created because it doesn't know what T
is.
It is technically possible to create some sort of functionality that will save the template.cpp file and switch out the types when it finds them in other sources, I think that the standard does have a keyword export
that will allow you to put templates in a separate cpp file but not that many compilers actually implement this.
Just a side note, when making specializations for a template class, you can separate the header from the implementation because a specialization by definition means that I am specializing for a concrete type that can be compiled and linked individually.
I would advice to check the logic of ListActivity
according to what is needed could be the best way not to lose much time
Using undefined
to make a decision is usually a sign of bad design in Javascript. You might consider doing something else.
However, to answer your question: I think the best way of doing so would be adding a helper function.
$scope.isUndefined = function (thing) {
return (typeof thing === "undefined");
}
and in the template
<div ng-show="isUndefined(foo)"></div>
I use TeXMaker. If you're using Ubuntu, it should be in the apt-get repository. To install texmaker
, run:
sudo apt-get install texmaker
You mean, like this:
grep -o '.\{0,20\}test_pattern.\{0,20\}' file
?
That will print up to twenty characters on either side of test_pattern
. The \{0,20\}
notation is like *
, but specifies zero to twenty repetitions instead of zero or more.The -o
says to show only the match itself, rather than the entire line.
In simple English from GROUP BY
with two parameters what we are doing is looking for similar value pairs and get the count to a 3rd column.
Look at the following example for reference. Here I'm using International football results from 1872 to 2020
+----------+----------------+--------+---+---+--------+---------+-------------------+-----+
| _c0| _c1| _c2|_c3|_c4| _c5| _c6| _c7| _c8|
+----------+----------------+--------+---+---+--------+---------+-------------------+-----+
|1872-11-30| Scotland| England| 0| 0|Friendly| Glasgow| Scotland|FALSE|
|1873-03-08| England|Scotland| 4| 2|Friendly| London| England|FALSE|
|1874-03-07| Scotland| England| 2| 1|Friendly| Glasgow| Scotland|FALSE|
|1875-03-06| England|Scotland| 2| 2|Friendly| London| England|FALSE|
|1876-03-04| Scotland| England| 3| 0|Friendly| Glasgow| Scotland|FALSE|
|1876-03-25| Scotland| Wales| 4| 0|Friendly| Glasgow| Scotland|FALSE|
|1877-03-03| England|Scotland| 1| 3|Friendly| London| England|FALSE|
|1877-03-05| Wales|Scotland| 0| 2|Friendly| Wrexham| Wales|FALSE|
|1878-03-02| Scotland| England| 7| 2|Friendly| Glasgow| Scotland|FALSE|
|1878-03-23| Scotland| Wales| 9| 0|Friendly| Glasgow| Scotland|FALSE|
|1879-01-18| England| Wales| 2| 1|Friendly| London| England|FALSE|
|1879-04-05| England|Scotland| 5| 4|Friendly| London| England|FALSE|
|1879-04-07| Wales|Scotland| 0| 3|Friendly| Wrexham| Wales|FALSE|
|1880-03-13| Scotland| England| 5| 4|Friendly| Glasgow| Scotland|FALSE|
|1880-03-15| Wales| England| 2| 3|Friendly| Wrexham| Wales|FALSE|
|1880-03-27| Scotland| Wales| 5| 1|Friendly| Glasgow| Scotland|FALSE|
|1881-02-26| England| Wales| 0| 1|Friendly|Blackburn| England|FALSE|
|1881-03-12| England|Scotland| 1| 6|Friendly| London| England|FALSE|
|1881-03-14| Wales|Scotland| 1| 5|Friendly| Wrexham| Wales|FALSE|
|1882-02-18|Northern Ireland| England| 0| 13|Friendly| Belfast|Republic of Ireland|FALSE|
+----------+----------------+--------+---+---+--------+---------+-------------------+-----+
And now I'm going to group by similar country(column _c7
) and tournament(_c5
) value pairs by GROUP BY
operation,
SELECT `_c5`,`_c7`,count(*) FROM res GROUP BY `_c5`,`_c7`
+--------------------+-------------------+--------+
| _c5| _c7|count(1)|
+--------------------+-------------------+--------+
| Friendly| Southern Rhodesia| 11|
| Friendly| Ecuador| 68|
|African Cup of Na...| Ethiopia| 41|
|Gold Cup qualific...|Trinidad and Tobago| 9|
|AFC Asian Cup qua...| Bhutan| 7|
|African Nations C...| Gabon| 2|
| Friendly| China PR| 170|
|FIFA World Cup qu...| Israel| 59|
|FIFA World Cup qu...| Japan| 61|
|UEFA Euro qualifi...| Romania| 62|
|AFC Asian Cup qua...| Macau| 9|
| Friendly| South Sudan| 1|
|CONCACAF Nations ...| Suriname| 3|
| Copa Newton| Argentina| 12|
| Friendly| Philippines| 38|
|FIFA World Cup qu...| Chile| 68|
|African Cup of Na...| Madagascar| 29|
|FIFA World Cup qu...| Burkina Faso| 30|
| UEFA Nations League| Denmark| 4|
| Atlantic Cup| Paraguay| 2|
+--------------------+-------------------+--------+
Explanation: The meaning of the first row is there were 11 Friendly tournaments held on Southern Rhodesia in total.
Note: Here it's mandatory to use a counter column in this case.
To answer your question, Hibernate is an implementation of the JPA standard. Hibernate has its own quirks of operation, but as per the Hibernate docs
By default, Hibernate uses lazy select fetching for collections and lazy proxy fetching for single-valued associations. These defaults make sense for most associations in the majority of applications.
So Hibernate will always load any object using a lazy fetching strategy, no matter what type of relationship you have declared. It will use a lazy proxy (which should be uninitialized but not null) for a single object in a one-to-one or many-to-one relationship, and a null collection that it will hydrate with values when you attempt to access it.
It should be understood that Hibernate will only attempt to fill these objects with values when you attempt to access the object, unless you specify fetchType.EAGER
.
Remove the comma
... Gender,Contact, " + ") VALUES ...
^-----------------here
You can make a function to give you results.
# your list
numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435,
453,435,324,34,456,56,567,65,34,435)
function1<-function(x){
if(x==value){return(1)}else{ return(0) }
}
# set your value here
value<-4
# make a vector which return 1 if it equal to your value, 0 else
vector<-sapply(numbers,function(x) function1(x))
sum(vector)
result: 2
try to change your build.gradle with these value:
android { compileSdkVersion 18 buildToolsVersion '21.0.1'
defaultConfig {
minSdkVersion 18
targetSdkVersion 18
}
I would do it this way if you needed an instance variable of the object to work with:
if @business = Business.where(:user_id => current_user.id).first
#Do stuff
else
#Do stuff
end
You're "setting" the value of that variable/attribute. Not overriding or overloading it. Your code is very, very common and normal.
All of these terms ("set", "override", "overload") have specific meanings. Override and Overload are about polymorphism (subclassing).
From http://en.wikipedia.org/wiki/Object-oriented_programming :
Polymorphism allows the programmer to treat derived class members just like their parent class' members. More precisely, Polymorphism in object-oriented programming is the ability of objects belonging to different data types to respond to method calls of methods of the same name, each one according to an appropriate type-specific behavior. One method, or an operator such as +, -, or *, can be abstractly applied in many different situations. If a Dog is commanded to speak(), this may elicit a bark(). However, if a Pig is commanded to speak(), this may elicit an oink(). They both inherit speak() from Animal, but their derived class methods override the methods of the parent class; this is Overriding Polymorphism. Overloading Polymorphism is the use of one method signature, or one operator such as "+", to perform several different functions depending on the implementation. The "+" operator, for example, may be used to perform integer addition, float addition, list concatenation, or string concatenation. Any two subclasses of Number, such as Integer and Double, are expected to add together properly in an OOP language. The language must therefore overload the addition operator, "+", to work this way. This helps improve code readability. How this is implemented varies from language to language, but most OOP languages support at least some level of overloading polymorphism.
ran into this problem today and wanted to include NaNs so I replace them temporarily with "" (empty string). Please comment if you do not understand something :). This solution assumes that "" is not a relevant value for you. It should also work with numerical data (I have tested it sucessfully but not extensively) since pandas will infer the data type again after replacing "" with np.nan.
import pandas as pd
# create test data
df = pd.DataFrame({'test':['foo','bar',None,None,'foo'],
'test2':['bar',None,None,None,'bar'],
'test3':[None, 'foo','bar',None,None]})
# fill null values with '' to not lose them during groupby
# groupby all columns and calculate the length of the resulting groups
# rename the series obtained with groupby to "group_count"
# reset the index to get a DataFrame
# replace '' with np.nan (this reverts our first operation)
# sort DataFrame by "group_count" descending
df = (df.fillna('')\
.groupby(df.columns.tolist()).apply(len)\
.rename('group_count')\
.reset_index()\
.replace('',np.nan)\
.sort_values(by = ['group_count'], ascending = False))
df
test test2 test3 group_count
3 foo bar NaN 2
0 NaN NaN NaN 1
1 NaN NaN bar 1
2 bar NaN foo 1
label.setForeground(Color.RED)
(I would probably put two labels next to each other using a GridLayout
or something, but here goes...)
You could use html in your label text as follows:
frame.add(new JLabel("<html>Text color: <font color='red'>red</font></html>"));
which produces:
adb kill-server
and adb start-server
only control the adb
daemon on the PC side. You need to restart adbd
daemon on the device itself after reverting the service.adb.root
property change done by adb root
:
~$ adb shell id
uid=2000(shell) gid=2000(shell)
~$ adb root
restarting adbd as root
~$ adb shell id
uid=0(root) gid=0(root)
~$ adb shell 'setprop service.adb.root 0; setprop ctl.restart adbd'
~$ adb shell id
uid=2000(shell) gid=2000(shell)
Expected situation
# Wrong output from cell_values()
42884.0
# Expected output
2017-5-29
Example: Let cell_values(2,2) from sheet number 0 will be the date targeted
Get the required variables as the following
workbook = xlrd.open_workbook("target.xlsx")
sheet = workbook.sheet_by_index(0)
wrongValue = sheet.cell_value(2,2)
And make use of xldate_as_tuple
y, m, d, h, i, s = xlrd.xldate_as_tuple(wrongValue, workbook.datemode)
print("{0} - {1} - {2}".format(y, m, d))
That's my solution
N = 10
with open("file.txt", "a") as file: # the a opens it in append mode
for i in range(N):
line = next(file).strip()
print(line)
The following code send and recieve the current date and time from and to the server
//The following code is for the server application:
namespace Server
{
class Program
{
const int PORT_NO = 5000;
const string SERVER_IP = "127.0.0.1";
static void Main(string[] args)
{
//---listen at the specified IP and port no.---
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
Console.WriteLine("Listening...");
listener.Start();
//---incoming client connected---
TcpClient client = listener.AcceptTcpClient();
//---get the incoming data through a network stream---
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received : " + dataReceived);
//---write back the text to the client---
Console.WriteLine("Sending back : " + dataReceived);
nwStream.Write(buffer, 0, bytesRead);
client.Close();
listener.Stop();
Console.ReadLine();
}
}
}
//this is the code for the client
namespace Client
{
class Program
{
const int PORT_NO = 5000;
const string SERVER_IP = "127.0.0.1";
static void Main(string[] args)
{
//---data to send to the server---
string textToSend = DateTime.Now.ToString();
//---create a TCPClient object at the IP and port no.---
TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
NetworkStream nwStream = client.GetStream();
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);
//---send the text---
Console.WriteLine("Sending : " + textToSend);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
//---read back the text---
byte[] bytesToRead = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
Console.WriteLine("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
Console.ReadLine();
client.Close();
}
}
}
I'm assuming mysql_fetch_array() perfroms a loop, so I'm interested in if using a while() in conjunction with it, if it saves a nested loop.
No. mysql_fetch_array
just returns the next row of the result and advances the internal pointer. It doesn't loop. (Internally it may or may not use some loop somewhere, but that's irrelevant.)
while ($row = mysql_fetch_array($result)) {
...
}
This does the following:
mysql_fetch_array
retrieves and returns the next row$row
true
, the contents of the loop are executed$row = mysql_fetch_array($result); foreach($row as $r) { ... }
This does the following:
mysql_fetch_array
retrieves and returns the next row$row
foreach
loops over the contents of the array and executes the contents of the loop as many times as there are items in the arrayIn both cases mysql_fetch_array
does exactly the same thing. You have only as many loops as you write. Both constructs do not do the same thing though. The second will only act on one row of the result, while the first will loop over all rows.
The answers posted here all didn't quite work for me. They mainly skipped signing embedded frameworks (or including the entitlements).
Here's what's worked for me (it assumes that one ipa file exists is in the current directory):
PROVISION="/path/to/file.mobileprovision"
CERTIFICATE="Name of certificate: To sign with" # must be in the keychain
unzip -q *.ipa
rm -rf Payload/*.app/_CodeSignature/
# Replace embedded provisioning profile
cp "$PROVISION" Payload/*.app/embedded.mobileprovision
# Extract entitlements from app
codesign -d --entitlements :entitlements.plist Payload/*.app/
# Re-sign embedded frameworks
codesign -f -s "$CERTIFICATE" --entitlements entitlements.plist Payload/*.app/Frameworks/*
# Re-sign the app (with entitlements)
codesign -f -s "$CERTIFICATE" --entitlements entitlements.plist Payload/*.app/
zip -qr resigned.ipa Payload
# Cleanup
rm entitlements.plist
rm -r Payload/
I would suggest that you use Apache's commons logging utility. It is highly scalable and supports separate log files for different loggers. See here.
In terms of functionality these are all the same, the difference between them is in code readability and style (which is important to consider)
The following should work as long as you're bound to anything that implements IEnumerable<string>. It will bind the column directly to the string itself, rather than to a Property Path of that string object.
<sdk:DataGridTextColumn Binding="{Binding}" />
I was having a problem fetching profile photos while using CURL. I thought for a while there was something wrong my implementation of the Facebook API, but I need to add a bit to my CURL called:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
In the latest version of Twitter Bootstrap the layout is fluid by default, hence you don't need extra classes to declare your layout as fluid.
You can further refer to -
http://bassjobsen.weblogs.fm/migrate-your-templates-from-twitter-bootstrap-2-x-to-twitter-bootstrap-3/ http://blog.getbootstrap.com/
I had encountered the same error with React version 16. This error comes when the Javascript that tries to render the React component is included before the static parent dom element in the html. Fix is same as the accepted answer, i.e. the JavaScript should get included only after the static parent dom element has been defined in the html.
JSONP stands for “JSON with Padding” and it is a workaround for loading data from different domains. It loads the script into the head of the DOM and thus you can access the information as if it were loaded on your own domain, thus by-passing the cross domain issue.
jsonCallback(
{
"sites":
[
{
"siteName": "JQUERY4U",
"domainName": "http://www.jquery4u.com",
"description": "#1 jQuery Blog for your Daily News, Plugins, Tuts/Tips & Code Snippets."
},
{
"siteName": "BLOGOOLA",
"domainName": "http://www.blogoola.com",
"description": "Expose your blog to millions and increase your audience."
},
{
"siteName": "PHPSCRIPTS4U",
"domainName": "http://www.phpscripts4u.com",
"description": "The Blog of Enthusiastic PHP Scripters"
}
]
});
(function($) {
var url = 'http://www.jquery4u.com/scripts/jquery4u-sites.json?callback=?';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.sites);
},
error: function(e) {
console.log(e.message);
}
});
})(jQuery);
Now we can request the JSON via AJAX using JSONP and the callback function we created around the JSON content. The output should be the JSON as an object which we can then use the data for whatever we want without restrictions.
I am trying to explain by putting problem statement and solution to it. I hope it will help
Problem Statement:
Find all the published products, whose name like ABC Product or PQR Product, and price should be less than 15/-
Solution:
Below are the conditions that need to be taken care of
Below is the statement that applies above criterion to create query and fetch data.
$elements = $collection->find(
Array(
[price] => Array( [$lt] => 15 ),
[$or] => Array(
[0]=>Array(
[product_name]=>Array(
[$in]=>Array(
[0] => ABC Product,
[1]=> PQR Product
)
)
)
),
[state]=>Published
)
);
As Nora suggests, you can use the python simple server.
Navigate to the folder from which you want to serve your html page, then execute python -m SimpleHTTPServer
.
Now you can use your web-browser and navigate to http://localhost:8000/ where your page is being served.
If your page is named index.html then the server automatically loads that for you. If you want to access any other page, you'll need to browse to http://localhost:8000/{your page name}
Expanding upon @freakish answer, async also offers a each method, which seems especially suited for your case:
var async = require('async');
async.each(['aaa','bbb','ccc'], function(name, callback) {
conn.collection(name).drop( callback );
}, function(err) {
if( err ) { return console.log(err); }
console.log('all dropped');
});
IMHO, this makes the code both more efficient and more legible. I've taken the liberty of removing the console.log('dropped')
- if you want it, use this instead:
var async = require('async');
async.each(['aaa','bbb','ccc'], function(name, callback) {
// if you really want the console.log( 'dropped' ),
// replace the 'callback' here with an anonymous function
conn.collection(name).drop( function(err) {
if( err ) { return callback(err); }
console.log('dropped');
callback()
});
}, function(err) {
if( err ) { return console.log(err); }
console.log('all dropped');
});
You can use Aggregate
, to concatenate the strings into a single, character separated string but will throw an Invalid Operation Exception if the collection is empty.
You can use Aggregate
function with a seed string.
var seed = string.Empty;
var seperator = ",";
var cars = new List<string>() { "Ford", "McLaren Senna", "Aston Martin Vanquish"};
var carAggregate = cars.Aggregate(seed,
(partialPhrase, word) => $"{partialPhrase}{seperator}{word}").TrimStart(',');
you can use string.Join
doesn’t care if you pass it an empty collection.
var seperator = ",";
var cars = new List<string>() { "Ford", "McLaren Senna", "Aston Martin Vanquish"};
var carJoin = string.Join(seperator, cars);
I'd suggest the following to see the difference "in commits". For symmetric difference, repeat the command with inverted args:
git cherry -v master [your branch, or HEAD as default]
Mate, my advice is to change virtual device. Download "Genimotion" application, its easy to use and there are a lot of any devices you need
for package in `sudo npm -g ls --depth=0 --parseable`; do
printf "${package##*/}\n";
done
I had exactly this problem a couple of months ago while working on a WYSIWYG email editor for my company. Outlook only supports background images if they're applied to the <body>
tag - any other element and it'll fail.
In the end, the only workaround I found was to use <div>
element for text input, then during the content submission process I fired an AJAX request with the <div>
's content to a PHP script which wrote the text onto a blank version of our header image, saved the file and returned its (uniquely generated) name. I then used Javascript to remove the <div>
and add an <img>
tag using the returned filename in the src
attribute.
You can get all the info/methodology from the imagecreatefrompng()
page on the PHP Docs site.
jQuery simple solution.
Should be triggered by user's click.
$("<textarea/>").appendTo("body").val(text).select().each(function () {
document.execCommand('copy');
}).remove();
I once got into the same situation, I solved it following way. I've only fulfilled the requirements of a hint box, you can make it more interactive by adding effects and other things on other events like on focus etc.
WPF CODE (I've removed styling to make it readable)
<Grid Margin="0,0,0,0" Background="White">
<Label Name="adminEmailHint" Foreground="LightGray" Padding="6" FontSize="14">Admin Email</Label>
<TextBox Padding="4,7,4,8" Background="Transparent" TextChanged="adminEmail_TextChanged" Height="31" x:Name="adminEmail" Width="180" />
</Grid>
<Grid Margin="10,0,10,0" Background="White" >
<Label Name="adminPasswordHint" Foreground="LightGray" Padding="6" FontSize="14">Admin Password</Label>
<PasswordBox Padding="4,6,4,8" Background="Transparent" PasswordChanged="adminPassword_PasswordChanged" Height="31" x:Name="adminPassword" VerticalContentAlignment="Center" VerticalAlignment="Center" Width="180" FontFamily="Helvetica" FontWeight="Light" FontSize="14" Controls:TextBoxHelper.Watermark="Admin Password" FontStyle="Normal" />
</Grid>
C# Code
private void adminEmail_TextChanged(object sender, TextChangedEventArgs e)
{
if(adminEmail.Text.Length == 0)
{
adminEmailHint.Visibility = Visibility.Visible;
}
else
{
adminEmailHint.Visibility = Visibility.Hidden;
}
}
private void adminPassword_PasswordChanged(object sender, RoutedEventArgs e)
{
if (adminPassword.Password.Length == 0)
{
adminPasswordHint.Visibility = Visibility.Visible;
}
else
{
adminPasswordHint.Visibility = Visibility.Hidden;
}
}
try this
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
} else {
// Show rationale and request permission.
}
What about this:
function recursiveDelete($dirPath, $deleteParent = true){
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dirPath, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $path) {
$path->isFile() ? unlink($path->getPathname()) : rmdir($path->getPathname());
}
if($deleteParent) rmdir($dirPath);
}
The HTTP/CGI way to do this would be for your program to return an HTTP status code of 204 (No Content).
Use org.apache.commons.lang3.StringUtils
String emptyString = new String();
result = StringUtils.defaultIfEmpty(emptyString, "default");
System.out.println(result);
String nullString = null;
result = StringUtils.defaultIfEmpty(nullString, "default");
System.out.println(result);
Both of the above options will print:
default
default
For a time difference, note that the calendar starts at 01.01.1970, 01:00, not at 00:00. If you're using java.util.Date and java.text.SimpleDateFormat, you will have to compensate for 1 hour:
long start = System.currentTimeMillis();
long end = start + (1*3600 + 23*60 + 45) * 1000 + 678; // 1 h 23 min 45.678 s
Date timeDiff = new Date(end - start - 3600000); // compensate for 1h in millis
SimpleDateFormat timeFormat = new SimpleDateFormat("H:mm:ss.SSS");
System.out.println("Duration: " + timeFormat.format(timeDiff));
This will print:
Duration: 1:23:45.678
This happens because the current account you have used to log in probably has very limited priviledges.
To fix this problem, you can change your the AllowNoPassword config setting to false in config.inc.php
. You may also force the authentication to use the config file and specify the default username and password .
$cfg['Servers'][$i]['AllowNoPassword'] = false;
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = ''; // leave blank if no password
After this, the PhPMyAdmin login page should show up when you refresh the page. You can then log in with the default root password.
More details can be found on this post ..
For Python 3.5+:
So, you can get the stacktrace from your exception as from any other exception. Use traceback.TracebackException
for it (just replace ex
with your exception):
print("".join(traceback.TracebackException.from_exception(ex).format())
An extended example and other features to do this:
import traceback
try:
1/0
except Exception as ex:
print("".join(traceback.TracebackException.from_exception(ex).format()) == traceback.format_exc() == "".join(traceback.format_exception(type(ex), ex, ex.__traceback__))) # This is True !!
print("".join(traceback.TracebackException.from_exception(ex).format()))
The output will be something like this:
True
Traceback (most recent call last):
File "untidsfsdfsdftled.py", line 29, in <module>
1/0
ZeroDivisionError: division by zero
Hope this will help you .
Here is Html code:-
<body>
<div ng-controller="MyController" class="container">
<h1>Modal example</h1>
<button ng-click="open()" class="btn btn-primary">Test Modal</button>
<modal title="Login form" visible="showModal">
<form role="form">
</form>
</modal>
</div>
</body>
AngularJs code:-
var mymodal = angular.module('mymodal', []);
mymodal.controller('MyController', function ($scope) {
$scope.showModal = false;
$scope.open = function(){
$scope.showModal = !$scope.showModal;
};
});
mymodal.directive('modal', function () {
return {
template: '<div class="modal fade">' +
'<div class="modal-dialog">' +
'<div class="modal-content">' +
'<div class="modal-header">' +
'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>' +
'<h4 class="modal-title">{{ title }}</h4>' +
'</div>' +
'<div class="modal-body" ng-transclude></div>' +
'</div>' +
'</div>' +
'</div>',
restrict: 'E',
transclude: true,
replace:true,
scope:true,
link: function postLink(scope, element, attrs) {
scope.title = attrs.title;
scope.$watch(attrs.visible, function(value){
if(value == true)
$(element).modal('show');
else
$(element).modal('hide');
});
$(element).on('shown.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = true;
});
});
$(element).on('hidden.bs.modal', function(){
scope.$apply(function(){
scope.$parent[attrs.visible] = false;
});
});
}
};
});
Check this--jsfiddle
You can use an array in the select() to define more columns and you can use the DB::raw() there with aliasing it to followers. Should look like this:
$query = DB::table('category_issue')
->select(array('issues.*', DB::raw('COUNT(issue_subscriptions.issue_id) as followers')))
->where('category_id', '=', 1)
->join('issues', 'category_issue.issue_id', '=', 'issues.id')
->left_join('issue_subscriptions', 'issues.id', '=', 'issue_subscriptions.issue_id')
->group_by('issues.id')
->order_by('followers', 'desc')
->get();
string[] tokens = str.Split(new[] { "is Marco and" }, StringSplitOptions.None);
If you have a single character delimiter (like for instance ,
), you can reduce that to (note the single quotes):
string[] tokens = str.Split(',');
Try the following
download HAXM from Intel https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager.
Unzip the file and Run intelhaxm-android.exe.
Run silent_install.bat.
In my computer Win10 x64 - VS2015 it worked
Actually, it is less complicated than it seems.
Sub
today_1()
ActiveCell.FormulaR1C1 = "=TODAY()"
ActiveCell.Value = Date
End Sub
First you should create one migration
file for your table like:
public function up()
{
Schema::create('test', function (Blueprint $table) {
$table->increments('id');
$table->string('fname',255);
$table->string('lname',255);
$table->rememberToken();
$table->timestamps();
});
}
After create test folder in migrations folder then newly created migration moved/copied in test folder and run below command in your terminal/cmd like:
php artisan migrate --path=/database/migrations/test/
If problem persists after setting permissions right for the
storage
andbootstrap/cache
folders, first confirm by turning off selinux with the command
setenforce 0
If this works after the above command, this should allow writing, but you've turned off added security server-wide. That's bad. Turn SELinux back.
setenforce 1
Then finally use SELinux to allow writing of the file by using this command
chcon -R -t httpd_sys_rw_content_t storage
And you're good to go!This link helped a lot!
JavaScript is what you need. If you are loading iframe when loading the page, insert the test for iframe using the onload event. If iframe is inserted in realtime, then create a callback function on insertion and hook in whatever action you need to take :)
Use date.ToShortDateString() to get the date without the time component
var date = DateTime.Now
var shortDate = date.ToShortDateString() //will give you 16/01/2019
use date.ToString() to customize the format of the date
var date = DateTime.Now
var shortDate = date.ToString('dd-MMM-yyyy') //will give you 16-Jan-2019
I believe that you will have to drop the foreign key constraints first. Then update all of the appropriate tables and remap them as they were.
ALTER TABLE [dbo.Details_tbl] DROP CONSTRAINT [FK_Details_tbl_User_tbl];
-- Perform more appropriate alters
ALTER TABLE [dbo.Details_tbl] ADD FOREIGN KEY (FK_Details_tbl_User_tbl)
REFERENCES User_tbl(appId);
-- Perform all appropriate alters to bring the key constraints back
However, unless memory is a really big issue, I would keep the identity as an INT. Unless you are 100% positive that your keys will never grow past the TINYINT restraints. Just a word of caution :)
Use the ieee.numeric_std
library, and the appropriate vector type for the numbers you are working on (unsigned
or signed
).
Then the operators are sla
/sra
for arithmetic shifts (ie fill with sign bit on right shifts and lsb on left shifts) and sll
/srl
for logical shifts (ie fill with '0's).
You pass a parameter to the operator to define the number of bits to shift:
A <= B srl 2; -- logical shift right 2 bits
I have no idea what I was writing above (thanks to Val for pointing that out!)
Of course the correct way to shift signed
and unsigned
types is with the shift_left
and shift_right
functions defined in ieee.numeric_std
.
The shift and rotate operators sll
, ror
etc are for vectors of boolean
, bit
or std_ulogic
, and can have interestingly unexpected behaviour in that the arithmetic shifts duplicate the end-bit even when shifting left.
And much more history can be found here:
http://jdebp.eu./FGA/bit-shifts-in-vhdl.html
However, the answer to the original question is still
sig <= tmp sll number_of_bits;
Below solution work for 2.3(Gingerbread)-4.4(Kitkat), 5.0(Lollipop) and 6.0(Marshmallow) also:-
Step 1 Code for opening the gallery to select pics:
public static final int PICK_IMAGE = 1;
private void takePictureFromGalleryOrAnyOtherFolder()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
Step 2 Code for getting data in onActivityResult
:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PICK_IMAGE) {
Uri selectedImageUri = data.getData();
String imagePath = getRealPathFromURI(selectedImageUri);
//Now you have imagePath do whatever you want to do now
}//end of inner if
}//end of outer if
}
public String getRealPathFromURI(Uri contentUri) {
//Uri contentUri = Uri.parse(contentURI);
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = null;
try {
if (Build.VERSION.SDK_INT > 19) {
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(contentUri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, sel, new String[] { id }, null);
} else {
cursor = context.getContentResolver().query(contentUri,
projection, null, null, null);
}
} catch (Exception e) {
e.printStackTrace();
}
String path = null;
try {
int column_index = cursor
.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index).toString();
cursor.close();
} catch (NullPointerException e) {
e.printStackTrace();
}
return path;
}
If you still get this error later after setting the permissions you may need to modify your creation mask. We found our new commits (folders under objects) were still being created with no group write permission, hence only the person who committed them could push into the repository.
We fixed this by setting the umask of the SSH users to 002 with an appropriate group shared by all users.
e.g.
umask 002
where the middle 0 is allowing group write by default.
Although it is an old question, I think this info bellow will add to the quality of the answers here.
When ignoring files with the executable bit set, I just use this command:
find . ! -perm -111
To keep it from recursively enter into other directories:
find . -maxdepth 1 ! -perm -111
No need for pipes to mix lots of commands, just the powerful plain find command.
That said, I hope this is useful to anyone.
Based on tips from https://developer.mozilla.org/en-US/docs/CSS/background-size I end up with the following recipe that worked for me
body {
overflow-y: hidden ! important;
overflow-x: hidden ! important;
background-color: #f8f8f8;
background-image: url('index.png');
/*background-size: cover;*/
background-size: contain;
background-repeat: no-repeat;
background-position: right;
}
No curly braces required you can directly write
@if($user->status =='waiting')
<td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{{ $user->travel_id }}" data-toggle="modal" data-target="#myModal">Approve/Reject<a></td>
@else
<td>{{ $user->status }}</td>
@endif
Another difference, I didn't see here:
Bubble sort has 3 value assignments per swap: you have to build a temporary variable first to save the value you want to push forward(no.1), than you have to write the other swap-variable into the spot you just saved the value of(no.2) and then you have to write your temporary variable in the spot other spot(no.3). You have to do that for each spot - you want to go forward - to sort your variable to the correct spot.
With insertion sort you put your variable to sort in a temporary variable and then put all variables in front of that spot 1 spot backwards, as long as you reach the correct spot for your variable. That makes 1 value assignement per spot. In the end you write your temp-variable into the the spot.
That makes far less value assignements, too.
This isn't the strongest speed-benefit, but i think it can be mentioned.
I hope, I expressed myself understandable, if not, sorry, I'm not a nativ Britain
As other answers have stated, there really just isn't a way that's any good. Base64 can be decoded. Bytecode can be decompiled. Python was initially just interpreted, and most interpreted languages try to speed up machine interpretation more than make it difficult for human interpretation.
Python was made to be readable and shareable, not obfuscated. The language decisions about how code has to be formatted were to promote readability across different authors.
Obfuscating python code just doesn't really mesh with the language. Re-evaluate your reasons for obfuscating the code.
Here is a var arg XOR method for java...
public static boolean XOR(boolean... args) {
boolean r = false;
for (boolean b : args) {
r = r ^ b;
}
return r;
}
Enjoy
I've got a better work around than OCR and to maintain the page alignment while extracting the text from a PDF. Should be of help:
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO
def convert_pdf_to_txt(path):
rsrcmgr = PDFResourceManager()
retstr = StringIO()
codec = 'utf-8'
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
fp = open(path, 'rb')
interpreter = PDFPageInterpreter(rsrcmgr, device)
password = ""
maxpages = 0
caching = True
pagenos=set()
for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
interpreter.process_page(page)
text = retstr.getvalue()
fp.close()
device.close()
retstr.close()
return text
text= convert_pdf_to_txt('test.pdf')
print(text)
Why not using pyvmomi original function SmartConnectNoSSL
.
They added this function on June 14, 2016
and named it ConnectNoSSL
, one day after they changed the name to SmartConnectNoSSL
, use that instead of by passing the warning with unnecessary lines of code in your project?
Provides a standard method for connecting to a specified server without SSL verification. Useful when connecting to servers with self-signed certificates or when you wish to ignore SSL altogether
service_instance = connect.SmartConnectNoSSL(host=args.ip,
user=args.user,
pwd=args.password)
i think unlink & link php versions are not enough because we are often using php with apache(httpd), so need to update httpd.conf after switch php version.
i have write shell script for disable/enable php_module
automatically inside httpd.conf
, look at line 46 to line 54 https://github.com/dangquangthai/switch-php-version-on-mac-sierra/blob/master/switch-php#L46
Follow my steps:
1) Check installed php versions by brew, for sure everything good
> brew list | grep php
#output
php56
php56-intl
php56-mcrypt
php71
php71-intl
php71-mcrypt
2) Run script
> switch-php 71 # or switch-php 56
#output
PHP version [71] found
Switching from [php56] to [php71] ...
Unlink php56 ... [OK] and Link php71 ... [OK]
Updating Apache2.4 Configuration /usr/local/etc/httpd/httpd.conf ... [OK]
Restarting Apache2.4 ... [OK]
PHP 7.1.11 (cli) (built: Nov 3 2017 08:48:02) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2017 Zend Technologies
3) Finally, when your got above message, check httpd.conf
, in my laptop:
vi /usr/local/etc/httpd/httpd.conf
You can see near by LoadModule lines
LoadModule php7_module /usr/local/Cellar/php71/7.1.11_22/libexec/apache2/libphp7.so
#LoadModule php5_module /usr/local/Cellar/php56/5.6.32_8/libexec/apache2/libphp5.so
4) open httpd://localhost/info.php
i hope it helpful
If your datetime column have the Pandas datetime type (e.g. datetime64[ns]
), for proper filtering you need the pd.Timestamp object, for example:
from datetime import date
import pandas as pd
value_to_check = pd.Timestamp(date.today().year, 1, 1)
filter_mask = df['date_column'] < value_to_check
filtered_df = df[filter_mask]
To expand on previous answers, a function to do this could work like this (changing the time and interval formats however you like them according to this for function.date, and this for DateInterval):
(I've also written an alternate form of the below function here.)
// Return adjusted time.
function addMinutesToTime( $time, $plusMinutes ) {
$time = DateTime::createFromFormat( 'g:i:s', $time );
$time->add( new DateInterval( 'PT' . ( (integer) $plusMinutes ) . 'M' ) );
$newTime = $time->format( 'g:i:s' );
return $newTime;
}
$adjustedTime = addMinutesToTime( '9:15:00', 15 );
echo '<h1>Adjusted Time: ' . $adjustedTime . '</h1>' . PHP_EOL . PHP_EOL;
Another way, just for completeness.
DECLARE @empNumber INT = 7123
SELECT STUFF('000000', 6-LEN(@empNumber)+1, LEN(@empNumber), @empNumber)
Or, as per your query
SELECT STUFF('000000', 6-LEN(EmployeeID)+1, LEN(EmployeeID), EmployeeID)
AS EmployeeCode
FROM dbo.RequestItems
WHERE ID=0
try this
counter = 0
def increment():
global counter
counter += 1
increment()
Let me summarize and add something:
1. new ArrayList<String>();
2. Arrays.asList("A", "B", "C")
1. Lists.newArrayList("Mike", "John", "Lesly");
2. Lists.asList("A","B", new String [] {"C", "D"});
Immutable List
1. Collections.unmodifiableList(new ArrayList<String>(Arrays.asList("A","B")));
2. ImmutableList.builder() // Guava
.add("A")
.add("B").build();
3. ImmutableList.of("A", "B"); // Guava
4. ImmutableList.copyOf(Lists.newArrayList("A", "B", "C")); // Guava
Empty immutable List
1. Collections.emptyList();
2. Collections.EMPTY_LIST;
List of Characters
1. Lists.charactersOf("String") // Guava
2. Lists.newArrayList(Splitter.fixedLength(1).split("String")) // Guava
List of Integers
Ints.asList(1,2,3); // Guava
Careful with rewriting URLs, though. I'm using this, so it keeps URLs rewritten.
Response.Redirect(Request.RawUrl);
Delete bin and obj folders. Then rebuild the solution.
//OnClick Listener
@Override
public void onClick(View v) {
String webUrl = news.getNewsURL();
if(webUrl!="")
Utils.intentWebURL(mContext, webUrl);
}
//Your Util Method
public static void intentWebURL(Context context, String url) {
if (!url.startsWith("http://") && !url.startsWith("https://")) {
url = "http://" + url;
}
boolean flag = isURL(url);
if (flag) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(url));
context.startActivity(browserIntent);
}
}
Instead of
Object.values(myObject);
use
Object["values"](myObject);
In your example case:
const values = Object["values"](data).map(x => x.substr(0, x.length - 4));
This will hide the ts compiler error.
Adding to Kim .J's solution: you can add preserveWhitespace=true
in order to avoid a Whitespace error. Like this:
soap.CreateClient(url,preserveWhitespace=true,function(...){
DON'T USE A TRANSAPENT OR NULL LAYOUT because then the button
(or the generic view) will no more highlight at click!!!
I had the same problem and finally I found the correct attribute from Android API to solve the problem. It can apply to any view
Use this in the button specifications
android:background="?android:selectableItemBackground"
This requires API 11
For older versions of Rails
ruby script/generate migration RemoveFieldNameFromTableName field_name:datatype
For Rails 3 and up
rails generate migration RemoveFieldNameFromTableName field_name:datatype
Append suffix L
: 23423429L
.
By default, java interpret all numeral literals as 32-bit integer values. If you want to explicitely specify that this is something bigger then 32-bit integer you should use suffix L
for long values.
In the first case you are simply starting a new thread while in the second case you are entering in the thread pool.
The thread pool job is to share and recycle threads. It allows to avoid losing a few millisecond every time we need to create a new thread.
There are a several ways to enter the thread pool:
No need to use datetime library. Using the dateutil library there is no need of any format:
>>> from dateutil import parser
>>> s= '25 April, 2020, 2:50, pm, IST'
>>> parser.parse(s)
datetime.datetime(2020, 4, 25, 14, 50)
I can see that this only for actually turning the dialogs back on. But if you are a web dev and you would like to see a way to possibly have some form of notification when these are off...in the case that you are using native alerts/confirms for validation or whatever. Check this solution to detect and notify the user https://stackoverflow.com/a/23697435/1248536
Taking a uniform random variable as the value of RGB may generate a large amount of gray, white, and black, which are often not the colors we want.
The cv::applyColorMap
can easily generate a random RGB palette, and you can choose a favorite color map from the list here
Example for C++11:
#include <algorithm>
#include <numeric>
#include <random>
#include <opencv2/opencv.hpp>
std::random_device rd;
std::default_random_engine re(rd());
// Generating randomized palette
cv::Mat palette(1, 255, CV_8U);
std::iota(palette.data, palette.data + 255, 0);
std::shuffle(palette.data, palette.data + 255, re);
cv::applyColorMap(palette, palette, cv::COLORMAP_JET);
// ...
// Picking random color from palette and drawing
auto randColor = palette.at<cv::Vec3b>(i % palette.cols);
cv::rectangle(img, cv::Rect(0, 0, 100, 100), randColor, -1);
Example for Python3:
import numpy as np, cv2
palette = np.arange(0, 255, dtype=np.uint8).reshape(1, 255, 1)
palette = cv2.applyColorMap(palette, cv2.COLORMAP_JET).squeeze(0)
np.random.shuffle(palette)
# ...
rand_color = tuple(palette[i % palette.shape[0]].tolist())
cv2.rectangle(img, (0, 0), (100, 100), rand_color, -1)
If you don't need so many colors, you can just cut the palette to the desired length.
For those looking to do this in VB, here's how I got mine to work with a checkbox.
Background: I was trying to make my own checkbox that is a slider/switch control. I've only included the relevant code for this question.
<asp:CheckBox ID="checkbox" runat="server" AutoPostBack="true" />
Create an EventHandler (OnCheckChanged). When an event fires on the control (ID="checkbox") inside your usercontrol (MyCheckBox.ascx), then fire your EventHandler (OnCheckChanged).
Public Event OnCheckChanged As EventHandler
Private Sub checkbox_CheckedChanged(sender As Object, e As EventArgs) Handles checkbox.CheckedChanged
RaiseEvent OnCheckChanged(Me, e)
End Sub
<uc:MyCheckbox runat="server" ID="myCheck" OnCheckChanged="myCheck_CheckChanged" />
Note: myCheck_CheckChanged didn't fire until I added the Handles clause below
Protected Sub myCheck_CheckChanged (sender As Object, e As EventArgs) Handles scTransparentVoting.OnCheckChanged
'Do some page logic here
End Sub
Here is a method using a lookup table of thresholds and associated colours to map the colours to the variable of interest.
# make a grid 'Grd' of points and number points for side of square 'GrdD'
Grd <- expand.grid(seq(0.5,400.5,10),seq(0.5,400.5,10))
GrdD <- length(unique(Grd$Var1))
# Add z-values to the grid points
Grd$z <- rnorm(length(Grd$Var1), mean = 10, sd =2)
# Make a vector of thresholds 'Brks' to colour code z
Brks <- c(seq(0,18,3),Inf)
# Make a vector of labels 'Lbls' for the colour threhsolds
Lbls <- Lbls <- c('0-3','3-6','6-9','9-12','12-15','15-18','>18')
# Make a vector of colours 'Clrs' for to match each range
Clrs <- c("grey50","dodgerblue","forestgreen","orange","red","purple","magenta")
# Make up lookup dataframe 'LkUp' of the lables and colours
LkUp <- data.frame(cbind(Lbls,Clrs),stringsAsFactors = FALSE)
# Add a new variable 'Lbls' the grid dataframe mapping the labels based on z-value
Grd$Lbls <- as.character(cut(Grd$z, breaks = Brks, labels = Lbls))
# Add a new variable 'Clrs' to the grid dataframe based on the Lbls field in the grid and lookup table
Grd <- merge(Grd,LkUp, by.x = 'Lbls')
# Plot the grid using the 'Clrs' field for the colour of each point
plot(Grd$Var1,
Grd$Var2,
xlim = c(0,400),
ylim = c(0,400),
cex = 1.0,
col = Grd$Clrs,
pch = 20,
xlab = 'mX',
ylab = 'mY',
main = 'My Grid',
axes = FALSE,
labels = FALSE,
las = 1
)
axis(1,seq(0,400,100))
axis(2,seq(0,400,100),las = 1)
box(col = 'black')
legend("topleft", legend = Lbls, fill = Clrs, title = 'Z')
cat filename | grep -v "pattern" > filename.1
mv filename.1 filename
There seems to be a lot of confusion regarding the preprocessor.
What the compiler does when it sees a #include
that it replaces that line with the contents of the included files, no questions asked.
So if you have a file a.h
with this contents:
typedef int my_number;
and a file b.c
with this content:
#include "a.h"
#include "a.h"
the file b.c
will be translated by the preprocessor before compilation to
typedef int my_number;
typedef int my_number;
which will result in a compiler error, since the type my_number
is defined twice. Even though the definition is the same this is not allowed by the C language.
Since a header often is used in more than one place include guards usually are used in C. This looks like this:
#ifndef _a_h_included_
#define _a_h_included_
typedef int my_number;
#endif
The file b.c
still would have the whole contents of the header in it twice after being preprocessed. But the second instance would be ignored since the macro _a_h_included_
would already have been defined.
This works really well, but has two drawbacks. First of all the include guards have to be written, and the macro name has to be different in every header. And secondly the compiler has still to look for the header file and read it as often as it is included.
Objective-C has the #import
preprocessor instruction (it also can be used for C and C++ code with some compilers and options). This does almost the same as #include
, but it also notes internally which file has already been included. The #import
line is only replaced by the contents of the named file for the first time it is encountered. Every time after that it is just ignored.
Instead of choosing Restore Database..., select Restore Files and Filegroups...
Then enter a database name, select your .bak file path as the source, check the restore checkbox, and click Ok. If the .bak file is valid, it will work.
(The SQL Server restore option names are not intuitive for what should a very simple task.)
The iterator of _.each
is called with 3 parameters (element, index, list)
. So yes, for _.each
you cab get the index.
You can do the same in sortBy
To force LF line endings for all text files, you can create .gitattributes
file in top-level of your repository with the following lines (change as desired):
# Ensure all C and PHP files use LF.
*.c eol=lf
*.php eol=lf
which ensures that all files that Git considers to be text files have normalized (LF
) line endings in the repository (normally core.eol
configuration controls which one do you have by default).
Based on the new attribute settings, any text files containing CRLFs should be normalized by Git. If this won't happen automatically, you can refresh a repository manually after changing line endings, so you can re-scan and commit the working directory by the following steps (given clean working directory):
$ echo "* text=auto" >> .gitattributes
$ rm .git/index # Remove the index to force Git to
$ git reset # re-scan the working directory
$ git status # Show files that will be normalized
$ git add -u
$ git add .gitattributes
$ git commit -m "Introduce end-of-line normalization"
or as per GitHub docs:
git add . -u
git commit -m "Saving files before refreshing line endings"
git rm --cached -r . # Remove every file from Git's index.
git reset --hard # Rewrite the Git index to pick up all the new line endings.
git add . # Add all your changed files back, and prepare them for a commit.
git commit -m "Normalize all the line endings" # Commit the changes to your repository.
See also: @Charles Bailey post.
In addition, if you would like to exclude any files to not being treated as a text, unset their text attribute, e.g.
manual.pdf -text
Or mark it explicitly as binary:
# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary
To see some more advanced git normalization file, check .gitattributes
at Drupal core:
# Drupal git normalization
# @see https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html
# @see https://www.drupal.org/node/1542048
# Normally these settings would be done with macro attributes for improved
# readability and easier maintenance. However macros can only be defined at the
# repository root directory. Drupal avoids making any assumptions about where it
# is installed.
# Define text file attributes.
# - Treat them as text.
# - Ensure no CRLF line-endings, neither on checkout nor on checkin.
# - Detect whitespace errors.
# - Exposed by default in `git diff --color` on the CLI.
# - Validate with `git diff --check`.
# - Deny applying with `git apply --whitespace=error-all`.
# - Fix automatically with `git apply --whitespace=fix`.
*.config text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.css text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.dist text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.engine text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.html text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=html
*.inc text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.install text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.js text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.json text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.lock text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.map text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.md text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.module text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.php text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.po text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.profile text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.script text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.sh text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.sql text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.svg text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.theme text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.twig text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.txt text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.xml text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.yml text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
# Define binary file attributes.
# - Do not treat them as text.
# - Include binary diff in patches instead of "binary files differ."
*.eot -text diff
*.exe -text diff
*.gif -text diff
*.gz -text diff
*.ico -text diff
*.jpeg -text diff
*.jpg -text diff
*.otf -text diff
*.phar -text diff
*.png -text diff
*.svgz -text diff
*.ttf -text diff
*.woff -text diff
*.woff2 -text diff
See also:
CSS3: http://webdesign.about.com/od/styleproperties/p/blspbgsize.htm
.style1 {
...
background-size: 100%;
}
You can specify just width or height with:
background-size: 100% 50%;
Which will stretch it 100% of the width and 50% of the height.
Browser support: http://caniuse.com/#feat=background-img-opts
My test string for the following:
testing='12345,abc,123,54321,ab15234,123456,52341';
If I understand your question, you'd want ["12345", "54321", "15234", "52341"]
.
If JS engines supported regexp lookbehinds, you could do:
testing.match(/(?<!\d)\d{5}(?!\d)/g)
Since it doesn't currently, you could:
testing.match(/(?:^|\D)(\d{5})(?!\d)/g)
and remove the leading non-digit from appropriate results, or:
pentadigit=/(?:^|\D)(\d{5})(?!\d)/g;
result = [];
while (( match = pentadigit.exec(testing) )) {
result.push(match[1]);
}
Note that for IE, it seems you need to use a RegExp stored in a variable rather than a literal regexp in the while
loop, otherwise you'll get an infinite loop.
I am using angular 4 and faced the same issue apply, all possible solution but finally, this solve my problem
export class AppRoutingModule {
constructor(private router: Router) {
this.router.errorHandler = (error: any) => {
this.router.navigate(['404']); // or redirect to default route
}
}
}
Hope this will help you.
You need to enable SQL Server Authentication:
For me the solution was a bit simpler, I just had to clean the repository : .m2/repository/org/apache/maven/archetypes
Try a using namespace std;
at the top of game.h
or use the fully-qualified std::string
instead of string
.
The namespace
in game.cpp
is after the header is included.
You can create these easily using the floating ability of CSS, for example. I have created a small example on Jsfiddle over here, all the related css and html is also provided there.
.foo {_x000D_
float: left;_x000D_
width: 20px;_x000D_
height: 20px;_x000D_
margin: 5px;_x000D_
border: 1px solid rgba(0, 0, 0, .2);_x000D_
}_x000D_
_x000D_
.blue {_x000D_
background: #13b4ff;_x000D_
}_x000D_
_x000D_
.purple {_x000D_
background: #ab3fdd;_x000D_
}_x000D_
_x000D_
.wine {_x000D_
background: #ae163e;_x000D_
}
_x000D_
<div class="foo blue"></div>_x000D_
<div class="foo purple"></div>_x000D_
<div class="foo wine"></div>
_x000D_
UNION removes duplicate records in other hand UNION ALL does not. But one need to check the bulk of data that is going to be processed and the column and data type must be same.
since union internally uses "distinct" behavior to select the rows hence it is more costly in terms of time and performance. like
select project_id from t_project
union
select project_id from t_project_contact
this gives me 2020 records
on other hand
select project_id from t_project
union all
select project_id from t_project_contact
gives me more than 17402 rows
on precedence perspective both has same precedence.
To get the token in a single oneliner:
kubectl -n kube-system describe secret $(kubectl -n kube-system get secret | awk '/^deployment-controller-token-/{print $1}') | awk '$1=="token:"{print $2}'
This assumes that your ~/.kube/config is present and valid. And also that kubectl config get-contexts
indicates that you are using the correct context (cluster and namespace) for the dashboard you are logging into.
I derived this answer from what I learned from @silverfox's answer. That is a very informative write up. Unfortunately it falls short of telling you how to actually put the information into practice. Maybe I've been doing DevOps too long, but I think in shell. It's much more difficult for me to learn or teach in English.
Here is that oneliner with line breaks and indents for readability:
kubectl -n kube-system describe secret $(
kubectl -n kube-system get secret | \
awk '/^deployment-controller-token-/{print $1}'
) | \
awk '$1=="token:"{print $2}'
There are 4 distinct commands and they get called in this order:
deployment-controller-token-
(which is the pod name)It says that the file C:\wamp\www\mysite\php\includes\dbconn.inc
doesn't exist, so the error is, you're missing the file.
Sorry, brief moment of synapse failure. Here's the real answer.
require 'date'
Time.at(seconds_since_epoch_integer).to_datetime
Brief example (this takes into account the current system timezone):
$ date +%s
1318996912
$ irb
ruby-1.9.2-p180 :001 > require 'date'
=> true
ruby-1.9.2-p180 :002 > Time.at(1318996912).to_datetime
=> #<DateTime: 2011-10-18T23:01:52-05:00 (13261609807/5400,-5/24,2299161)>
Further update (for UTC):
ruby-1.9.2-p180 :003 > Time.at(1318996912).utc.to_datetime
=> #<DateTime: 2011-10-19T04:01:52+00:00 (13261609807/5400,0/1,2299161)>
Recent Update: I benchmarked the top solutions in this thread while working on a HA service a week or two ago, and was surprised to find that Time.at(..)
outperforms DateTime.strptime(..)
(update: added more benchmarks).
# ~ % ruby -v
# => ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-darwin13.0]
irb(main):038:0> Benchmark.measure do
irb(main):039:1* ["1318996912", "1318496912"].each do |s|
irb(main):040:2* DateTime.strptime(s, '%s')
irb(main):041:2> end
irb(main):042:1> end
=> #<Benchmark ... @real=2.9e-05 ... @total=0.0>
irb(main):044:0> Benchmark.measure do
irb(main):045:1> [1318996912, 1318496912].each do |i|
irb(main):046:2> DateTime.strptime(i.to_s, '%s')
irb(main):047:2> end
irb(main):048:1> end
=> #<Benchmark ... @real=2.0e-05 ... @total=0.0>
irb(main):050:0* Benchmark.measure do
irb(main):051:1* ["1318996912", "1318496912"].each do |s|
irb(main):052:2* Time.at(s.to_i).to_datetime
irb(main):053:2> end
irb(main):054:1> end
=> #<Benchmark ... @real=1.5e-05 ... @total=0.0>
irb(main):056:0* Benchmark.measure do
irb(main):057:1* [1318996912, 1318496912].each do |i|
irb(main):058:2* Time.at(i).to_datetime
irb(main):059:2> end
irb(main):060:1> end
=> #<Benchmark ... @real=2.0e-05 ... @total=0.0>
You can probably add two foreign key constraints (honestly: I've never tried it), but it'd then insist the parent row exist in both tables.
Instead you probably want to create a supertype for your two employee subtypes, and then point the foreign key there instead. (Assuming you have a good reason to split the two types of employees, of course).
employee
employees_ce ———————— employees_sn
———————————— type ————————————
empid —————————> empid <——————— empid
name /|\ name
|
|
deductions |
—————————— |
empid ————————+
name
type
in the employee table would be ce
or sn
.
If you want to run it @build time :
CMD /bin/bash /file.sh arg1
if you want to run it @run time :
ENTRYPOINT ["/bin/bash"]
CMD ["/file.sh", "arg1"]
Then in the host shell
docker build -t test .
docker run -i -t test
Here is how it works for me with no Servlet use.
Let's say I am trying to access web.xml in project/WebContent/WEB-INF/web.xml
In project property Source-tab add source folder by pointing to the parent container for WEB-INF folder (in my case WebContent )
Now let's use class loader:
InputStream inStream = class.getClass().getClassLoader().getResourceAsStream("Web-INF/web.xml")
new syntax
<%= form_for :user, url: custom_user_path, method: :post do |f|%>
<%end%>
I think what you are trying to do is to wrap long text without spaces.
look at this :Hyphenator.js and it's demo.
In Emulator, to view this file click on Settings>Storage>Other>Android>data>com.companyname.textapp>file>Download. Here, textapp is the name of the app you are working on.
The limitation relates to the simplified CommonJS syntax vs. the normal callback syntax:
Loading a module is inherently an asynchronous process due to the unknown timing of downloading it. However, RequireJS in emulation of the server-side CommonJS spec tries to give you a simplified syntax. When you do something like this:
var foomodule = require('foo');
// do something with fooModule
What's happening behind the scenes is that RequireJS is looking at the body of your function code and parsing out that you need 'foo' and loading it prior to your function execution. However, when a variable or anything other than a simple string, such as your example...
var module = require(path); // Call RequireJS require
...then Require is unable to parse this out and automatically convert it. The solution is to convert to the callback syntax;
var moduleName = 'foo';
require([moduleName], function(fooModule){
// do something with fooModule
})
Given the above, here is one possible rewrite of your 2nd example to use the standard syntax:
define(['dyn_modules'], function (dynModules) {
require(dynModules, function(){
// use arguments since you don't know how many modules you're getting in the callback
for (var i = 0; i < arguments.length; i++){
var mymodule = arguments[i];
// do something with mymodule...
}
});
});
EDIT: From your own answer, I see you're using underscore/lodash, so using _.values
and _.object
can simplify the looping through arguments array as above.
This can also be done using a wrapper. Very general way of keeping time.
The wrapper in this example code wraps any function and prints the amount of time needed to execute the function:
def timethis(f):
import time
def wrapped(*args, **kwargs):
start = time.time()
r = f(*args, **kwargs)
print "Executing {0} took {1} seconds".format(f.func_name, time.time()-start)
return r
return wrapped
@timethis
def thistakestime():
for x in range(10000000):
pass
thistakestime()
Just to add to @MichaelMocko answer. Tuples have couple of gotchas at the moment:
Example:
public static (string name, string surname) GetPersonName(this PersonContext ctx, int id)
{
return ctx.Persons
.Where(person => person.Id == id)
// Selecting as Tuple
.Select(person => (person.Name, person.Surname))
.First();
}
This will fail to compile with "An expression tree may not contain a tuple literal" error. Unfortunately, the expression trees API wasn't expanded with support for tuples when these were added to the language.
Track (and upvote) this issue for the updates: https://github.com/dotnet/roslyn/issues/12897
To get around the problem, you can cast it to anonymous type first and then convert the value to tuple:
// Will work
public static (string name, string surname) GetPersonName(this PersonContext ctx, int id)
{
return ctx.Persons
.Where(person => person.Id == id)
.Select(person => new { person.Name, person.Surname })
.ToList()
.Select(person => (person.Name, person.Surname))
.First();
}
Another option is to use ValueTuple.Create:
// Will work
public static (string name, string surname) GetPersonName(this PersonContext ctx, int id)
{
return ctx.Persons
.Where(person => person.Id == id)
.Select(person => ValueTuple.Create(person.Name, person.Surname))
.First();
}
References:
There's a proposal to add the support: https://github.com/dotnet/csharplang/issues/258
Example:
public static IQueryable<(string name, string surname)> GetPersonName(this PersonContext ctx, int id)
{
return ctx.Persons
.Where(person => person.Id == id)
.Select(person => ValueTuple.Create(person.Name, person.Surname));
}
// This won't work
ctx.GetPersonName(id).Select((name, surname) => { return name + surname; })
// But this will
ctx.GetPersonName(id).Select(t => { return t.name + t.surname; })
References:
using System;
using Newtonsoft.Json;
public class Program
{
public static void Main() {
var me = (age: 21, favoriteFood: "Custard");
string json = JsonConvert.SerializeObject(me);
// Will output {"Item1":21,"Item2":"Custard"}
Console.WriteLine(json);
}
}
Tuple field names are only available at compile time and are completely wiped out at runtime.
References:
i think you try to align the content to the right within the div, the div with offset already push itself to the right, here some code and LIVE sample:
FYI: .pull-right
only push the div to the right, but not the content inside the div.
HTML:
<div class="row">
<div class="container">
<div class="col-md-4 someclass">
left content
</div>
<div class="col-md-4 col-md-offset-4 someclass">
<div class="yellow_background totheright">right content</div>
</div>
</div>
</div>
CSS:
.someclass{ /*this class for testing purpose only*/
border:1px solid blue;
line-height:2em;
}
.totheright{ /*this will align the text to the right*/
text-align:right;
}
.yellow_background{
background-color:yellow;
}
Another modification:
...
<div class="yellow_background totheright">
<span>right content</span>
<br/>image also align-right<br/>
<img width="15%" src="https://www.google.com/images/srpr/logo11w.png"/>
</div>
...
hope it will clear your problem
By using CHMOD yes:
For Recursive file:
chmod -R 777 foldername or pathname
For non recursive:
chmod 777 foldername or pathname
For those it might help, I use this list as a reference to define my content-type when I have to deal with images on my app.
It says that jpg extension can be declared with Content-type : image/jpeg
There isn't any image/jpg
attribute for content-type.
I have found the iMacros Firefox plugin (which is free) to work very well.
It can be automated with Python using Windows COM object interfaces. Here's some example code from http://wiki.imacros.net/Python. It requires Python Windows Extensions:
import win32com.client
def Hello():
w=win32com.client.Dispatch("imacros")
w.iimInit("", 1)
w.iimPlay("Demo\\FillForm")
if __name__=='__main__':
Hello()
There is a typo error :
$('#activelist :checkbox')...
Should be :
$('#inactivelist:checkbox')...
In project properties, under the run tab, specify your main class. Moreover, To avoid this issue, you need to check "Create main class" during creating new project. Specifying main class in properties should always work, but if in some rare case it doesn't work, then the issue could be resolved by re-creating the project and not forgetting to check "Create main class" if it is unchecked.
Laravel Server Requirements mention that BCMath
, Ctype
, JSON
, Mbstring
, OpenSSL
, PDO
, Tokenizer
, and XML
extensions are required. Most of the extensions are installed and enabled by default.
You can run the following command in Ubuntu to make sure the extensions are installed.
sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip
PHP version specific installation (if PHP 7.4 installed)
sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring
You may need other PHP extensions for your composer packages. Find from links below.
PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)
PHP extensions for Ubuntu 18.04 LTS (Bionic)
PHP extensions for Ubuntu 16.04 LTS (Xenial)
All you need is
e.preventDefault();
on child element.
The blog article is mostly right, but not complete. To have a full understanding of what an odex file does, you have to understand a little about how application files (APK) work.
Applications are basically glorified ZIP archives. The java code is stored in a file called classes.dex and this file is parsed by the Dalvik JVM and a cache of the processed classes.dex file is stored in the phone's Dalvik cache.
An odex is basically a pre-processed version of an application's classes.dex that is execution-ready for Dalvik. When an application is odexed, the classes.dex is removed from the APK archive and it does not write anything to the Dalvik cache. An application that is not odexed ends up with 2 copies of the classes.dex file--the packaged one in the APK, and the processed one in the Dalvik cache. It also takes a little longer to launch the first time since Dalvik has to extract and process the classes.dex file.
If you are building a custom ROM, it's a really good idea to odex both your framework JAR files and the stock apps in order to maximize the internal storage space for user-installed apps. If you want to theme, then simply deodex -> apply your theme -> reodex -> release.
To actually deodex, use small and baksmali:
Here's some pure-Python code you can use to calculate the mean and standard deviation.
All code below is based on the statistics
module in Python 3.4+.
def mean(data):
"""Return the sample arithmetic mean of data."""
n = len(data)
if n < 1:
raise ValueError('mean requires at least one data point')
return sum(data)/n # in Python 2 use sum(data)/float(n)
def _ss(data):
"""Return sum of square deviations of sequence data."""
c = mean(data)
ss = sum((x-c)**2 for x in data)
return ss
def stddev(data, ddof=0):
"""Calculates the population standard deviation
by default; specify ddof=1 to compute the sample
standard deviation."""
n = len(data)
if n < 2:
raise ValueError('variance requires at least two data points')
ss = _ss(data)
pvar = ss/(n-ddof)
return pvar**0.5
Note: for improved accuracy when summing floats, the statistics
module uses a custom function _sum
rather than the built-in sum
which I've used in its place.
Now we have for example:
>>> mean([1, 2, 3])
2.0
>>> stddev([1, 2, 3]) # population standard deviation
0.816496580927726
>>> stddev([1, 2, 3], ddof=1) # sample standard deviation
0.1
I just made jkid which is a small command-line json explorer that I made to easily explore big json objects. Objects can be explored "transversally" and a "preview" option is there to avoid console overflow.
$ echo '{"john":{"size":20, "eyes":"green"}, "bob":{"size":30, "eyes":"brown"}}' > test3.json
$ jkid . eyes test3.json
object[.]["eyes"]
{
"bob": "brown",
"john": "green"
}
I had the same problem and in order to execute pip install inside virtualenv I had to use this command:
RUN pip install virtualenv virtualenvwrapper
RUN mkdir -p /opt/virtualenvs
ENV WORKON_HOME /opt/virtualenvs
RUN /bin/bash -c "source /usr/local/bin/virtualenvwrapper.sh \
&& mkvirtualenv myapp \
&& workon myapp \
&& pip install -r /mycode/myapp/requirements.txt"
I hope it helps.
In my case, I was working on a web api project and although the project was set correctly to full debug, I was still seeing this error every time I attached to the IIS process I was trying to debug. Then I realized the publish profile was set to use the Release configuration. So one more place to check is your publish profile if you're using the 'Publish' feature of your dotnet web api project.
You can create a new queue item to do your removing of the class:
$("#div").addClass("error").delay(1000).queue(function(next){
$(this).removeClass("error");
next();
});
Or using the dequeue method:
$("#div").addClass("error").delay(1000).queue(function(){
$(this).removeClass("error").dequeue();
});
The reason you need to call next
or dequeue
is to let jQuery know that you are done with this queued item and that it should move on to the next one.
$ svn log | head -10
on whatever directory that has a .svn
folder
I believe what you want is:
SELECT ItemName, GROUP_CONCAT(DepartmentId) FROM table_name GROUP BY ItemName
If you're using MySQL
Reference
Try this - set Ajax call by setting up the header as follows:
var uri = "http://localhost:50869/odata/mydatafeeds"
$.ajax({
url: uri,
beforeSend: function (request) {
request.setRequestHeader("Authorization", "Negotiate");
},
async: true,
success: function (data) {
alert(JSON.stringify(data));
},
error: function (xhr, textStatus, errorMessage) {
alert(errorMessage);
}
});
Then run your code by opening Chrome with the following command line:
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
For compatibility with all browsers stick with .ico
.
.png is getting more and more support though as it is easier to create using multiple programs.
for .ico
<link rel="shortcut icon" href="http://example.com/myicon.ico" />
for .png, you need to specify the type
<link rel="icon" type="image/png" href="http://example.com/image.png" />
I'm on lubuntu 19.10
I've used combination of previous answers, and didn't tweak the $PATH
.
npm uninstall --global gulp gulp-cli
This removes any package if they are already there.sudo npm install --global gulp-cli
Reinstall it as root user.If you want to do copy and paste
npm uninstall --global gulp gulp-cli && sudo npm install --global gulp-cli
should work
I guess --global
is unnecessary here as it's installed using sudo
, but I've used it just in case.
In my case Mac OS High Sierra 10.13.6
brew -v
OutPut-
Homebrew 2.2.2
Homebrew/homebrew-core (git revision 71aa; last commit 2020-01-07)
Homebrew/homebrew-cask (git revision 84f00; last commit 2020-01-07)
Regarding whitehawk's accepted answer. I am just trying to add a bit hands on experience. Was just trying to add a comments, but SO complains it's too long.
Basically, without IE 9 installed, the registry switch FEATURE_BROWSER_EMULATION won't work AT ALL.
For example, my own experience today I was trying to get the .net webcontrol to work with IE10 mode because one html I am trying to render won't work with .netControl under VS2012, and not even work when I load the html to IE8 directly, still css won't render properly(even after I say allow blocked content). But I have tested the same html ok with IE10 on a friend's win 8 machine. That's why I am trying to set the .net webControl to IE 10 mode but just keeps failing...
Now I figured this is bcos my win 7 machine only have IE8 installed, so regardless which value I set to the FEATURE_BROWSER_EMULATION switch(value to IE9, IE10 IE11), it just won't work AT ALL !
Then I downloaded and installed IE 10 on my win 7 machine. Still it won't work, then I added the FEATURE_BROWSER_EMULATION, it started working !
Also I noticed regardless which value I set , even set it to value 0 by default, the webControl is still using IE 10 mode which still works for me.
So to summarise, If you have IE X installed but you want your .Net webControl to work under IE (X+N) N>0 modo, TWO things you need to do:
Go to MS website & download and install IE (X+N) on your machine, you will need to reboot after installation.
apply whitehawk's answer.
Basically: To control the value of this feature by using the registry, add the name of your executable file to the following setting and set the value to match the desired setting.
HKEY_LOCAL_MACHINE (or HKEY_CURRENT_USER)
SOFTWARE
Microsoft
Internet Explorer
Main
FeatureControl
FEATURE_BROWSER_EMULATION
contoso.exe = (DWORD) 00009000
Windows Internet Explorer 8 and later. The FEATURE_BROWSER_EMULATION feature defines the default emulation mode for Internet Explorer and supports the following values.
Value Description
11001 (0x2AF9 Internet Explorer 11. Webpages are displayed in IE11 edge mode, regardless of the !DOCTYPE directive.
11000 (0x2AF8) IE11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 edge mode. Default value for IE11.
10001 (0x2711) Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive.
10000 (0x02710) Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10.
9999 (0x270F) Windows Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the !DOCTYPE directive.
9000 (0x2328) Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode. Default value for Internet Explorer 9.
Important In Internet Explorer 10, Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode.
8888 (0x22B8) Webpages are displayed in IE8 Standards mode, regardless of the !DOCTYPE directive.
8000 (0x1F40) Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. Default value for Internet Explorer 8 Important In Internet Explorer 10, Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode.
7000 (0x1B58) Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode. Default value for applications hosting the WebBrowser Control.
Full ref here
For AngularJs you have to use "angular-datatables.min.js" file for datatable settings. You will get this from http://l-lin.github.io/angular-datatables/#/welcome.
After that you can write code like below,
<script>
var app = angular.module('AngularWayApp', ['datatables']);
</script>
<div ng-app="AngularWayApp" ng-controller="AngularWayCtrl">
<table id="example" datatable="ng" class="table">
<thead>
<tr>
<th><b>UserID</b></th>
<th><b>Firstname</b></th>
<th><b>Lastname</b></th>
<th><b>Email</b></th>
<th><b>Actions</b></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users" ng-click="testingClick(user)">
<td>
{{user.UserId}}
</td>
<td>
{{user.FirstName}}
</td>
<td>
{{user.Lastname}}
</td>
<td>
{{user.Email}}
</td>
<td>
<span ng-click="editUser(user)" style="color:blue;cursor: pointer; font-weight:500; font-size:15px" class="btnAdd" data-toggle="modal" data-target="#myModal">Edit</span> |
<span ng-click="deleteUser(user)" style="color:red; cursor: pointer; font-weight:500; font-size:15px" class="btnRed">Delete</span>
</td>
</tr>
</tbody>
</table>
</div>
I'm having a hard time figuring out what exactly you're looking for here, so hope I'm not way off base.
I'm assuming what you mean is that when a keyup event occurs on the input with class "start" you want to get the values of all the inputs in neighbouring <td>s:
$('.start').keyup(function() {
var otherInputs = $(this).parents('td').siblings().find('input');
for(var i = 0; i < otherInputs.length; i++) {
alert($(otherInputs[i]).val());
}
return false;
});
msgbox("your text here" & Environment.NewLine & "more text") is the easist way. no point in making your code harder or more ocmplicated than you need it to be...
I got into this situation ("Missing private key.") after Xcode failed to create new distribution certificate - an unknown error occurred.
Then, I struggled to obtain the private key or to generate new certificate. From the certificate manager in Xcode I got strange errors like "The passphrase you entered is wrong". But it did not even ask me for any passphrase.
What helped me was:
After that, Xcode was able to create new distribution certificate and no private key was missing.
Lesson learned: Restart your Mac as much as your Windows ;)
Little addition to Jason's answer:
ToShortDateString()
is culture-sensitive.From MSDN:
The string returned by the ToShortDateString method is culture-sensitive. It reflects the pattern defined by the current culture's DateTimeFormatInfo object. For example, for the en-US culture, the standard short date pattern is "M/d/yyyy"; for the de-DE culture, it is "dd.MM.yyyy"; for the ja-JP culture, it is "yyyy/M/d". The specific format string on a particular computer can also be customized so that it differs from the standard short date format string.
That's mean it's better to use the ToString()
method and define format explicitly (as Jason said). Although if this string appeas in UI the ToShortDateString()
is a good solution because it returns string which is familiar to a user.
DateTime.Today
.None of the answers worked for me when using Docker Toolbox on Windows 10 Home, but 10.0.2.2 did, since it uses VirtualBox which exposes the host to the VM on this address.
Code To Get Today's date in any specific Format
You can define the desired format in SimpleDateFormat instance to get the date in that specific formate
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
String todaysdate = dateFormat.format(date);
System.out.println("Today's date : " + todaysdate);
Follow below links to see the valid date format combination.
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
CODE : To get x days ahead or Previous from Today's date, To get the past date or Future date.
For Example :
Today date : 11/27/2018
xdayFromTodaysDate = 2 to get date as 11/29/2018
xdayFromTodaysDate = -2 to get date as 11/25/2018
public String getAniversaryDate(int xdayFromTodaysDate ){
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
Date date = cal.getTime();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH,xdayFromTodaysDate);
date = cal.getTime();
String aniversaryDate = dateFormat.format(date);
LOGGER.info("Today's date : " + todaysdate);
return aniversaryDate;
}
CODE : To get x days ahead or Previous from a Given date
public String getAniversaryDate(String givendate, int xdayFromTodaysDate ){
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
try {
Date date = dateFormat.parse(givendate);
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH,xdayFromTodaysDate);
date = cal.getTime();
String aniversaryDate = dateFormat.format(date);
LOGGER.info("aniversaryDate : " + aniversaryDate);
return aniversaryDate;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
Upgrading from Kepler to Luna worked for me.
I had just added some components for Java 1.8 support. It seems that they where not as compatible as I would like or that I mixed the wrong ones. It really caused a lot of problems. Trying to update the system reported errors as they couldn't fulfill some dependencies. Maven upgrades didn't work. Tried a lot of things.
So, if there is no reason to avoid the upgrade just add the luna repository to avalilable software sites (Luna http://download.eclipse.org/releases/luna/ ) and "check for updates". It is better to have all the components with the same version and there are some nice new features.
If you're using a Mac computer, you can use the new updateR package to update the R version from RStudio: http://www.andreacirillo.com/2018/02/10/updater-package-update-r-version-with-a-function-on-mac-osx/
In summary, you need to perform this:
To update your R version from within Rstudio using updateR you just have to run these five lines of code:
install.packages('devtools') #assuming it is not already installed library(devtools) install_github('andreacirilloac/updateR') library(updateR) updateR(admin_password = 'Admin user password')
at the end of installation process a message is going to confirm you the happy end:
everything went smoothly open a Terminal session and run 'R' to assert that latest version was installed
I found this site useful: http://www.vanseodesign.com/css/vertical-centering/ This worked for me:
HTML
<div id="parent">
<div id="child">Content here</div>
</div>
CSS
#parent {
padding: 5% 0;
}
#child {
padding: 10% 0;
}
François Wahl approach, but a bit shorter:
$("#search").keyup(function() {
var value = this.value;
$("table").find("tr").each(function(index) {
if (!index) return;
var id = $(this).find("td").first().text();
$(this).toggle(id.indexOf(value) !== -1);
});
});
Same as the answer from 'Richie' but a bit more concise.
Query for user constraints only
SELECT column_name FROM all_cons_columns WHERE constraint_name = (
SELECT constraint_name FROM user_constraints
WHERE UPPER(table_name) = UPPER('tableName') AND CONSTRAINT_TYPE = 'P'
);
Query for all constraints
SELECT column_name FROM all_cons_columns WHERE constraint_name = (
SELECT constraint_name FROM all_constraints
WHERE UPPER(table_name) = UPPER('tableName') AND CONSTRAINT_TYPE = 'P'
);
This might be what you are looking for:
<?php
$text = 'This is a Simple text.';
// this echoes "is is a Simple text." because 'i' is matched first
echo strpbrk($text, 'mi');
// this echoes "Simple text." because chars are case sensitive
echo strpbrk($text, 'S');
?>
Is it?
Or maybe this:
<?php
$mystring = 'abc';
$findme = 'a';
$pos = strpos($mystring, $findme);
// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
?>
Or even this
<?php
$email = '[email protected]';
$domain = strstr($email, '@');
echo $domain; // prints @example.com
$user = strstr($email, '@', true); // As of PHP 5.3.0
echo $user; // prints name
?>
You can read all about them in the documentation here:
Update: I took your saying "click" literally, which was a bit dumb of me. You can substitute focus
for click
in all of the below if you also want the action to happen when the user tabs to the input, which seems likely.
Update 2: My guess is that you're looking to do placeholders; see note and example at the end.
Original answer:
You can do this:
$("selector_for_the_input").click(function() {
this.value = '';
});
...but that will clear the text regardless of what it is. If you only want to clear it if it's a specific value:
$("selector_for_the_input").click(function() {
if (this.value === "TEXT") {
this.value = '';
}
});
So for example, if the input has an id
, you could do:
$("#theId").click(function() {
if (this.value === "TEXT") {
this.value = '';
}
});
Or if it's in a form with an id
(say, "myForm") and you want to do this for every form field:
$("#myForm input").click(function() {
if (this.value === "TEXT") {
this.value = '';
}
});
You may also be able to do it with delegation:
$("#myForm").delegate("input", "click", function() {
if (this.value === "TEXT") {
this.value = '';
}
});
That uses delegate
to hook up a handler on the form but apply it to the inputs on the form, rather than hooking up a handler to each individual input.
If you're trying to do placeholders, there's more to it than that and you may want to find a good plug-in to do it. But here's the basics:
HTML:
<form id='theForm'>
<label>Field 1:
<input type='text' value='provide a value for field 1'>
</label>
<br><label>Field 2:
<input type='text' value='provide a value for field 2'>
</label>
<br><label>Field 3:
<input type='text' value='provide a value for field 3'>
</label>
</form>
JavaScript using jQuery:
jQuery(function($) {
// Save the initial values of the inputs as placeholder text
$('#theForm input').attr("data-placeholdertext", function() {
return this.value;
});
// Hook up a handler to delete the placeholder text on focus,
// and put it back on blur
$('#theForm')
.delegate('input', 'focus', function() {
if (this.value === $(this).attr("data-placeholdertext")) {
this.value = '';
}
})
.delegate('input', 'blur', function() {
if (this.value.length == 0) {
this.value = $(this).attr("data-placeholdertext");
}
});
});
Of course, you can also use the new placeholder
attribute from HTML5 and only do the above if your code is running on a browser that doesn't support it, in which case you want to invert the logic I used above:
HTML:
<form id='theForm'>
<label>Field 1:
<input type='text' placeholder='provide a value for field 1'>
</label>
<br><label>Field 2:
<input type='text' placeholder='provide a value for field 2'>
</label>
<br><label>Field 3:
<input type='text' placeholder='provide a value for field 3'>
</label>
</form>
JavaScript with jQuery:
jQuery(function($) {
// Is placeholder supported?
if ('placeholder' in document.createElement('input')) {
// Yes, no need for us to do it
display("This browser supports automatic placeholders");
}
else {
// No, do it manually
display("Manual placeholders");
// Set the initial values of the inputs as placeholder text
$('#theForm input').val(function() {
if (this.value.length == 0) {
return $(this).attr('placeholder');
}
});
// Hook up a handler to delete the placeholder text on focus,
// and put it back on blur
$('#theForm')
.delegate('input', 'focus', function() {
if (this.value === $(this).attr("placeholder")) {
this.value = '';
}
})
.delegate('input', 'blur', function() {
if (this.value.length == 0) {
this.value = $(this).attr("placeholder");
}
});
}
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
(Kudos to diveintohtml5.ep.io for the placholder
feature-detection code.)
The trick is to add both max-height: 100%;
and max-width: 100%;
to .container img
. Example CSS:
.container {
width: 300px;
border: dashed blue 1px;
}
.container img {
max-height: 100%;
max-width: 100%;
}
In this way, you can vary the specified width of .container
in whatever way you want (200px or 10% for example), and the image will be no larger than its natural dimensions. (You could specify pixels instead of 100% if you didn't want to rely on the natural size of the image.)
Here's the whole fiddle: http://jsfiddle.net/KatieK/Su28P/1/
ssize_t
is not included in the standard and isn't portable. size_t
should be used when handling the size of objects (there's ptrdiff_t
too, for pointer differences).
Here's an explanation in layman's terms.
Let's assume you want to fill up a library with books and not just stuff them in there, but you want to be able to easily find them again when you need them.
So, you decide that if the person that wants to read a book knows the title of the book and the exact title to boot, then that's all it should take. With the title, the person, with the aid of the librarian, should be able to find the book easily and quickly.
So, how can you do that? Well, obviously you can keep some kind of list of where you put each book, but then you have the same problem as searching the library, you need to search the list. Granted, the list would be smaller and easier to search, but still you don't want to search sequentially from one end of the library (or list) to the other.
You want something that, with the title of the book, can give you the right spot at once, so all you have to do is just stroll over to the right shelf, and pick up the book.
But how can that be done? Well, with a bit of forethought when you fill up the library and a lot of work when you fill up the library.
Instead of just starting to fill up the library from one end to the other, you devise a clever little method. You take the title of the book, run it through a small computer program, which spits out a shelf number and a slot number on that shelf. This is where you place the book.
The beauty of this program is that later on, when a person comes back in to read the book, you feed the title through the program once more, and get back the same shelf number and slot number that you were originally given, and this is where the book is located.
The program, as others have already mentioned, is called a hash algorithm or hash computation and usually works by taking the data fed into it (the title of the book in this case) and calculates a number from it.
For simplicity, let's say that it just converts each letter and symbol into a number and sums them all up. In reality, it's a lot more complicated than that, but let's leave it at that for now.
The beauty of such an algorithm is that if you feed the same input into it again and again, it will keep spitting out the same number each time.
Ok, so that's basically how a hash table works.
Technical stuff follows.
First, there's the size of the number. Usually, the output of such a hash algorithm is inside a range of some large number, typically much larger than the space you have in your table. For instance, let's say that we have room for exactly one million books in the library. The output of the hash calculation could be in the range of 0 to one billion which is a lot higher.
So, what do we do? We use something called modulus calculation, which basically says that if you counted to the number you wanted (i.e. the one billion number) but wanted to stay inside a much smaller range, each time you hit the limit of that smaller range you started back at 0, but you have to keep track of how far in the big sequence you've come.
Say that the output of the hash algorithm is in the range of 0 to 20 and you get the value 17 from a particular title. If the size of the library is only 7 books, you count 1, 2, 3, 4, 5, 6, and when you get to 7, you start back at 0. Since we need to count 17 times, we have 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, and the final number is 3.
Of course modulus calculation isn't done like that, it's done with division and a remainder. The remainder of dividing 17 by 7 is 3 (7 goes 2 times into 17 at 14 and the difference between 17 and 14 is 3).
Thus, you put the book in slot number 3.
This leads to the next problem. Collisions. Since the algorithm has no way to space out the books so that they fill the library exactly (or the hash table if you will), it will invariably end up calculating a number that has been used before. In the library sense, when you get to the shelf and the slot number you wish to put a book in, there's already a book there.
Various collision handling methods exist, including running the data into yet another calculation to get another spot in the table (double hashing), or simply to find a space close to the one you were given (i.e. right next to the previous book assuming the slot was available also known as linear probing). This would mean that you have some digging to do when you try to find the book later, but it's still better than simply starting at one end of the library.
Finally, at some point, you might want to put more books into the library than the library allows. In other words, you need to build a bigger library. Since the exact spot in the library was calculated using the exact and current size of the library, it goes to follow that if you resize the library you might end up having to find new spots for all the books since the calculation done to find their spots has changed.
I hope this explanation was a bit more down to earth than buckets and functions :)
I know this is late, but this is how I normally do it,
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream stream = classLoader.getResourceAsStream("../test/foo.txt");
If you are using MySQL you can do it like this:
SELECT '2008-12-31 23:59:59' + INTERVAL 30 MINUTE;
For a pure PHP solution use strtotime
strtotime('+ 30 minute',$yourdate);
One of the main benefits of using streams is that it gives the ability to process data in a declarative way, that is, using a functional style of programming. It also gives multi-threading capability for free meaning there is no need to write any extra multi-threaded code to make your stream concurrent.
Assuming the reason you are exploring this style of programming is that you want to exploit these benefits then your first code sample is potentially not functional since the foreach
method is classed as being terminal (meaning that it can produce side-effects).
The second way is preferred from functional programming point of view since the map function can accept stateless lambda functions. More explicitly, the lambda passed to the map function should be
ArrayList
).Another benefit with the second approach is if the stream is parallel and the collector is concurrent and unordered then these characteristics can provide useful hints to the reduction operation to do the collecting concurrently.
If you trust the host, either add the valid certificate, specify --no-check-certificate
or add:
check_certificate = off
into your ~/.wgetrc
.
In some rare cases, your system time could be out-of-sync therefore invalidating the certificates.
Look into Doctrine.
Doctrine 1.2 implements Active Record. Doctrine 2+ is a DataMapper ORM.
Also, check out Xyster. It's based on the Data Mapper pattern.
Also, take a look at DataMapper vs. Active Record.
The solution below does only one groupBy and extract the rows of your dataframe that contain the maxValue in one shot. No need for further Joins, or Windows.
import org.apache.spark.sql.Row
import org.apache.spark.sql.catalyst.encoders.RowEncoder
import org.apache.spark.sql.DataFrame
//df is the dataframe with Day, Category, TotalValue
implicit val dfEnc = RowEncoder(df.schema)
val res: DataFrame = df.groupByKey{(r) => r.getInt(0)}.mapGroups[Row]{(day: Int, rows: Iterator[Row]) => i.maxBy{(r) => r.getDouble(2)}}
DROP TABLE deletes the table.
TRUNCATE TABLE empties it, but leaves its structure for future data.
If you didn't push the update in remote then the simple solution is remove last local commit using following command: git reset HEAD^
. Then add all files and commit again.
You should put all your words into some kind of Collection or List and then call it like this:
var searchFor = new List<string>();
searchFor.Add("pineapple");
searchFor.Add("mango");
bool containsAnySearchString = searchFor.Any(word => compareString.Contains(word));
If you need to make a case or culture independent search you should call it like this:
bool containsAnySearchString =
searchFor.Any(word => compareString.IndexOf
(word, StringComparison.InvariantCultureIgnoreCase >= 0);
UPDATE will not do anything if the row does not exist.
Where as the INSERT OR REPLACE would insert if the row does not exist, or replace the values if it does.
Remember to put not only the tag but also the repository in which that tag is, this way:
docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
elixir 1.7-centos7_3 e15e6bf57262 20 hours ago 925MB
You should reference it this way:
elixir:1.7-centos7_3
Updated @Hussein solution with preview height that will adapt to the paragraph number of lines.
So with this bit of code : - You can choose the number of lines you want to show in preview, it will works for all screen sizes, even if font-size is responsive. - There is no need to add classes or back-end editing to separate preview from whole content.
http://jsfiddle.net/7Vv8u/5816/
var h = $('div')[0].scrollHeight;
divLineHeight = parseInt($('div').css('line-height'));
divPaddingTop = parseInt($('div').css('padding-top'));
lineToShow = 2;
divPreviewHeight = divLineHeight*lineToShow - divPaddingTop;
$('div').css('height', divPreviewHeight );
$('#more').click(function(e) {
e.stopPropagation();
$('div').animate({
'height': h
})
});
$(document).click(function() {
$('div').animate({
'height': divPreviewHeight
})
})
$_ is an variable which iterates over each object/element passed from the previous | (pipe).
You can also use the computeIfAbsent()
method in the HashMap
class.
In the following example, map
stores a list of transactions (integers) that are applied to the key (the name of the bank account). To add 2 transactions of 100
and 200
to checking_account
you can write:
HashMap<String, ArrayList<Integer>> map = new HashMap<>();
map.computeIfAbsent("checking_account", key -> new ArrayList<>())
.add(100)
.add(200);
This way you don't have to check to see if the key checking_account
exists or not.
computeIfAbsent()
. Really elegant!
From the LESS website:
If you want to import a CSS file, and don’t want LESS to process it, just use the .css extension:
@import "lib.css"; The directive will just be left as is, and end up in the CSS output.
As jitbit points out in the comments below, this is really only useful for development purposes, as you wouldn't want to have unnecessary @import
s consuming precious bandwidth.
The best way would be to use the unslick
setting or function(depending on your version of slick) as stated in the other answers but that did not work for me. I'm getting some errors from slick that seem to be related to this.
What did work for now, however, is removing the slick-initialized
and slick-slider
classes from the container before reinitializing slick, like so:
function slickCarousel() {
$('.skills_section').removeClass("slick-initialized slick-slider");
$('.skills_section').slick({
infinite: true,
slidesToShow: 3,
slidesToScroll: 1
});
}
Removing the classes doesn't seem to initiate the destroy event(not tested but makes sense) but does cause the later slick()
call to behave properly so as long as you don't have any triggers on destroy, you should be good.
You can sort by multiple values simply by appending the values into a string and comparing the strings. It is helpful to add a split key character to prevent runoff from one key to the next.
const arr = [
{ a: 1, b: 'a', c: 3 },
{ a: 2, b: 'a', c: 5 },
{ a: 1, b: 'b', c: 4 },
{ a: 2, b: 'a', c: 4 }
]
function sortBy (arr, keys, splitKeyChar='~') {
return arr.sort((i1,i2) => {
const sortStr1 = keys.reduce((str, key) => str + splitKeyChar+i1[key], '')
const sortStr2 = keys.reduce((str, key) => str + splitKeyChar+i2[key], '')
return sortStr1.localeCompare(sortStr2)
})
}
console.log(sortBy(arr, ['a', 'b', 'c']))
_x000D_
You can also use Recursion to do this. It is a bit more complex than the String Appending Method but it allows you to do ASC and DESC on the key level. I'm commenting on each section as it is a bit more complex.
There are a few commented out tests to show and verify the sorting works with a mixture of order and default order.
const arr = [
{ a: 1, b: 'a', c: 3 },
{ a: 2, b: 'a', c: 5 },
{ a: 1, b: 'b', c: 4 },
{ a: 2, b: 'a', c: 4 }
]
function sortBy (arr, keys) {
return arr.sort(function sort (i1,i2, sKeys=keys) {
// Get order and key based on structure
const compareKey = (sKeys[0].key) ? sKeys[0].key : sKeys[0];
const order = sKeys[0].order || 'ASC'; // ASC || DESC
// Calculate compare value and modify based on order
let compareValue = i1[compareKey].toString().localeCompare(i2[compareKey].toString())
compareValue = (order.toUpperCase() === 'DESC') ? compareValue * -1 : compareValue
// See if the next key needs to be considered
const checkNextKey = compareValue === 0 && sKeys.length !== 1
// Return compare value
return (checkNextKey) ? sort(i1, i2, sKeys.slice(1)): compareValue;
})
}
// console.log(sortBy(arr, ['a', 'b', 'c']))
console.log(sortBy(arr, [{key:'a',order:'desc'}, 'b', 'c']))
// console.log(sortBy(arr, ['a', 'b', {key:'c',order:'desc'}]))
// console.log(sortBy(arr, ['a', {key:'b',order:'desc'}, 'c']))
// console.log(sortBy(arr, [{key:'a',order:'asc'}, {key:'b',order:'desc'}, {key:'c',order:'desc'}]))
From the documentation for strtotime()
:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
In your date string, you have 12-16-2013
. 16
isn't a valid month, and hence strtotime()
returns false
.
Since you can't use DateTime class, you could manually replace the -
with /
using str_replace()
to convert the date string into a format that strtotime()
understands:
$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16
When a module is loaded from a file in Python, __file__
is set to its path. You can then use that with other functions to find the directory that the file is located in.
Taking your examples one at a time:
A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.
B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.
C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.
You can see the various values returned from these here:
import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))
and make sure you run it from different locations (such as ./text.py
, ~/python/text.py
and so forth) to see what difference that makes.
I just want to address some confusion first. __file__
is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.
http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.
In this case __file__
is an attribute of a module (a module object). In Python a .py
file is a module. So import amodule
will have an attribute of __file__
which means different things under difference circumstances.
Taken from the docs:
__file__
is the pathname of the file from which the module was loaded, if it was loaded from a file. The__file__
attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.
In your case the module is accessing it's own __file__
attribute in the global namespace.
To see this in action try:
# file: test.py
print globals()
print __file__
And run:
python test.py
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py
I also had the same issue though am using MacOS. The issue is kind of bug. I solved this issue by repeatedly running the commands,
sudo npm cache clean --force
sudo npm uninstall
sudo npm install
One time it did not work but when I repeatedly cleaned the cache and after uninstalling npm, reinstalling npm, the error went off. I am using Angular 8 and this issue is common
This code helped me get this behaviour: With a list a,b,c, I should get compared ab, ac and bc, but any other pair would be excess / not needed.
import java.util.*;
import static java.lang.System.out;
// rl = rawList; lr = listReversed
ArrayList<String> rl = new ArrayList<String>();
ArrayList<String> lr = new ArrayList<String>();
rl.add("a");
rl.add("b");
rl.add("c");
rl.add("d");
rl.add("e");
rl.add("f");
lr.addAll(rl);
Collections.reverse(lr);
for (String itemA : rl) {
lr.remove(lr.size()-1);
for (String itemZ : lr) {
System.out.println(itemA + itemZ);
}
}
The loop goes as like in this picture: Triangular comparison visual example
or as this:
| f e d c b a
------------------------------
a | af ae ad ac ab ·
b | bf be bd bc ·
c | cf ce cd ·
d | df de ·
e | ef ·
f | ·
total comparisons is a triangular number (n * n-1)/2
If you don't have the source code and API documentation, the machine code is all there is, you need to disassemble the dll library using something like IDA Pro , another option is use the trial version of PE Explorer.
PE Explorer provides a Disassembler. There is only one way to figure out the parameters: run the disassembler and read the disassembly output. Unfortunately, this task of reverse engineering the interface cannot be automated.
PE Explorer comes bundled with descriptions for 39 various libraries, including the core Windows® operating system libraries (eg. KERNEL32, GDI32, USER32, SHELL32, WSOCK32), key graphics libraries (DDRAW, OPENGL32) and more.
(source: heaventools.com)
If you are using WebView in Android developing the problem is that you didn't add uses permission
<uses-permission android:name="android.permission.INTERNET" />
You can use Delorean to travel in space and time!
import datetime
import delorean
dt = datetime.datetime.utcnow()
delorean.Delorean(dt, timezone="UTC").epoch
There is a simple, easy and better approach, if we need to change only the color of hamburger/back icon.
It is better as it changes color only of desired icon, whereas colorControlNormal
and android:textColorSecondary
might affect other childviews of toolbar as well.
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>
<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
<item name="spinBars">true</item>
<item name="color">@android:color/white</item>
</style>
Depending on some details you might need to do something like this:
r=$(pwd)
case "$TARG" in
/*) p=$r;;
*) p="";;
esac
cd "$SRC" && cp -r . "$p/$TARG"
cd "$r"
... this basically changes to the SRC directory and copies it to the target, then returns back to whence ever you started.
The extra fussing is to handle relative or absolute targets.
(This doesn't rely on subtle semantics of the cp
command itself ... about how it handles source specifications with or without a trailing / ... since I'm not sure those are stable, portable, and reliable beyond just GNU cp
and I don't know if they'll continue to be so in the future).
It's top google stackoverflow question, but all answers are not jQuery related!
$(".someclass").click(
function(event)
{
console.log(event, this);
}
);
'event' contains 2 important values:
event.currentTarget - element to which event is triggered ('.someclass' element)
event.target - element clicked (in case when inside '.someclass' [div] are other elements and you clicked on of them)
this - is set to triggered element ('.someclass'), but it's JavaScript element, not jQuery element, so if you want to use some jQuery function on it, you must first change it to jQuery element: $(this)
When your refresh the page and reload the scripts again; this method not work. You have to use jquery "unbind" method.
If you're a heavy visual studio user, you can simply open your preference settings and add the following to your settings.json:
...
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
....
Hopefully this can be helpful!
The answer is a simple PowerShell
one-liner:
Get-WmiObject Win32_NetworkConnection | ft "RemoteName","LocalName" -A
If you only want to pull the UNC
for one particular drive, add a where statement:
Get-WmiObject Win32_NetworkConnection | where -Property 'LocalName' -eq 'Z:' | ft "RemoteName","LocalName" -A
According to the specification, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf:
A string is a sequence of Unicode code points wrapped with quotation marks (
U+0022
). All characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark (U+0022
), reverse solidus (U+005C
), and the control charactersU+0000
toU+001F
. There are two-character escape sequence representations of some characters.
So you can't pass 0x0A
or 0x0C
codes directly. It is forbidden! The specification suggests to use escape sequences for some well-defined codes from U+0000
to U+001F
:
\f
represents the form feed character (U+000C
).\n
represents the line feed character (U+000A
).As most of programming languages uses \
for quoting, you should escape the escape syntax (double-escape - once for language/platform, once for JSON itself):
jsonStr = "{ \"name\": \"Multi\\nline.\" }";
Here is an example of how to use ProcessBuilder
to execute your remote application. Since you do not care about input/output and/or errors, you can do as follows:
List<String> args = new ArrayList<String>();
args.add ("script.bat"); // command name
args.add ("-option"); // optional args added as separate list items
ProcessBuilder pb = new ProcessBuilder (args);
Process p = pb.start();
p.waitFor();
the waitFor()
method will wait until the process had ended before continuing. This method returns the error code of the process but, since you don't care about it, I didn't put it in the example.
Use seaborn instead i am using distplot of seaborn with mean=5 std=3 of 1000 values
value = np.random.normal(loc=5,scale=3,size=1000)
sns.distplot(value)
You will get a normal distribution curve
Just use an <a>
by itself, set it to display: block;
and set width
and height
. Get rid of the <span>
and <div>
. This is the semantic way to do it. There is no need to wrap things in <divs>
(or any element) for layout. That is what CSS is for.
Demo: http://jsfiddle.net/ThinkingStiff/89Enq/
HTML:
<a id="music" href="Music.html">Music I Like</a>
CSS:
#music {
background-color: black;
color: white;
display: block;
height: 40px;
line-height: 40px;
text-decoration: none;
width: 100px;
text-align: center;
}
Output:
This solution provides a strict FixedLengthArray (ak.a. SealedArray) type signature based in Tuples.
Syntax example :
// Array containing 3 strings
let foo : FixedLengthArray<[string, string, string]>
This is the safest approach, considering it prevents accessing indexes out of the boundaries.
Implementation :
type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift' | number
type ArrayItems<T extends Array<any>> = T extends Array<infer TItems> ? TItems : never
type FixedLengthArray<T extends any[]> =
Pick<T, Exclude<keyof T, ArrayLengthMutationKeys>>
& { [Symbol.iterator]: () => IterableIterator< ArrayItems<T> > }
Tests :
var myFixedLengthArray: FixedLengthArray< [string, string, string]>
// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ] // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ] // ? TYPE ERROR
myFixedLengthArray = [ 'a' ] // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ] // ? LENGTH ERROR
// Index assignment tests
myFixedLengthArray[1] = 'foo' // ? OK
myFixedLengthArray[1000] = 'foo' // ? INVALID INDEX ERROR
// Methods that mutate array length
myFixedLengthArray.push('foo') // ? MISSING METHOD ERROR
myFixedLengthArray.pop() // ? MISSING METHOD ERROR
// Direct length manipulation
myFixedLengthArray.length = 123 // ? READ-ONLY ERROR
// Destructuring
var [ a ] = myFixedLengthArray // ? OK
var [ a, b ] = myFixedLengthArray // ? OK
var [ a, b, c ] = myFixedLengthArray // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? INVALID INDEX ERROR
(*) This solution requires the noImplicitAny
typescript configuration directive to be enabled in order to work (commonly recommended practice)
This solution behaves as an augmentation of the Array
type, accepting an additional second parameter(Array length). Is not as strict and safe as the Tuple based solution.
Syntax example :
let foo: FixedLengthArray<string, 3>
Keep in mind that this approach will not prevent you from accessing an index out of the declared boundaries and set a value on it.
Implementation :
type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift'
type FixedLengthArray<T, L extends number, TObj = [T, ...Array<T>]> =
Pick<TObj, Exclude<keyof TObj, ArrayLengthMutationKeys>>
& {
readonly length: L
[ I : number ] : T
[Symbol.iterator]: () => IterableIterator<T>
}
Tests :
var myFixedLengthArray: FixedLengthArray<string,3>
// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ] // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ] // ? TYPE ERROR
myFixedLengthArray = [ 'a' ] // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ] // ? LENGTH ERROR
// Index assignment tests
myFixedLengthArray[1] = 'foo' // ? OK
myFixedLengthArray[1000] = 'foo' // ? SHOULD FAIL
// Methods that mutate array length
myFixedLengthArray.push('foo') // ? MISSING METHOD ERROR
myFixedLengthArray.pop() // ? MISSING METHOD ERROR
// Direct length manipulation
myFixedLengthArray.length = 123 // ? READ-ONLY ERROR
// Destructuring
var [ a ] = myFixedLengthArray // ? OK
var [ a, b ] = myFixedLengthArray // ? OK
var [ a, b, c ] = myFixedLengthArray // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? SHOULD FAIL
I wrote following function to return a default representation 0 or false of a primitive or Number:
/**
* Retrieves the default value 0 / false for any primitive representative or
* {@link Number} type.
*
* @param type
*
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getDefault(final Class<T> type)
{
if (type.equals(Long.class) || type.equals(Long.TYPE))
return (T) new Long(0);
else if (type.equals(Integer.class) || type.equals(Integer.TYPE))
return (T) new Integer(0);
else if (type.equals(Double.class) || type.equals(Double.TYPE))
return (T) new Double(0);
else if (type.equals(Float.class) || type.equals(Float.TYPE))
return (T) new Float(0);
else if (type.equals(Short.class) || type.equals(Short.TYPE))
return (T) new Short((short) 0);
else if (type.equals(Byte.class) || type.equals(Byte.TYPE))
return (T) new Byte((byte) 0);
else if (type.equals(Character.class) || type.equals(Character.TYPE))
return (T) new Character((char) 0);
else if (type.equals(Boolean.class) || type.equals(Boolean.TYPE))
return (T) new Boolean(false);
else if (type.equals(BigDecimal.class))
return (T) BigDecimal.ZERO;
else if (type.equals(BigInteger.class))
return (T) BigInteger.ZERO;
else if (type.equals(AtomicInteger.class))
return (T) new AtomicInteger();
else if (type.equals(AtomicLong.class))
return (T) new AtomicLong();
else if (type.equals(DoubleAdder.class))
return (T) new DoubleAdder();
else
return null;
}
I use it in hibernate ORM projection queries when the underlying SQL query returns null instead of 0.
/**
* Retrieves the unique result or zero, <code>false</code> if it is
* <code>null</code> and represents a number
*
* @param criteria
*
* @return zero if result is <code>null</code>
*/
public static <T> T getUniqueResultDefault(final Class<T> type, final Criteria criteria)
{
final T result = (T) criteria.uniqueResult();
if (result != null)
return result;
else
return Utils.getDefault(type);
}
One of the many unnecessary complex things about Java making it unintuitive to use. Why instance variables are initialized with default 0 but local are not is not logical. Similar why enums dont have built in flag support and many more options. Java lambda is a nightmare compared to C# and not allowing class extension methods is also a big problem.
Java ecosystem comes up with excuses why its not possible but me as the user / developer i dont care about their excuses. I want easy approach and if they dont fix those things they will loose big in the future since C# and other languages are not waiting to make life of developers more simple. Its just sad to see the decline in the last 10 years since i work daily with Java.
Simple way to handle this is to include this in your application.properties or .yml file:
server.port=0
for application.properties and server.port: 0
for application.yml files. Of course need to be aware these may change depending on the springboot version you are using.
These will allow your machine to dynamically allocate any free port available for use.
To statically assign a port change the above to server.port = someportnumber
. If running unix based OS you may want to check for zombie activities on the port in question and if possible kill it using fuser -k {theport}/tcp
.
Your .yml or .properties should look like this.
server:
port: 8089
servlet:
context-path: /somecontextpath
you can use "Automatically generate script on every save", if you are using management studio. This is not certainly logging. Check if useful for you.. ;)
You would usually do something like this:
while ( resultSet.next() ) {
// Read the next item
resultSet.getString("columnName");
}
If you want to report an empty set, add a variable counting the items read. If you only need to read a single item, then your code is adequate.
The trick is pretty simple... The request cycle is still pretty much alive. You can just add a new variable that will create a temporary, calling
app.get('some/url/endpoint', middleware1, middleware2);
Since you can handle your request in the first middleware
(req, res, next) => {
var yourvalue = anyvalue
}
In middleware 1 you handle your logic and store your value like below:
req.anyvariable = yourvalue
In middleware 2 you can catch this value from middleware 1 doing the following:
(req, res, next) => {
var storedvalue = req.yourvalue
}
Here is the raw way to do it
$startTimeStamp = strtotime("2011/07/01");
$endTimeStamp = strtotime("2011/07/17");
$timeDiff = abs($endTimeStamp - $startTimeStamp);
$numberDays = $timeDiff/86400; // 86400 seconds in one day
// and you might want to convert to integer
$numberDays = intval($numberDays);
You can use tree to generate something very similar to your example. Once you have the output, you can wrap it in a <pre>
tag to preserve the plain text formatting.
I use this, it works with php...
<span><?php
if (file_exists("image/".$data['img_name'])) {
?>
<img src="image/<?php echo $data['img_name']; ?>" width="100" height="100">
<?php
}else{
echo "Image Not Found";
}>?
</span>
Essentially what the code is doing, is checking for the File. The $data
variable will be used with our array then actually make the desired change. If it isn't found, it will throw an Exception.
Here in 2017, Promises are built into JavaScript, they were added by the ES2015 spec (polyfills are available for outdated environments like IE8-IE11). The syntax they went with uses a callback you pass into the Promise
constructor (the Promise
executor) which receives the functions for resolving/rejecting the promise as arguments.
First, since async
now has a meaning in JavaScript (even though it's only a keyword in certain contexts), I'm going to use later
as the name of the function to avoid confusion.
Using native promises (or a faithful polyfill) it would look like this:
function later(delay) {
return new Promise(function(resolve) {
setTimeout(resolve, delay);
});
}
Note that that assumes a version of setTimeout
that's compliant with the definition for browsers where setTimeout
doesn't pass any arguments to the callback unless you give them after the interval (this may not be true in non-browser environments, and didn't used to be true on Firefox, but is now; it's true on Chrome and even back on IE8).
If you want your function to optionally pass a resolution value, on any vaguely-modern browser that allows you to give extra arguments to setTimeout
after the delay and then passes those to the callback when called, you can do this (current Firefox and Chrome; IE11+, presumably Edge; not IE8 or IE9, no idea about IE10):
function later(delay, value) {
return new Promise(function(resolve) {
setTimeout(resolve, delay, value); // Note the order, `delay` before `value`
/* Or for outdated browsers that don't support doing that:
setTimeout(function() {
resolve(value);
}, delay);
Or alternately:
setTimeout(resolve.bind(null, value), delay);
*/
});
}
If you're using ES2015+ arrow functions, that can be more concise:
function later(delay, value) {
return new Promise(resolve => setTimeout(resolve, delay, value));
}
or even
const later = (delay, value) =>
new Promise(resolve => setTimeout(resolve, delay, value));
If you want to make it possible to cancel the timeout, you can't just return a promise from later
, because promises can't be cancelled.
But we can easily return an object with a cancel
method and an accessor for the promise, and reject the promise on cancel:
const later = (delay, value) => {
let timer = 0;
let reject = null;
const promise = new Promise((resolve, _reject) => {
reject = _reject;
timer = setTimeout(resolve, delay, value);
});
return {
get promise() { return promise; },
cancel() {
if (timer) {
clearTimeout(timer);
timer = 0;
reject();
reject = null;
}
}
};
};
Live Example:
const later = (delay, value) => {_x000D_
let timer = 0;_x000D_
let reject = null;_x000D_
const promise = new Promise((resolve, _reject) => {_x000D_
reject = _reject;_x000D_
timer = setTimeout(resolve, delay, value);_x000D_
});_x000D_
return {_x000D_
get promise() { return promise; },_x000D_
cancel() {_x000D_
if (timer) {_x000D_
clearTimeout(timer);_x000D_
timer = 0;_x000D_
reject();_x000D_
reject = null;_x000D_
}_x000D_
}_x000D_
};_x000D_
};_x000D_
_x000D_
const l1 = later(100, "l1");_x000D_
l1.promise_x000D_
.then(msg => { console.log(msg); })_x000D_
.catch(() => { console.log("l1 cancelled"); });_x000D_
_x000D_
const l2 = later(200, "l2");_x000D_
l2.promise_x000D_
.then(msg => { console.log(msg); })_x000D_
.catch(() => { console.log("l2 cancelled"); });_x000D_
setTimeout(() => {_x000D_
l2.cancel();_x000D_
}, 150);
_x000D_
Usually you'll have a promise library (one you write yourself, or one of the several out there). That library will usually have an object that you can create and later "resolve," and that object will have a "promise" you can get from it.
Then later
would tend to look something like this:
function later() {
var p = new PromiseThingy();
setTimeout(function() {
p.resolve();
}, 2000);
return p.promise(); // Note we're not returning `p` directly
}
In a comment on the question, I asked:
Are you trying to create your own promise library?
and you said
I wasn't but I guess now that's actually what I was trying to understand. That how a library would do it
To aid that understanding, here's a very very basic example, which isn't remotely Promises-A compliant: Live Copy
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Very basic promises</title>
</head>
<body>
<script>
(function() {
// ==== Very basic promise implementation, not remotely Promises-A compliant, just a very basic example
var PromiseThingy = (function() {
// Internal - trigger a callback
function triggerCallback(callback, promise) {
try {
callback(promise.resolvedValue);
}
catch (e) {
}
}
// The internal promise constructor, we don't share this
function Promise() {
this.callbacks = [];
}
// Register a 'then' callback
Promise.prototype.then = function(callback) {
var thispromise = this;
if (!this.resolved) {
// Not resolved yet, remember the callback
this.callbacks.push(callback);
}
else {
// Resolved; trigger callback right away, but always async
setTimeout(function() {
triggerCallback(callback, thispromise);
}, 0);
}
return this;
};
// Our public constructor for PromiseThingys
function PromiseThingy() {
this.p = new Promise();
}
// Resolve our underlying promise
PromiseThingy.prototype.resolve = function(value) {
var n;
if (!this.p.resolved) {
this.p.resolved = true;
this.p.resolvedValue = value;
for (n = 0; n < this.p.callbacks.length; ++n) {
triggerCallback(this.p.callbacks[n], this.p);
}
}
};
// Get our underlying promise
PromiseThingy.prototype.promise = function() {
return this.p;
};
// Export public
return PromiseThingy;
})();
// ==== Using it
function later() {
var p = new PromiseThingy();
setTimeout(function() {
p.resolve();
}, 2000);
return p.promise(); // Note we're not returning `p` directly
}
display("Start " + Date.now());
later().then(function() {
display("Done1 " + Date.now());
}).then(function() {
display("Done2 " + Date.now());
});
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
</script>
</body>
</html>
With Git 2.23 (August 2019), that would be, using git switch -f
:
git switch -f master
That avoids the confusion with git checkout
(which deals with files or branches).
And that will proceeds, even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.
If --recurse-submodules
is specified, submodule content is also restored to match the switching target.
This is used to throw away local changes.
Ok. As the other answerers explained, a stack is a last-in, first-out data structure. You add an element to the top of the stack with a Push operation. You take an element off the top with a Pop operation. The elements are removed in reverse order to the order they were put inserted (hence Last In, First Out). For example, if you push the elments 1,2,3 in that order, the number 3 will be at the top of the stack. A Pop operation will remove it (it was the last in) and leave 2 at the top of the stack.
Regarding the rest of the lecture, the lecturer tried to describe a stack-based machine that evaluates arithmetic expressions. The machine operates by continuously popping 3 elements from the top of the stack. The first two elements are operands and the third is an operator (+, -, *, /). It then applies this operator on the operands, and pushes the result onto the stack. The process continues until there is only one element on the stack, which is the value of the expression.
So, suppose we begin by pushing the values "+/*23-21*5-41" in left-to-right order onto the stack. We then pop 3 elements from the top. The last in is first out, which means the first 3 element are "1", "4", and "-" in that order. We push the number 3 (the result of 4-1) onto the stack, then pop the three topmost elements: 3, 5, *. Push the result, 15, onto the stack, and so on.
You can do it more simply, guaranteeing that your .gitconfig
is left in a meaningful state:
git push -u hub master
when pushing, or:
git branch -u hub/master
(This will set the remote for the currently checked-out branch to hub/master
)
git branch --set-upstream-to hub/master
(This will set the remote for the branch named branch_name
to hub/master
)
git branch branch_name --set-upstream-to hub/master
v1.7.x
or earlieryou must use --set-upstream
:
git branch --set-upstream master hub/master
If you would like to duplicate a line and paste it right away below the current like, just like in Sublime Ctrl+Shift+D, then you can add this to your .vimrc
file.
nmap <S-C-d> <Esc>Yp
Or, for Insert mode:
imap <S-C-d> <Esc>Ypa