Default value for parameters are evaluated at "compilation", once. So obviously you can't access self
. The classic example is list
as default parameter. If you add elements into it, the default value for the parameter changes!
The workaround is to use another default parameter, typically None
, and then check and update the variable.
A file can be tracked or not, you use hg add to track a file and hg remove or hg forget to un-track it. Using hg remove without flags will both delete the file and un-track it, hg forget will simply un-track it without deleting it.
Applying the full_extent()
function in an answer by @Joe 3 years later from here, you can get exactly what the OP was looking for. Alternatively, you can use Axes.get_tightbbox()
which gives a little tighter bounding box
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from matplotlib.transforms import Bbox
def full_extent(ax, pad=0.0):
"""Get the full extent of an axes, including axes labels, tick labels, and
titles."""
# For text objects, we need to draw the figure first, otherwise the extents
# are undefined.
ax.figure.canvas.draw()
items = ax.get_xticklabels() + ax.get_yticklabels()
# items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label]
items += [ax, ax.title]
bbox = Bbox.union([item.get_window_extent() for item in items])
return bbox.expanded(1.0 + pad, 1.0 + pad)
# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')
ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')
# Save the full figure...
fig.savefig('full_figure.png')
# Save just the portion _inside_ the second axis's boundaries
extent = full_extent(ax2).transformed(fig.dpi_scale_trans.inverted())
# Alternatively,
# extent = ax.get_tightbbox(fig.canvas.renderer).transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)
I'd post a pic but I lack the reputation points
There are many ways to perform your task, but the most elegant are, I believe, using css. Here are basic steps
This works pretty well if there a few divs, since more elements you want to toggle, more css rules should be written. Here is more general solution, binding action, base on following steps: 1. find all elements using some selector (usually it looks like '.menu-container .menu-item') 2. find one of found elements, which is current visible, hide it 3. make visible another element, the one you desire to be visible under new circumstances.
javascript it a rather timtoady language )
An artifact is a file, usually a JAR, that gets deployed to a Maven repository.
A Maven build produces one or more artifacts, such as a compiled JAR and a "sources" JAR.
Each artifact has a group ID (usually a reversed domain name, like com.example.foo), an artifact ID (just a name), and a version string. The three together uniquely identify the artifact.
A project's dependencies are specified as artifacts.
This is "By Design". The parseFloat
function will only consider the parts of the string up until in reaches a non +, -, number, exponent or decimal point. Once it sees the comma it stops looking and only considers the "75" portion.
To fix this convert the commas to decimal points.
var fullcost = parseFloat($("#fullcost").text().replace(',', '.'));
In T-Sql there are two ways:
--filter out the max
select max( col )
from [table]
where col < (
select max( col )
from [table] )
--sort top two then bottom one
select top 1 col
from (
select top 2 col
from [table]
order by col) topTwo
order by col desc
In Microsoft SQL the first way is twice as fast as the second, even if the column in question is clustered.
This is because the sort operation is relatively slow compared to the table or index scan that the max
aggregation uses.
Alternatively, in Microsoft SQL 2005 and above you can use the ROW_NUMBER()
function:
select col
from (
select ROW_NUMBER() over (order by col asc) as 'rowNum', col
from [table] ) withRowNum
where rowNum = 2
Well I think the best way would be (will be?) to define 2 recordsets and use them as an intermediate between the 2 tables.
This method is particularly interesting if you plan to update tables from different databases (ie each recordset can have its own connection ...)
Try something like:
$post_data="dispnumber=567567567&extension=6";
$url="http://xxxxxxxx.xxx/xx/xx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result;
With the constructor:
// create a vector with 20 integer elements
std::vector<int> arr(20);
for(int x = 0; x < 20; ++x)
arr[x] = x;
Unit testing involves breaking your program into pieces, and subjecting each piece to a series of tests.
Usually tests are run as separate programs, but the method of testing varies, depending on the language, and type of software (GUI, command-line, library).
Most languages have unit testing frameworks, you should look into one for yours.
Tests are usually run periodically, often after every change to the source code. The more often the better, because the sooner you will catch problems.
save as png solved the problem for me.
Every time you used the mysql console, the version is shown.
mysql -u user
Successful console login shows the following which includes the mysql server version.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1432
Server version: 5.5.9-log Source distribution
Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
You can also check the mysql server version directly by executing the following command:
mysql --version
You may also check the version information from the mysql console itself using the version variables:
mysql> SHOW VARIABLES LIKE "%version%";
Output will be something like this:
+-------------------------+---------------------+
| Variable_name | Value |
+-------------------------+---------------------+
| innodb_version | 1.1.5 |
| protocol_version | 10 |
| slave_type_conversions | |
| version | 5.5.9-log |
| version_comment | Source distribution |
| version_compile_machine | i386 |
| version_compile_os | osx10.4 |
+-------------------------+---------------------+
7 rows in set (0.01 sec)
You may also use this:
mysql> select @@version;
The STATUS command display version information as well.
mysql> STATUS
You can also check the version by executing this command:
mysql -v
It's worth mentioning that if you have encountered something like this:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket
'/tmp/mysql.sock' (2)
you can fix it by:
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp/mysql.sock
Changing the casing to all lowercases worked for me.
The best and the safest way to show a 'ProgressDialog' in an AsyncTask, avoiding memory leak problem is to use a 'Handler' with Looper.main().
private ProgressDialog tProgressDialog;
then in the 'onCreate'
tProgressDialog = new ProgressDialog(this);
tProgressDialog.setMessage(getString(R.string.loading));
tProgressDialog.setIndeterminate(true);
Now you r done with the setup part. Now call 'showProgress()' and 'hideProgress()' in AsyncTask.
private void showProgress(){
new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
tProgressDialog.show();
}
}.sendEmptyMessage(1);
}
private void hideProgress(){
new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
tProgressDialog.dismiss();
}
}.sendEmptyMessage(1);
}
I have modified the top liked code to indent in a jupyter notebook python 3 correctly
import numpy as np
from sklearn.tree import _tree
def tree_to_code(tree, feature_names):
tree_ = tree.tree_
feature_name = [feature_names[i]
if i != _tree.TREE_UNDEFINED else "undefined!"
for i in tree_.feature]
print("def tree({}):".format(", ".join(feature_names)))
def recurse(node, depth):
indent = " " * depth
if tree_.feature[node] != _tree.TREE_UNDEFINED:
name = feature_name[node]
threshold = tree_.threshold[node]
print("{}if {} <= {}:".format(indent, name, threshold))
recurse(tree_.children_left[node], depth + 1)
print("{}else: # if {} > {}".format(indent, name, threshold))
recurse(tree_.children_right[node], depth + 1)
else:
print("{}return {}".format(indent, np.argmax(tree_.value[node])))
recurse(0, 1)
Since the verification is based on package's name, you can change the package name inside your config.xml or manifest file for another name you want.
When publishing your app don't forget to change back the name!
easiest way ta make java leap year and more clear to understandenter code here
import java.util.Scanner;
class que19{
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
double a;
System.out.println("enter the year here ");
a=input.nextDouble();
if ((a % 4 ==0 ) && (a%100!=0) || (a%400==0)) {
System.out.println("leep year");
}
else {
System.out.println("not a leap year");
}
}
}
I figured the issue. Its because Charles 3.7 has some bugs for Android devices. I updated to Charles 3.8 Beta version and seems to working fine for me.
Updated Answer for Changed Documentation
The information is now spread across several guides in the documentation. Here's a list of required reading:
The answer to this question now depends entirely on whether you're using an ARC-managed application (the modern default for new projects) or forcing manual memory management.
Assign vs. Weak - Use assign to set a property's pointer to the address of the object without retaining it or otherwise curating it; use weak to have the property point to nil automatically if the object assigned to it is deallocated. In most cases you'll want to use weak so you're not trying to access a deallocated object (illegal access of a memory address - "EXC_BAD_ACCESS
") if you don't perform proper cleanup.
Retain vs. Copy - Declared properties use retain by default (so you can simply omit it altogether) and will manage the object's reference count automatically whether another object is assigned to the property or it's set to nil; Use copy to automatically send the newly-assigned object a -copy
message (which will create a copy of the passed object and assign that copy to the property instead - useful (even required) in some situations where the assigned object might be modified after being set as a property of some other object (which would mean that modification/mutation would apply to the property as well).
Firefox is more stringent than other browsers and will require proper installation of an intermediate server certificate. This can be supplied by the cert authority the certificate was purchased from. the intermediate cert is typically installed in the same location as the server cert and requires the proper entry in the httpd.conf file.
while many are chastising Firefox for it's (generally) exclusive 'flagging' of this, it's actually demonstrating a higher level of security standards.
Ahah! Checkout the previous commit, then checkout the master.
git checkout HEAD^
git checkout -f master
Use this,
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "email"){
rx = /[ '"]/gi;
}else if(elem == "search" || elem == "comment"){
rx = /[^a-z 0-9.,?]/gi;
}else{
rx = /[^a-z0-9]/gi;
}
tf.value = tf.value.replace(rx , "" );
}
On the backend, for java , Try using StringUtils class or a custom script.
public static String HTMLEncode(String aTagFragment) {
final StringBuffer result = new StringBuffer();
final StringCharacterIterator iterator = new
StringCharacterIterator(aTagFragment);
char character = iterator.current();
while (character != StringCharacterIterator.DONE )
{
if (character == '<')
result.append("<");
else if (character == '>')
result.append(">");
else if (character == '\"')
result.append(""");
else if (character == '\'')
result.append("'");
else if (character == '\\')
result.append("\");
else if (character == '&')
result.append("&");
else {
//the char is not a special one
//add it to the result as is
result.append(character);
}
character = iterator.next();
}
return result.toString();
}
the pattern maybe looks like this :
substr(STRING, ( length(STRING) - (TOTAL_GET_LENGTH - 1) ),TOTAL_GET_LENGTH)
in your case , it will like this :
substr('299123456789', (length('299123456789')-(9 - 1)),9)
substr('299123456789', (12-8),9)
substr('299123456789', 4,9)
the result ? of course '123456789'
the length is dynamic , voila :)
Python is a lot about clarity and no programmer is likely to correctly guess the meaning of --a
unless s/he's learned a language having that construct.
Python is also a lot about avoiding constructs that invite mistakes and the ++
operators are known to be rich sources of defects.
These two reasons are enough not to have those operators in Python.
The decision that Python uses indentation to mark blocks rather than syntactical means such as some form of begin/end bracketing or mandatory end marking is based largely on the same considerations.
For illustration, have a look at the discussion around introducing a conditional operator (in C: cond ? resultif : resultelse
) into Python in 2005.
Read at least the first message and the decision message of that discussion (which had several precursors on the same topic previously).
Trivia: The PEP frequently mentioned therein is the "Python Extension Proposal" PEP 308. LC means list comprehension, GE means generator expression (and don't worry if those confuse you, they are none of the few complicated spots of Python).
I had this problem with a fresh install of wamp and using only default settings without setting any passwords. I found an incorrect default setting and I solved it by the following steps:
The problem seems to be that someone forgot to make the server and host match in the configuration files.
A well-explained answer is already given by @mkobit, but I will add a big picture of the range key and hash key.
In a simple words range + hash key = composite primary key
CoreComponents of Dynamodb
A primary key is consists of a hash key and an optional range key. Hash key is used to select the DynamoDB partition. Partitions are parts of the table data. Range keys are used to sort the items in the partition, if they exist.
So both have a different purpose and together help to do complex query.
In the above example hashkey1 can have multiple n-range.
Another example of range and hashkey is game, userA(hashkey)
can play Ngame(range)
The Music table described in Tables, Items, and Attributes is an example of a table with a composite primary key (Artist and SongTitle). You can access any item in the Music table directly, if you provide the Artist and SongTitle values for that item.
A composite primary key gives you additional flexibility when querying data. For example, if you provide only the value for Artist, DynamoDB retrieves all of the songs by that artist. To retrieve only a subset of songs by a particular artist, you can provide a value for Artist along with a range of values for SongTitle.
https://www.slideshare.net/InfoQ/amazon-dynamodb-design-patterns-best-practices https://www.slideshare.net/AmazonWebServices/awsome-day-2016-module-4-databases-amazon-dynamodb-and-amazon-rds https://ceyhunozgun.blogspot.com/2017/04/implementing-object-persistence-with-dynamodb.html
Since you didn't mention the version of Eclipse, I advice you to download the latest version of Eclipse Luna
which comes with Java 8 support by default.
Consider the case statement as well which is compatible with most sh-based shells:
case $str in
/*)
echo 1
;;
*)
echo 0
;;
esac
I got the same error and it turned out I was in the wrong directory. It's a simple mistake to make so double check that you are in the root and then run heroku create
and heroku git push master
again. Of course you must have done git init
, as mentioned in StickMaNX answer above, already before the heroku steps.
Its Got simpler with Android Studio All you need is to first choose
3.based on the type of project and library you used like (ActionBarSherlock) you may prompted special import wizard so go ahead and click next then finish. in this case it was simple one
but sometimes the debug or Run options do not work and a error msg shows like
"this project structure is not gradle based or migrate it to gradle"
something to solve this close the opened eclipse project and reopen same project through the same process as we did before with import project (eclipse adt,gradle,etc)) this time android studio gonna add all necessary gradle files and green debug option will work too. i have did this somehow accidentally but it worked, i just hope it works for you too.
You can't use an aggregate directly in a WHERE clause; that's what HAVING clauses are for.
You can use a sub-query which contains an aggregate in the WHERE clause.
My 5 cents (because it appears more straightforward/simpler and sufficient for short lists):
public static T Median<T>(this IEnumerable<T> items)
{
var i = (int)Math.Ceiling((double)(items.Count() - 1) / 2);
if (i >= 0)
{
var values = items.ToList();
values.Sort();
return values[i];
}
return default(T);
}
P.S. using "higher median" as described by ShitalShah.
try this one
<asp:DropDownList ID="ddList" runat="server">
<asp:ListItem Value="">--Select Month--</asp:ListItem>
<asp:ListItem Value="1">January</asp:ListItem>
<asp:ListItem Value="2">Feburary</asp:ListItem>
...
<asp:ListItem Value="12">December</asp:ListItem>
</asp:DropDownList>
Value should be empty for the default selected listitem, then it works fine
You simply need to create an instance of ReportHandler:
ReportHandler rh = new ReportHandler(/* constructor args here */);
rh.executeBatchInsert(); // Having fixed name to follow conventions
The important point of instance methods is that they're meant to be specific to a particular instance of the class... so you'll need to create an instance first. That way the instance will have access to the right connection and prepared statement in your case. Just calling ReportHandler.executeBatchInsert
, there isn't enough context.
It's really important that you understand that:
Once you understand that fundamental difference, it makes sense that you can't call an instance method without creating an instance... For example, it makes sense to ask, "What is the height of that person?" (for a specific person) but it doesn't make sense to ask, "What is the height of Person?" (without specifying a person).
Assuming you're leaning Java from a book or tutorial, you should read up on more examples of static and non-static methods etc - it's a vital distinction to understand, and you'll have all kinds of problems until you've understood it.
Try this :
Proc sql;
select employee, salary
from (select * from test having salary < max(salary))
having salary = max(salary)
;
Quit;
To settext in any of in activity than use this below code... Follow these step one by one:
1.Declare
private TextView event_post;
2.Bind this
event_post = (TextView) findViewById(R.id.text_post);
3.SetText in
event_post.setText(event_post_count);
I have the same problem. I avoid it with remove.packages("Package making this confusion")
and it works. In my case, I don't need the second package, so that is not a very good idea.
This reply may be late but it may help users having similar problem. The opencv-contrib (available at https://github.com/opencv/opencv_contrib/releases) contains extra modules but the build procedure has to be done from core opencv (available at from https://github.com/opencv/opencv/releases) modules.
Follow below steps (assuming you are building it using CMake GUI)
Download openCV (from https://github.com/opencv/opencv/releases) and unzip it somewhere on your computer. Create build folder inside it
Download exra modules from OpenCV. (from https://github.com/opencv/opencv_contrib/releases). Ensure you download the same version.
Unzip the folder.
Open CMake
Click Browse Source and navigate to your openCV folder.
Click Browse Build and navigate to your build Folder.
Click the configure button. You will be asked how you would like to generate the files. Choose Unix-Makefile from the drop down menu and Click OK. CMake will perform some tests and return a set of red boxes appear in the CMake Window.
Search for "OPENCV_EXTRA_MODULES_PATH" and provide the path to modules folder (e.g. /Users/purushottam_d/Programs/OpenCV3_4_5_contrib/modules)
Click Configure again, then Click Generate.
Go to build folder
# cd build
# make
# sudo make install
I would use the following function. I don't like sprintf
; it doesn't do what I want!!
#define hexchar(x) ((((x)&0x0F)>9)?((x)+'A'-10):((x)+'0'))
typedef signed long long Int64;
// Special printf for numbers only
// See formatting information below.
//
// Print the number "n" in the given "base"
// using exactly "numDigits".
// Print +/- if signed flag "isSigned" is TRUE.
// Use the character specified in "padchar" to pad extra characters.
//
// Examples:
// sprintfNum(pszBuffer, 6, 10, 6, TRUE, ' ', 1234); --> " +1234"
// sprintfNum(pszBuffer, 6, 10, 6, FALSE, '0', 1234); --> "001234"
// sprintfNum(pszBuffer, 6, 16, 6, FALSE, '.', 0x5AA5); --> "..5AA5"
void sprintfNum(char *pszBuffer, int size, char base, char numDigits, char isSigned, char padchar, Int64 n)
{
char *ptr = pszBuffer;
if (!pszBuffer)
{
return;
}
char *p, buf[32];
unsigned long long x;
unsigned char count;
// Prepare negative number
if (isSigned && (n < 0))
{
x = -n;
}
else
{
x = n;
}
// Set up small string buffer
count = (numDigits-1) - (isSigned?1:0);
p = buf + sizeof (buf);
*--p = '\0';
// Force calculation of first digit
// (to prevent zero from not printing at all!!!)
*--p = (char)hexchar(x%base);
x = x / base;
// Calculate remaining digits
while(count--)
{
if(x != 0)
{
// Calculate next digit
*--p = (char)hexchar(x%base);
x /= base;
}
else
{
// No more digits left, pad out to desired length
*--p = padchar;
}
}
// Apply signed notation if requested
if (isSigned)
{
if (n < 0)
{
*--p = '-';
}
else if (n > 0)
{
*--p = '+';
}
else
{
*--p = ' ';
}
}
// Print the string right-justified
count = numDigits;
while (count--)
{
*ptr++ = *p++;
}
return;
}
The simplest solution I have found is to wrap your Font Awesome Icon in an <a></a>
tag:
<Tooltip title="Node.js" >
<a>
<FontAwesomeIcon icon={faNode} size="2x" />
</a>
</Tooltip>
The Groovy way to do this is
def list = []
list << new MyType(...)
which creates a list and uses the overloaded leftShift
operator to append an item
See the Groovy docs on Lists for lots of examples.
In Sql Developer, navidate to Tools->preferences->Datababae->advanced->Set Tnsname directory to the directory containing tnsnames.ora
As @wrikken mentioned in his comments, id -u
is a much better check for root.
In addition, with proper use of sudo
, you could have the script check and see if it is running as root. If not, have it recall itself via sudo
and then run with root permissions.
Depending on what the script does, another option may be to set up a sudo
entry for whatever specialized commands the script may need.
By using the array initializer list syntax, ie:
String myArray[] = { "one", "two", "three" };
I used some of the answers and found one that fit my case ( make sure all tasks are in the release branch).
Other methods works as well but I found that they might add lines that I do not need, like merge commits that add no value.
git fetch
git log origin/master..origin/release-1.1 --oneline --no-merges
or you can compare your current with master
git fetch
git log origin/master..HEAD --oneline --no-merges
git fetch
is there to make sure you are using updated info.
In this way each commit will be on a line and you can copy/paste that into an text editor and start comparing the tasks with the commits that will be merged.
an abstract method must be call override in derived class other wise it will give compile-time error and in virtual you may or may not override it's depend if it's good enough use it
Example:
abstract class twodshape
{
public abstract void area(); // no body in base class
}
class twodshape2 : twodshape
{
public virtual double area()
{
Console.WriteLine("AREA() may be or may not be override");
}
}
scanf()
and friends return the number of input items successfully matched. For your code, that would be two or less (in case of less matches than specified). In short, be a little more careful with the manual pages:
#include <stdio.h>
#include <errno.h>
#include <stdbool.h>
int main(void)
{
char item[9], status;
FILE *fp;
if((fp = fopen("D:\\Sample\\database.txt", "r+")) == NULL) {
printf("No such file\n");
exit(1);
}
while (true) {
int ret = fscanf(fp, "%s %c", item, &status);
if(ret == 2)
printf("\n%s \t %c", item, status);
else if(errno != 0) {
perror("scanf:");
break;
} else if(ret == EOF) {
break;
} else {
printf("No match.\n");
}
}
printf("\n");
if(feof(fp)) {
puts("EOF");
}
return 0;
}
I would do something like:
$(documento).on('click', '#answer', function() {
feedback('hey there');
});
First we should know that regular expression can separately be used. Here is an example:
import scala.util.matching.Regex
val pattern = "Scala".r // <=> val pattern = new Regex("Scala")
val str = "Scala is very cool"
val result = pattern findFirstIn str
result match {
case Some(v) => println(v)
case _ =>
} // output: Scala
Second we should notice that combining regular expression with pattern matching would be very powerful. Here is a simple example.
val date = """(\d\d\d\d)-(\d\d)-(\d\d)""".r
"2014-11-20" match {
case date(year, month, day) => "hello"
} // output: hello
In fact, regular expression itself is already very powerful; the only thing we need to do is to make it more powerful by Scala. Here are more examples in Scala Document: http://www.scala-lang.org/files/archive/api/current/index.html#scala.util.matching.Regex
$query="SELECT * FROM contacts";
$result=mysql_query($query);
It took me a while to understand @user1996230's answer so I decided to provide a more explicit example. In the below example I make a proxy for an object loaded in another AppDomain and call a method on that object from another domain.
class ProxyObject : MarshalByRefObject
{
private Type _type;
private Object _object;
public void InstantiateObject(string AssemblyPath, string typeName, object[] args)
{
assembly = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + AssemblyPath); //LoadFrom loads dependent DLLs (assuming they are in the app domain's base directory
_type = assembly.GetType(typeName);
_object = Activator.CreateInstance(_type, args); ;
}
public void InvokeMethod(string methodName, object[] args)
{
var methodinfo = _type.GetMethod(methodName);
methodinfo.Invoke(_object, args);
}
}
static void Main(string[] args)
{
AppDomainSetup setup = new AppDomainSetup();
setup.ApplicationBase = @"SomePathWithDLLs";
AppDomain domain = AppDomain.CreateDomain("MyDomain", null, setup);
ProxyObject proxyObject = (ProxyObject)domain.CreateInstanceFromAndUnwrap(typeof(ProxyObject).Assembly.Location,"ProxyObject");
proxyObject.InstantiateObject("SomeDLL","SomeType", new object[] { "someArgs});
proxyObject.InvokeMethod("foo",new object[] { "bar"});
}
If you are using EF6 (Entity Framework 6+), this has changed for database calls to SQL.
See: http://msdn.microsoft.com/en-us/data/dn456843.aspx
use context.Database.BeginTransaction.
using (var context = new BloggingContext()) { using (var dbContextTransaction = context.Database.BeginTransaction()) { try { context.Database.ExecuteSqlCommand( @"UPDATE Blogs SET Rating = 5" + " WHERE Name LIKE '%Entity Framework%'" ); var query = context.Posts.Where(p => p.Blog.Rating >= 5); foreach (var post in query) { post.Title += "[Cool Blog]"; } context.SaveChanges(); dbContextTransaction.Commit(); } catch (Exception) { dbContextTransaction.Rollback(); //Required according to MSDN article throw; //Not in MSDN article, but recommended so the exception still bubbles up } } }
Google's Guava library has a Primitives utility that check if a class is a wrapper type for a primitive: Primitives.isWrapperType(class)
.
Class.isPrimitive() works for primitives
What actually worked for me in the end was this:
Intent myIntent = new Intent(getBaseContext(), MainActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
I think the problem can be because of the NAT. Normally the DNS clients make requests via UDP. But when the DNS server is behind the NAT the UDP requests will not work.
$('#formID')[0].reset(); // Reset all form fields
function findLongestWord(str) {
str = str.split(" ");
var sorted = str.sort(function(prev,current){
return prev.length - current.length;
});
var index = sorted.length;
str = sorted[index-1];
return str;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
I was getting this error until I did the following.
public void somethingHappened(final Context context)
{
Handler handler = new Handler(Looper.getMainLooper());
handler.post(
new Runnable()
{
@Override
public void run()
{
Toast.makeText(context, "Something happened.", Toast.LENGTH_SHORT).show();
}
}
);
}
And made this into a singleton class:
public enum Toaster {
INSTANCE;
private final Handler handler = new Handler(Looper.getMainLooper());
public void postMessage(final String message) {
handler.post(
new Runnable() {
@Override
public void run() {
Toast.makeText(ApplicationHolder.INSTANCE.getCustomApplication(), message, Toast.LENGTH_SHORT)
.show();
}
}
);
}
}
You can minimize the command prompt on during the run but you'll need two additional scripts: windowMode and getCmdPid.bat:
@echo off
call getCmdPid
call windowMode -pid %errorlevel% -mode minimized
cd /d C:\leads\ssh
call C:\Ruby192\bin\setrbvars.bat
ruby C:\leads\ssh\put_leads.rb
Try this :
Create anim folder inside your res folder and copy this four files :
slide_in_bottom.xml :
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="100%p"
android:duration="@android:integer/config_longAnimTime"/>
slide_out_bottom.xml :
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="0"
android:duration="@android:integer/config_longAnimTime" />
slide_in_top.xml :
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:toYDelta="0%p"
android:duration="@android:integer/config_longAnimTime" />
slide_out_top.xml :
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:toYDelta="100%p"
android:duration="@android:integer/config_longAnimTime" />
When you click on image view call:
overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_bottom);
When you click on original place call:
overridePendingTransition(R.anim.slide_in_top, R.anim.slide_out_top);
Main Activity :
package com.example.animationtest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, test.class));
}
});
}
}
activity_main.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1" />
</LinearLayout>
test.java :
package com.example.animationtest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class test extends Activity {
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
btn1 = (Button) findViewById(R.id.btn1);
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
overridePendingTransition(R.anim.slide_in_right,
R.anim.slide_out_right);
startActivity(new Intent(test.this, MainActivity.class));
}
});
}
}
test.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1" />
</LinearLayout>
Hope this helps.
first you can check console.log(typeof Object)
if the output is object then var {data}=object ie just destructure the object according to the object keys. and the function can be like this.
const abc=(str1,str2=null)=>{
var result=[];
result.push(str1);result.push(str2);
return result.join("");
}
The newly released PyCharm 5 supports type hinting. In their blog post about it (see Python 3.5 type hinting in PyCharm 5) they offer a great explanation of what type hints are and aren't along with several examples and illustrations for how to use them in your code.
Additionally, it is supported in Python 2.7, as explained in this comment:
PyCharm supports the typing module from PyPI for Python 2.7, Python 3.2-3.4. For 2.7 you have to put type hints in *.pyi stub files since function annotations were added in Python 3.0.
SELECT DATENAME(weekday, GetDate())
Check this for sql server: http://msdn.microsoft.com/en-US/library/ms174395(v=sql.90).aspx Check this for .net: http://msdn.microsoft.com/en-us/library/bb762911.aspx
There is no definite way to do that. JS may have the API, but the browser vendor may choose not to implement it or implement it in another way.
Also, as far as I remember, Opera even provides the user preferences to prevent JS from making such changes, like have the window move, change status bar content, and stuff like that.
You need to build query from "data" object using the following function
function buildQuery(obj) {
var Result= '';
if(typeof(obj)== 'object') {
jQuery.each(obj, function(key, value) {
Result+= (Result) ? '&' : '';
if(typeof(value)== 'object' && value.length) {
for(var i=0; i<value.length; i++) {
Result+= [key+'[]', encodeURIComponent(value[i])].join('=');
}
} else {
Result+= [key, encodeURIComponent(value)].join('=');
}
});
}
return Result;
}
and then proceed with
var data= {
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work, facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
}
$.ajax({
type: 'POST',
url: "http://localhost:8080/project/server/rest/subjects",
data: buildQuery(data),
error: function(e) {
console.log(e);
}
});
Update for Brian's answer:
If a function in Python 3 has keyword-only arguments, then you need to use inspect.getfullargspec
:
def yay(a, b=10, *, c=20, d=30):
pass
inspect.getfullargspec(yay)
yields this:
FullArgSpec(args=['a', 'b'], varargs=None, varkw=None, defaults=(10,), kwonlyargs=['c', 'd'], kwonlydefaults={'c': 20, 'd': 30}, annotations={})
The accepted answer works great if you just want to use a different context in your partial. However, it doesn't let you reference any of the parent context. To pass in multiple arguments, you need to write your own helper. Here's a working helper for Handlebars 2.0.0
(the other answer works for versions <2.0.0
):
Handlebars.registerHelper('renderPartial', function(partialName, options) {
if (!partialName) {
console.error('No partial name given.');
return '';
}
var partial = Handlebars.partials[partialName];
if (!partial) {
console.error('Couldnt find the compiled partial: ' + partialName);
return '';
}
return new Handlebars.SafeString( partial(options.hash) );
});
Then in your template, you can do something like:
{{renderPartial 'myPartialName' foo=this bar=../bar}}
And in your partial, you'll be able to access those values as context like:
<div id={{bar.id}}>{{foo}}</div>
If you use SQLiteOpenHelper you can do this
String myPath = DB_PATH + DB_NAME;
SQLiteDatabase.deleteDatabase(new File(myPath));
Microsoft introduced schema in version 2008. For those who didn’t know about schema, and those who didn’t care, objects were put into a default schema dbo
.
dbo
stands for DataBase Owner, but that’s not really important.
Think of a schema as you would a folder for files:
You can always access any object from any schema.
Because dbo
is the default, you normally don’t need to specify it within a single database:
SELECT * FROM customers;
SELECT * FROM dbo.customers;
mean the same thing.
I am inclined to disagree with the notion of always using the dbo.
prefix, since the more you clutter your code with unnecessary detail, the harder it is to read and manage.
For the most part, you can ignore the schema. However, the schema will make itself apparent in the following situations:
If you view the tables in either the object navigator or in an external application, such as Microsoft Excel or Access, you will see the dbo.
prefix. You can still ignore it.
If you reference a table in another database, you will need its full name in the form database.schema.table
:
SELECT * FROM bookshop.dbo.customers;
For historical reasons, if you write a user defined scalar function, you will need to call it with the schema prefix:
CREATE FUNCTION tax(@amount DECIMAL(6,2) RETURNS DECIMAL(6,2) AS
BEGIN
RETURN @amount * 0.1;
END;
GO
SELECT total, dbo.tax(total) FROM pricelist;
This does not apply to other objects, such as table functions, procedures and views.
You can use schema to overcome naming conflicts. For example, if every user has a personal schema, they can create additional objects without having to fight with other users over the name.
The Css vertical-align property should help you out here:
vertical-align: bottom;
is what you need for your smaller header :)
I juste wrote a proxy in nodejs that take care of HTTPS with optional decoding of the message. This proxy also can add proxy-authentification header in order to go through a corporate proxy. You need to give as argument the url to find the proxy.pac file in order to configurate the usage of corporate proxy.
function getMeta(url){
$("<img/>",{
load : function(){
alert(this.width+' '+this.height);
},
src : url
});
}
function getMeta(url){
var img = new Image();
img.onload = function(){
alert( this.width+' '+ this.height );
};
img.src = url;
}
function getMeta(url){
var img = new Image();
img.addEventListener("load", function(){
alert( this.naturalWidth +' '+ this.naturalHeight );
});
img.src = url;
}
Use the above simply as: getMeta( "http://example.com/img.jpg" );
https://developer.mozilla.org/en/docs/Web/API/HTMLImageElement
Try Genymotion for Android Studio. Blazing fast! Just needs one time installation. No more AVD pain.
I've just created an android library, that allows you to easily modify the button color and the ripple color
https://github.com/xgc1986/RippleButton
<com.xgc1986.ripplebutton.widget.RippleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn"
android:text="Android button modified in layout"
android:textColor="@android:color/white"
app:buttonColor="@android:color/black"
app:rippleColor="@android:color/white"/>
You don't need to create an style for every button you want wit a different color, allowing you to customize the colors randomly
Accepted answer didn't work for me either, however I found solution in a similar thread: Switch to selected tab by name in Jquery-UI Tabs
var index = $('#tabs a[href="#simple-tab-2"]').parent().index();
$('#tabs').tabs('select', index);
With jQuery UI >= 1.9:
var index = $('#tabs a[href="#simple-tab-2"]').parent().index();
$("#tabs").tabs("option", "active", index);
In Unix systems the end of a line is represented with a line feed (LF). In windows a line is represented with a carriage return (CR) and a line feed (LF) thus (CRLF). when you get code from git that was uploaded from a unix system they will only have an LF.
If you are a single developer working on a windows machine, and you don't care that git automatically replaces LFs to CRLFs, you can turn this warning off by typing the following in the git command line
git config core.autocrlf true
If you want to make an intelligent decision how git should handle this, read the documentation
Here is a snippet
Formatting and Whitespace
Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. Git has a few configuration options to help with these issues.
core.autocrlf
If you’re programming on Windows and working with people who are not (or vice-versa), you’ll probably run into line-ending issues at some point. This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas Mac and Linux systems use only the linefeed character. This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key.
Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true – this converts LF endings into CRLF when you check out code:
$ git config --global core.autocrlf true
If you’re on a Linux or Mac system that uses LF line endings, then you don’t want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. You can tell Git to convert CRLF to LF on commit but not the other way around by setting core.autocrlf to input:
$ git config --global core.autocrlf input
This setup should leave you with CRLF endings in Windows checkouts, but LF endings on Mac and Linux systems and in the repository.
If you’re a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to false:
$ git config --global core.autocrlf false
Try something like this:
<html>
<body>
<script type="text/javascript">
function doSomething(event) {
var source = event.target || event.srcElement;
console.log(source);
alert('test');
if(window.event) {
// IE8 and earlier
// doSomething
} else if(e.which) {
// IE9/Firefox/Chrome/Opera/Safari
// doSomething
}
}
</script>
<button onclick="doSomething('param')" id="id_button">
action
</button>
</body>
</html>
You have two ways:
First go to the particular path of Android SDK:
1) Open your command prompt and traverse to the platform-tools directory through it such as
$ cd Frameworks\Android-Sdk\platform-tools
2) Run your adb commands now such as to know that your adb is working properly :
$ adb devices OR adb logcat OR simply adb
Second way is :
1) Right click on your My Computer.
2) Open Environment variables.
3) Add new variable to your System PATH variable(Add if not exist otherwise no need to add new variable if already exist).
4) Add path of platform-tools directory to as value of this variable such as C:\Program Files\android-sdk\platform-tools.
5) Restart your computer once.
6) Now run the above adb commands such adb devices or other adb commands from anywhere in command prompt.
Also on you can fire a command on terminal setx PATH "%PATH%;C:\Program Files\android-sdk\platform-tools"
Easy:
SELECT question_id, wm_concat(element_id) as elements
FROM questions
GROUP BY question_id;
Pesonally tested on 10g ;-)
From http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php
The DatePicker class has methods for getting the month, year, day of month. Or you can use an OnDateChangedListener.
I had to add packaging, so:
mvn install:install-file \
-DgroupId=javax.transaction \
-DartifactId=jta \
-Dversion=1.0.1B \
-Dfile=jta-1.0.1B.jar \
-DgeneratePom=true \
-Dpackaging=jar
This isn't my code sample, but I've used it in the past.
//First Add this to extend jQuery
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});
//Second call with this:
// Get object of URL parameters
var allVars = $.getUrlVars();
// Getting URL var by its name
var byName = $.getUrlVar('name');
Instead of src
you need ng-src
.
AngularJS views support binary operators
condition && true || false
So your img
tag would look like this
<img ng-src="{{interface == 'UP' && 'green-checkmark.png' || 'big-black-X.png'}}"/>
Note : the quotes (ie 'green-checkmark.png') are important here. It won't work without quotes.
plunker here (open dev tools to see the produced HTML)
In your viewDidLoad
, register at notification center to listen to this opened from background action
NotificationCenter.default.addObserver(self, selector:#selector(doSomething), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
Then add this function and perform needed action
func doSomething(){
//...
}
Finally add this function to clean up the notification observer when your view controller is destroyed.
deinit {
NotificationCenter.default.removeObserver(self)
}
It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.
In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue"
to then end of the URL you are opening. :
http://www.somesite.com/send.php?variableName=someValue
or
http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue
This way, from PHP you can access this value as:
$phpVariableName = $_POST["variableName"];
for forms using POST method or:
$phpVariableName = $_GET["variableName"];
for forms using GET method or the append to url method I've mentioned above (querystring).
Use FileUtils to handle all these headaches.
Edit: For example, use below code to write to a file, this method will 'checking and creating the parent directory if it does not exist'.
openOutputStream(File file [, boolean append])
On Windows:
NOTE: Path should be appended
JAVA_HOME %ProgramFiles%\Android\Android Studio\jre
ANDROID_SDK_ROOT %LocalAppData%\Android\Sdk
Path %LocalAppData%\Android\Sdk
NOTE: Accept all licenses (say y
)
%ANDROID_SDK_ROOT%/tools/bin/sdkmanager.bat --licenses
(like below, or another command that failed for you):
cd \myapp\
react-native run-android
$string="1,2,3,4,5";
$array=array_map('intval', explode(',', $string));
$array = implode("','",$array);
$query=mysqli_query($conn, "SELECT name FROM users WHERE id IN ('".$array."')");
NB: the syntax is:
SELECT * FROM table WHERE column IN('value1','value2','value3')
The split() method in javascript accepts two parameters: a separator and a limit. The separator specifies the character to use for splitting the string. If you don't specify a separator, the entire string is returned, non-separated. But, if you specify the empty string as a separator, the string is split between each character.
Therefore:
s.split('')
will have the effect you seek.
More information here
I am a beginner to screen but I find it immensely useful while restoring lost connections. Your question has already been answered but this information might serve as an add on - I use putty with putty connection manager and name my screens - "tab1", "tab2", etc. - as for me the overall picture of the 8-10 tabs is more important than each individual tab name. I use the 8th tab for connecting to db, the 7th for viewing logs, etc. So when I want to reattach my screens I have written a simple wrapper which says:
#!/bin/bash
screen -d -r tab$1
where first argument is the tab number.
// sort algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::sort
#include <vector> // std::vector
using namespace std;
int main () {
char myints[] = {'F','C','E','G','A','H','B','D'};
vector<char> myvector (myints, myints+8); // 32 71 12 45 26 80 53 33
// using default comparison (operator <):
sort (myvector.begin(), myvector.end()); //(12 32 45 71)26 80 53 33
// print out content:
cout << "myvector contains:";
for (int i=0; i!=8; i++)
cout << ' ' <<myvector[i];
cout << '\n';
system("PAUSE");
return 0;
}
According to phpbench:
Is it worth the effort to calculate the length of the loop in advance?
//pre-calculate the size of array
$size = count($x); //or $size = sizeOf($x);
for ($i=0; $i<$size; $i++) {
//...
}
//don't pre-calculate
for ($i=0; $i<count($x); $i++) { //or $i<sizeOf($x);
//...
}
A loop with 1000 keys with 1 byte values are given.
+---------+----------+
| count() | sizeof() |
+-----------------+---------+----------+
| With precalc | 152 | 212 |
| Without precalc | 70401 | 50644 |
+-----------------+---------+----------+ (time in µs)
So I personally prefer to use count() instead of sizeof() with pre calc.
PowerShell (Core-compatible) one-liner to ease copypaste scenarios:
netstat -aon | Select-String 8080 | ForEach-Object { $_ -replace '\s+', ',' } | ConvertFrom-Csv -Header @('Empty', 'Protocol', 'AddressLocal', 'AddressForeign', 'State', 'PID') | ForEach-Object { $portProcess = Get-Process | Where-Object Id -eq $_.PID; $_ | Add-Member -NotePropertyName 'ProcessName' -NotePropertyValue $portProcess.ProcessName; Write-Output $_ } | Sort-Object ProcessName, State, Protocol, AddressLocal, AddressForeign | Select-Object ProcessName, State, Protocol, AddressLocal, AddressForeign | Format-Table
Output:
ProcessName State Protocol AddressLocal AddressForeign
----------- ----- -------- ------------ --------------
System LISTENING TCP [::]:8080 [::]:0
System LISTENING TCP 0.0.0.0:8080 0.0.0.0:0
Same code, developer-friendly:
$Port = 8080
# Get PID's listening to $Port, as PSObject
$PidsAtPortString = netstat -aon `
| Select-String $Port
$PidsAtPort = $PidsAtPortString `
| ForEach-Object { `
$_ -replace '\s+', ',' `
} `
| ConvertFrom-Csv -Header @('Empty', 'Protocol', 'AddressLocal', 'AddressForeign', 'State', 'PID')
# Enrich port's list with ProcessName data
$ProcessesAtPort = $PidsAtPort `
| ForEach-Object { `
$portProcess = Get-Process `
| Where-Object Id -eq $_.PID; `
$_ | Add-Member -NotePropertyName 'ProcessName' -NotePropertyValue $portProcess.ProcessName; `
Write-Output $_;
}
# Show output
$ProcessesAtPort `
| Sort-Object ProcessName, State, Protocol, AddressLocal, AddressForeign `
| Select-Object ProcessName, State, Protocol, AddressLocal, AddressForeign `
| Format-Table
You can delete any component by removing all its lines from app.module.ts . Its working fine for me.
I forgot that I had already an unused labs
branch. Deleting it solved my problem:
git branch -d labs
git checkout -b labs/feature
Explanation:
Each name can only be a parent branch or a normal branch, not both. Thats why the branches labs
and labs/feature
can't exists both at the same time.
The reason: Branches are stored in the file system and there you also can't have a file labs
and a directory labs
at the same level.
You could do it in one document if you had a conditional based on params sent over. Eg:
if (isset($_GET['secret_param'])) {
<run script>
} else {
<display button>
}
I think the best way though is to have two files.
In this case no conditionals are needed to set the variable.
This one-liner XPath expression:
boolean(joined-subclass)
is true()
only when the child of the current node, named joined-subclass
exists and it is false()
otherwise.
The complete stylesheet is:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="class">
<xsl:variable name="subexists"
select="boolean(joined-subclass)"
/>
subexists: <xsl:text/>
<xsl:value-of select="$subexists" />
</xsl:template>
</xsl:stylesheet>
Do note, that the use of the XPath function boolean()
in this expression is to convert a node (or its absense) to one of the boolean values true()
or false()
.
Use Controls
object
For i = 1 To X
Controls("Label" & i).Caption = MySheet.Cells(i + 1, i).Value
Next
A bit different opinion instead of storing the Fragments yourself just leave it to the FragmentManager and when you need to do something with the fragments look for them in the FragmentManager:
//make sure you have the right FragmentManager
//getSupportFragmentManager or getChildFragmentManager depending on what you are using to manage this stack of fragments
List<Fragment> fragments = fragmentManager.getFragments();
if(fragments != null) {
int count = fragments.size();
for (int x = 0; x < count; x++) {
Fragment fragment = fragments.get(x);
//check if this is the fragment we want,
//it may be some other inspection, tag etc.
if (fragment instanceof MyFragment) {
//do whatever we need to do with it
}
}
}
If you have a lot of Fragments and the cost of instanceof check may be not what you want, but it is good thing to have in mind that the FragmentManager already keeps account of Fragments.
I have a dataset in my app and I went to set changes (deleting a row) to it but ds.tabales["TableName"]
is read only. Then I found this solution.
It's a wpf C#
app,
try {
var results = from row in ds.Tables["TableName"].AsEnumerable() where row.Field<string>("Personalid") == "47" select row;
foreach (DataRow row in results) {
ds.Tables["TableName"].Rows.Remove(row);
}
}
I would set up a shortcut, either to CMD or to the thing you want to run, then set the properties of the shortcut to require admin, and then run the shortcut from your batch file. I haven't tested to confirm it will respect the properties, but I think it's more elegant and doesn't require activating the Administrator account.
Also if you do it as a scheduled task (which can be set up from code) there is an option to run it elevated there.
Save code below as command.sql
USE restaurant
TRUNCATE `orders`;
TRUNCATE `order_items`;
Then run
mysql -u root <comands.sql> output.tab
git push --tags production
I know this is hyper-optimization land, but it seemed like a good excuse to kick the wheels of BenchmarkDotNet
. The result of this test (on .NET Core even) is that Substring
is ever so slightly faster than Remove
, in this sample test: 19.37ns vs 22.52ns for Remove
. So some ~16% faster.
using System;
using BenchmarkDotNet.Attributes;
namespace BenchmarkFun
{
public class StringSubstringVsRemove
{
public readonly string SampleString = " My name is Daffy Duck.";
[Benchmark]
public string StringSubstring() => SampleString.Substring(1);
[Benchmark]
public string StringRemove() => SampleString.Remove(0, 1);
public void AssertTestIsValid()
{
string subsRes = StringSubstring();
string remvRes = StringRemove();
if (subsRes == null
|| subsRes.Length != SampleString.Length - 1
|| subsRes != remvRes) {
throw new Exception("INVALID TEST!");
}
}
}
class Program
{
static void Main()
{
// let's make sure test results are really equal / valid
new StringSubstringVsRemove().AssertTestIsValid();
var summary = BenchmarkRunner.Run<StringSubstringVsRemove>();
}
}
}
Results:
BenchmarkDotNet=v0.11.4, OS=Windows 10.0.17763.253 (1809/October2018Update/Redstone5)
Intel Core i7-6700HQ CPU 2.60GHz (Skylake), 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=3.0.100-preview-010184
[Host] : .NET Core 3.0.0-preview-27324-5 (CoreCLR 4.6.27322.0, CoreFX 4.7.19.7311), 64bit RyuJIT
DefaultJob : .NET Core 3.0.0-preview-27324-5 (CoreCLR 4.6.27322.0, CoreFX 4.7.19.7311), 64bit RyuJIT
| Method | Mean | Error | StdDev |
|---------------- |---------:|----------:|----------:|
| StringSubstring | 19.37 ns | 0.3940 ns | 0.3493 ns |
| StringRemove | 22.52 ns | 0.4062 ns | 0.3601 ns |
You can't.
The only way to set the value of a file input is by the user to select a file.
This is done for security reasons. Otherwise you would be able to create a JavaScript that automatically uploads a specific file from the client's computer.
Rethink your approach. Why would you copy only part of the sheet? You are referring to a named range "WholePrintArea" which doesn't exist. Also you should never use activate, select, copy or paste in your script. These make the "script" vulnerable to user actions and other simultaneous executions. In worst case scenario data ends up in wrong hands.
I have one generic log4j.xml file for you:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration debug="false">
<appender name="default.console" class="org.apache.log4j.ConsoleAppender">
<param name="target" value="System.out" />
<param name="threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
</layout>
</appender>
<appender name="default.file" class="org.apache.log4j.FileAppender">
<param name="file" value="/log/mylogfile.log" />
<param name="append" value="false" />
<param name="threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
</layout>
</appender>
<appender name="another.file" class="org.apache.log4j.FileAppender">
<param name="file" value="/log/anotherlogfile.log" />
<param name="append" value="false" />
<param name="threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
</layout>
</appender>
<logger name="com.yourcompany.SomeClass" additivity="false">
<level value="debug" />
<appender-ref ref="another.file" />
</logger>
<root>
<priority value="info" />
<appender-ref ref="default.console" />
<appender-ref ref="default.file" />
</root>
</log4j:configuration>
with one console, two file appender and one logger poiting to the second file appender instead of the first.
EDIT
In one of the older projects I have found a simple log4j.properties file:
# For the general syntax of property based configuration files see
# the documentation of org.apache.log4j.PropertyConfigurator.
# The root category uses two appenders: default.out and default.file.
# The first one gathers all log output, the latter only starting with
# the priority INFO.
# The root priority is DEBUG, so that all classes can be logged unless
# defined otherwise in more specific properties.
log4j.rootLogger=DEBUG, default.out, default.file
# System.out.println appender for all classes
log4j.appender.default.out=org.apache.log4j.ConsoleAppender
log4j.appender.default.out.threshold=DEBUG
log4j.appender.default.out.layout=org.apache.log4j.PatternLayout
log4j.appender.default.out.layout.ConversionPattern=%-5p %c: %m%n
log4j.appender.default.file=org.apache.log4j.FileAppender
log4j.appender.default.file.append=true
log4j.appender.default.file.file=/log/mylogfile.log
log4j.appender.default.file.threshold=INFO
log4j.appender.default.file.layout=org.apache.log4j.PatternLayout
log4j.appender.default.file.layout.ConversionPattern=%-5p %c: %m%n
For the description of all the layout arguments look here: log4j PatternLayout arguments
Do you want the JDK or the JRE? Anyways, I had this problem too, a few weeks ago. I followed the instructions here and it worked:
http://www.backtrack-linux.org/wiki/index.php/Java_Install
root@bt:~# killall -9 /opt/firefox/firefox-bin
root@bt:~# mkdir /opt/java
root@bt:~# mv -f jre1.7.0_05/ /opt/java/
root@bt:~# update-alternatives --install /usr/bin/java java /opt/java/jre1.7.0_05/bin/java 1
root@bt:~# update-alternatives --set java /opt/java/jre1.7.0_05/bin/java
root@bt:~# export JAVA_HOME="/opt/java/jre1.7.0_05"
For Java 7 (32 bit)
root@bt:~# ln -sf $JAVA_HOME/lib/i386/libnpjp2.so /usr/lib/mozilla/plugins/
For Java 8 (64 bit)
root@bt:~# ln -sf $JAVA_HOME/jre/lib/amd64/libnpjp2.so /usr/lib/mozilla/plugins/
root@bt:~# firefox http://java.com/en/download/testjava.jsp
Commands:
chown www-data:www-data -R *
find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;
Where ftp-user is what user you are using to upload the files
chown -R ftp-user:www-data wp-content
chmod -R 775 wp-content
As a follow-up to the answer of @maciej-bukowski above ^^^, in modern browsers as of now (spring 2017) that support async/await you can load as follows. In this example we load the load html2canvas library:
async function loadScript(url) {_x000D_
let response = await fetch(url);_x000D_
let script = await response.text();_x000D_
eval(script);_x000D_
}_x000D_
_x000D_
let scriptUrl = 'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js'_x000D_
loadScript(scriptUrl);
_x000D_
If you run the snippet and then open your browser's console you should see the function html2canvas() is now defined.
"5 * x^3 - 6 * x^1 + 1".replaceAll("\\W*\\*\\W*","").replaceAll("\\^(\\d+)","<sup>$1</sup>");
please note that joining both replacements in a single regex/replacement would be a bad choice because more general expressions such as x^3 - 6 * x
would fail.
Actually - if you are ok with floating the dropdown
wrapper - I've found it to be as easy as to add navbar-right
to the dropdown
.
This seems like cheating, since it's not in a navbar, but it works fine for me.
<div class="dropdown navbar-right">
...
</div>
You can then further customize the floating with a pull-left
directly in the dropdown
...
<div class="dropdown pull-left navbar-right">
...
</div>
... or as a wrapper around it ...
<div class="pull-left">
<div class="dropdown navbar-right">
...
</div>
</div>
Try this.
CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
String cameraId = null; // Usually front camera is at 0 position.
try {
cameraId = camManager.getCameraIdList()[0];
camManager.setTorchMode(cameraId, true);
} catch (CameraAccessException e) {
e.printStackTrace();
}
Let me clear two points here :
def example(a, b, c=None, r="w" , d=[], *ae, **ab):
(a,b) are positional parameter
(c=none) is optional parameter
(r="w") is keyword parameter
(d=[]) is list parameter
(*ae) is keyword-only
(**ab) is var-keyword parameter
def example(a, b, c=a,d=b):
argument is not defined when default values are saved,Python computes and saves default values when you define the function
c and d are not defined, does not exist, when this happens (it exists only when the function is executed)
"a,a=b" its not allowed in parameter.
The SaveFileDialog
control won't do any saving at all. All it does is providing you a convenient interface to actually display Windows' default file save dialog.
Set the property InitialDirectory
to the drive you'd like it to show some other default. Just think of other computers that might have a different layout. By default windows will save the directory used the last time and present it again.
That is handled outside the control. You'll have to check the dialog's results and then do the saving yourself (e.g. write a text or binary file).
Just as a quick example (there are alternative ways to do it).
savefile
is a control of type SaveFileDialog
SaveFileDialog savefile = new SaveFileDialog();
// set a default file name
savefile.FileName = "unknown.txt";
// set filters - this can be done in properties as well
savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
if (savefile.ShowDialog() == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(savefile.FileName))
sw.WriteLine ("Hello World!");
}
For those looking for a C# workaround:
If you need for some reason to have the "AutoGeneratedColumns" enabled, one thing you can do is to specify all the columns's width except the ones you want to be auto resized (it will not take the remaining space, but it will resize to the cell's content).
Example (dgShopppingCart is my DataGrid):
dgShoppingCart.Columns[0].Visibility = Visibility.Hidden;
dgShoppingCart.Columns[1].Header = "Qty";
dgShoppingCart.Columns[1].Width = 100;
dgShoppingCart.Columns[2].Header = "Product Name"; /*This will be resized to cell content*/
dgShoppingCart.Columns[3].Header = "Price";
dgShoppingCart.Columns[3].Width = 100;
dgShoppingCart.Columns[4].Visibility = Visibility.Hidden;
For me it works as a workaround because I needed to have the DataGrid resized when the user maximize the Window.
I also had the same problem while accessing RESTful web services. And I their with the below code to overcome the issue:
public class Test {
//Bypassing the SSL verification to execute our code successfully
static {
disableSSLVerification();
}
public static void main(String[] args) {
//Access HTTPS URL and do something
}
//Method used for bypassing SSL verification
public static void disableSSLVerification() {
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
SSLContext sc = null;
try {
sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
}
It worked for me. try it!!
You are using a forward declaration for the type MainWindowClass
. That's fine, but it also means that you can only declare a pointer or reference to that type. Otherwise the compiler has no idea how to allocate the parent object as it doesn't know the size of the forward declared type (or if it actually has a parameterless constructor, etc.)
So, you either want:
// forward declaration, details unknown
class A;
class B {
A *a; // pointer to A, ok
};
Or, if you can't use a pointer or reference....
// declaration of A
#include "A.h"
class B {
A a; // ok, declaration of A is known
};
At some point, the compiler needs to know the details of A
.
If you are only storing a pointer to A
then it doesn't need those details when you declare B
. It needs them at some point (whenever you actually dereference the pointer to A
), which will likely be in the implementation file, where you will need to include the header which contains the declaration of the class A
.
// B.h
// header file
// forward declaration, details unknown
class A;
class B {
public:
void foo();
private:
A *a; // pointer to A, ok
};
// B.cpp
// implementation file
#include "B.h"
#include "A.h" // declaration of A
B::foo() {
// here we need to know the declaration of A
a->whatever();
}
I know this question has an accepted answer, but I feel that it doesn't work in all cases.
For completeness and since I spent too much time on this, here is what we did: we ended up using a function from php.js (which is a pretty nice library for those more familiar with PHP but also doing a little JavaScript every now and then):
http://phpjs.org/functions/strip_tags:535
It seemed to be the only piece of JavaScript code which successfully dealt with all the different kinds of input I stuffed into my application. That is, without breaking it – see my comments about the <script />
tag above.
Just wanted to add extension method for an array.
interface Array<T> {
remove(element: T): Array<T>;
}
Array.prototype.remove = function (element) {
const index = this.indexOf(element, 0);
if (index > -1) {
return this.splice(index, 1);
}
return this;
};
This will work in Python 3
import urllib.request
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
url = "http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers"
headers={'User-Agent':user_agent,}
request=urllib.request.Request(url,None,headers) #The assembled request
response = urllib.request.urlopen(request)
data = response.read() # The data u need
Frame vs bounds
Take a look at this SO post answer and also look at this basic authentication tutorial from the urllib2 missing manual.
In order for urllib2 basic authentication to work, the http response must contain HTTP code 401 Unauthorized and a key "WWW-Authenticate"
with the value "Basic"
otherwise, Python won't send your login info, and you will need to either use Requests, or urllib.urlopen(url)
with your login in the url, or add a the header like in @Flowpoke's answer.
You can view your error by putting your urlopen
in a try block:
try:
urllib2.urlopen(urllib2.Request(url))
except urllib2.HTTPError, e:
print e.headers
print e.headers.has_key('WWW-Authenticate')
same way you did the fill in, but reverse the indexes:
>>> for j in range(columns):
... for i in range(rows):
... print mylist[i][j],
...
0,0 1,0 2,0 0,1 1,1 2,1
>>>
A generic, pure Java solution..
For Windows and MacOS, the following can be inferred (most of the time)...
public static boolean isJDK() {
String path = System.getProperty("sun.boot.library.path");
if(path != null && path.contains("jdk")) {
return true;
}
return false;
}
However... on Linux this isn't as reliable... For example...
openjdk
the pathSo a more fail-safe approach is to check for the existence of the javac
executable.
public static boolean isJDK() {
String path = System.getProperty("sun.boot.library.path");
if(path != null) {
String javacPath = "";
if(path.endsWith(File.separator + "bin")) {
javacPath = path;
} else {
int libIndex = path.lastIndexOf(File.separator + "lib");
if(libIndex > 0) {
javacPath = path.substring(0, libIndex) + File.separator + "bin";
}
}
if(!javacPath.isEmpty()) {
return new File(javacPath, "javac").exists() || new File(javacPath, "javac.exe").exists();
}
}
return false;
}
Warning: This will still fail for JRE + JDK combos which report the JRE's sun.boot.library.path
identically between the JRE and the JDK. For example, Fedora's JDK will fail (or pass depending on how you look at it) when the above code is run. See unit tests below for more info...
Unit tests:
# Unix
java -XshowSettings:properties -version 2>&1|grep "sun.boot.library.path"
# Windows
java -XshowSettings:properties -version 2>&1|find "sun.boot.library.path"
# PASS: MacOS AdoptOpenJDK JDK11
/Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home/lib
# PASS: Windows Oracle JDK12
c:\Program Files\Java\jdk-12.0.2\bin
# PASS: Windows Oracle JRE8
C:\Program Files\Java\jre1.8.0_181\bin
# PASS: Windows Oracle JDK8
C:\Program Files\Java\jdk1.8.0_181\bin
# PASS: Ubuntu AdoptOpenJDK JDK11
/usr/lib/jvm/adoptopenjdk-11-hotspot-amd64/lib
# PASS: Ubuntu Oracle JDK11
/usr/lib/jvm/java-11-oracle/lib
# PASS: Fedora OpenJDK JDK8
/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.141-1.b16.fc24.x86_64/jre/lib/amd64
#### FAIL: Fedora OpenJDK JDK8
/usr/java/jdk1.8.0_231-amd64/jre/lib/amd64
Your code concatenates three strings, then converts the result to a number.
You need to convert each variable to a number by calling parseFloat()
around each one.
total = parseFloat(myInt1) + parseFloat(myInt2) + parseFloat(myInt3);
You can limit the scope of a playbook by changing the hosts header in its plays without relying on your special host label ‘local’ in your inventory. Localhost does not need a special line in inventories.
- name: run on all except local
hosts: all:!local
Substring. This method extracts strings. It requires the location of the substring (a start index, a length). It then returns a new string with the characters in that range.
See a small example :
string input = "OneTwoThree";
// Get first three characters.
string sub = input.Substring(0, 3);
Console.WriteLine("Substring: {0}", sub);
Output : Substring: One
It is not an import problem. You simply call .dropDuplicates()
on a wrong object. While class of sqlContext.createDataFrame(rdd1, ...)
is pyspark.sql.dataframe.DataFrame
, after you apply .collect()
it is a plain Python list
, and lists don't provide dropDuplicates
method. What you want is something like this:
(df1 = sqlContext
.createDataFrame(rdd1, ['column1', 'column2', 'column3', 'column4'])
.dropDuplicates())
df1.collect()
Maybe the 40 bytes fits into the pipe buffer, and the 40000 bytes doesn't?
Edit:
The sending process is sent a SIGPIPE signal when you try to write to a closed pipe. I don't know exactly when the signal is sent, or what effect the pipe buffer has on this. You may be able to recover by trapping the signal with the sigaction call.
I have the same problem, but I resolved adding jquery.min.js before angular.min.js.
You just need to bind a variable into the directive "ng-class" and change it from the controller. Here is an example of how to do this:
var app = angular.module("ap",[]);_x000D_
_x000D_
app.controller("con",function($scope){_x000D_
$scope.class = "red";_x000D_
$scope.changeClass = function(){_x000D_
if ($scope.class === "red")_x000D_
$scope.class = "blue";_x000D_
else_x000D_
$scope.class = "red";_x000D_
};_x000D_
});
_x000D_
.red{_x000D_
color:red;_x000D_
}_x000D_
_x000D_
.blue{_x000D_
color:blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<body ng-app="ap" ng-controller="con">_x000D_
<div ng-class="class">{{class}}</div>_x000D_
<button ng-click="changeClass()">Change Class</button> _x000D_
</body>
_x000D_
Here is the example working on jsFiddle
I know this question is older but I was looking thru the answers and thought that I might be able to expand on the "dynamic" portion of the problem and possibly help someone out.
First and foremost I built this solution to solve a problem a couple of coworkers were having with inconstant and large data sets needing to be pivoted quickly.
This solution requires the creation of a stored procedure so if that is out of the question for your needs please stop reading now.
This procedure is going to take in the key variables of a pivot statement to dynamically create pivot statements for varying tables, column names and aggregates. The Static column is used as the group by / identity column for the pivot(this can be stripped out of the code if not necessary but is pretty common in pivot statements and was necessary to solve the original issue), the pivot column is where the end resultant column names will be generated from, and the value column is what the aggregate will be applied to. The Table parameter is the name of the table including the schema (schema.tablename) this portion of the code could use some love because it is not as clean as I would like it to be. It worked for me because my usage was not publicly facing and sql injection was not a concern. The Aggregate parameter will accept any standard sql aggregate 'AVG', 'SUM', 'MAX' etc. The code also defaults to MAX as an aggregate this is not necessary but the audience this was originally built for did not understand pivots and were typically using max as an aggregate.
Lets start with the code to create the stored procedure. This code should work in all versions of SSMS 2005 and above but I have not tested it in 2005 or 2016 but I can not see why it would not work.
create PROCEDURE [dbo].[USP_DYNAMIC_PIVOT]
(
@STATIC_COLUMN VARCHAR(255),
@PIVOT_COLUMN VARCHAR(255),
@VALUE_COLUMN VARCHAR(255),
@TABLE VARCHAR(255),
@AGGREGATE VARCHAR(20) = null
)
AS
BEGIN
SET NOCOUNT ON;
declare @AVAIABLE_TO_PIVOT NVARCHAR(MAX),
@SQLSTRING NVARCHAR(MAX),
@PIVOT_SQL_STRING NVARCHAR(MAX),
@TEMPVARCOLUMNS NVARCHAR(MAX),
@TABLESQL NVARCHAR(MAX)
if isnull(@AGGREGATE,'') = ''
begin
SET @AGGREGATE = 'MAX'
end
SET @PIVOT_SQL_STRING = 'SELECT top 1 STUFF((SELECT distinct '', '' + CAST(''[''+CONVERT(VARCHAR,'+ @PIVOT_COLUMN+')+'']'' AS VARCHAR(50)) [text()]
FROM '+@TABLE+'
WHERE ISNULL('+@PIVOT_COLUMN+','''') <> ''''
FOR XML PATH(''''), TYPE)
.value(''.'',''NVARCHAR(MAX)''),1,2,'' '') as PIVOT_VALUES
from '+@TABLE+' ma
ORDER BY ' + @PIVOT_COLUMN + ''
declare @TAB AS TABLE(COL NVARCHAR(MAX) )
INSERT INTO @TAB EXEC SP_EXECUTESQL @PIVOT_SQL_STRING, @AVAIABLE_TO_PIVOT
SET @AVAIABLE_TO_PIVOT = (SELECT * FROM @TAB)
SET @TEMPVARCOLUMNS = (SELECT replace(@AVAIABLE_TO_PIVOT,',',' nvarchar(255) null,') + ' nvarchar(255) null')
SET @SQLSTRING = 'DECLARE @RETURN_TABLE TABLE ('+@STATIC_COLUMN+' NVARCHAR(255) NULL,'+@TEMPVARCOLUMNS+')
INSERT INTO @RETURN_TABLE('+@STATIC_COLUMN+','+@AVAIABLE_TO_PIVOT+')
select * from (
SELECT ' + @STATIC_COLUMN + ' , ' + @PIVOT_COLUMN + ', ' + @VALUE_COLUMN + ' FROM '+@TABLE+' ) a
PIVOT
(
'+@AGGREGATE+'('+@VALUE_COLUMN+')
FOR '+@PIVOT_COLUMN+' IN ('+@AVAIABLE_TO_PIVOT+')
) piv
SELECT * FROM @RETURN_TABLE'
EXEC SP_EXECUTESQL @SQLSTRING
END
Next we will get our data ready for the example. I have taken the data example from the accepted answer with the addition of a couple of data elements to use in this proof of concept to show the varied outputs of the aggregate change.
create table temp
(
date datetime,
category varchar(3),
amount money
)
insert into temp values ('1/1/2012', 'ABC', 1000.00)
insert into temp values ('1/1/2012', 'ABC', 2000.00) -- added
insert into temp values ('2/1/2012', 'DEF', 500.00)
insert into temp values ('2/1/2012', 'DEF', 1500.00) -- added
insert into temp values ('2/1/2012', 'GHI', 800.00)
insert into temp values ('2/10/2012', 'DEF', 700.00)
insert into temp values ('2/10/2012', 'DEF', 800.00) -- addded
insert into temp values ('3/1/2012', 'ABC', 1100.00)
The following examples show the varied execution statements showing the varied aggregates as a simple example. I did not opt to change the static, pivot, and value columns to keep the example simple. You should be able to just copy and paste the code to start messing with it yourself
exec [dbo].[USP_DYNAMIC_PIVOT] 'date','category','amount','dbo.temp','sum'
exec [dbo].[USP_DYNAMIC_PIVOT] 'date','category','amount','dbo.temp','max'
exec [dbo].[USP_DYNAMIC_PIVOT] 'date','category','amount','dbo.temp','avg'
exec [dbo].[USP_DYNAMIC_PIVOT] 'date','category','amount','dbo.temp','min'
This execution returns the following data sets respectively.
shape
is a property of both numpy ndarray's and matrices.
A.shape
will return a tuple (m, n), where m is the number of rows, and n is the number of columns.
In fact, the numpy matrix
object is built on top of the ndarray
object, one of numpy's two fundamental objects (along with a universal function object), so it inherits from ndarray
I have posted one small tutorial about integrating the FileBrowser available in old FCKEditor into CKEditor.
http://www.mixedwaves.com/2010/02/integrating-fckeditor-filemanager-in-ckeditor/
It contains step by step instructions for doing so and its pretty simple. I hope anybody in search of this will find this tutorial helpful.
SELECT DEPTNAME
FROM(SELECT D.DEPTNAME,COUNT(EMPID) AS TOTEMP
FROM DEPT AS D,EMPLOYEE AS E
WHERE D.DEPTID=E.DEPTID AND SALARY>1000
GROUP BY D.DEPTID
)
WHERE TOTEMP>2;
on the other side of the coin, you should use "non-char" regex that looks like this if special characters = allChars - number - ABC - space in your app context.
String regepx = "[^\\s\\w]*";
This code example that follows shows a basic UILabel
configuration.
let lbl = UILabel(frame: CGRectMake(0, 0, 300, 200))
lbl.text = "yourString"
// Enum type, two variations:
lbl.textAlignment = NSTextAlignment.Right
lbl.textAlignment = .Right
lbl.textColor = UIColor.red
lbl.shadowColor = UIColor.black
lbl.font = UIFont(name: "HelveticaNeue", size: CGFloat(22))
self.view.addSubview(lbl)
php_flag display_errors on
To turn the actual display of errors on.
To set the types of errors you are displaying, you will need to use:
php_value error_reporting <integer>
Combined with the integer values from this page: http://php.net/manual/en/errorfunc.constants.php
Note if you use -1 for your integer, it will show all errors, and be future proof when they add in new types of errors.
data-src attribute is part of the data-* attributes collection introduced in HTML5. data-src allow us to store extra data that have no meaning to the browser but that can be use by Javascript Code or CSS rules.
What you return from a program is just a convention.
No, I can't think of any circumstances where "EXIT_SUCCESS" wouldn't be "0".
Personally, I'd recommend "0".
IMHO...
I have created a module for anuglar2 autocomplete In this module you can use array, or url npm link : ang2-autocomplete
Do you want to insert one dictionary into the other, as one of its elements, or do you want to reference the values of one dictionary from the keys of another?
Previous answers have already covered the first case, where you are creating a dictionary within another dictionary.
To re-reference the values of one dictionary into another, you can use dict.update
:
>>> d1 = {1: [1]}
>>> d2 = {2: [2]}
>>> d1.update(d2)
>>> d1
{1: [1], 2: [2]}
A change to a value that's present in both dictionaries will be visible in both:
>>> d1[2].append('appended')
>>> d1
{1: [1], 2: [2, 'appended']}
>>> d2
{2: [2, 'appended']}
This is the same as copying the value over or making a new dictionary with it, i.e.
>>> d3 = {1: d1[1]}
>>> d3[1].append('appended from d3')
>>> d1[1]
[1, 'appended from d3']
This is really not a good idea, doing something like this would cause the entire page to freeze up while the system waited for your function to return.
Add a user option in msyql.
GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION;
and this link will be useful.
If it's not working why don't you try using jQuery's scrollTop method?
$("#id").scrollTop($("#id").scrollTop() + 100);
If you're looking to scroll smoothly you could use basic javascript setTimeout/setInterval function to make it scroll in increments of 1px over a set length of time.
You can use DISTINCT inside the COUNT like what milkovsky said
in my case:
select COUNT(distinct user_id) from answers_votes where answer_id in (694,695);
This will pull the count of answer votes considered the same user_id as one count
Try this query:
SELECT sysdate FROM schema_name.table_name;
This should display the timestamp that you might need.
I understand the ZooKeeper in general but had problems with the terms "quorum" and "split brain" so maybe I can share my findings with you (I consider myself also a layman).
Let's say we have a ZooKeeper cluster of 5 servers. One of the servers will become the leader and the others will become followers.
These 5 servers form a quorum. Quorum simply means "these servers can vote upon who should be the leader".
So the voting is based on majority. Majority simply means "more than half" so more than half of the number of servers must agree for a specific server to become the leader.
So there is this bad thing that may happen called "split brain". A split brain is simply this, as far as I understand: The cluster of 5 servers splits into two parts, or let's call it "server teams", with maybe one part of 2 and the other of 3 servers. This is really a bad situation as if both "server teams" must execute a specific order how would you decide wich team should be preferred? They might have received different information from the clients. So it is really important to know what "server team" is still relevant and which one can/should be ignored.
Majority is also the reason you should use an odd number of servers. If you have 4 servers and a split brain where 2 servers seperate then both "server teams" could say "hey, we want to decide who is the leader!" but how should you decide which 2 servers you should choose? With 5 servers it's simple: The server team with 3 servers has the majority and is allowed to select the new leader.
Even if you just have 3 servers and one of them fails the other 2 still form the majority and can agree that one of them will become the new leader.
I realize once you think about it some time and understand the terms it's not so complicated anymore. I hope this also helps anyone in understanding these terms.
Creating new DOM elements is a core feature of the jQuery()
method, see:
If the label
immediately follows a specified input
element:
input#example + label { ... }
input:checked + label { ... }
Alex made a great point on readability. Equivalently, a function is also interface enough to define the type(s) being returned and you also get meaningful variable names.
delegate void OpDelegate(int op);
Task<bool> GetDataTaskAsync(OpDelegate callback)
{
bool canGetData = true;
if (canGetData) callback(5);
return Task.FromResult(canGetData);
}
Callers provide a lambda (or a named function) and intellisense helps by copying the variable name(s) from the delegate.
int myOp;
bool result = await GetDataTaskAsync(op => myOp = op);
This particular approach is like a "Try" method where myOp
is set if the method result is true
. Otherwise, you don't care about myOp
.
You can use str_pad
for adding 0's
str_pad($month, 2, '0', STR_PAD_LEFT);
string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )
detach().detach()
not working after support library update 25.1.0 (may be earlier).
This solution works fine after update:
getSupportFragmentManager()
.beginTransaction()
.detach(oldFragment)
.commitNowAllowingStateLoss();
getSupportFragmentManager()
.beginTransaction()
.attach(oldFragment)
.commitAllowingStateLoss();
As per my Answer here: How to remove a directory from git repository?
Steps to remove directory
git rm -r --cached FolderName
git commit -m "Removed folder from repository"
git push origin master
Steps to ignore that folder in next commits
To ignore that folder from next commits make one file in root named .gitignore and put that folders name into it. You can put as many as you want
.gitignore file will be look like this
/FolderName
If you can define the parent's width and height, there's a simpler way to centralize the image without having to create a container for it.
For some reason, if you define the min-width, IE will recognize max-width as well.
This solution works for IE10+, Firefox and Chrome.
<div>
<img src="http://placehold.it/350x150"/>
</div>
div {
display: -ms-flexbox;
display: flex;
-ms-flex-pack: center;
justify-content: center;
-ms-flex-align: center;
align-items: center;
border: 1px solid orange;
width: 100px;
height: 100px;
}
img{
min-width: 10%;
max-width: 100%;
min-height: 10%;
max-height: 100%;
}
Method 1->Markdown way
![Alt Text](https://raw.github.com/{USERNAME}/{REPOSITORY}/{BRANCH}/{PATH})
Method 2->HTML way
<img src="https://link(format same as above)" width="100" height="100"/>
or
<img src="https://link" style=" width:100px ; height:100px " />
Note-> If you don't want to style your image i.e resize remove the style part
You can post axios data by using FormData() like:
var bodyFormData = new FormData();
And then add the fields to the form you want to send:
bodyFormData.append('userName', 'Fred');
If you are uploading images, you may want to use .append
bodyFormData.append('image', imageFile);
And then you can use axios post method (You can amend it accordingly)
axios({
method: "post",
url: "myurl",
data: bodyFormData,
headers: { "Content-Type": "multipart/form-data" },
})
.then(function (response) {
//handle success
console.log(response);
})
.catch(function (response) {
//handle error
console.log(response);
});
Related GitHub issue:
Can't get a .post with 'Content-Type': 'multipart/form-data' to work @ axios/axios
For Subversion 1.7 and above, the server doesn't provide a footer that indicates the server version. But you can run the following command to gain the version from the response headers
$ curl -s -D - http://svn.server.net/svn/repository
HTTP/1.1 401 Authorization Required
Date: Wed, 09 Jan 2013 03:01:43 GMT
Server: Apache/2.2.9 (Unix) DAV/2 SVN/1.7.4
Note that this also works on Subversion servers where you don't have authorization to access.
Yes, with set_index you can make Locality
your row index.
data.set_index('Locality', inplace=True)
If inplace=True
is not provided, set_index
returns the modified dataframe as a result.
Example:
> import pandas as pd
> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
['ABERFELDIE', 534000, 600000]],
columns=['Locality', 2005, 2006])
> df
Locality 2005 2006
0 ABBOTSFORD 427000 448000
1 ABERFELDIE 534000 600000
> df.set_index('Locality', inplace=True)
> df
2005 2006
Locality
ABBOTSFORD 427000 448000
ABERFELDIE 534000 600000
> df.loc['ABBOTSFORD']
2005 427000
2006 448000
Name: ABBOTSFORD, dtype: int64
> df.loc['ABBOTSFORD'][2005]
427000
> df.loc['ABBOTSFORD'].values
array([427000, 448000])
> df.loc['ABBOTSFORD'].tolist()
[427000, 448000]
Try the following script:
Exec sp_msforeachtable 'SET QUOTED_IDENTIFIER ON; ALTER INDEX ALL ON ? REBUILD'
GO
Also
I prefer(After a long search) to use the following script, it contains @fillfactor
determines how much percentage of the space on each leaf-level page is filled with data.
DECLARE @TableName VARCHAR(255)
DECLARE @sql NVARCHAR(500)
DECLARE @fillfactor INT
SET @fillfactor = 80
DECLARE TableCursor CURSOR FOR
SELECT QUOTENAME(OBJECT_SCHEMA_NAME([object_id]))+'.' + QUOTENAME(name) AS TableName
FROM sys.tables
OPEN TableCursor
FETCH NEXT FROM TableCursor INTO @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
SET @sql = 'ALTER INDEX ALL ON ' + @TableName + ' REBUILD WITH (FILLFACTOR = ' + CONVERT(VARCHAR(3),@fillfactor) + ')'
EXEC (@sql)
FETCH NEXT FROM TableCursor INTO @TableName
END
CLOSE TableCursor
DEALLOCATE TableCursor
GO
for more info, check the following link:
and if you want to Check Index Fragmentation on Indexes in a Database, try the following script:
SELECT dbschemas.[name] as 'Schema',
dbtables.[name] as 'Table',
dbindexes.[name] as 'Index',
indexstats.avg_fragmentation_in_percent,
indexstats.page_count
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS indexstats
INNER JOIN sys.tables dbtables on dbtables.[object_id] = indexstats.[object_id]
INNER JOIN sys.schemas dbschemas on dbtables.[schema_id] = dbschemas.[schema_id]
INNER JOIN sys.indexes AS dbindexes ON dbindexes.[object_id] = indexstats.[object_id]
AND indexstats.index_id = dbindexes.index_id
WHERE indexstats.database_id = DB_ID() AND dbtables.[name] like '%%'
ORDER BY indexstats.avg_fragmentation_in_percent desc
For more information, Check the following link:
FOR /r %%X IN (*) DO (ECHO %%X & DEL %%X)
I am a bit surprised that nobody seems to know that you're perfectly allowed to do:
<label>Put your stuff here: <input value="Stuff"></label>
Which won't get picked up by any of the suggested answers, but will label the input correctly.
Here's some code that does take this case into account:
$.fn.getLabels = function() {
return this.map(function() {
var labels = $(this).parents('label');
if (this.id) {
labels.add('label[for="' + this.id + '"]');
}
return labels.get();
});
};
Usage:
$('#myfancyinput').getLabels();
Some notes:
aria-labelledby
if you were to use that (left as an exercise to the reader).There are couple of ways to initialize the const members inside the class..
Definition of const member in general, needs initialization of the variable too..
1) Inside the class , if you want to initialize the const the syntax is like this
static const int a = 10; //at declaration
2) Second way can be
class A
{
static const int a; //declaration
};
const int A::a = 10; //defining the static member outside the class
3) Well if you don't want to initialize at declaration, then the other way is to through constructor, the variable needs to be initialized in the initialization list(not in the body of the constructor). It has to be like this
class A
{
const int b;
A(int c) : b(c) {} //const member initialized in initialization list
};
I'd factor out the prepared statement handling to at least a method. In this case, because there are no results it is fairly simple (and assuming that the connection is an instance variable that doesn't change):
private PreparedStatement updateSales;
public void updateSales(int sales, String cof_name) throws SQLException {
if (updateSales == null) {
updateSales = con.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
}
updateSales.setInt(1, sales);
updateSales.setString(2, cof_name);
updateSales.executeUpdate();
}
At that point, it is then just a matter of calling:
updateSales(75, "Colombian");
Which is pretty simple to integrate with other things, yes? And if you call the method many times, the update will only be constructed once and that will make things much faster. Well, assuming you don't do crazy things like doing each update in its own transaction...
Note that the types are fixed. This is because for any particular query/update, they should be fixed so as to allow the database to do its job efficiently. If you're just pulling arbitrary strings from a CSV file, pass them in as strings. There's also no locking; far better to keep individual connections to being used from a single thread instead.
If you want to delete any commit then you might need to use git rebase command
git rebase -i HEAD~2
it will show you last 2 commit messages, if you delete the commit message and save that file deleted commit will automatically disappear...
Here is a working connection string for someone who needs reference.
<connectionStrings>
<add name="IdentityConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\IdentityDb.mdf;Integrated Security=True;MultipleActiveResultSets=true;" providerName="System.Data.SqlClient" />
</connectionStrings>
At the time of writing this answer, there was no method to embed which let the user navigate inside folders and view the files without her leaving the website (the method in other answers, makes everything open in a new tab on google drive website), so I made my own tool for it. To embed a drive, paste the iframe code below in your HTML:
<iframe src="https://googledriveembedder.collegefam.com/?key=YOUR_API_KEY&folderid=FOLDER_ID_WHIHCH_IS_PUBLICLY_VIEWABLE" style="border:none;" width="100%"></iframe>
In the above code, you need to have your own API key and the folder ID. You can set the height as per your wish.
To get the API key:
1.) Go to https://console.developers.google.com/ Create a new project.
2.) From the menu button, go to 'APIs and Services' --> 'Dashboard' --> Click on 'Enable APIs and Services'.
3.) Search for 'Google Drive API', enable it. Then go to "credentials' tab, and create credentials. Keep your API key unrestricted.
4.) Copy the newly generated API key.
To get the folder ID:
1.)Go to the google drive folder you want to embed (for example, drive.google.com/drive/u/0/folders/1v7cGug_e3lNT0YjhvtYrwKV7dGY-Nyh5u [this is not a real folder]) Ensure that the folder is publicly shared and visible to anyone.
2.) Copy the part after 'folders/', this is your folder ID.
Now put both the API key and folder id in the above code and embed.
Note: To hide the download button for files, add '&allowdl=no' at the end of the iframe's src URL.
I made the widget keeping mobile users in mind, however it suits both mobile and desktop. If you run into issues, leave a comment here. I have attached some screenshots of the content of the iframe here.
Actually ngAfterViewInit()
will initiate only once when the component initiate.
If you really want a event triggers after the HTML element renter on the screen then you can use ngAfterViewChecked()
What about using the .click() function and the tag?
(Compressed version)
<a id="downloadtag" href="examplefolder/testfile.txt" hidden download></a>_x000D_
_x000D_
<button onclick="document.getElementById('downloadtag').click()">Download</button>
_x000D_
Now you can trigger it with js. It also doesn't open, as other examples, image and text files!
(js-function version)
function download(){_x000D_
document.getElementById('downloadtag').click();_x000D_
}
_x000D_
<!-- HTML -->_x000D_
<button onclick="download()">Download</button>_x000D_
<a id="downloadtag" href="coolimages/awsome.png" hidden download></a>
_x000D_
If you know the actual enum labels correlated to their values, you can use containers and C++17's std::string_view
to quickly access values and their string representations with the [
]
operator while tracking it yourself. std::string_view
will only allocate memory when created. They can also be designated with static constexpr
if you want them available at run-time for more performance savings. This little console app should be fairly fast.
#include <iostream>
#include <string_view>
#include <tuple>
int main() {
enum class Weekdays { //default behavior starts at 0 and iterates by 1 per entry
Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday
};
static constexpr std::string_view Monday = "Monday";
static constexpr std::string_view Tuesday = "Tuesday";
static constexpr std::string_view Wednesday = "Wednesday";
static constexpr std::string_view Thursday = "Thursday";
static constexpr std::string_view Friday = "Friday";
static constexpr std::string_view Saturday = "Saturday";
static constexpr std::string_view Sunday = "Sunday";
static constexpr std::string_view opener = "enum[";
static constexpr std::string_view closer = "] is ";
static constexpr std::string_view semi = ":";
std::pair<Weekdays, std::string_view> Weekdays_List[] = {
std::make_pair(Weekdays::Monday, Monday),
std::make_pair(Weekdays::Tuesday, Tuesday),
std::make_pair(Weekdays::Wednesday, Wednesday),
std::make_pair(Weekdays::Thursday, Thursday),
std::make_pair(Weekdays::Friday, Friday),
std::make_pair(Weekdays::Saturday, Saturday),
std::make_pair(Weekdays::Sunday, Sunday)
};
for (int i=0;i<sizeof(Weekdays_List)/sizeof(Weekdays_List[0]);i++) {
std::cout<<opener<<i<<closer<<Weekdays_List[(int)i].second<<semi\
<<(int)Weekdays_List[(int)i].first<<std::endl;
}
return 0;
}
Output:
enum[0] is Monday:0
enum[1] is Tuesday:1
enum[2] is Wednesday:2
enum[3] is Thursday:3
enum[4] is Friday:4
enum[5] is Saturday:5
enum[6] is Sunday:6
just use '!' before the pip command in spyder terminal and it will be fine
Eg:
!pip install imutils
I had the same issue, came to find out that the deployment to IIS did not set the connection strings correctly. they were '$(ReplacableToken_devConnection-Web.config Connection String_0)' when viewing the connection strings of the site in IIS, instead of the actual connection string. I updated them there, and all worked as expected
One point: you have to set NumberFormat property BEFORE loading the value into the cell. I had a nine digit number that still displayed as 9.14E+08 when the NumberFormat was set after the cell was loaded. Setting the property before loading the value made the number appear as I wanted, as straight text.
OR:
Could you try an autofit first:
Excel_Obj.Columns("A:V").EntireColumn.AutoFit
Write Thread.sleep(1000);
it will make the thread sleep for 1000ms
Using with hooks :
This answer would be helpful if your content dimension changes after loading.
onreadystatechange : Occurs when the load state of the data that belongs to an element or a HTML document changes. The onreadystatechange event is fired on a HTML document when the load state of the page's content has changed.
import {useState, useEffect, useRef} from 'react';
const ref = useRef();
useEffect(() => {
document.onreadystatechange = () => {
console.log(ref.current.clientHeight);
};
}, []);
I was trying to work with a youtube video player embedding whose dimensions may change after loading.
How about:
$timezone = new DateTimeZone('UTC');
$date = new DateTime('2011-04-21 13:14', $timezone);
echo $date->format;
So, you want to treat your .properties
file on the same folder as the main/runnable jar as a file rather than as a resource of the main/runnable jar. In that case, my own solution is as follows:
First thing first: your program file architecture shall be like this (assuming your main program is main.jar and its main properties file is main.properties):
./ - the root of your program
|__ main.jar
|__ main.properties
With this architecture, you can modify any property in the main.properties file using any text editor before or while your main.jar is running (depending on the current state of the program) since it is just a text-based file. For example, your main.properties file may contain:
app.version=1.0.0.0
app.name=Hello
So, when you run your main program from its root/base folder, normally you will run it like this:
java -jar ./main.jar
or, straight away:
java -jar main.jar
In your main.jar, you need to create a few utility methods for every property found in your main.properties file; let say the app.version
property will have getAppVersion()
method as follows:
/**
* Gets the app.version property value from
* the ./main.properties file of the base folder
*
* @return app.version string
* @throws IOException
*/
import java.util.Properties;
public static String getAppVersion() throws IOException{
String versionString = null;
//to load application's properties, we use this class
Properties mainProperties = new Properties();
FileInputStream file;
//the base folder is ./, the root of the main.properties file
String path = "./main.properties";
//load the file handle for main.properties
file = new FileInputStream(path);
//load all the properties from this file
mainProperties.load(file);
//we have loaded the properties, so close the file handle
file.close();
//retrieve the property we are intrested, the app.version
versionString = mainProperties.getProperty("app.version");
return versionString;
}
In any part of the main program that needs the app.version
value, we call its method as follows:
String version = null;
try{
version = getAppVersion();
}
catch (IOException ioe){
ioe.printStackTrace();
}
Bootswatch is a good alternative, but you can also find multiple types of free templates made for ASP.NET MVC that use MDBootstrap (a front-end framework built on top of Bootstrap) here:
since you only want values copied, you can pass the values of arr1 directly to arr2 and avoid copy/paste. code inside the loop:
Sheets("SheetB").Range(arr2(i) & firstrowDB).Resize(lastrow, 1).Value = .Range(.Cells(1, arr1(i)), .Cells(lastrow, arr1(i))).Value
The default display
property for a table is display:table;
. The only other useful value is inline-table
. All other display
values are invalid for table elements.
There isn't an auto
option to reset it to default, although if you're working in Javascript, you can set it to an empty string, which will do the trick.
width:auto;
is valid, but isn't the default. The default width for a table is 100%
, whereas width:auto;
will make the element only take up as much width as it needs to.
min-width:auto;
isn't allowed. If you set min-width
, it must have a value, but setting it to zero is probably as good as resetting it to default.
Please check your project/module language levels (Project Structure | Project; Project Structure | Modules | module-name | Sources). You might also want to take a look at Settings | Compiler | Java Compiler | Per-module bytecode version.
Set also this:
File -> Project Structure -> Modules :: Sources (next to Paths and Dependencies) and that has a "Language level" option which also needs to be set correctly.
bool b = list.Contains("Hello", StringComparer.CurrentCultureIgnoreCase);
[EDIT] extension code:
public static bool Contains(this string source, string cont
, StringComparison compare)
{
return source.IndexOf(cont, compare) >= 0;
}
This could work :)
I know it's an old question. but I faced this problem after updating to Android Studio 3.0
. I solved it by deleting app.iml
file inside my app module and then Invalidate Caches / Restart.
dt.Rows[1].ItemArray
gives you a copy of item arrays. When you modify it, you're not modifying the original.
You can simply do this:
dt.Rows[1][3] = "Value";
ItemArray property is used when you want to modify all row values.
ex.:
dt.Rows[1].ItemArray = newItemArray;
Start in the background:
./long_running_process options &
And disown the job before you log out:
disown
Although this is not a built in Unix solution, I've implemented a solution for this using a shell script that can be included in whatever shell script you are using. This is usable on POSIX compliant setups. (sh, bash, ksh, zsh) The full description is available in the github repo -> https://github.com/plyint/encpass.sh. This solution will auto-generate a key for your script and store the key and your password (or other secrets) in a hidden directory under your user (i.e. ~/.encpass).
In your script you just need to source encpass.sh and then call the get_secret method. For example:
#!/bin/sh
. encpass.sh
password=$(get_secret)
Pasted below is lite version of the code for encpass.sh(you can get the full version over on github) for easier visibility:
#!/bin/sh
################################################################################
# Copyright (c) 2020 Plyint, LLC <[email protected]>. All Rights Reserved.
# This file is licensed under the MIT License (MIT).
# Please see LICENSE.txt for more information.
#
# DESCRIPTION:
# This script allows a user to encrypt a password (or any other secret) at
# runtime and then use it, decrypted, within a script. This prevents shoulder
# surfing passwords and avoids storing the password in plain text, which could
# inadvertently be sent to or discovered by an individual at a later date.
#
# This script generates an AES 256 bit symmetric key for each script (or user-
# defined bucket) that stores secrets. This key will then be used to encrypt
# all secrets for that script or bucket. encpass.sh sets up a directory
# (.encpass) under the user's home directory where keys and secrets will be
# stored.
#
# For further details, see README.md or run "./encpass ?" from the command line.
#
################################################################################
encpass_checks() {
[ -n "$ENCPASS_CHECKS" ] && return
if [ -z "$ENCPASS_HOME_DIR" ]; then
ENCPASS_HOME_DIR="$HOME/.encpass"
fi
[ ! -d "$ENCPASS_HOME_DIR" ] && mkdir -m 700 "$ENCPASS_HOME_DIR"
if [ -f "$ENCPASS_HOME_DIR/.extension" ]; then
# Extension enabled, load it...
ENCPASS_EXTENSION="$(cat "$ENCPASS_HOME_DIR/.extension")"
ENCPASS_EXT_FILE="encpass-$ENCPASS_EXTENSION.sh"
if [ -f "./extensions/$ENCPASS_EXTENSION/$ENCPASS_EXT_FILE" ]; then
# shellcheck source=/dev/null
. "./extensions/$ENCPASS_EXTENSION/$ENCPASS_EXT_FILE"
elif [ ! -z "$(command -v encpass-"$ENCPASS_EXTENSION".sh)" ]; then
# shellcheck source=/dev/null
. "$(command -v encpass-$ENCPASS_EXTENSION.sh)"
else
encpass_die "Error: Extension $ENCPASS_EXTENSION could not be found."
fi
# Extension specific checks, mandatory function for extensions
encpass_"${ENCPASS_EXTENSION}"_checks
else
# Use default OpenSSL implementation
if [ ! -x "$(command -v openssl)" ]; then
echo "Error: OpenSSL is not installed or not accessible in the current path." \
"Please install it and try again." >&2
exit 1
fi
[ ! -d "$ENCPASS_HOME_DIR/keys" ] && mkdir -m 700 "$ENCPASS_HOME_DIR/keys"
[ ! -d "$ENCPASS_HOME_DIR/secrets" ] && mkdir -m 700 "$ENCPASS_HOME_DIR/secrets"
[ ! -d "$ENCPASS_HOME_DIR/exports" ] && mkdir -m 700 "$ENCPASS_HOME_DIR/exports"
fi
ENCPASS_CHECKS=1
}
# Checks if the enabled extension has implented the passed function and if so calls it
encpass_ext_func() {
[ ! -z "$ENCPASS_EXTENSION" ] && ENCPASS_EXT_FUNC="$(command -v "encpass_${ENCPASS_EXTENSION}_$1")" || return
[ ! -z "$ENCPASS_EXT_FUNC" ] && shift && $ENCPASS_EXT_FUNC "$@"
}
# Initializations performed when the script is included by another script
encpass_include_init() {
encpass_ext_func "include_init" "$@"
[ ! -z "$ENCPASS_EXT_FUNC" ] && return
if [ -n "$1" ] && [ -n "$2" ]; then
ENCPASS_BUCKET=$1
ENCPASS_SECRET_NAME=$2
elif [ -n "$1" ]; then
if [ -z "$ENCPASS_BUCKET" ]; then
ENCPASS_BUCKET=$(basename "$0")
fi
ENCPASS_SECRET_NAME=$1
else
ENCPASS_BUCKET=$(basename "$0")
ENCPASS_SECRET_NAME="password"
fi
}
encpass_generate_private_key() {
ENCPASS_KEY_DIR="$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET"
[ ! -d "$ENCPASS_KEY_DIR" ] && mkdir -m 700 "$ENCPASS_KEY_DIR"
if [ ! -f "$ENCPASS_KEY_DIR/private.key" ]; then
(umask 0377 && printf "%s" "$(openssl rand -hex 32)" >"$ENCPASS_KEY_DIR/private.key")
fi
}
encpass_set_private_key_abs_name() {
ENCPASS_PRIVATE_KEY_ABS_NAME="$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET/private.key"
[ ! -n "$1" ] && [ ! -f "$ENCPASS_PRIVATE_KEY_ABS_NAME" ] && encpass_generate_private_key
}
encpass_set_secret_abs_name() {
ENCPASS_SECRET_ABS_NAME="$ENCPASS_HOME_DIR/secrets/$ENCPASS_BUCKET/$ENCPASS_SECRET_NAME.enc"
[ ! -n "$1" ] && [ ! -f "$ENCPASS_SECRET_ABS_NAME" ] && set_secret
}
encpass_rmfifo() {
trap - EXIT
kill "$1" 2>/dev/null
rm -f "$2"
}
encpass_mkfifo() {
fifo="$ENCPASS_HOME_DIR/$1.$$"
mkfifo -m 600 "$fifo" || encpass_die "Error: unable to create named pipe"
printf '%s\n' "$fifo"
}
get_secret() {
encpass_checks
encpass_ext_func "get_secret" "$@"; [ ! -z "$ENCPASS_EXT_FUNC" ] && return
[ "$(basename "$0")" != "encpass.sh" ] && encpass_include_init "$1" "$2"
encpass_set_private_key_abs_name
encpass_set_secret_abs_name
encpass_decrypt_secret "$@"
}
set_secret() {
encpass_checks
encpass_ext_func "set_secret" "$@"; [ ! -z "$ENCPASS_EXT_FUNC" ] && return
if [ "$1" != "reuse" ] || { [ -z "$ENCPASS_SECRET_INPUT" ] && [ -z "$ENCPASS_CSECRET_INPUT" ]; }; then
echo "Enter $ENCPASS_SECRET_NAME:" >&2
stty -echo
read -r ENCPASS_SECRET_INPUT
stty echo
echo "Confirm $ENCPASS_SECRET_NAME:" >&2
stty -echo
read -r ENCPASS_CSECRET_INPUT
stty echo
# Use named pipe to securely pass secret to openssl
fifo="$(encpass_mkfifo set_secret_fifo)"
fi
if [ "$ENCPASS_SECRET_INPUT" = "$ENCPASS_CSECRET_INPUT" ]; then
encpass_set_private_key_abs_name
ENCPASS_SECRET_DIR="$ENCPASS_HOME_DIR/secrets/$ENCPASS_BUCKET"
[ ! -d "$ENCPASS_SECRET_DIR" ] && mkdir -m 700 "$ENCPASS_SECRET_DIR"
# Generate IV and create secret file
printf "%s" "$(openssl rand -hex 16)" > "$ENCPASS_SECRET_DIR/$ENCPASS_SECRET_NAME.enc"
ENCPASS_OPENSSL_IV="$(cat "$ENCPASS_SECRET_DIR/$ENCPASS_SECRET_NAME.enc")"
echo "$ENCPASS_SECRET_INPUT" > "$fifo" &
# Allow expansion now so PID is set
# shellcheck disable=SC2064
trap "encpass_rmfifo $! $fifo" EXIT HUP TERM INT TSTP
# Append encrypted secret to IV in the secret file
openssl enc -aes-256-cbc -e -a -iv "$ENCPASS_OPENSSL_IV" \
-K "$(cat "$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET/private.key")" \
-in "$fifo" 1>> "$ENCPASS_SECRET_DIR/$ENCPASS_SECRET_NAME.enc"
else
encpass_die "Error: secrets do not match. Please try again."
fi
}
encpass_decrypt_secret() {
encpass_ext_func "decrypt_secret" "$@"; [ ! -z "$ENCPASS_EXT_FUNC" ] && return
if [ -f "$ENCPASS_PRIVATE_KEY_ABS_NAME" ]; then
ENCPASS_DECRYPT_RESULT="$(dd if="$ENCPASS_SECRET_ABS_NAME" ibs=1 skip=32 2> /dev/null | openssl enc -aes-256-cbc \
-d -a -iv "$(head -c 32 "$ENCPASS_SECRET_ABS_NAME")" -K "$(cat "$ENCPASS_PRIVATE_KEY_ABS_NAME")" 2> /dev/null)"
if [ ! -z "$ENCPASS_DECRYPT_RESULT" ]; then
echo "$ENCPASS_DECRYPT_RESULT"
else
# If a failed unlock command occurred and the user tries to show the secret
# Present either a locked or failed decrypt error.
if [ -f "$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET/private.lock" ]; then
echo "**Locked**"
else
# The locked file wasn't present as expected. Let's display a failure
echo "Error: Failed to decrypt"
fi
fi
elif [ -f "$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET/private.lock" ]; then
echo "**Locked**"
else
echo "Error: Unable to decrypt. The key file \"$ENCPASS_PRIVATE_KEY_ABS_NAME\" is not present."
fi
}
encpass_die() {
echo "$@" >&2
exit 1
}
#LITE
According to the docker-compose reference,
Expose ports. Either specify both ports (HOST:CONTAINER), or just the container port (a random host port will be chosen).
My docker-compose.yml
looks like:
mysql:
image: mysql:5.7
ports:
- "3306"
If I do docker-compose ps
, it will look like:
Name Command State Ports
-------------------------------------------------------------------------------------
mysql_1 docker-entrypoint.sh mysqld Up 0.0.0.0:32769->3306/tcp
Expose ports without publishing them to the host machine - they’ll only be accessible to linked services. Only the internal port can be specified.
Ports are not exposed to host machines, only exposed to other services.
mysql:
image: mysql:5.7
expose:
- "3306"
If I do docker-compose ps
, it will look like:
Name Command State Ports
---------------------------------------------------------------
mysql_1 docker-entrypoint.sh mysqld Up 3306/tcp
In recent versions of Docker, expose
doesn't have any operational impact anymore, it is just informative. (see also)
I simply needed to update my project's dependencies and then restart the server.
Copy and paste this format yyyy-mm-dd hh:MM:ss in format cells by clicking customs category under Type
There is a good polyfill for that: louisremi/background-size-polyfill
To quote the documentation:
Upload backgroundsize.min.htc to your website, along with the .htaccess that will send the mime-type required by IE (Apache only — it's built in nginx, node and IIS).
Everywhere you use background-size in your CSS, add a reference to this file.
.selector { background-size: cover; /* The url is relative to the document, not to the css file! */ /* Prefer absolute urls to avoid confusion. */ -ms-behavior: url(/backgroundsize.min.htc); }
The current recommended way is with the flask
command line utility.
https://flask.palletsprojects.com/en/1.1.x/quickstart/#debug-mode
Example:
$ export FLASK_APP=main.py
$ export FLASK_ENV=development
$ flask run
or in one command:
$ FLASK_APP=main.py FLASK_ENV=development flask run
If you want different port than the default (5000
) add --port
option.
Example:
$ FLASK_APP=main.py FLASK_ENV=development flask run --port 8080
More options are available with:
$ flask run --help
FLASK_APP
can also be set to module:app
or module:create_app
instead of module.py
. See https://flask.palletsprojects.com/en/1.1.x/cli/#application-discovery for a full explanation.
You should initialize yours recordings. You are passing to adapter null
ArrayList<String> recordings = null; //You are passing this null
If I Understood correctly you need to view the .db file that you extracted from internal storage of Emulator. If that's the case use this
http://sourceforge.net/projects/sqlitebrowser/
to view the db.
You can also use a firefox extension
https://addons.mozilla.org/en-us/firefox/addon/sqlite-manager/
EDIT: For online tool use : https://sqliteonline.com/
You can do this type of checking with Flash or Silverlight but not Javascript. The javascript sandbox does not allow access to the file system. The size check would need to be done server side after it has been uploaded.
If you want to go the Silverlight/Flash route, you could check that if they are not installed to default to a regular file upload handler that uses the normal controls. This way, if the do have Silverlight/Flash installed their experience will be a bit more rich.
I was running into the same problem and after some trial and error discovered that my hosts
file customisation was causing the problem.
My localhost
DNS was overwritten and because of that a simple ping was failing:
$ ping http://localhost
# ping: cannot resolve http://localhost: Unknown host
Once I resolved the configuration of /private/etc/hosts
file, pinging localhost
successfully worked, and was no longer getting the error that you were seeing:
# Fatal error: getaddrinfo ENOTFOUND
You can use Perl::Tidy for Perl.
I Use data from another column to generate a "hash" or unique string
UPDATE table_name SET column_name = Right( MD5(another_column_with_data), 8 )
You can also create a tarball of what the image needs first and use that as your context.
https://docs.docker.com/engine/reference/commandline/build/#/tarball-contexts