To answer the title of the question (but not the question about the output you're getting):
Copying the following folder from your dev machine to your build server fixes this if it's just web applications
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\WebApplications
Remove x86 according to how your build breaks. If you have other project types you will probably need to copy the entire msbuild folder.
If you want only those commits which are done by you in a particular branch, use the below command.
git log branch_name --author='Dyaniyal'
We have one more option to do order by
public Cursor getlistbyrank(String rank) {
try {
//This can be used
return db.`query("tablename", null, null, null, null, null, rank +"DESC",null );
OR
return db.rawQuery("SELECT * FROM table order by rank", null);
} catch (SQLException sqle) {
Log.e("Exception on query:-", "" + sqle.getMessage());
return null;
}
}
You can use this two method for order
It might be a bit late but in order to understand what an immutable object is, consider the following example from the new Java 8 Date and Time API (java.time). As you probably know all date objects from Java 8 are immutable so in the following example
LocalDate date = LocalDate.of(2014, 3, 18);
date.plusYears(2);
System.out.println(date);
Output:
2014-03-18
This prints the same year as the initial date because the plusYears(2)
returns a new object so the old date is still unchanged because it's an immutable object. Once created you cannot further modify it and the date variable still points to it.
So, that code example should capture and use the new object instantiated and returned by that call to plusYears
.
LocalDate date = LocalDate.of(2014, 3, 18);
LocalDate dateAfterTwoYears = date.plusYears(2);
date.toString()… 2014-03-18
dateAfterTwoYears.toString()… 2016-03-18
Looking at the internets there can be various of causes. In my case leaving everything default except...
apc.shm_size = 64M
...cleared the countless warnings that I was getting earlier.
This will do it:
foreach($b as $value)
{
if(in_array("Irix", $value, true))
{
echo "Got Irix";
}
}
in_array
only operates on a one dimensional array, so you need to loop over each sub array and run in_array
on each.
As others have noted, this will only for for a 2-dimensional array. If you have more nested arrays, a recursive version would be better. See the other answers for examples of that.
in my case, datas
is an objects of Array for more information please Click Here
<% for(let [index,data] of datas.entries() || []){ %>
Index : <%=index%>
Data : <%=data%>
<%} %>
You can look up the constraint name in the sys.key_constraints table:
SELECT name
FROM sys.key_constraints
WHERE [type] = 'PK'
AND [parent_object_id] = Object_id('dbo.Student');
If you don't care about the name, but simply want to drop it, you can use a combination of this and dynamic sql:
DECLARE @table NVARCHAR(512), @sql NVARCHAR(MAX);
SELECT @table = N'dbo.Student';
SELECT @sql = 'ALTER TABLE ' + @table
+ ' DROP CONSTRAINT ' + name + ';'
FROM sys.key_constraints
WHERE [type] = 'PK'
AND [parent_object_id] = OBJECT_ID(@table);
EXEC sp_executeSQL @sql;
This code is from Aaron Bertrand (source).
I'd get a logic analyzer and wire it up to the serial port. I think there are probably only two lines you need (Tx/Rx), so there should be plenty of cheap logic analyzers available. You don't have a clock line handy though, so that could get tricky.
I know this is an old question, but I think found a very simple answer, in case anybody needs it.
If you put string quotes inside your string ("'hello'"), ast_literaleval() will understand it perfectly.
You can use a simple function:
def doubleStringify(a):
b = "\'" + a + "\'"
return b
Or probably more suitable for this example:
def perfectEval(anonstring):
try:
ev = ast.literal_eval(anonstring)
return ev
except ValueError:
corrected = "\'" + anonstring + "\'"
ev = ast.literal_eval(corrected)
return ev
I feel stupid in front of all this complicated answsers.
Why can't it be :
int random1_to_7()
{
return (random1_to_5() * 7) / 5;
}
?
To access the index in this case you access the name
attribute:
In [182]:
df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
def rowFunc(row):
return row['a'] + row['b'] * row['c']
def rowIndex(row):
return row.name
df['d'] = df.apply(rowFunc, axis=1)
df['rowIndex'] = df.apply(rowIndex, axis=1)
df
Out[182]:
a b c d rowIndex
0 1 2 3 7 0
1 4 5 6 34 1
Note that if this is really what you are trying to do that the following works and is much faster:
In [198]:
df['d'] = df['a'] + df['b'] * df['c']
df
Out[198]:
a b c d
0 1 2 3 7
1 4 5 6 34
In [199]:
%timeit df['a'] + df['b'] * df['c']
%timeit df.apply(rowIndex, axis=1)
10000 loops, best of 3: 163 µs per loop
1000 loops, best of 3: 286 µs per loop
EDIT
Looking at this question 3+ years later, you could just do:
In[15]:
df['d'],df['rowIndex'] = df['a'] + df['b'] * df['c'], df.index
df
Out[15]:
a b c d rowIndex
0 1 2 3 7 0
1 4 5 6 34 1
but assuming it isn't as trivial as this, whatever your rowFunc
is really doing, you should look to use the vectorised functions, and then use them against the df index:
In[16]:
df['newCol'] = df['a'] + df['b'] + df['c'] + df.index
df
Out[16]:
a b c d rowIndex newCol
0 1 2 3 7 0 6
1 4 5 6 34 1 16
I had this problem for several days, it turns out if I created the db inside phpMyAdmin it wouldn't appear to Laravel, so, I created the db through MySqlWorkbench, and it worked :)
This should do the trick retrieving the params from the url:
constructor(private activatedRoute: ActivatedRoute) {
this.activatedRoute.queryParams.subscribe(params => {
let date = params['startdate'];
console.log(date); // Print the parameter to the console.
});
}
The local variable date should now contain the startdate parameter from the URL. The modules Router and Params can be removed (if not used somewhere else in the class).
I have tried some solutions,but here is basic production snippet. Please, pay attention to console output during quality assurance of this snippet.
Mark Up :
<!DOCTYPE html>
<html ng-app="appUp">
<head>
<title>
Angular Select snippet
</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />
</head>
<body ng-controller="upController">
<div class="container">
<div class="row">
<div class="col-md-4">
</div>
<div class="col-md-3">
<div class="form-group">
<select name="slct" id="slct" class="form-control" ng-model="selBrand" ng-change="Changer(selBrand)" ng-options="brand as brand.name for brand in stock">
<option value="">
Select Brand
</option>
</select>
</div>
<div class="form-group">
<input type="hidden" name="delimiter" value=":" ng-model="delimiter" />
<input type="hidden" name="currency" value="$" ng-model="currency" />
<span>
{{selBrand.name}}{{delimiter}}{{selBrand.price}}{{currency}}
</span>
</div>
</div>
<div class="col-md-4">
</div>
</div>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js">
</script>
<script src="js/ui-bootstrap-tpls-2.5.0.min.js"></script>
<script src="js/main.js"></script>
</body>
</html>
Code:
var c = console;
var d = document;
var app = angular.module('appUp',[]).controller('upController',function($scope){
$scope.stock = [{
name:"Adidas",
price:420
},
{
name:"Nike",
price:327
},
{
name:"Clark",
price:725
}
];//data
$scope.Changer = function(){
if($scope.selBrand){
c.log("brand:"+$scope.selBrand.name+",price:"+$scope.selBrand.price);
$scope.currency = "$";
$scope.delimiter = ":";
}
else{
$scope.currency = "";
$scope.delimiter = "";
c.clear();
}
}; // onchange handler
});
Explanation: important point here is null check of the changed value, i.e. if value is 'undefined' or 'null' we should to handle this situation.
numpy.linspace()
gives you a one-dimensional NumPy array. For example:
>>> my_array = numpy.linspace(1, 10, 10)
>>> my_array
array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
Therefore:
for index,point in my_array
cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:
>>> two_d = numpy.array([[1, 2], [4, 5]])
>>> two_d
array([[1, 2], [4, 5]])
Now you can do this:
>>> for x, y in two_d:
print(x, y)
1 2
4 5
For having a Datagrid you must have a method which is formatting your Datagrid. If you want clear the Datagrid you just recall the method.
Here is my method:
public string[] dgv_Headers = new string[] { "Id","Hotel", "Lunch", "Dinner", "Excursions", "Guide", "Bus" }; // This defined at Public partial class
private void SetDgvHeader()
{
dgv.Rows.Clear();
dgv.ColumnCount = 7;
dgv.RowHeadersVisible = false;
int Nbr = int.Parse(daysBox.Text); // in my method it's the textbox where i keep the number of rows I have to use
dgv.Rows.Add(Nbr);
for(int i =0; i<Nbr;++i)
dgv.Rows[i].Height = 20;
for (int i = 0; i < dgv_Headers.Length; ++i)
{
if(i==0)
dgv.Columns[i].Visible = false; // I need an invisible cells if you don't need you can skip it
else
dgv.Columns[i].Width = 78;
dgv.Columns[i].HeaderText = dgv_Headers[i];
}
dgv.Height = (Nbr* dgv.Rows[0].Height) + 35;
dgv.AllowUserToAddRows = false;
}
dgv is the name of DataGridView
The problem is that you used the select option, this is where you went wrong. Select signifies that a textbox or textArea has a focus. What you need to do is use change. "Fires when a new choice is made in a select element", also used like blur when moving away from a textbox or textArea.
function start(){
document.getElementById("activitySelector").addEventListener("change", addActivityItem, false);
}
function addActivityItem(){
//option is selected
alert("yeah");
}
window.addEventListener("load", start, false);
table td{
color:#0000ff;
}
<table>
<tbody>
<tr>
<td>
<select name="test">
<option value="Basic">Basic : $30.00 USD - yearly</option>
<option value="Sustaining">Sustaining : $60.00 USD - yearly</option>
<option value="Supporting">Supporting : $120.00 USD - yearly</option>
</select>
</td>
</tr>
</tbody>
</table>
In your component i.e angular js code:
function getthefile (){
window.location.href='http://localhost:1036/CourseRegConfirm/getfile';
};
In addition, correct way to count total item number would be:
sum(len(x) for x in input)
The data type in the Job table (Varchar2(20)) does not match the data type in the USER table (NUMBER NOT NULL).
What about just assigning a class to your widget and then binding that class to the JQuery datepicker?
Django forms.py:
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['my_date_field'].widget.attrs['class'] = 'datepicker'
And some JavaScript for the template:
$(".datepicker").datepicker();
I found the following approach to be the most effective for sampling a DataFrame:
print(df[A:B]) ## 'A' and 'B' are the first and last records in range
For example, print(df[10:15])
will print rows 10 through 15 - inclusive - from your data set.
// creation
cv::SimpleBlobDetector * blob_detector;
blob_detector = new SimpleBlobDetector();
blob_detector->create("SimpleBlobDetector");
// change params - first move it to public!!
blob_detector->params.filterByArea = true;
blob_detector->params.minArea = 1;
blob_detector->params.maxArea = 32000;
// or read / write them with file
FileStorage fs("test_fs.yml", FileStorage::WRITE);
FileNode fn = fs["features"];
//blob_detector->read(fn);
// detect
vector<KeyPoint> keypoints;
blob_detector->detect(img_text, keypoints);
fs.release();
I do know why, but params are protected. So I moved it in file features2d.hpp to be public:
virtual void read( const FileNode& fn );
virtual void write( FileStorage& fs ) const;
public:
Params params;
protected:
struct CV_EXPORTS Center
{
Point2d loc
If you will not do this, the only way to change params is to create file (FileStorage fs("test_fs.yml", FileStorage::WRITE);
), than open it in notepad, and edit. Or maybe there is another way, but I`m not aware of it.
Index the list then the dict.
print L[1]['d']
You may do as follows. one line of code will be enough
let array = $('ul>li').toArray().map(item => $(item).html());
Get the interested element
get children
get the array from toArray() method
filter out the results you want
let array = $('ul>li').toArray().map(item => $(item).html());_x000D_
console.log(array);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<ul>_x000D_
<li>text1</li>_x000D_
<li>text2</li>_x000D_
<li>text3</li>_x000D_
</ul>
_x000D_
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.
To print the content of Root store:
certutil -store Root
To output content to a file:
certutil -store Root > root_content.txt
To add certificate to Root store:
certutil -addstore -enterprise Root file.cer
var myNewString = myOldString.replace(/'/g, "\\'");
The reason #2 fails is because sys.modules['module']
does not exist (the import routine has its own scope, and cannot see the module
local name), and there's no module
module or package on-disk. Note that you can separate multiple imported names by commas.
from package.subpackage.module import attribute1, attribute2, attribute3
Also:
from package.subpackage import module
print module.attribute1
If you are executing using gradle wrapper, you can run the command with JDK path like following
./gradlew -Dorg.gradle.java.home=/jdk_path_directory
Now the following wont help you with files that are already cached, but moving forward, you can use the following to easily force a request to get something new, without changing the actual filename.
# Rewrite all requests for JS and CSS files to files of the same name, without
# any numbers in them. This lets the JS and CSS be force out of cache easily
# by putting a number at the end of the filename
# e.g. a request for static/js/site-52.js will get the file static/js/site.js instead.
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^static/(js|css)/([a-z]+)-([0-9]+)\.(js|css)$ /site/$1/$2.$4 [R=302,NC,L]
</IfModule>
Of course, the higher up in your folder structure you do this type of approach, the more you kick things out of cache with a simple change.
So for example, if you store the entire css and javascript of your site in one main folder
/assets/js
/assets/css
/assets/...
Then you can could start referencing it as "assets-XXX" in your html, and use a rule like so to kick all assets content out of cache.
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^assets-([a-z0-9]+)/(.*) /$2 [R=302,NC,L]
</IfModule>
Note that if you do go with this, after you have it working, change the 302 to a 301, and then caching will kick in. When it's a 302 it wont cache at the browser level because it's a temporary redirect. If you do it this way, then you could bump up the expiry default time to 30 days for all assets, since you can easily kick things out of cache by simply changing the folder name in the login page.
<IfModule mod_expires.c>
ExpiresActive on
ExpiresDefault A2592000
</IfModule>
As of yet there are no parent selectors (or as Shaun Inman calls them, qualified selectors), so you will have to apply styles to the child list items to override the styles on the parent list items.
Cascading is sort of the whole point of Cascading Style Sheets, hence the name.
Do as below create class and call it like this
Check : Reset all Controls (Textbox, ComboBox, CheckBox, ListBox) in a Windows Form using C#
private void button1_Click(object sender, EventArgs e)
{
Utilities.ResetAllControls(this);
}
public class Utilities
{
public static void ResetAllControls(Control form)
{
foreach (Control control in form.Controls)
{
if (control is TextBox)
{
TextBox textBox = (TextBox)control;
textBox.Text = null;
}
if (control is ComboBox)
{
ComboBox comboBox = (ComboBox)control;
if (comboBox.Items.Count > 0)
comboBox.SelectedIndex = 0;
}
if (control is CheckBox)
{
CheckBox checkBox = (CheckBox)control;
checkBox.Checked = false;
}
if (control is ListBox)
{
ListBox listBox = (ListBox)control;
listBox.ClearSelected();
}
}
}
}
remove the .git
folder in your project root folder
if you installed submodules and want to remove their git, also remove .git
from submodules folders
I'm not sure if this is the most pythonic method ... I had a list of tuples that needed sorting 1st by descending integer values and 2nd alphabetically. This required reversing the integer sort but not the alphabetical sort. Here was my solution: (on the fly in an exam btw, I was not even aware you could 'nest' sorted functions)
a = [('Al', 2),('Bill', 1),('Carol', 2), ('Abel', 3), ('Zeke', 2), ('Chris', 1)]
b = sorted(sorted(a, key = lambda x : x[0]), key = lambda x : x[1], reverse = True)
print(b)
[('Abel', 3), ('Al', 2), ('Carol', 2), ('Zeke', 2), ('Bill', 1), ('Chris', 1)]
This is not possible now, but there is a work around. You can engage with the user in the public realm and ask them to send you private messages, but you can't send private messages back, only public ones. Of course, this all depends on if the user gives you the correct permissions.
If you have given permission to access a person's friends, you can then theoretically post on that users wall with references to each one of the friends, asking them to publicly interact with you and then potentially privately message you.
Get Friends
#if authenticated
https://graph.facebook.com/me/friends
http://developers.facebook.com/docs/reference/api/user/
Post in the Public Domain
http://developers.facebook.com/docs/reference/api/status/
Get Messages sent to that user (if given permission)
http://developers.facebook.com/docs/reference/api/message/
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class form_city : System.Web.UI.Page
{
connection con = new connection();
DataTable dtable;
string status = "";
protected void Page_Load(object sender, EventArgs e)
{
TextBoxWatermarkExtender1.WatermarkText = "Enter State Name !";
if (!IsPostBack)
{
status = "Active";
fillgrid();
Session.Add("ope", "Listing");
}
}
protected void fillgrid()
{
//Session.Add("ope", "Listing");
string query = "select *";
query += "from State_Detail where Status='" + status + "'";
dtable = con.sqlSelect(query);
grdList.DataSource = dtable;
grdList.DataBind();
lbtnBack.Visible = false;
}
protected void grdList_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grdList.PageIndex = e.NewPageIndex;
string operation = Session["ope"].ToString();
if (operation == "ViewLog")
status = "Inactive";
else if (operation == "Listing")
status = "Active";
fillgrid();
}
public string GetImage(string status)
{
if (status == "Active")
return "~/images/green_acti.png";
else
return "~/images/red_acti.png";
}
protected void grdList_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string st = "Inactive";
int State_Id = Convert.ToInt32(grdList.DataKeys[e.RowIndex].Values[0]);
string query = "update State_Detail set Status='" + st + "'";
query += " where State_Id=" + State_Id;
con.sqlInsUpdDel(query);
status = "Active";
fillgrid();
}
protected void grdList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("Select"))
{
string query = "select * ";
query += "from State_Detail where State_Id=" + e.CommandArgument;
dtable = con.sqlSelect(query);
grdList.DataSource = dtable;
grdList.DataBind();
lbtnBack.Visible = true;
}
}
protected void ibtnSearch_Click(object sender, ImageClickEventArgs e)
{
Session.Add("ope", "Listing");
if (txtDepId.Text != "")
{
string query = "select * from State_Detail where State_Name like '" + txtDepId.Text + "%'";
dtable = con.sqlSelect(query);
grdList.DataSource = dtable;
grdList.DataBind();
txtDepId.Text = "";
}
}
protected void grdList_RowEditing(object sender, GridViewEditEventArgs e)
{
int State_Id = Convert.ToInt32(grdList.DataKeys[e.NewEditIndex].Values[0]);
Session.Add("ope", "Edit");
Session.Add("State_Id", State_Id);
Response.Redirect("form_state.aspx");
}
protected void grdList_Sorting(object sender, GridViewSortEventArgs e)
{
string operation = Session["ope"].ToString();
if (operation == "ViewLog")
status = "Inactive";
else if (operation == "Listing")
status = "Active";
string query = "select * from State_Detail";
query += " where Status='" + status + "'";
dtable = con.sqlSelect(query);
DataView dview = new DataView(dtable);
dview.Sort = e.SortExpression + " asc";
grdList.DataSource = dview;
grdList.DataBind();
}
}
<asp:Image ID="imgGreenAct" ImageUrl='<%# GetImage(Convert.ToString(DataBinder.Eval(Container.DataItem, "Status")))%>' AlternateText='<%# Bind("Status") %>' runat="server" />
Here's an alternate solution, without using dblink
.
Suppose B represents the source database and A represents the target database: Then,
Copy table from source DB to target DB:
pg_dump -t <source_table> <source_db> | psql <target_db>
Open psql prompt, connect to target_db, and use a simple insert
:
psql
# \c <target_db>;
# INSERT INTO <target_table>(id, x, y) SELECT id, x, y FROM <source_table>;
At the end, delete the copy of source_table that you created in target_table.
# DROP TABLE <source_table>;
eclipse\configuration\
"config.ini"
Modify the line
osgi.instance.area.default="F:/Workspace/Java"
where "F:/Workspace/Java"
should be your default workspace!
If you want to increase your heap space, you can use java -Xms<initial heap size> -Xmx<maximum heap size>
on the command line. By default, the values are based on the JRE version and system configuration. You can find out more about the VM options on the Java website.
However, I would recommend profiling your application to find out why your heap size is being eaten. NetBeans has a very good profiler included with it. I believe it uses the jvisualvm
under the hood. With a profiler, you can try to find where many objects are being created, when objects get garbage collected, and more.
I was getting this error with my Nexus 10. I tried all of the answers I could find, and then I realized I was using a different USB port than usual. I switched to using the port I usually use, which is on the other side of my laptop, and the authorization popped up on my tablet!
You can also use the undocumented sp_MSforeachtable stored procedure as such if you are looking to do this for every table:
sp_MSforeachtable @command1 ="PRINT 'TABLE NAME: ' + '?' DECLARE @RowCount INT SET @RowCount = (SELECT COUNT(*) FROM ?) PRINT @RowCount"
Fortunately there is a little bit in the docs about the splash images, which put me on the road to getting the right location for the icon images as well. So here it goes.
Where the files are placed
Once you have built your project using command-line interface "cordova build ios" you should have a complete file structure for your iOS app in the platforms/ios/
folder.
Inside that folder is a folder with the name of your app. Which in turn contains a resources/
directory where you will find the icons/
and splashscreen/
folders.
In the icons folder you will find four icon files (for 57px and 72 px, each in regular and @2x version). These are the Phonegap placeholder icons you've been seeing so far.
What to do
All you have to do is save the icon files in this folder. So that's:
YourPhonegapProject/Platforms/ios/YourAppName/Resources/icons
Same for splashscreen files.
Notes
After placing the files there, rebuild the project using cordova build ios
AND use xCode's 'Clean product' menu command. Without this, you'll still be seeing the Phonegap placeholders.
It's wisest to rename your files the iOS/Apple way (i.e. [email protected] etc) instead of editing the names in the info.plist or config.xml. At least that worked for me.
And by the way, ignore the weird path and the weird filename given for the icons in config.xml (i.e. <icon gap:platform="ios" height="114" src="res/icon/ios/icon-57-2x.png" width="114" />
). I just left those definitions there, and the icons showed up just fine even though my 114px icon was named [email protected]
instead of icon-57-2x.png
.
Don't use config.xml to prevent Apple's gloss effect on the icon. Instead, tick the box in xCode (click the project title in the left navigation column, select your app under the Target header, and scroll down to the icons section).
Here's a quicker way than multi-layer menus without resorting to plug-ins:
Use the Quick Access tool at the upper left corner.
Type in "font", then, from the list that drops down, click on the link for "Preferences->Colors and Fonts->General->Appearance".
One click replaces the 4 needed to get there through menus. I do it so often, my Quick Access tool pulls it up as a previous choice right at the top of the list so I can just type "font" with a tap on the enter key and Boom!, I'm there.
If you want a keyboard shortcut, Ctrl+3 sets the focus to the Quick Access tool. Better yet, this even automatically brings up a list with your previous choices. The last one you chose will be on top, in which case a simple Ctrl+3 followed by enter would bring you straight there! I use this all the time to make it bigger during long typing or reading sessions to ease eye strain, or to make it smaller if I need more text on the screen at one time to make it easier to find something.
It's not quite as nice as zooming with the scroll wheel, but it's a lot better than navigating through the menus every time!
Use "E"
See the section on Date and Time Patterns:
I wrote a little tool for that. Perhaps it's useful to somebody. It works without jQuery.
https://github.com/schickling/calculate-size
Usage:
var size = calculateSize("Hello world!", {
font: 'Arial',
fontSize: '12px'
});
console.log(size.width); // 65
console.log(size.height); // 14
Fiddle: http://jsfiddle.net/PEvL8/
Hi heres a javascript version which changes the background image src according to screen resolution. You have to have the different images saved in the right size.
<html>
<head>
<title>Javascript Change Div Background Image</title>
<style type="text/css">
body {
margin:0;
width:100%;
height:100%;
}
#div1 {
background-image:url('sky.jpg');
width:100%
height:100%
}
p {
font-family:Verdana;
font-weight:bold;
font-size:11px;
}
</style>
<script language="javascript" type="text/javascript">
function changeDivImage()
{
//change the image path to a string
var imgPath = new String();
imgPath = document.getElementById("div1").style.backgroundImage;
//get screen res of customer
var custHeight=screen.height;
var custWidth=screen.width;
//if their screen width is less than or equal to 640 then use the 640 pic url
if (custWidth <= 640)
{
document.getElementById("div1").style.backgroundImage = "url(640x480.jpg)";
}
else if (custWidth <= 800)
{
document.getElementById("div1").style.backgroundImage = "url(800x600.jpg)";
}
else if (custWidth <= 1024)
{
document.getElementById("div1").style.backgroundImage = "url(1024x768.jpg)";
}
else if (custWidth <= 1280)
{
document.getElementById("div1").style.backgroundImage = "url(1280x960.jpg)";
}
else if (custWidth <= 1600)
{
document.getElementById("div1").style.backgroundImage = "url(1600x1200.jpg)";
}
else {
document.getElementById("div1").style.backgroundImage = "url(graffiti.jpg)";
}
/*if(imgPath == "url(sky.jpg)" || imgPath == "")
{
document.getElementById("div1").style.backgroundImage = "url(graffiti.jpg)";
}
else
{
document.getElementById("div1").style.backgroundImage = "url(sky.jpg)";
}*/
}
</script>
</head>
<body onload="changeDivImage()">
<div id="div1">
<p>This Javascript Example will change the background image of<br />HTML Div Tag onload using javascript screen resolution.</p>
<p>paragraph</p>
</div>
<br/>
</body>
</html>
If you get the error even after following the above step. then try below.
Since it is a node script. I am using the below option to create as of now.
node C:\Users\Administrator\AppData\Roaming\npm\node_modules\angular-cli\bin\ng version
May be symbolic links are required. Not researched further.
On Further Research: Set Path as : %PATH%;C:\Users\Administrator\AppData\Roaming\npm;
In Windows, npm.cmd file is in the above path. If the above Environment variable is set, you can execute as ng version ng init
"When programming with C# you don’t usually need to worry about the underlying target platform. There are however a few cases when the Application and OS architecture can affect program logic, change functionality and cause unexpected exceptions."
"It is common misconception that selecting a specific target will result in the compiler generating platform specific code. This is not the case and instead it simply sets a flag in the assembly’s CLR header. This information can be easily extracted, and modified, using Microsoft’s CoreFlags tool"
https://medium.com/@trapdoorlabs/c-target-platforms-x64-vs-x86-vs-anycpu-5f0c3be6c9e2
Using PDO:[1]
$in = join(',', array_fill(0, count($ids), '?'));
$select = <<<SQL
SELECT *
FROM galleries
WHERE id IN ($in);
SQL;
$statement = $pdo->prepare($select);
$statement->execute($ids);
Using MySQLi [2]
$in = join(',', array_fill(0, count($ids), '?'));
$select = <<<SQL
SELECT *
FROM galleries
WHERE id IN ($in);
SQL;
$statement = $mysqli->prepare($select);
$statement->bind_param(str_repeat('i', count($ids)), ...$ids);
$statement->execute();
$result = $statement->get_result();
Explanation:
IN()
operator to check if a value exists in a given list.In general it looks like this:
expr IN (value,...)
We can build an expression to place inside the ()
from our array. Note that there must be at least one value inside the parenthesis or MySQL will return an error; this equates to making sure that our input array has at least one value. To help prevent against SQL injection attacks, first generate a ?
for each input item to create a parameterized query. Here I assume that the array containing your ids is called $ids
:
$in = join(',', array_fill(0, count($ids), '?'));
$select = <<<SQL
SELECT *
FROM galleries
WHERE id IN ($in);
SQL;
Given an input array of three items $select
will look like:
SELECT *
FROM galleries
WHERE id IN (?, ?, ?)
Again note that there is a ?
for each item in the input array. Then we'll use PDO or MySQLi to prepare and execute the query as noted above.
IN()
operator with stringsIt is easy to change between strings and integers because of the bound parameters. For PDO there is no change required; for MySQLi change str_repeat('i',
to str_repeat('s',
if you need to check strings.
[1]: I've omitted some error checking for brevity. You need to check for the usual errors for each database method (or set your DB driver to throw exceptions).
[2]: Requires PHP 5.6 or higher. Again I've omitted some error checking for brevity.
In case you already have d3.js as a dependency in your project, or don't mind bringing it in, d3-time (d3.js library is modular as of v4.0.0) has got Intervals.
They might prove useful when setting dates to "default" values, e.g. midnight, 0.00 seconds, the first of the month, etc.
var d = new Date(); // Wed Aug 02 2017 15:01:07 GMT+0200 (CEST)
d3.timeHour(d) // Wed Aug 02 2017 00:00:00 GMT+0200 (CEST)
d3.timeMonth(d) // Tue Aug 01 2017 00:00:00 GMT+0200 (CEST)
Tested with: log4j-ap 2.13.2, log4j-core 2.13.2.
<build> <resources> <resource> <filtering>false</filtering> <directory>src/main/resources</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> </build>
I am using angular 5 and you can simply check the status property of your form using FormGroup e.g.
this.form = new FormGroup({
firstName: new FormControl('', [Validators.required, validateName]),
lastName: new FormControl('', [Validators.required, validateName]),
email: new FormControl('', [Validators.required, validateEmail]),
dob: new FormControl('', [Validators.required, validateDate])
});
this.form.status would be "INVALID" unless all the fields pass all the validation rules.
The best part is that it detects changes in real-time.
This is what i had written to parse file and set it as env variables which skips comments and non key value lines added switches to specify hg:d
and specify properties file that needs to be parsed eg : python EnvParamSet.py -c # -s = env.properties
import pipes
import sys , getopt
import os.path
class Parsing :
def __init__(self , seprator , commentChar , propFile):
self.seprator = seprator
self.commentChar = commentChar
self.propFile = propFile
def parseProp(self):
prop = open(self.propFile,'rU')
for line in prop :
if line.startswith(self.commentChar)==False and line.find(self.seprator) != -1 :
keyValue = line.split(self.seprator)
key = keyValue[0].strip()
value = keyValue[1].strip()
print("export %s=%s" % (str (key),pipes.quote(str(value))))
class EnvParamSet:
def main (argv):
seprator = '='
comment = '#'
if len(argv) is 0:
print "Please Specify properties file to be parsed "
sys.exit()
propFile=argv[-1]
try :
opts, args = getopt.getopt(argv, "hs:c:f:", ["help", "seprator=","comment=", "file="])
except getopt.GetoptError,e:
print str(e)
print " possible arguments -s <key value sperator > -c < comment char > <file> \n Try -h or --help "
sys.exit(2)
if os.path.isfile(args[0])==False:
print "File doesnt exist "
sys.exit()
for opt , arg in opts :
if opt in ("-h" , "--help"):
print " hg:d \n -h or --help print usage summary \n -c Specify char that idetifes comment \n -s Sperator between key and value in prop file \n specify file "
sys.exit()
elif opt in ("-s" , "--seprator"):
seprator = arg
elif opt in ("-c" , "--comment"):
comment = arg
p = Parsing( seprator, comment , propFile)
p.parseProp()
if __name__ == "__main__":
main(sys.argv[1:])
As DanielaWaranie mentioned in her answer - there is a way to specify the type of $item when you iterating over $items in $collectionObject: Add @return MyEntitiesClassName
to current()
and rest of the Iterator
and ArrayAccess
-methods which return values.
Boom! No need in /** @var SomeObj[] $collectionObj */
over foreach
, and works right with collection object, no need to return collection with specific method described as @return SomeObj[]
.
I suspect not all IDE support it but it works perfectly fine in PhpStorm, which makes me happier.
Example:
class MyCollection implements Countable, Iterator, ArrayAccess {
/**
* @return User
*/
public function current() {
return $this->items[$this->cursor];
}
//... implement rest of the required `interface` methods and your custom
}
In my case current()
and rest of interface
-methods are implemented in Abstract
-collection class and I do not know what kind of entities will eventually be stored in collection.
So here is the trick: Do not specify return type in abstract class, instead use PhpDoc instuction @method
in description of specific collection class.
Example:
class User {
function printLogin() {
echo $this->login;
}
}
abstract class MyCollection implements Countable, Iterator, ArrayAccess {
protected $items = [];
public function current() {
return $this->items[$this->cursor];
}
//... implement rest of the required `interface` methods and your custom
//... abstract methods which will be shared among child-classes
}
/**
* @method User current()
* ...rest of methods (for ArrayAccess) if needed
*/
class UserCollection extends MyCollection {
function add(User $user) {
$this->items[] = $user;
}
// User collection specific methods...
}
Now, usage of classes:
$collection = new UserCollection();
$collection->add(new User(1));
$collection->add(new User(2));
$collection->add(new User(3));
foreach ($collection as $user) {
// IDE should `recognize` method `printLogin()` here!
$user->printLogin();
}
Once again: I suspect not all IDE support it, but PhpStorm does. Try yours, post in comment the results!
Appending data to an existing array is a natural thing to want to do for anyone with python experience. However, if you find yourself regularly appending to large arrays, you'll quickly discover that NumPy doesn't easily or efficiently do this the way a python list
will. You'll find that every "append" action requires re-allocation of the array memory and short-term doubling of memory requirements. So, the more general solution to the problem is to try to allocate arrays to be as large as the final output of your algorithm. Then perform all your operations on sub-sets (slices) of that array. Array creation and destruction should ideally be minimized.
That said, It's often unavoidable and the functions that do this are:
for 2-D arrays:
for 3-D arrays (the above plus):
for N-D arrays:
One thing I noticed is that neither of the top two methods have any notion of what color the first row should be in a group; the group will just start with the opposite color from the last line of the previous group. I wanted my groups to always start with the same color...the first row of each group should always be white, and the next row colored.
The basic concept was to reset the toggle when each group starts, so I added a bit of code:
Private bOddRow As Boolean
'*************************************************************************
' -- Display green-bar type color banding in detail rows
' -- Call from BackGroundColor property of all detail row textboxes
' -- Set Toggle True for first item, False for others.
'*************************************************************************
Function AlternateColor(ByVal OddColor As String, _
ByVal EvenColor As String, ByVal Toggle As Boolean) As String
If Toggle Then bOddRow = Not bOddRow
If bOddRow Then
Return OddColor
Else
Return EvenColor
End If
End Function
'
Function RestartColor(ByVal OddColor As String) As String
bOddRow = True
Return OddColor
End Function
So I have three different kinds of cell backgrounds now:
This works for me. If you want the grouping row to be non-colored, or a different color, it should be fairly obvious from this how to change it around.
Please feel free to add comments about what could be done to improve this code: I'm brand new to both SSRS and VB, so I strongly suspect that there's plenty of room for improvement, but the basic idea seems sound (and it was useful for me) so I wanted to throw it out here.
If you have multiple references to a particular variable i.e. User or IdentityFile, the first entry in the ssh config file always takes precedence, if you want something specific then put it in first, anything generic put it at the bottom.
There is a similar question Extract main domain name from a given url. If you take a look at this answer , you will see that it is very easy. You just need to use java.net.URL
and String
utility - Split
This works for me: $('#profile1').attr('onclick')
You can open the preferences (multiple options):
Tools
-> Preferences
And depending on the Spyder version you can change the interpreter in the Python interpreter
section (Spyder 3.x):
or in the advanced Console
section (Spyder 2.x):
As stated on http://en.wikipedia.org/wiki/Logarithm:
logb(x) = logk(x) / logk(b)
Which means that:
log2(x) = log10(x) / log10(2)
You can also check if any process is using this file and show a list of programs you must close to continue like an installer does.
public static string GetFileProcessName(string filePath)
{
Process[] procs = Process.GetProcesses();
string fileName = Path.GetFileName(filePath);
foreach (Process proc in procs)
{
if (proc.MainWindowHandle != new IntPtr(0) && !proc.HasExited)
{
ProcessModule[] arr = new ProcessModule[proc.Modules.Count];
foreach (ProcessModule pm in proc.Modules)
{
if (pm.ModuleName == fileName)
return proc.ProcessName;
}
}
}
return null;
}
I recommend you use:
var returnedData = JSON.parse(data);
to convert the JSON string (if it is just text) to a JavaScript object.
Give the relative path URL value to the pom.xml file
../parentfoldername/pom.xml
update table_name set (col1,col2,col3) values(col1,col2,col);
Is not standard SQL and not working you got to use this as Gordon Linoff said:
update table
set col1 = expr1,
col2 = expr2,
. . .
coln = exprn
where some condition
I came across this issue, however my inline function was withing an angularJS view. Therefore on the load i could not access the inline script to add the debug, as only the index.html was available in the sources tab of the debugger.
This meant that when i was opening the particular view with my inline (had no choice on this) it was not accessible.
The onlly way i was able to hit it was to put an erroneous function or call inside the inline JS function.
My solution included :
function doMyInline(data) {
//Throw my undefined error here.
$("select.Sel").debug();
//This is the real onclick i was passing to
angular.element(document.getElementById(data.id)).scope().doblablabla(data.id);
}
This mean when i clicked on my button, i was then prompted in the chrome consolse.
Uncaught TypeError: undefined is not a function
The important thing here was the source of this : VM5658:6
clicking on this allowed me to step through the inline and hold the break point there for later..
Extremely convoluted way of reaching it.. But it worked and might prove useful for when dealing with Single page apps which dynamically load your views.
The VM[n]
has no significant value, and the n
on equates to the script ID. This info can be found here : Chrome "[VM]"
You can also define an environment variable that is visible only within Eclipse.
Go to Run -> Run Configurations... and Select tab "Environment".
There you can add several environment variables that will be specific to your application.
The phpqrcode library is really fast to configure and the API documentation is easy to understand.
In addition to abaumg's answer I have attached 2 examples in PHP
from http://phpqrcode.sourceforge.net/examples/index.php
1. QR code encoder
first include the library from your local path
include('../qrlib.php');
then to output the image directly as PNG stream do for example:
QRcode::png('your texte here...');
to save the result locally as a PNG image:
$tempDir = EXAMPLE_TMP_SERVERPATH;
$codeContents = 'your message here...';
$fileName = 'qrcode_name.png';
$pngAbsoluteFilePath = $tempDir.$fileName;
$urlRelativeFilePath = EXAMPLE_TMP_URLRELPATH.$fileName;
QRcode::png($codeContents, $pngAbsoluteFilePath);
2. QR code decoder
See also the zxing decoder:
http://zxing.org/w/decode.jspx
Pretty useful to check the output.
3. List of Data format
A list of data format you can use in your QR code according to the data type :
http://
)change to
buildToolsVersion "23.0.2" in app gradle file.
File SongsTableSeeder.php should be in database/seeds directory or in its subdirectory.
You need to run:
composer dump-autoload
and then:
php artisan db:seed
or:
php artisan db:seed --class=SongsTableSeeder
I think this is the easiest way for multy selection/update/insert/delete. You can run as many update/insert/delete as u want after select (you have to make a select first(a dummy if needed)) with executeUpdate(str) (just use new int(count1,count2,...)) and if u need a new selection close 'statement' and 'connection' and make new for next select. Like example:
String str1 = "select * from users";
String str9 = "INSERT INTO `port`(device_id, potition, port_type, di_p_pt) VALUE ('"+value1+"', '"+value2+"', '"+value3+"', '"+value4+"')";
String str2 = "Select port_id from port where device_id = '"+value1+"' and potition = '"+value2+"' and port_type = '"+value3+"' ";
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
theConnection=(Connection) DriverManager.getConnection(dbURL,dbuser,dbpassword);
theStatement = theConnection.prepareStatement(str1);
ResultSet theResult = theStatement.executeQuery();
int count8 = theStatement.executeUpdate(str9);
theStatement.close();
theConnection.close();
theConnection=DriverManager.getConnection(dbURL,dbuser,dbpassword);
theStatement = theConnection.prepareStatement(str2);
theResult = theStatement.executeQuery();
ArrayList<Port> portList = new ArrayList<Port>();
while (theResult.next()) {
Port port = new Port();
port.setPort_id(theResult.getInt("port_id"));
portList.add(port);
}
I hope it helps
String methodName =Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println("methodName = " + methodName);
one of the other tool (besides file) you can use is xdg-mime
eg xdg-mime query filetype <file>
if you have yum,
yum install xdg-utils.noarch
An example comparison of xdg-mime and file on a Subrip(subtitles) file
$ xdg-mime query filetype subtitles.srt
application/x-subrip
$ file --mime-type subtitles.srt
subtitles.srt: text/plain
in the above file only show it as plain text.
pd.unique
returns the unique values from an input array, or DataFrame column or index.
The input to this function needs to be one-dimensional, so multiple columns will need to be combined. The simplest way is to select the columns you want and then view the values in a flattened NumPy array. The whole operation looks like this:
>>> pd.unique(df[['Col1', 'Col2']].values.ravel('K'))
array(['Bob', 'Joe', 'Bill', 'Mary', 'Steve'], dtype=object)
Note that ravel()
is an array method that returns a view (if possible) of a multidimensional array. The argument 'K'
tells the method to flatten the array in the order the elements are stored in the memory (pandas typically stores underlying arrays in Fortran-contiguous order; columns before rows). This can be significantly faster than using the method's default 'C' order.
An alternative way is to select the columns and pass them to np.unique
:
>>> np.unique(df[['Col1', 'Col2']].values)
array(['Bill', 'Bob', 'Joe', 'Mary', 'Steve'], dtype=object)
There is no need to use ravel()
here as the method handles multidimensional arrays. Even so, this is likely to be slower than pd.unique
as it uses a sort-based algorithm rather than a hashtable to identify unique values.
The difference in speed is significant for larger DataFrames (especially if there are only a handful of unique values):
>>> df1 = pd.concat([df]*100000, ignore_index=True) # DataFrame with 500000 rows
>>> %timeit np.unique(df1[['Col1', 'Col2']].values)
1 loop, best of 3: 1.12 s per loop
>>> %timeit pd.unique(df1[['Col1', 'Col2']].values.ravel('K'))
10 loops, best of 3: 38.9 ms per loop
>>> %timeit pd.unique(df1[['Col1', 'Col2']].values.ravel()) # ravel using C order
10 loops, best of 3: 49.9 ms per loop
Also make sense to provide Boost version: This will modify original strings.
#include <boost/algorithm/string.hpp>
string str1 = "hello world!!!";
string str2 = "HELLO";
boost::algorithm::to_lower(str1)
boost::algorithm::to_lower(str2)
if (str1.find(str2) != std::string::npos)
{
// str1 contains str2
}
or using perfect boost xpression library
#include <boost/xpressive/xpressive.hpp>
using namespace boost::xpressive;
....
std::string long_string( "very LonG string" );
std::string word("long");
smatch what;
sregex re = sregex::compile(word, boost::xpressive::icase);
if( regex_match( long_string, what, re ) )
{
cout << word << " found!" << endl;
}
In this example you should pay attention that your search word don't have any regex special characters.
How about a list?
mystring.split(",")
It might help if you could explain what kind of info we are looking at. Maybe some background info also?
EDIT:
I had a thought you might want the info in groups of two?
then try:
re.split(r"\d*,\d*", mystring)
and also if you want them into tuples
[(pair[0], pair[1]) for match in re.split(r"\d*,\d*", mystring) for pair in match.split(",")]
in a more readable form:
mylist = []
for match in re.split(r"\d*,\d*", mystring):
for pair in match.split(",")
mylist.append((pair[0], pair[1]))
If you are using SQL Server 2005+, then you can use the PIVOT
function to transform the data from rows into columns.
It sounds like you will need to use dynamic sql if the weeks are unknown but it is easier to see the correct code using a hard-coded version initially.
First up, here are some quick table definitions and data for use:
CREATE TABLE #yt
(
[Store] int,
[Week] int,
[xCount] int
);
INSERT INTO #yt
(
[Store],
[Week], [xCount]
)
VALUES
(102, 1, 96),
(101, 1, 138),
(105, 1, 37),
(109, 1, 59),
(101, 2, 282),
(102, 2, 212),
(105, 2, 78),
(109, 2, 97),
(105, 3, 60),
(102, 3, 123),
(101, 3, 220),
(109, 3, 87);
If your values are known, then you will hard-code the query:
select *
from
(
select store, week, xCount
from yt
) src
pivot
(
sum(xcount)
for week in ([1], [2], [3])
) piv;
See SQL Demo
Then if you need to generate the week number dynamically, your code will be:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(Week)
from yt
group by Week
order by Week
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT store,' + @cols + ' from
(
select store, week, xCount
from yt
) x
pivot
(
sum(xCount)
for week in (' + @cols + ')
) p '
execute(@query);
See SQL Demo.
The dynamic version, generates the list of week
numbers that should be converted to columns. Both give the same result:
| STORE | 1 | 2 | 3 |
---------------------------
| 101 | 138 | 282 | 220 |
| 102 | 96 | 212 | 123 |
| 105 | 37 | 78 | 60 |
| 109 | 59 | 97 | 87 |
Side Note:
Starting at rails 5.0.0
rake
has been changed to rails
So perform the following
rails db:migrate VERSION=0
I was uninstalled compass 1.0.1 and install compass 0.12.7, this fix problem for me
$ sudo gem uninstall compass
$ sudo gem install compass -v 0.12.7
Perhaps they would have been satisfied with a knowledge of memalign? And as Jonathan Leffler points out, there are two newer preferable functions to know about.
Oops, florin beat me to it. However, if you read the man page I linked to, you'll most likely understand the example supplied by an earlier poster.
Convert your document to utf8. LaTeX just reads your text as it is. If you want to use the utf8 input encoding, your document has to be encoded in utf8. This can usually be set by the editor. There is also the program iconv
that is useful for converting files from iso encodings to utf.
In the end, you'll have to use an editor that is capable of supporting utf. (I have no idea about the status of utf support on windows, but any reasonable editor on linux should be fine).
select column_name, data_type, character_maximum_length
from information_schema.columns
where table_name = 'myTable'
You can use this function.
import org.apache.commons.lang.StringUtils;
public static double roundToDecimals(double number, int c)
{
String rightPad = StringUtils.rightPad("1", c+1, "0");
int decimalPoint = Integer.parseInt(rightPad);
number = Math.round(number * decimalPoint);
return number/decimalPoint;
}
In the nav go View => Layout => Columns:2
(alt+shift+2
) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py
)
It appears you can also reopen the file using the command File -> New View into File
which will open the current file in a new tab
Taken from Scott Hanselman's Blog:
public static bool IsNumeric(object expression)
{
if (expression == null)
return false;
double number;
return Double.TryParse( Convert.ToString( expression
, CultureInfo.InvariantCulture)
, System.Globalization.NumberStyles.Any
, NumberFormatInfo.InvariantInfo
, out number);
}
Another option: when cell type is unknown at compile time and cell is formatted as Date Range.Value
returns a desired DateTime
object.
public static DateTime? GetAsDateTimeOrDefault(Range cell)
{
object cellValue = cell.Value;
if (cellValue is DateTime result)
{
return result;
}
return null;
}
Here is the simple explanation of Redux over Flux. Redux does not have a dispatcher.It relies on pure functions called reducers. It does not need a dispatcher. Each actions are handled by one or more reducers to update the single store. Since data is immutable, reducers returns a new updated state that updates the store
For more information Flux vs Redux
You mean you want to add a new row and only put data in a certain column? Try the following:
var row = dataTable.NewRow();
row[myColumn].Value = "my new value";
dataTable.Add(row);
As it is a data table, though, there will always be data of some kind in every column. It just might be DBNull.Value
instead of whatever data type you imagine it would be.
Just ask it for the objectForKey:@"b"
. If it returns nil
, no object is set at that key.
if ([xyz objectForKey:@"b"]) {
NSLog(@"There's an object set for key @\"b\"!");
} else {
NSLog(@"No object set for key @\"b\"");
}
Edit: As to your edited second question, it's simply NSUInteger mCount = [xyz count];
. Both of these answers are documented well and easily found in the NSDictionary class reference ([1] [2]).
First make sure you have the runat="server"
attribute in your textarea
tag like this
<textarea id="TextArea1" cols="20" rows="2" runat="server"></textarea>
Then you can access the content via:
string body = TextArea1.value;
For Linux Run this command
date -d '06/12/2012 07:21:22' +"%s"
For mac OSX run this command
date -j -u -f "%a %b %d %T %Z %Y" "Tue Sep 28 19:35:15 EDT 2010" "+%s"
The guide by Ani Menon (thx!) almost worked for me on windows 10, i just had to get a newer winutils.exe off that git (currently hadoop-2.8.1): https://github.com/steveloughran/winutils
I'm not so comfortable with regular expressions, and my example results from a datetimepicker field formatted m/d/Y h:mA. In this legal example, you have to arrive before the actual deposition hearing. I use replace function to clean up the dates so that I can process them as Date objects and compare them.
function compareDateTimes() {
//date format ex "04/20/2017 01:30PM"
//the problem is that this format results in Invalid Date
//var d0 = new Date("04/20/2017 01:30PM"); => Invalid Date
var start_date = $(".letter #depo_arrival_time").val();
var end_date = $(".letter #depo_dateandtime").val();
if (start_date=="" || end_date=="") {
return;
}
//break it up for processing
var d1 = stringToDate(start_date);
var d2 = stringToDate(end_date);
var diff = d2.getTime() - d1.getTime();
if (diff < 0) {
end_date = moment(d2).format("MM/DD/YYYY hh:mA");
$(".letter #depo_arrival_time").val(end_date);
}
}
function stringToDate(the_date) {
var arrDate = the_date.split(" ");
var the_date = arrDate[0];
var the_time = arrDate[1];
var arrTime = the_time.split(":");
var blnPM = (arrTime[1].indexOf("PM") > -1);
//first fix the hour
if (blnPM) {
if (arrTime[0].indexOf("0")==0) {
var clean_hour = arrTime[0].substr(1,1);
arrTime[0] = Number(clean_hour) + 12;
}
arrTime[1] = arrTime[1].replace("PM", ":00");
} else {
arrTime[1] = arrTime[1].replace("AM", ":00");
}
var date_object = new Date(the_date);
//now replace the time
date_object = String(date_object).replace("00:00:00", arrTime.join(":"));
date_object = new Date(date_object);
return date_object;
}
Access is a great multi-user database. It has lots of built in features to handle the multi-user situation. In fact, it is so very popular because it is such a great multi-user database. There is an upper limit on how many users can all use the database at the same time doing updates and edits - depending on how knowledgeable the developer is about access and how the database has been designed - anywhere from 20 users to approx 50 users. Some access databases can be built to handle up to 50 concurrent users, while many others can handle 20 or 25 concurrent users updating the database. These figures have been observed for databases that have been in use for several or more years and have been discussed many times on the access newsgroups.
In addition to this solution (https://stackoverflow.com/a/3727813/5218712) just want to add that it should work only if listView.getChildCount() == yourDataList.size();
There could be additional view inside ListView.
.nav ul li a#nav-ask{
display:none;
}
Just tried this rule, and it worked with GoDaddy hosting since they've already have the Microsoft URL Rewriting module installed for every IIS 7 account.
<rewrite>
<rules>
<rule name="enquiry" stopProcessing="true">
<match url="^enquiry$" />
<action type="Rewrite" url="/Enquiry.aspx" />
</rule>
</rules>
</rewrite>
You can do it this way in python3:
print(a,b,end=" ")
For Windows10 Pro, Following steps fix the issue. select properties check the Unblock program option. run the installer, run the command CMD with Admin rights. At command promp run composer --version
to make sure it is globally installed. you should be able to now run composer require drush/drush
This is for drush dependency using composer.
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py
create hello.py
then write the following function as its content:
def helloworld():
print "hello"
Then you can import hello
:
>>> import hello
>>> hello.helloworld()
'hello'
>>>
To group many .py
files put them in a folder. Any folder with an __init__.py
is considered a module by python and you can call them a package
|-HelloModule
|_ __init__.py
|_ hellomodule.py
You can go about with the import statement on your module the usual way.
For more information, see 6.4. Packages.
r+
is the canonical mode for reading and writing at the same time. This is not different from using the fopen()
system call since file()
/ open()
is just a tiny wrapper around this operating system call.
[Updated to adapt to modern pandas
, which has isnull
as a method of DataFrame
s..]
You can use isnull
and any
to build a boolean Series and use that to index into your frame:
>>> df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)])
>>> df.isnull()
0 1 2
0 False False False
1 False True False
2 False False True
3 False False False
4 False False False
>>> df.isnull().any(axis=1)
0 False
1 True
2 True
3 False
4 False
dtype: bool
>>> df[df.isnull().any(axis=1)]
0 1 2
1 0 NaN 0
2 0 0 NaN
[For older pandas
:]
You could use the function isnull
instead of the method:
In [56]: df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)])
In [57]: df
Out[57]:
0 1 2
0 0 1 2
1 0 NaN 0
2 0 0 NaN
3 0 1 2
4 0 1 2
In [58]: pd.isnull(df)
Out[58]:
0 1 2
0 False False False
1 False True False
2 False False True
3 False False False
4 False False False
In [59]: pd.isnull(df).any(axis=1)
Out[59]:
0 False
1 True
2 True
3 False
4 False
leading to the rather compact:
In [60]: df[pd.isnull(df).any(axis=1)]
Out[60]:
0 1 2
1 0 NaN 0
2 0 0 NaN
To create a Java project: create a new project directory, jump into it and execute
gradle init --type java-library
Source folders and a Gradle build file (including a wrapper) will be build.
I have this method, I call it the Derp method for lack of a better name.
while (str.indexOf(" ") !== -1) {
str = str.replace(/ /g, " ");
}
My project was using pipenv
. The following command worked for me:
pipenv install mysql-connector-python
It looks like you're trying to scale the background image? There's a great article in the reference bellow where you can use css3 to achieve this.
And if I miss-read the question then I humbly accept the votes down. (Still good to know though)
Please consider the following code:
#some_div_or_body {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
This will work on all major browsers, of course it doesn't come easy on IE. There are some workarounds however such as using Microsoft's filters:
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";
There are some alternatives that can be used with a little bit peace of mind by using jQuery:
HTML
<img src="images/bg.jpg" id="bg" alt="">
CSS
#bg { position: fixed; top: 0; left: 0; }
.bgwidth { width: 100%; }
.bgheight { height: 100%; }
jQuery:
$(window).load(function() {
var theWindow = $(window),
$bg = $("#bg"),
aspectRatio = $bg.width() / $bg.height();
function resizeBg() {
if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
$bg
.removeClass()
.addClass('bgheight');
} else {
$bg
.removeClass()
.addClass('bgwidth');
}
}
theWindow.resize(resizeBg).trigger("resize");
});
I hope this helps!
In PHP:
$data = "<html>....";
exit(json_encode($data));
Then you should use AJAX to retrieve the data and do what you want with it. I suggest using JQuery: http://api.jquery.com/jQuery.getJSON/
I have a mac but would assume all linux are the same for this part...
In my case I got this:
2018-12-03 11:13:27 - Start server:
2018-12-03 11:13:27 - Server start done.
2018-12-03 11:13:27 - Checking server status...
2018-12-03 11:13:27 - Trying to connect to MySQL...
2018-12-03 11:13:27 - Lost connection to MySQL server at 'reading authorization packet', system error: 0 (2013)
2018-12-03 11:13:27 - Assuming server is not running
I ran this:
sudo killall mysqld
And then started the mysql again through mysqlworkbench although in your case it might be like this:
mysql.server start
*sidenote: I tried running mysql.server stop
and got this Shutting down MySQL
.... SUCCESS!
but after running ps aux | grep mysql
I saw that it hasn't really shut down...
You can do this with map()
var arrOfObj = [{_x000D_
name: 'eve'_x000D_
}, {_x000D_
name: 'john'_x000D_
}, {_x000D_
name: 'jane'_x000D_
}];_x000D_
_x000D_
var result = arrOfObj.map(function(o) {_x000D_
o.isActive = true;_x000D_
return o;_x000D_
})_x000D_
_x000D_
console.log(result)
_x000D_
If you want to keep original array you can clone objects with Object.assign()
var arrOfObj = [{_x000D_
name: 'eve'_x000D_
}, {_x000D_
name: 'john'_x000D_
}, {_x000D_
name: 'jane'_x000D_
}];_x000D_
_x000D_
var result = arrOfObj.map(function(el) {_x000D_
var o = Object.assign({}, el);_x000D_
o.isActive = true;_x000D_
return o;_x000D_
})_x000D_
_x000D_
console.log(arrOfObj);_x000D_
console.log(result);
_x000D_
I have been successfull at impersonating users in another domain, but only with a trust set up between the 2 domains.
var token = IntPtr.Zero;
var result = LogonUser(userID, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token);
if (result)
{
return WindowsIdentity.Impersonate(token);
}
If you identify a page that takes time to load, use SharePoint's Developer Dashboard to see which component takes time.
Are you sure that you want "055" as opposed to "55"? Some programs interpret a leading zero as meaning octal, so that it would read 055 as (decimal) 45 instead of (decimal) 55.
That should just mean dropping the '0' (zero-fill) flag.
e.g., change System.out.printf("%03d ", x);
to the simpler System.out.printf("%3d ", x);
The Application settings of an Android project's properties in Visual Studio 2017 (15.8.5) has them combined:
does this example help ?
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
using (StreamWriter output = new StreamWriter("practice.txt"))
{
// Create and write a string containing the symbol for Pi.
string srcString = "Area = \u03A0r^2";
// Convert the UTF-16 encoded source string to UTF-8 and ASCII.
byte[] utf8String = Encoding.UTF8.GetBytes(srcString);
byte[] asciiString = Encoding.ASCII.GetBytes(srcString);
// Write the UTF-8 and ASCII encoded byte arrays.
output.WriteLine("UTF-8 Bytes: {0}", BitConverter.ToString(utf8String));
output.WriteLine("ASCII Bytes: {0}", BitConverter.ToString(asciiString));
// Convert UTF-8 and ASCII encoded bytes back to UTF-16 encoded
// string and write.
output.WriteLine("UTF-8 Text : {0}", Encoding.UTF8.GetString(utf8String));
output.WriteLine("ASCII Text : {0}", Encoding.ASCII.GetString(asciiString));
Console.WriteLine(Encoding.UTF8.GetString(utf8String));
Console.WriteLine(Encoding.ASCII.GetString(asciiString));
}
}
}
After upgrading lots of packages (Spyder
3 to 4, Keras
and Tensorflow
and lots of their dependencies), I had the same problem today! I cannot figure out what happened; but the (conda-based) virtual environment that kept using Spyder
3 did not have the problem. Although installing tkinter
or changing the backend, via matplotlib.use('TkAgg)
as shown above, or this nice post on how to change the backend, might well resolve the problem, I don't see these as rigid solutions. For me, uninstalling matplotlib
and reinstalling it was magic and the problem was solved.
pip uninstall matplotlib
... then, install
pip install matplotlib
From all the above, this could be a package management problem, and BTW, I use both conda
and pip
, whenever feasible.
I had this error and I found that the name of one of my connection strings was wrong. Check the names as well as the actual string.
As far as I know Angular-cli file can't be created via a command like Package-lock file, If you want to create it, you have to do it manually.
You can type ng new to create a new angular project
Locate its .angular-cli.json file
Copy all its content
Create a folder in your original project, and name it .angular-cli.json
Paste what copied from new project in newly created angular cli file of original project.
Locate this line in angular cli file you created, and change the name field to original project's name. You can find the project name in package.json file
project": { "name": "<name of the project>" },
However, in newer angular version now it uses angular.json instead of angular-cli.json.
This may or may not be helpful but on Windows you can read the console log using Event Tracing for Windows
http://msdn.microsoft.com/en-us/library/ms751538.aspx
Our integration tests are run in .NET so I use this method to add the console log to our test output. I've made a sample console project to demonstrate here: https://github.com/jkells/chrome-trace
--enable-logging --v=1 doesn't seem to work on the latest version of Chrome.
AppBar
If you use AppBar
then updating status bar color is as simple as this:
Scaffold(
appBar: AppBar(
// Use [Brightness.light] for black status bar
// or [Brightness.dark] for white status bar
// https://stackoverflow.com/a/58132007/1321917
brightness: Brightness.light
),
body: ...
)
To apply for all app bars:
return MaterialApp(
theme: Theme.of(context).copyWith(
appBarTheme: Theme.of(context)
.appBarTheme
.copyWith(brightness: Brightness.light),
...
),
AppBar
Wrap your content with AnnotatedRegion
and set value
to SystemUiOverlayStyle.light
or SystemUiOverlayStyle.dark
:
return AnnotatedRegion<SystemUiOverlayStyle>(
// Use [SystemUiOverlayStyle.light] for white status bar
// or [SystemUiOverlayStyle.dark] for black status bar
// https://stackoverflow.com/a/58132007/1321917
value: SystemUiOverlayStyle.light,
child: Scaffold(...),
);
It's also important to put
table-layout:fixed;
Onto the containing table, so it operates well in IE9 (if your utilize max-width) as well.
Java has a method for this, "convertStringArrayToIntArray".
String numbers = sc.nextLine();
int[] intArray = convertStringArrayToIntArray(numbers.split(", "));
A worthy note for readability/maintainability:
You can keep the JSONDeserializer::
qualifier with the definition in your implementation file (*.cpp).
As long as your in-class declaration (as mentioned by others) does not have the qualifier, g++/gcc will play nice.
For example:
In myFile.h:
class JSONDeserializer
{
Value ParseValue(TDR type, const json_string& valueString);
};
And in myFile.cpp:
Value JSONDeserializer::ParseValue(TDR type, const json_string& valueString)
{
do_something(type, valueString);
}
When myFile.cpp implements methods from many classes, it helps to know who belongs to who, just by looking at the definition.
... I don't know if you're using an activex button or not, but when I insert an activex button into sheet1 in Excel called CommandButton1, the following code works fine:
Sub test()
Sheets(1).CommandButton1.Enabled = False
End Sub
Hope this helps...
An idempotent operation can be repeated an arbitrary number of times and the result will be the same as if it had been done only once. In arithmetic, adding zero to a number is idempotent.
Idempotence is talked about a lot in the context of "RESTful" web services. REST seeks to maximally leverage HTTP to give programs access to web content, and is usually set in contrast to SOAP-based web services, which just tunnel remote procedure call style services inside HTTP requests and responses.
REST organizes a web application into "resources" (like a Twitter user, or a Flickr image) and then uses the HTTP verbs of POST, PUT, GET, and DELETE to create, update, read, and delete those resources.
Idempotence plays an important role in REST. If you GET a representation of a REST resource (eg, GET a jpeg image from Flickr), and the operation fails, you can just repeat the GET again and again until the operation succeeds. To the web service, it doesn't matter how many times the image is gotten. Likewise, if you use a RESTful web service to update your Twitter account information, you can PUT the new information as many times as it takes in order to get confirmation from the web service. PUT-ing it a thousand times is the same as PUT-ing it once. Similarly DELETE-ing a REST resource a thousand times is the same as deleting it once. Idempotence thus makes it a lot easier to construct a web service that's resilient to communication errors.
Further reading: RESTful Web Services, by Richardson and Ruby (idempotence is discussed on page 103-104), and Roy Fielding's PhD dissertation on REST. Fielding was one of the authors of HTTP 1.1, RFC-2616, which talks about idempotence in section 9.1.2.
Syntax errors is not checked easily in external servers, just runtime errors.
What I do? Just like you, I use
ini_set('display_errors', 'On');
error_reporting(E_ALL);
However, before run I check syntax errors in a PHP file using an online PHP syntax checker.
The best, IMHO is PHP Code Checker
I copy all the source code, paste inside the main box and click the Analyze
button.
It is not the most practical method, but the 2 procedures are complementary and it solves the problem completely
The default PostgreSQL port is 5432
. The host that the database is operating on should have been provided by your hosting provider; I'd guess it would be the same host as the web server if one wasn't specified. Typically this would be configured as localhost, assuming your web server and database server are on the same host.
alert($("#form_id").serialize());
As others have hinted, you should consider dumping org.json's library. It's pretty much obsolete these days, and trying to work around its problems is waste of time.
But to specific question; type variable T just does not have any information to help you, as it is little more than compile-time information. Instead you need to pass actual class (as 'Class cls' argument), and you can then create an instance with 'cls.newInstance()'.
I don't know that regex would handle something like that very well. Try something like this
line = line.Trim();
if(line.StartsWith("for") && line.EndsWith(";")){
//your code here
}
If you find the onCreateOptionsMenu(Menu menu, MenuInflater inflater)
method is not being invoked, make sure you call the following from the Fragment's onCreate(Bundle savedInstanceState)
method:
setHasOptionsMenu(true)
Here is an example using PREPARE statements. You still can't use ?
, but you can use $n
notation:
PREPARE foo(integer) AS
SELECT *
FROM somewhere
WHERE something = $1;
EXECUTE foo(5);
DEALLOCATE foo;
Editing hostconfig.json seems to not working now. It only ends with that port being exposed but not published to host. Commiting and recreating containers is not the best approach to me. No one mentioned docker network
?
The best solution would be using reversed proxy within the same network
Create a new network if your previous container not in any named ones.
docker network create my_network
Join your existing container to the created network
docker network connect my_network my_existing_container
Start a reversed proxy service(e.g. nginx) publishing the ports you need, joining the same network
docker run -d --name nginx --network my_network -p 9000:9000 nginx
Optionally remove the default.conf in nginx
docker exec nginx rm /etc/nginx/conf.d/default.conf
Create a new nginx config
server
{
listen 9000;
location / {
proxy_pass http://my_existing_container:9000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
Copy the config to nginx container.
docker cp ./my_conf.conf nginx:/etc/nginx/conf.d/my_conf.conf
Restart nginx
docker restart nginx
Advantages: To publish new ports, you can safely stop/update/recreate nginx container as you wish without touching the business container. If you need zero down time for nginx, it is possible to add more reversed proxy services joining the same network. Besides, a container can join more than one network.
Edit:
To reverse proxy non-http services, the config file is a bit different. Here is a simple example:
upstream my_service {
server my_existing_container:9000;
}
server {
listen 9000;
proxy_pass my_service;
}
That you can do, but I think you should not break the normal flow of activity. If you want to finish you activity then you can simply send a broadcast from your activity B to activity A.
Create a broadcast receiver before starting your activity B:
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent intent) {
String action = intent.getAction();
if (action.equals("finish_activity")) {
finish();
// DO WHATEVER YOU WANT.
}
}
};
registerReceiver(broadcastReceiver, new IntentFilter("finish_activity"));
Send broadcast from activity B to activity A when you want to finish activity A from B
Intent intent = new Intent("finish_activity");
sendBroadcast(intent);
I hope it will work for you...
I know this thread has been answered, but another solution that may be useful for some, particularly to those with multiple pages where they want to have this button, is to give the input an id and place the code in a JavaScript file. You can then place the code for the button on multiple pages, taking up less space in your code.
For the button:
<input type="button" id="cancel_edit" value="Cancel"></input>
in the JavaScript file:
$("#cancel_edit").click(function(){
window.open('','_parent','');
window.close();
});
After so many trials I stumbled on a solution to this. I generated and added both debug and release keys to the Facebook developer console and still got the error.
The only solution that worked for me was is to uninstall the OpenSSL program from Google and download from Win32/Win64 OpenSSL Installer for Windows
It really works like magic.
1 for month is February. The 30th of February is changed to 1st of March. You should set 0 for month. The best is to use the constant defined in Calendar:
c1.set(2000, Calendar.JANUARY, 30);
Example: Suppose you have set some text in textview and you want to provide a link on a particular text expression: "Click on #facebook will take you to facebook.com"
In layout xml:
<TextView
android:id="@+id/testtext"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
In Activity:
String text = "Click on #facebook will take you to facebook.com";
tv.setText(text);
Pattern tagMatcher = Pattern.compile("[#]+[A-Za-z0-9-_]+\\b");
String newActivityURL = "content://ankit.testactivity/";
Linkify.addLinks(tv, tagMatcher, newActivityURL);
Also create one tag provider as:
public class TagProvider extends ContentProvider {
@Override
public int delete(Uri arg0, String arg1, String[] arg2) {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getType(Uri arg0) {
return "vnd.android.cursor.item/vnd.cc.tag";
}
@Override
public Uri insert(Uri arg0, ContentValues arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean onCreate() {
// TODO Auto-generated method stub
return false;
}
@Override
public Cursor query(Uri arg0, String[] arg1, String arg2, String[] arg3,
String arg4) {
// TODO Auto-generated method stub
return null;
}
@Override
public int update(Uri arg0, ContentValues arg1, String arg2, String[] arg3) {
// TODO Auto-generated method stub
return 0;
}
}
In manifest file make as entry for provider and test activity as:
<provider
android:name="ankit.TagProvider"
android:authorities="ankit.testactivity" />
<activity android:name=".TestActivity"
android:label = "@string/app_name">
<intent-filter >
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="vnd.android.cursor.item/vnd.cc.tag" />
</intent-filter>
</activity>
Now when you click on #facebook, it will invoke testactivtiy. And in test activity you can get the data as:
Uri uri = getIntent().getData();
The Immediate Window can also be used to execute commands. Just type a >
followed by the command.
For example >shell cmd
will start a command shell (this can be useful to check what environment variables were passed to Visual Studio, for example). >cls
will clear the screen.
Here is a list of commands that are so commonly used that they have their own aliases: https://msdn.microsoft.com/en-us/library/c3a0kd3x.aspx
Just tried this recently and when trying to select the JDK... /System/Library/Java/JavaVirtualMachines/
appears as empty when opening&selecting through IntelliJ. Therefore i couldn't select the JDK...
I've found that to workaround this, when the finder windows open (pressing [+] JDK) just use the shortcut Shift + CMD + G to specify the path. (/System/Library/Java/JavaVirtualMachines/1.6.0.jdk
in my case)
And voila, IntelliJ can find everything from that point on.
You could read from a blocking queue in one thread and write to it in another thread.
I have posted a very simple method to install OpenCV 2.4 for Python in Windows here : Install OpenCV in Windows for Python
It is just as simple as copy and paste. Hope it will be useful for future viewers.
Download Python, Numpy, OpenCV from their official sites.
Extract OpenCV (will be extracted to a folder opencv)
Copy ..\opencv\build\python\x86\2.7\cv2.pyd
Paste it in C:\Python27\Lib\site-packages
Open Python IDLE or terminal, and type
>>> import cv2
If no errors shown, it is OK.
UPDATE (Thanks to dana for this info):
If you are using the VideoCapture feature, you must copy opencv_ffmpeg.dll
into your path as well. See: https://stackoverflow.com/a/11703998/1134940
You can use java split function to split the filename from the extension, if you are sure there is only one dot in the filename which for extension.
File filename = new File('test.txt');
File.getName().split("[.]");
so the split[0]
will return "test" and split[1] will return "txt"
TypeScript supports structural typing (also called duck typing), meaning that types are compatible when they share the same members. Your problem is that Apple
and Pear
don't share all their members, which means that they are not compatible. They are however compatible to another type that has only the isDecayed: boolean
member. Because of structural typing, you don' need to inherit Apple
and Pear
from such an interface.
There are different ways to assign such a compatible type:
Assign type during variable declaration
This statement is implicitly typed to Apple[] | Pear[]
:
const fruits = fruitBasket[key];
You can simply use a compatible type explicitly in in your variable declaration:
const fruits: { isDecayed: boolean }[] = fruitBasket[key];
For additional reusability, you can also define the type first and then use it in your declaration (note that the Apple
and Pear
interfaces don't need to be changed):
type Fruit = { isDecayed: boolean };
const fruits: Fruit[] = fruitBasket[key];
Cast to compatible type for the operation
The problem with the given solution is that it changes the type of the fruits
variable. This might not be what you want. To avoid this, you can narrow the array down to a compatible type before the operation and then set the type back to the same type as fruits
:
const fruits: fruitBasket[key];
const freshFruits = (fruits as { isDecayed: boolean }[]).filter(fruit => !fruit.isDecayed) as typeof fruits;
Or with the reusable Fruit
type:
type Fruit = { isDecayed: boolean };
const fruits: fruitBasket[key];
const freshFruits = (fruits as Fruit[]).filter(fruit => !fruit.isDecayed) as typeof fruits;
The advantage of this solution is that both, fruits
and freshFruits
will be of type Apple[] | Pear[]
.
You can use Padding
widget in between those two widget or wrap those widgets with Padding
widget.
Update
SizedBox widget can be use in between two widget to add space between two widget and it makes code more readable than padding widget.
Ex:
Column(
children: <Widget>[
Widget1(),
SizedBox(height: 10),
Widget2(),
],
),
You have to create an instance of one of the subclasses. Stream
is an abstract class that can't be instantiated directly.
There are a bunch of choices if you look at the bottom of the reference here:
Stream Class | Microsoft Developer Network
The most common probably being FileStream
or MemoryStream
. Basically, you need to decide where you wish the data backing your stream to come from, then create an instance of the appropriate subclass.
YourButton.Attributes.Add("onclick", "return false");
or
<asp:button runat="server" ... OnClientClick="return false" />
This is what I do when i want to send email with attachment, work fine. :)
public class NewClass {
public static void main(String[] args) {
try {
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465"); // smtp port
Authenticator auth = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username-gmail", "password-gmail");
}
};
Session session = Session.getDefaultInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("[email protected]"));
msg.setSubject("Try attachment gmail");
msg.setRecipient(RecipientType.TO, new InternetAddress("[email protected]"));
//add atleast simple body
MimeBodyPart body = new MimeBodyPart();
body.setText("Try attachment");
//do attachment
MimeBodyPart attachMent = new MimeBodyPart();
FileDataSource dataSource = new FileDataSource(new File("file-sent.txt"));
attachMent.setDataHandler(new DataHandler(dataSource));
attachMent.setFileName("file-sent.txt");
attachMent.setDisposition(MimeBodyPart.ATTACHMENT);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
multipart.addBodyPart(attachMent);
msg.setContent(multipart);
Transport.send(msg);
} catch (AddressException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
} catch (MessagingException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
One thing that adds confusion to this subject is the idea of decorators is not made very clear, and when we consider something like...
@HostBinding('attr.something')
get something() {
return this.somethingElse;
}
It works, because it is a get
accessor. You couldn't use a function equivalent:
@HostBinding('attr.something')
something() {
return this.somethingElse;
}
Otherwise, the benefit of using @HostBinding
is it assures change detection is run when the bound value changes.
This one is quite simple and does not require a delegate as you say.
resultString = Regex.Replace(subjectString,
@"(?im)^[{(]?[0-9A-F]{8}[-]?(?:[0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?$",
"'$0'");
This matches the following styles, which are all equivalent and acceptable formats for a GUID.
ca761232ed4211cebacd00aa0057b223
CA761232-ED42-11CE-BACD-00AA0057B223
{CA761232-ED42-11CE-BACD-00AA0057B223}
(CA761232-ED42-11CE-BACD-00AA0057B223)
Update 1
@NonStatic makes the point in the comments that the above regex will match false positives which have a wrong closing delimiter.
This can be avoided by regex conditionals which are broadly supported.
Conditionals are supported by the JGsoft engine, Perl, PCRE, Python, and the .NET framework. Ruby supports them starting with version 2.0. Languages such as Delphi, PHP, and R that have regex features based on PCRE also support conditionals. (source http://www.regular-expressions.info/conditional.html)
The regex that follows Will match
{123}
(123)
123
And will not match
{123)
(123}
{123
(123
123}
123)
Regex:
^({)?(\()?\d+(?(1)})(?(2)\))$
The solutions is simplified to match only numbers to show in a more clear way what is required if needed.
Right way is using pytest.raises
but I found interesting alternative way in comments here and want to save it for future readers of this question:
try:
thing_that_rasises_typeerror()
assert False
except TypeError:
assert True
If you're still facing the issue even after replacing doGet()
with doPost()
and changing the form method="post"
. Try clearing the cache of the browser or hit the URL in another browser or incognito/private mode. It may works!
For best practices, please follow this link. https://www.oracle.com/technetwork/articles/javase/servlets-jsp-140445.html
The only portable way to achieve consistency between rooms and tags and making sure rooms are never returned after they had been deleted is locking them with SELECT FOR UPDATE
.
However in some systems locking is a side effect of concurrency control, and you achieve the same results without specifying FOR UPDATE
explicitly.
To solve this problem, Thread 1 should
SELECT id FROM rooms FOR UPDATE
, thereby preventing Thread 2 from deleting fromrooms
until Thread 1 is done. Is that correct?
This depends on the concurrency control your database system is using.
MyISAM
in MySQL
(and several other old systems) does lock the whole table for the duration of a query.
In SQL Server
, SELECT
queries place shared locks on the records / pages / tables they have examined, while DML
queries place update locks (which later get promoted to exclusive or demoted to shared locks). Exclusive locks are incompatible with shared locks, so either SELECT
or DELETE
query will lock until another session commits.
In databases which use MVCC
(like Oracle
, PostgreSQL
, MySQL
with InnoDB
), a DML
query creates a copy of the record (in one or another way) and generally readers do not block writers and vice versa. For these databases, a SELECT FOR UPDATE
would come handy: it would lock either SELECT
or the DELETE
query until another session commits, just as SQL Server
does.
When should one use
REPEATABLE_READ
transaction isolation versusREAD_COMMITTED
withSELECT ... FOR UPDATE
?
Generally, REPEATABLE READ
does not forbid phantom rows (rows that appeared or disappeared in another transaction, rather than being modified)
In Oracle
and earlier PostgreSQL
versions, REPEATABLE READ
is actually a synonym for SERIALIZABLE
. Basically, this means that the transaction does not see changes made after it has started. So in this setup, the last Thread 1
query will return the room as if it has never been deleted (which may or may not be what you wanted). If you don't want to show the rooms after they have been deleted, you should lock the rows with SELECT FOR UPDATE
In InnoDB
, REPEATABLE READ
and SERIALIZABLE
are different things: readers in SERIALIZABLE
mode set next-key locks on the records they evaluate, effectively preventing the concurrent DML
on them. So you don't need a SELECT FOR UPDATE
in serializable mode, but do need them in REPEATABLE READ
or READ COMMITED
.
Note that the standard on isolation modes does prescribe that you don't see certain quirks in your queries but does not define how (with locking or with MVCC
or otherwise).
When I say "you don't need SELECT FOR UPDATE
" I really should have added "because of side effects of certain database engine implementation".
Any future date in JavaScript (postman test uses JavaScript) can be retrieved as:
var dateNow = new Date();
var twoWeeksFutureDate = new Date(dateNow.setDate(dateNow.getDate() + 14)).toISOString();
postman.setEnvironmentVariable("future-date", twoWeeksFutureDate);
Please rewrite your query like
select /*+ MAX_EXECUTION_TIME(1000) */ * from table
this statement will kill your query after the specified time
First look for the main method is there or not.If it is there, do restart your eclipse and right click on the page which having main method, Go to run as Java application.
For folks who ended up here and are using CYGWIN
, install following packages in cygwin and re-run:
If you need to store null characters in text fields and don't want to change your data type other than text then you can follow my solution too:
Before insert:
myValue = myValue.replaceAll("\u0000", "SomeVerySpecialText")
After select:
myValue = myValue.replaceAll("SomeVerySpecialText","\u0000")
I've used "null" as my SomeVerySpecialText which I am sure that there will be no any "null" string in my values at all.
As explained in the Apache POI Javadocs, you should not use cell.setCellType(Cell.CELL_TYPE_STRING)
to get the string value of a numeric cell, as you'll loose all the formatting
Instead, as the javadocs explain, you should use DataFormatter
What DataFormatter does is take the floating point value representing the cell is stored in the file, along with the formatting rules applied to it, and returns you a string that look like it the cell does in Excel.
So, if you're after a String of the cell, looking much as you had it looking in Excel, just do:
// Create a formatter, do this once
DataFormatter formatter = new DataFormatter(Locale.US);
.....
for (int i=1; i <= sheet.getLastRowNum(); i++) {
Row r = sheet.getRow(i);
if (r == null) {
// empty row, skip
} else {
String j_username = formatter.formatCellValue(row.getCell(0));
String j_password = formatter.formatCellValue(row.getCell(1));
// Use these
}
}
The formatter will return String cells as-is, and for Numeric cells will apply the formatting rules on the style to the number of the cell
Authentication - Are you the person you claim to be?
Authorization - Are you authorized to do whatever it is you're trying to do?
A web app uses Google Sign-In. After a user successfully signs in, Google sends back:
Additionally:
The company may have an admin dashboard that allows customer support to manage the company's users. Instead of providing a custom signup solution that would allow customer support to access this dashboard, the company uses Google Sign-In.
The JWT token (received from the Google sign in process) is sent to the company's authorization server to figure out if the user has a G Suite account with the organization's hosted domain ([email protected])? And if they do, are they a member of the company's Google Group that was created for customer support? If yes to all of the above, we can consider them authenticated.
The company's authorization server then sends the dashboard app an access token. This access token can be used to make authorized requests to the company's resource server (e.g. ability to make a GET request to an endpoint that sends back all of the company's users).
The split() method is used to split a string into an array of substrings, and returns the new array.
Syntax:
string.split(separator,limit)
arr = strVale.split(',');
Make sure that your package is installed in your $GOPATH
directory or already inside your workspace/package.
For example: if your $GOPATH = "c:\go"
, make sure that the package inside C:\Go\src\pkgName
In my case it was simply an error in the web.config.
I had:
<endpoint address="http://localhost/WebService/WebOnlineService.asmx"
It should have been:
<endpoint address="http://localhost:10593/WebService/WebOnlineService.asmx"
The port number (:10593) was missing from the address.
I know this is old but here's a one liner list comprehension:
data = ['word1, 23, 12','word2, 10, 19','word3, 11, 15']
[[int(item) if item.isdigit() else item for item in items.split(', ')] for items in data]
or
[int(item) if item.isdigit() else item for items in data for item in items.split(', ')]
Using str.format
:
>>> array_alpha = [ 133, 53, 234, 241 ]
>>> print ''.join('{:02x}'.format(x) for x in array_alpha)
8535eaf1
or using format
>>> print ''.join(format(x, '02x') for x in array_alpha)
8535eaf1
Note: In the format statements, the
02
means it will pad with up to 2 leading0
s if necessary. This is important since[0x1, 0x1, 0x1] i.e. (0x010101)
would be formatted to"111"
instead of"010101"
or using bytearray
with binascii.hexlify
:
>>> import binascii
>>> binascii.hexlify(bytearray(array_alpha))
'8535eaf1'
Here is a benchmark of above methods in Python 3.6.1:
from timeit import timeit
import binascii
number = 10000
def using_str_format() -> str:
return "".join("{:02x}".format(x) for x in test_obj)
def using_format() -> str:
return "".join(format(x, "02x") for x in test_obj)
def using_hexlify() -> str:
return binascii.hexlify(bytearray(test_obj)).decode('ascii')
def do_test():
print("Testing with {}-byte {}:".format(len(test_obj), test_obj.__class__.__name__))
if using_str_format() != using_format() != using_hexlify():
raise RuntimeError("Results are not the same")
print("Using str.format -> " + str(timeit(using_str_format, number=number)))
print("Using format -> " + str(timeit(using_format, number=number)))
print("Using binascii.hexlify -> " + str(timeit(using_hexlify, number=number)))
test_obj = bytes([i for i in range(255)])
do_test()
test_obj = bytearray([i for i in range(255)])
do_test()
Result:
Testing with 255-byte bytes:
Using str.format -> 1.459474583090427
Using format -> 1.5809937679100738
Using binascii.hexlify -> 0.014521426401399307
Testing with 255-byte bytearray:
Using str.format -> 1.443447684109402
Using format -> 1.5608712609513171
Using binascii.hexlify -> 0.014114164661833684
Methods using format
do provide additional formatting options, as example separating numbers with spaces " ".join
, commas ", ".join
, upper-case printing "{:02X}".format(x)
/format(x, "02X")
, etc., but at a cost of great performance impact.
ReduceByKey reduceByKey(func, [numTasks])
-
Data is combined so that at each partition there should be at least one value for each key. And then shuffle happens and it is sent over the network to some particular executor for some action such as reduce.
GroupByKey - groupByKey([numTasks])
It doesn't merge the values for the key but directly the shuffle process happens and here lot of data gets sent to each partition, almost same as the initial data.
And the merging of values for each key is done after the shuffle. Here lot of data stored on final worker node so resulting in out of memory issue.
AggregateByKey - aggregateByKey(zeroValue)(seqOp, combOp, [numTasks])
It is similar to reduceByKey but you can provide initial values when performing aggregation.
Use of reduceByKey
reduceByKey
can be used when we run on large data set.
reduceByKey
when the input and output value types are of same type
over aggregateByKey
Moreover it recommended not to use groupByKey
and prefer reduceByKey
. For details you can refer here.
You can also refer this question to understand in more detail how reduceByKey
and aggregateByKey
.
You can cast an integer to a string in this way
intval::text
and so in your case
SELECT * FROM table WHERE <some integer>::text = 'string of numbers'
There is no direct equivalent to mvn exec:java
in gradle, you need to either apply the application
plugin or have a JavaExec
task.
application
pluginActivate the plugin:
plugins {
id 'application'
...
}
Configure it as follows:
application {
mainClassName = project.hasProperty("mainClass") ? getProperty("mainClass") : "NULL"
}
On the command line, write
$ gradle -PmainClass=Boo run
JavaExec
taskDefine a task, let's say execute
:
task execute(type:JavaExec) {
main = project.hasProperty("mainClass") ? getProperty("mainClass") : "NULL"
classpath = sourceSets.main.runtimeClasspath
}
To run, write gradle -PmainClass=Boo execute
. You get
$ gradle -PmainClass=Boo execute
:compileJava
:compileGroovy UP-TO-DATE
:processResources UP-TO-DATE
:classes
:execute
I am BOO!
mainClass
is a property passed in dynamically at command line. classpath
is set to pickup the latest classes.
If you do not pass in the mainClass
property, both of the approaches fail as expected.
$ gradle execute
FAILURE: Build failed with an exception.
* Where:
Build file 'xxxx/build.gradle' line: 4
* What went wrong:
A problem occurred evaluating root project 'Foo'.
> Could not find property 'mainClass' on task ':execute'.
From the documentation of __init__
:
As a special constraint on constructors, no value may be returned; doing so will cause a TypeError to be raised at runtime.
As a proof, this code:
class Foo(object):
def __init__(self):
return 2
f = Foo()
Gives this error:
Traceback (most recent call last):
File "test_init.py", line 5, in <module>
f = Foo()
TypeError: __init__() should return None, not 'int'
Very simple avoid using DateTime.MinValue
use System.Data.SqlTypes.SqlDateTime.MinValue
instead.
Can do this in jQuery. Try all options .height()
, .innerHeight()
or .outerHeight()
.
$('document').ready(function() {
$('#right_div').css({'height': $('#left_div').innerHeight()});
});
Example Screenshot
Hope this helps. Thanks!!
In your .htaccess file , if you are using apache you can try with
Rule for Error Page - 404ErrorDocument 404 http://www.domain.com/notFound.html
you could also change from the .get()
method to the .getJSON()
method, jQuery will then parse the string returned as data
to a javascript object and/or array that you can then reference like any other javascript object/array.
using your code above, if you changed .get
to .getJSON
, you should get an alert of [object Object]
for each element in the array. If you changed the alert to alert(item.name)
you will get the names.
You could find the difference between dates in columns in a data frame by using the function difftime
as follows:
df$diff_in_days<- difftime(df$datevar1 ,df$datevar2 , units = c("days"))
The correct format for passing variables in a GET request is
?variable1=value1&variable2=value2&variable3=value3...
^ ---notice &--- ^
But essentially, you have the right idea.
import os
print len(os.listdir(os.getcwd()))
Each directive's compile
function is only called once, when Angular bootstraps.
Officially, this is the place to perform (source) template manipulations that do not involve scope or data binding.
Primarily, this is done for optimisation purposes; consider the following markup:
<tr ng-repeat="raw in raws">
<my-raw></my-raw>
</tr>
The <my-raw>
directive will render a particular set of DOM markup. So we can either:
ng-repeat
to duplicate the source template (<my-raw>
), and then modify the markup of each instance template (outside the compile
function).compile
function), and then allow ng-repeat
to duplicate it.If there are 1000 items in the raws
collection, the latter option may be faster than the former one.
If you are using Bootstrap 3.3.x then use this code (you need to add class name carousel-fade to your carousel).
.carousel-fade .carousel-inner .item {
-webkit-transition-property: opacity;
transition-property: opacity;
}
.carousel-fade .carousel-inner .item,
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
opacity: 0;
}
.carousel-fade .carousel-inner .active,
.carousel-fade .carousel-inner .next.left,
.carousel-fade .carousel-inner .prev.right {
opacity: 1;
}
.carousel-fade .carousel-inner .next,
.carousel-fade .carousel-inner .prev,
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
left: 0;
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
.carousel-fade .carousel-control {
z-index: 2;
}
There is the solution if you need only outline without border. It's not mine. I got if from Bootstrap css file. If you specify outline: 1px auto certain_color
, you'll get thin outer line around div of certain color. In this case the specified width has no matter, even if you specify 10 px width, anyway it will be thin line. The key word in mentioned rule is "auto".
If you need outline with rounded corners and certain width, you may add css rule on border with needed width and same color. It makes outline thicker.
<!--[if !IE]><!--><script src="zepto.min.js"></script><!--<![endif]-->
<!--[if IE]><script src="jquery-1.7.2.min.js"></script><![endif]-->
Note: These conditional comments are no longer supported from IE 10 onwards.
There is an operator just for this. For example, if I wanted to change a variable i by 3 then:
var someValue = 9;
var Increment = 3;
for(var i=0;i<someValue;i+=Increment){
//do whatever
}
_x000D_
var someValue = 3;
var Increment = 3;
for(var i=9;i>someValue;i+=Increment){
//do whatever
}
_x000D_
I just had this issue from a namespace mismatch. My XAML file was getting ported over and it had a different namespace from that in the code behind file.
Exception code 0xc0000005
is an Access Violation. An AV at fault offset 0x00000000
means that something in your service's code is accessing a nil
pointer. You will just have to debug the service while it is running to find out what it is accessing. If you cannot run it inside a debugger, then at least install a third-party exception logger framework, such as EurekaLog or MadExcept, to find out what your service was doing at the time of the AV.
You've missed the time zone info (already answered, agreed)
arrow
package allows to avoid this torture with datetimes; It is already written, tested, pypi-published, cross-python (2.6 — 3.xx).
All you need: pip install arrow
(or add to dependencies)
dt = datetime(2013,9,1,11)
arrow.get(dt).timestamp
# >>> 1378033200
bc = arrow.get(1378033200).datetime
print(bc)
# >>> datetime.datetime(2013, 9, 1, 11, 0, tzinfo=tzutc())
print(bc.isoformat())
# >>> '2013-09-01T11:00:00+00:00'
The usual way is to use UPDATE:
UPDATE mytable
SET new_column = <expr containing old_column>
You should be able to do this is a single transaction.
c1.set(2017, 12 , 01); //Ex: 1999 jan 20 //System.out.println("Date is : " + sdf.format(c1.getTime()));
c1.add(Calendar.MONTH, -2); // substract 1 month
System.out.println
("Date minus 1 month : "
+ sdf.format(c1.getTime()));
If there is a hierarchy of exceptions you can use the base class to catch all subclasses of exceptions. In the degenerate case you can catch all Java exceptions with:
try {
...
} catch (Exception e) {
someCode();
}
In a more common case if RepositoryException is the the base class and PathNotFoundException is a derived class then:
try {
...
} catch (RepositoryException re) {
someCode();
} catch (Exception e) {
someCode();
}
The above code will catch RepositoryException and PathNotFoundException for one kind of exception handling and all other exceptions are lumped together. Since Java 7, as per @OscarRyz's answer above:
try {
...
} catch( IOException | SQLException ex ) {
...
}
Hopefully someone else finds this useful:
Using the Join is the best way to use a multi-value parameter. But what if you want to have an efficient 'Select All'? If there are 100s+ then the query will be very inefficient.
To solve this instead of using a SQL Query as is, change it to using an expression (click the Fx button top right) then build your query something like this (speech marks are necessary):
= "Select * from tProducts Where 1 = 1 "
IIF(Parameters!ProductID.Value(0)=-1,Nothing," And ProductID In (" & Join(Parameters!ProductID.Value,"','") & ")")
In your Parameter do the following:
SELECT -1 As ProductID, 'All' as ProductName Union All
Select
tProducts.ProductID,tProducts.ProductName
FROM
tProducts
By building the query as an expression means you can make the SQL Statement more efficient but also handle the difficulty SQL Server has with handling values in an 'In' statement.
You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.
I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).
To install it, you can either download it from the linked website or use the command:
pip install pyinstaller
...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:
pyinstaller myscript.py
You can find more information about how to use Pyinstaller and customize the build process via the documentation.
You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.
(The first options are of course mentioned in other answers, here the goal is to show that glob uses os.scandir
internally, and provide a direct answer with this).
As explained before, with Python 3.5+, it's easy:
import glob
for f in glob.glob('d:/temp/**/*', recursive=True):
print(f)
#d:\temp\New folder
#d:\temp\New Text Document - Copy.txt
#d:\temp\New folder\New Text Document - Copy.txt
#d:\temp\New folder\New Text Document.txt
from pathlib import Path
for f in Path('d:/temp').glob('**/*'):
print(f)
os.scandir
is what glob
does internally. So here is how to do it directly, with a use of yield
:
def listpath(path):
for f in os.scandir(path):
f2 = os.path.join(path, f)
if os.path.isdir(f):
yield f2
yield from listpath(f2)
else:
yield f2
for f in listpath('d:\\temp'):
print(f)
Try setting 'clientCredentialType' to 'Windows' instead of 'Ntlm'.
I think that this is what the server is expecting - i.e. when it says the server expects "Negotiate,NTLM", that actually means Windows Auth, where it will try to use Kerberos if available, or fall back to NTLM if not (hence the 'negotiate')
I'm basing this on somewhat reading between the lines of: Selecting a Credential Type
.phtml
was the standard file extension for PHP 2 programs. .php3
took over for PHP 3. When PHP 4 came out they switched to a straight .php
.
The older file extensions are still sometimes used, but aren't so common.
$timeFirst = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;
You will then be able to use the seconds to find minutes, hours, days, etc.
Another reason why this exception occurs is if you call the configure method twice on a Configuration
or AnnotatedConfiguration
object like this -
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(MyClass.class);
//Use this if config files are in src folder
config.configure();
//Use this if config files are in a subfolder of src, such as "resources"
config.configure("/resources/hibernate.cfg.xml");
Btw, this project structure is inside eclipse.
While checking null or Empty
value for a column, I noticed that there are some support concerns in various Databases.
Every Database doesn't support TRIM
method.
Below is the matrix just to understand the supported methods by different databases.
The TRIM function in SQL is used to remove specified prefix or suffix from a string. The most common pattern being removed is white spaces. This function is called differently in different databases:
TRIM(), RTRIM(), LTRIM()
RTRIM(), LTRIM()
TRIM(), RTRIM(), LTRIM()
How to Check Empty/Null/Whitespace :-
Below are two different ways according to different Databases-
The syntax for these trim functions are:
Use of Trim to check-
SELECT FirstName FROM UserDetails WHERE TRIM(LastName) IS NULL
Use of LTRIM & RTRIM to check-
SELECT FirstName FROM UserDetails WHERE LTRIM(RTRIM(LastName)) IS NULL
Above both ways provide same result just use based on your DataBase support. It Just returns the FirstName
from UserDetails
table if it has an empty LastName
Hoping this will help others too :)
This is a stab in the dark, but maybe do you need to wrap your JSON arguments; like say something like this:
data: "{'Ids':[{'Id1':'2'},{'Id2':'2'}]}"
Make sure your JSON is properly formed?