It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.
Other than that, I would suggest two things...
First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...
ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0
Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.
I assume you have a connection to your database and you can not do the insert parameters using c #.
You are not adding the parameters in your query. It should look like:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username,@password, @email)";
SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("@id","abc");
command.Parameters.Add("@username","abc");
command.Parameters.Add("@password","abc");
command.Parameters.Add("@email","abc");
command.ExecuteNonQuery();
Updated:
using(SqlConnection connection = new SqlConnection(_connectionString))
{
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (@id,@username,@password, @email)";
using(SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@id", "abc");
command.Parameters.AddWithValue("@username", "abc");
command.Parameters.AddWithValue("@password", "abc");
command.Parameters.AddWithValue("@email", "abc");
connection.Open();
int result = command.ExecuteNonQuery();
// Check Error
if(result < 0)
Console.WriteLine("Error inserting data into Database!");
}
}
Please check the below code. Automatically it will convert as DataTable
private void ConvertDataReaderToTableManually()
{
SqlConnection conn = null;
try
{
string connString = ConfigurationManager.ConnectionStrings["NorthwindConn"].ConnectionString;
conn = new SqlConnection(connString);
string query = "SELECT * FROM Customers";
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dtSchema = dr.GetSchemaTable();
DataTable dt = new DataTable();
// You can also use an ArrayList instead of List<>
List<DataColumn> listCols = new List<DataColumn>();
if (dtSchema != null)
{
foreach (DataRow drow in dtSchema.Rows)
{
string columnName = System.Convert.ToString(drow["ColumnName"]);
DataColumn column = new DataColumn(columnName, (Type)(drow["DataType"]));
column.Unique = (bool)drow["IsUnique"];
column.AllowDBNull = (bool)drow["AllowDBNull"];
column.AutoIncrement = (bool)drow["IsAutoIncrement"];
listCols.Add(column);
dt.Columns.Add(column);
}
}
// Read rows from DataReader and populate the DataTable
while (dr.Read())
{
DataRow dataRow = dt.NewRow();
for (int i = 0; i < listCols.Count; i++)
{
dataRow[((DataColumn)listCols[i])] = dr[i];
}
dt.Rows.Add(dataRow);
}
GridView2.DataSource = dt;
GridView2.DataBind();
}
catch (SqlException ex)
{
// handle error
}
catch (Exception ex)
{
// handle error
}
finally
{
conn.Close();
}
}
Setting CommandTimeout to 120 is not recommended. Try using pagination as mentioned above. Setting CommandTimeout to 30 is considered as normal. Anything more than that is consider bad approach and that usually concludes something wrong with the Implementation. Now the world is running on MiliSeconds Approach.
You could do this using an IF
statement:
IF NOT EXISTS
( SELECT 1
FROM tblSoftwareTitles
WHERE Softwarename = @SoftwareName
AND SoftwareSystemType = @Softwaretype
)
BEGIN
INSERT tblSoftwareTitles (SoftwareName, SoftwareSystemType)
VALUES (@SoftwareName, @SoftwareType)
END;
You could do it without IF
using SELECT
INSERT tblSoftwareTitles (SoftwareName, SoftwareSystemType)
SELECT @SoftwareName,@SoftwareType
WHERE NOT EXISTS
( SELECT 1
FROM tblSoftwareTitles
WHERE Softwarename = @SoftwareName
AND SoftwareSystemType = @Softwaretype
);
Both methods are susceptible to a race condition, so while I would still use one of the above to insert, but you can safeguard duplicate inserts with a unique constraint:
CREATE UNIQUE NONCLUSTERED INDEX UQ_tblSoftwareTitles_Softwarename_SoftwareSystemType
ON tblSoftwareTitles (SoftwareName, SoftwareSystemType);
ADDENDUM
In SQL Server 2008 or later you can use MERGE
with HOLDLOCK
to remove the chance of a race condition (which is still not a substitute for a unique constraint).
MERGE tblSoftwareTitles WITH (HOLDLOCK) AS t
USING (VALUES (@SoftwareName, @SoftwareType)) AS s (SoftwareName, SoftwareSystemType)
ON s.Softwarename = t.SoftwareName
AND s.SoftwareSystemType = t.SoftwareSystemType
WHEN NOT MATCHED BY TARGET THEN
INSERT (SoftwareName, SoftwareSystemType)
VALUES (s.SoftwareName, s.SoftwareSystemType);
Three things: use the using
statement, use AddWithValue
and prefix parameters with ? and add Allow User Variables=True
to the connection string.
string connString = ConfigurationManager.ConnectionStrings["default"].ConnectionString;
using (var conn = new MySqlConnection(connString))
{
conn.Open();
var comm = conn.CreateCommand();
comm.CommandText = "INSERT INTO room(person,address) VALUES(@person, @address)";
comm.Parameters.AddWithValue("?person", "Myname");
comm.Parameters.AddWithValue("?address", "Myaddress");
comm.ExecuteNonQuery();
}
Also see http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx for more information about the command usage, and http://dev.mysql.com/doc/refman/5.1/en/connector-net-connection-options.html for information about the Allow User Variables option (only supported in version 5.2.2 and above).
Here's what u can also try....
run your application....while it is still running launch your command prompt
while your application is running type netstat -n on the command prompt. You should see a list of TCP/IP connections. Check if your list is not very long. Ideally you should have less than 5 connections in the list. Check the status of the connections.
If you have too many connections with a TIME_WAIT status it means the connection has been closed and is waiting for the OS to release the resources. If you are running on Windows, the default ephemeral port rang is between 1024 and 5000 and the default time it takes Windows to release the resource from TIME_WAIT status is 4 minutes. So if your application used more then 3976 connections in less then 4 minutes, you will get the exception you got.
Suggestions to fix it:
If you continue to receive the same error message (which is highly unlikely) you can then try the following: (Please don't do it if you are not familiar with the Windows registry)
Modify the settings so they read:
MaxUserPort = dword:00004e20 (10,000 decimal) TcpTimedWaitDelay = dword:0000001e (30 decimal)
This will increase the number of ports to 10,000 and reduce the time to release freed tcp/ip connections.
Only use suggestion 2 if 1 fails.
Thank you.
Procedure never returns a value.You have to use a output parameter in store procedure.
ALTER PROC TESTLOGIN
@UserName varchar(50),
@password varchar(50)
@retvalue int output
as
Begin
declare @return int
set @return = (Select COUNT(*)
FROM CPUser
WHERE UserName = @UserName AND Password = @password)
set @retvalue=@return
End
Then you have to add a sqlparameter from c# whose parameter direction is out. Hope this make sense.
A couple of things wrong here.
Do you really want to open and close the connection for every single log entry?
Shouldn't you be using SqlCommand
instead of SqlDataAdapter
?
The data adapter (or SqlCommand
) needs exactly what the error message tells you it's missing: an active connection. Just because you created a connection object does not magically tell C# that it is the one you want to use (especially if you haven't opened the connection).
I highly recommend a C# / SQL Server tutorial.
The difference is the implicit conversion when using AddWithValue. If you know that your executing SQL query (stored procedure) is accepting a value of type int, nvarchar, etc, there's no reason in re-declaring it in your code.
For complex type scenarios (example would be DateTime, float), I'll probably use Add since it's more explicit but AddWithValue for more straight-forward type scenarios (Int to Int).
There are a several things you need to address to get it working
@ouput
its @code
AddWithValue
since its not supposed to have a value just you Add
.ExecuteNonQuery
if you're not returning rows Try
SqlParameter output = new SqlParameter("@code", SqlDbType.Int);
output.Direction = ParameterDirection.Output;
cmd.Parameters.Add(output);
cmd.ExecuteNonQuery();
MessageBox.Show(output.Value.ToString());
The .NET Data Providers consist of a number of classes used to connect to a data source, execute commands, and return recordsets. The Command Object in ADO.NET provides a number of Execute methods that can be used to perform the SQL queries in a variety of fashions.
A stored procedure is a pre-compiled executable object that contains one or more SQL statements. In many cases stored procedures accept input parameters and return multiple values . Parameter values can be supplied if a stored procedure is written to accept them. A sample stored procedure with accepting input parameter is given below :
CREATE PROCEDURE SPCOUNTRY
@COUNTRY VARCHAR(20)
AS
SELECT PUB_NAME FROM publishers WHERE COUNTRY = @COUNTRY
GO
The above stored procedure is accepting a country name (@COUNTRY VARCHAR(20)) as parameter and return all the publishers from the input country. Once the CommandType is set to StoredProcedure, you can use the Parameters collection to define parameters.
command.CommandType = CommandType.StoredProcedure;
param = new SqlParameter("@COUNTRY", "Germany");
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
command.Parameters.Add(param);
The above code passing country parameter to the stored procedure from C# application.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter ;
SqlCommand command = new SqlCommand();
SqlParameter param ;
DataSet ds = new DataSet();
int i = 0;
connetionString = "Data Source=servername;Initial Catalog=PUBS;User ID=sa;Password=yourpassword";
connection = new SqlConnection(connetionString);
connection.Open();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "SPCOUNTRY";
param = new SqlParameter("@COUNTRY", "Germany");
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
command.Parameters.Add(param);
adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show (ds.Tables[0].Rows[i][0].ToString ());
}
connection.Close();
}
}
}
This should work:
txtfarmersize = Convert.ToInt32(reader["farmsize"]);
No, arrays/lists can't be passed to SQL Server directly.
The following options are available:
You've already done it correctly by using a DateTime
parameter with the value from the DateTime
, so it should already work. Forget about ToString()
- since that isn't used here.
If there is a difference, it is most likely to do with different precision between the two environments; maybe choose a rounding (seconds, maybe?) and use that. Also keep in mind UTC/local/unknown (the DB has no concept of the "kind" of date; .NET does).
I have a table and the date-times in it are in the format:
2011-07-01 15:17:33.357
Note that datetimes in the database aren't in any such format; that is just your query-client showing you white lies. It is stored as a number (and even that is an implementation detail), because humans have this odd tendency not to realise that the date you've shown is the same as 40723.6371916281
. Stupid humans. By treating it simply as a "datetime" throughout, you shouldn't get any problems.
You need to add return parameter to the command:
using (SqlConnection conn = new SqlConnection(getConnectionString()))
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = parameterStatement.getQuery();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("SeqName", "SeqNameValue");
var returnParameter = cmd.Parameters.Add("@ReturnVal", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
conn.Open();
cmd.ExecuteNonQuery();
var result = returnParameter.Value;
}
Generic
public static DataTable ToTableValuedParameter<T, TProperty>(this IEnumerable<T> list, Func<T, TProperty> selector)
{
var tbl = new DataTable();
tbl.Columns.Add("Id", typeof(T));
foreach (var item in list)
{
tbl.Rows.Add(selector.Invoke(item));
}
return tbl;
}
A simple extension method for this would be:
public static void AddParameter(this SqlCommand sqlCommand, string parameterName,
SqlDbType sqlDbType, object item)
{
sqlCommand.Parameters.Add(parameterName, sqlDbType).Value = item ?? DBNull.Value;
}
Passing an array of items as a collapsed parameter to the WHERE..IN clause will fail since query will take form of WHERE Age IN ("11, 13, 14, 16")
.
But you can pass your parameter as an array serialized to XML or JSON:
nodes()
method:StringBuilder sb = new StringBuilder();
foreach (ListItem item in ddlAge.Items)
if (item.Selected)
sb.Append("<age>" + item.Text + "</age>"); // actually it's xml-ish
sqlComm.CommandText = @"SELECT * from TableA WHERE Age IN (
SELECT Tab.col.value('.', 'int') as Age from @Ages.nodes('/age') as Tab(col))";
sqlComm.Parameters.Add("@Ages", SqlDbType.NVarChar);
sqlComm.Parameters["@Ages"].Value = sb.ToString();
OPENXML
method:using System.Xml.Linq;
...
XElement xml = new XElement("Ages");
foreach (ListItem item in ddlAge.Items)
if (item.Selected)
xml.Add(new XElement("age", item.Text);
sqlComm.CommandText = @"DECLARE @idoc int;
EXEC sp_xml_preparedocument @idoc OUTPUT, @Ages;
SELECT * from TableA WHERE Age IN (
SELECT Age from OPENXML(@idoc, '/Ages/age') with (Age int 'text()')
EXEC sp_xml_removedocument @idoc";
sqlComm.Parameters.Add("@Ages", SqlDbType.Xml);
sqlComm.Parameters["@Ages"].Value = xml.ToString();
That's a bit more on the SQL side and you need a proper XML (with root).
OPENJSON
method (SQL Server 2016+):using Newtonsoft.Json;
...
List<string> ages = new List<string>();
foreach (ListItem item in ddlAge.Items)
if (item.Selected)
ages.Add(item.Text);
sqlComm.CommandText = @"SELECT * from TableA WHERE Age IN (
select value from OPENJSON(@Ages))";
sqlComm.Parameters.Add("@Ages", SqlDbType.NVarChar);
sqlComm.Parameters["@Ages"].Value = JsonConvert.SerializeObject(ages);
Note that for the last method you also need to have Compatibility Level at 130+.
Old question, but here's a fairly clean way to create a nullable parameter:
new SqlParameter("@note", (object) request.Body ?? DBNull.Value);
If request.Body has a value, then it's value is used. If it's null, then DbNull.Value is used.
For those of us who did not see -1 by Michal Chaniewski, the complete line of code:
cmd.Parameters.Add("@blah",SqlDbType.VarChar,-1).Value = "some large text";
retval.Direction = ParameterDirection.Output;
ParameterDirection.ReturnValue
should be used for the "return value" of the procedure, not output parameters. It gets the value returned by the SQL RETURN
statement (with the parameter named @RETURN_VALUE
).
Instead of RETURN @b
you should SET @b = something
By the way, return value parameter is always int
, not string.
If you use Microsoft.ApplicationBlocks.Data
it'll make calling your sprocs a single line
SqlHelper.ExecuteNonQuery(ConnectionString, "SprocName", DOB)
Oh and I think casperOne is correct...if you want to ensure the correct datetime over multiple timezones then simply convert the value to UTC before you send the value to SQL Server
SqlHelper.ExecuteNonQuery(ConnectionString, "SprocName", DOB.ToUniversalTime())
First - why is that an EXEC? Shouldn't that just be
AS
SELECT Column_Name, ...
FROM ...
WHERE TABLE_NAME = @template
The current SP doesn't make sense? In particular, that would look for a column matching @template, not the varchar value of @template. i.e. if @template is 'Column_Name'
, it would search WHERE TABLE_NAME = Column_Name
, which is very rare (to have table and column named the same).
Also, if you do have to use dynamic SQL, you should use EXEC sp_ExecuteSQL
(keeping the values as parameters) to prevent from injection attacks (rather than concatenation of input). But it isn't necessary in this case.
Re the actual problem - it looks OK from a glance; are you sure you don't have a different copy of the SP hanging around? This is a common error...
Sadly there are no operation-assignment
operators in VBA.
(Addition-assignment +=
are available in VB.Net)
Pointless workaround;
Sub Inc(ByRef i As Integer)
i = i + 1
End Sub
...
Static value As Integer
inc value
inc value
There is another way to solve this, using a map:
vector<double> v = {...}; // input data
map<double, unsigned> m; // mapping from value to its index
for (auto it = v.begin(); it != v.end(); ++it)
m[*it] = it - v.begin();
This will eradicate non-unique elements though. If that's not acceptable, use a multimap:
vector<double> v = {...}; // input data
multimap<double, unsigned> m; // mapping from value to its index
for (auto it = v.begin(); it != v.end(); ++it)
m.insert(make_pair(*it, it - v.begin()));
In order to output the indices, iterate over the map or multimap:
for (auto it = m.begin(); it != m.end(); ++it)
cout << it->second << endl;
It may help to other people.
Lots of popular apps have the different approach to show the progress of anything like network request, file loading etc. Loading spinner doesn't show the how much content has been loaded or remaining to load. There is a period of uncertainty which is bad in the perspective of UI/UX. Lot of popular apps(Facebook, Linkedin etc) has resolved this issue by showing the bare bones UI displays first. Then the loaded content is gradually populated on-screen.
I have used the shimmer for my apps to solve this issue.
There is a good article about this which will be beneficial for other people
I just add
apt-get install php5-mysqlnd
This will ask to overwrite mysql.so from "php5-mysql".
This work for me.
When I try to cast data source from datagridview that used bindingsource it error accor cannot casting:
----------Solution------------
'I changed casting from bindingsource that bind with datagridview
'Code here
Dim dtdata As New DataTable()
dtdata = CType(bndsData.DataSource, DataTable)
You typically have to do this in a single syscall, or else you will get a race condition.
This will open for reading and writing, creating the file if necessary.
FILE *fp = fopen("scores.dat", "ab+");
If you want to read it and then write a new version from scratch, then do it as two steps.
FILE *fp = fopen("scores.dat", "rb");
if (fp) {
read_scores(fp);
}
// Later...
// truncates the file
FILE *fp = fopen("scores.dat", "wb");
if (!fp)
error();
write_scores(fp);
This is how I was able to trigger a button click when the page loads.
<li ng-repeat="a in array">
<a class="button" id="btn" ng-click="function(a)" index="$index" on-load-clicker>
{{a.name}}
</a>
</li>
A simple directive that takes the index from the ng-repeat and uses a condition to call the first button in the index and click it when the page loads.
angular
.module("myApp")
.directive('onLoadClicker', function ($timeout) {
return {
restrict: 'A',
scope: {
index: '=index'
},
link: function($scope, iElm) {
if ($scope.index == 0) {
$timeout(function() {
iElm.triggerHandler('click');
}, 0);
}
}
};
});
This was the only way I was able to even trigger an auto click programmatically in the first place. angular.element(document.querySelector('#btn')).click();
Did not work from the controller so making this simple directive seems most effective if you are trying to run a click on page load and you can specify which button to click by passing in the index. I got help through this stack-overflow answer from another post reference: https://stackoverflow.com/a/26495541/4684183 onLoadClicker Directive.
Unless you're part of the 0.1% of applications where using open
is an actual performance benefit, there really is no good reason not to use fopen
. As far as fdopen
is concerned, if you aren't playing with file descriptors, you don't need that call.
Stick with fopen
and its family of methods (fwrite
, fread
, fprintf
, et al) and you'll be very satisfied. Just as importantly, other programmers will be satisfied with your code.
Visio professional has a database reverse-engineering tool built into it. You should be able to use it with MySQL through an ODBC driver. It works best when you reverse engineer the database and then create the diagrams by dragging them off the tables and views panel. It will drag any foreign key objects and put them on the diagram as well.
You can try joda-time.
Here is an easy one:
$myVar > "c:\myfilepath\myfilename.myextension"
You can also try:
Get-content "c:\someOtherPath\someOtherFile.myextension" > "c:\myfilepath\myfilename.myextension"
I just use:
$('body').animate({ 'scrollTop': '-=-'+<yourValueScroll>+'px' }, 2000);
_x000D_
The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.
According to this Google blogpost:
It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.
When referencing the mipmap- folders ensure you are using the following reference:
android:icon="@mipmap/ic_launcher"
The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.
I am not experienced at all so feel free to correct things. However, I tried all these answers, but always had a problem in some screen. So I tried the following that worked for me and looks as I want it in almost all screens with the exception of mobile.
<div class="wrapper">
<div id="Section-Title">
<div id="h2"> YOUR TITLE
<div id="line"><hr></div>
</div>
</div>
</div>
CSS:
.wrapper{
background:#fff;
max-width:100%;
margin:20px auto;
padding:50px 5%;}
#Section-Title{
margin: 2% auto;
width:98%;
overflow: hidden;}
#h2{
float:left;
width:100%;
position:relative;
z-index:1;
font-family:Arial, Helvetica, sans-serif;
font-size:1.5vw;}
#h2 #line {
display:inline-block;
float:right;
margin:auto;
margin-left:10px;
width:90%;
position:absolute;
top:-5%;}
#Section-Title:after{content:""; display:block; clear:both; }
.wrapper:after{content:""; display:block; clear:both; }
Minor variation to user1850980's answer (for the question "How to initialize a list of empty dictionaries") using list constructor:
dictlistGOOD = list( {} for i in xrange(listsize) )
I found out to my chagrin, this does NOT work:
dictlistFAIL = [{}] * listsize # FAIL!
as it creates a list of references to the same empty dictionary, so that if you update one dictionary in the list, all the other references get updated too.
Try these updates to see the difference:
dictlistGOOD[0]["key"] = "value"
dictlistFAIL[0]["key"] = "value"
(I was actually looking for user1850980's answer to the question asked, so his/her answer was helpful.)
The @Qualifier
annotation is used to resolve the autowiring conflict, when there are multiple beans of same type.
The @Qualifier
annotation can be used on any class annotated with @Component
or on methods annotated with @Bean
. This annotation can also be applied on constructor arguments or method parameters.
Ex:-
public interface Vehicle {
public void start();
public void stop();
}
There are two beans, Car and Bike implements Vehicle interface
@Component(value="car")
public class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car started");
}
@Override
public void stop() {
System.out.println("Car stopped");
}
}
@Component(value="bike")
public class Bike implements Vehicle {
@Override
public void start() {
System.out.println("Bike started");
}
@Override
public void stop() {
System.out.println("Bike stopped");
}
}
Injecting Bike bean in VehicleService using @Autowired
with @Qualifier
annotation. If you didn't use @Qualifier
, it will throw NoUniqueBeanDefinitionException.
@Component
public class VehicleService {
@Autowired
@Qualifier("bike")
private Vehicle vehicle;
public void service() {
vehicle.start();
vehicle.stop();
}
}
Reference:- @Qualifier annotation example
Have you configured the jupyter_notebook_config.py file to allow external connections?
By default, Jupyter Notebook only accepts connections from localhost (eg, from the same computer that its running on). By modifying the NotebookApp.allow_origin option from the default ' ' to '*', you allow Jupyter to be accessed externally.
c.NotebookApp.allow_origin = '*' #allow all origins
You'll also need to change the IPs that the notebook will listen on:
c.NotebookApp.ip = '0.0.0.0' # listen on all IPs
Also see the details in a subsequent answer in this thread.
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO
In order to support "matches any of ..." scenarios, I created a function that is pretty easy to read. My version has a lot more to it because its a PowerShell 2.0 cmdlet but the version I'm pasting below should work in 1.0 and has no frills.
You call it like so:
Get-Process | Where-Match Company -Like '*VMWare*','*Microsoft*'
Get-Process | Where-Match Company -Regex '^Microsoft.*'
filter Where-Match($Selector,[String[]]$Like,[String[]]$Regex) {
if ($Selector -is [String]) { $Value = $_.$Selector }
elseif ($Selector -is [ScriptBlock]) { $Value = &$Selector }
else { throw 'Selector must be a ScriptBlock or property name' }
if ($Like.Length) {
foreach ($Pattern in $Like) {
if ($Value -like $Pattern) { return $_ }
}
}
if ($Regex.Length) {
foreach ($Pattern in $Regex) {
if ($Value -match $Pattern) { return $_ }
}
}
}
filter Where-NotMatch($Selector,[String[]]$Like,[String[]]$Regex) {
if ($Selector -is [String]) { $Value = $_.$Selector }
elseif ($Selector -is [ScriptBlock]) { $Value = &$Selector }
else { throw 'Selector must be a ScriptBlock or property name' }
if ($Like.Length) {
foreach ($Pattern in $Like) {
if ($Value -like $Pattern) { return }
}
}
if ($Regex.Length) {
foreach ($Pattern in $Regex) {
if ($Value -match $Pattern) { return }
}
}
return $_
}
Hmm, Arraylist can be used in cases like follows I guess:
For eg, you need to import and access all elements in a contact list (the size of which is unknown to you)
To Get the Value when the radio button is checked
if (rdbtnSN06.IsChecked == true)
{
string RadiobuttonContent =Convert.ToString(rdbtnSN06.Content.ToString());
}
else
{
string RadiobuttonContent =Convert.ToString(rdbtnSN07.Content.ToString());
}
C++17
simplified this a bit more with an If statement with initializer
.
This way you can have your cake and eat it too.
if ( auto it{ m.find( "key" ) }; it != std::end( m ) )
{
// Use `structured binding` to get the key
// and value.
auto[ key, value ] { *it };
// Grab either the key or value stored in the pair.
// The key is stored in the 'first' variable and
// the 'value' is stored in the second.
auto mkey{ it->first };
auto mvalue{ it->second };
// That or just grab the entire pair pointed
// to by the iterator.
auto pair{ *it };
}
else
{
// Key was not found..
}
Knowing that you are dealing with a UTF-8 byte array, you'll definitely want to use the String constructor that accepts a charset name. Otherwise you may leave yourself open to some charset encoding based security vulnerabilities. Note that it throws UnsupportedEncodingException
which you'll have to handle. Something like this:
public String openFileToString(String fileName) {
String file_string;
try {
file_string = new String(_bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
// this should never happen because "UTF-8" is hard-coded.
throw new IllegalStateException(e);
}
return file_string;
}
Try this: import headers as mentioned.. gives seconds and milliseconds only. If you need to explain the code read this link.
#include <windows.h>
#include <stdio.h>
void main()
{
SYSTEMTIME st;
SYSTEMTIME lt;
GetSystemTime(&st);
// GetLocalTime(<);
printf("The system time is: %02d:%03d\n", st.wSecond, st.wMilliseconds);
// printf("The local time is: %02d:%03d\n", lt.wSecond, lt.wMilliseconds);
}
What the browser does when you've got
<a onclick="alert('Hi');" ... >
is to set the actual value of "onclick" to something effectively like:
new Function("event", "alert('Hi');");
That is, it creates a function that expects an "event" parameter. (Well, IE doesn't; it's more like a plain simple anonymous function.)
First examine if you really need a global variable instead using it blatantly without consideration to your software architecture.
Let's assuming it passes the test. Depending on usage, Globals can be hard to debug with race conditions and many other "bad things", it's best to approach them from an angle where you're prepared to handle such bad things. So,
static
class (for manageability). The basic outline for such a class would be:
public class Globals
{
private static bool _expired;
public static bool Expired
{
get
{
// Reads are usually simple
return _expired;
}
set
{
// You can add logic here for race conditions,
// or other measurements
_expired = value;
}
}
// Perhaps extend this to have Read-Modify-Write static methods
// for data integrity during concurrency? Situational.
}
Usage from other classes (within same namespace)
// Read
bool areWeAlive = Globals.Expired;
// Write
// past deadline
Globals.Expired = true;
Using standard javax.sound API, a single Maven dependency, completely Open Source (Java 7 or later required), this should be able to play most WAVs, OGG Vorbis and MP3 files:
pom.xml:
<!--
We have to explicitly instruct Maven to use tritonus-share 0.3.7-2
and NOT 0.3.7-1, otherwise vorbisspi won't work.
-->
<dependency>
<groupId>com.googlecode.soundlibs</groupId>
<artifactId>tritonus-share</artifactId>
<version>0.3.7-2</version>
</dependency>
<dependency>
<groupId>com.googlecode.soundlibs</groupId>
<artifactId>mp3spi</artifactId>
<version>1.9.5-1</version>
</dependency>
<dependency>
<groupId>com.googlecode.soundlibs</groupId>
<artifactId>vorbisspi</artifactId>
<version>1.0.3-1</version>
</dependency>
Code:
import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine.Info;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import static javax.sound.sampled.AudioSystem.getAudioInputStream;
import static javax.sound.sampled.AudioFormat.Encoding.PCM_SIGNED;
public class AudioFilePlayer {
public static void main(String[] args) {
final AudioFilePlayer player = new AudioFilePlayer ();
player.play("something.mp3");
player.play("something.ogg");
}
public void play(String filePath) {
final File file = new File(filePath);
try (final AudioInputStream in = getAudioInputStream(file)) {
final AudioFormat outFormat = getOutFormat(in.getFormat());
final Info info = new Info(SourceDataLine.class, outFormat);
try (final SourceDataLine line =
(SourceDataLine) AudioSystem.getLine(info)) {
if (line != null) {
line.open(outFormat);
line.start();
stream(getAudioInputStream(outFormat, in), line);
line.drain();
line.stop();
}
}
} catch (UnsupportedAudioFileException
| LineUnavailableException
| IOException e) {
throw new IllegalStateException(e);
}
}
private AudioFormat getOutFormat(AudioFormat inFormat) {
final int ch = inFormat.getChannels();
final float rate = inFormat.getSampleRate();
return new AudioFormat(PCM_SIGNED, rate, 16, ch, ch * 2, rate, false);
}
private void stream(AudioInputStream in, SourceDataLine line)
throws IOException {
final byte[] buffer = new byte[4096];
for (int n = 0; n != -1; n = in.read(buffer, 0, buffer.length)) {
line.write(buffer, 0, n);
}
}
}
References:
If you're using at least .NET 3.5, i would suggest to use Linq-To-DataTable
instead since it's much more readable and powerful:
DataTable tblFiltered = table.AsEnumerable()
.Where(row => row.Field<String>("Nachname") == username
&& row.Field<String>("Ort") == location)
.OrderByDescending(row => row.Field<String>("Nachname"))
.CopyToDataTable();
Above code is just an example, actually you have many more methods available.
Remember to add using System.Linq;
and for the AsEnumerable
extension method a reference to the System.Data.DataSetExtensions
dll (How).
Jordans analysis of why the $_POST-array isn't populated is correct. However, you can use
$data = file_get_contents("php://input");
to just retrieve the http body and handle it yourself. See PHP input/output streams.
From a protocol perspective this is actually more correct, since you're not really processing http multipart form data anyway. Also, use application/json as content-type when posting your request.
For anyone trying to use jQuery.active with JSONP requests (like I was) you'll need enable it with this:
jQuery.ajaxPrefilter(function( options ) {
options.global = true;
});
Keep in mind that you'll need a timeout on your JSONP request to catch failures.
Five different ways to convert a double to a normal number:
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class Runner {
public static void main(String[] args) {
double myvalue = 0.00000021d;
//Option 1 Print bare double.
System.out.println(myvalue);
//Option2, use decimalFormat.
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(8);
System.out.println(df.format(myvalue));
//Option 3, use printf.
System.out.printf("%.9f", myvalue);
System.out.println();
//Option 4, convert toBigDecimal and ask for toPlainString().
System.out.print(new BigDecimal(myvalue).toPlainString());
System.out.println();
//Option 5, String.format
System.out.println(String.format("%.12f", myvalue));
}
}
This program prints:
2.1E-7
.00000021
0.000000210
0.000000210000000000000001085015324114868562332958390470594167709350585
0.000000210000
Which are all the same value.
Protip: If you are confused as to why those random digits appear beyond a certain threshold in the double value, this video explains: computerphile why does 0.1
+0.2
equal 0.30000000000001
?
This is called string interpolation, and you do it like this:
"The #{animal} #{action} the #{second_animal}"
Important: it will only work when string is inside double quotes (" ").
Example of code that will not work as you expect:
'The #{animal} #{action} the #{second_animal}'
NOTE: The recommended way to do string formatting in Python is to use format()
, as outlined in the accepted answer. I'm preserving this answer as an example of the C-style syntax that's also supported.
# NOTE: format() is a better choice!
string1 = "go"
string2 = "now"
string3 = "great"
s = """
I will %s there
I will go %s
%s
""" % (string1, string2, string3)
print(s)
Some reading:
For the record, rjson and RJSONIO do change the file type, but they don't really parse per se. For instance, I receive ugly MongoDB data in JSON format, convert it with rjson or RJSONIO, then use unlist and tons of manual correction to actually parse it into a usable matrix.
There is no need of adding JAR to your project by yourself, just add dependency in build.gradle (Module lavel). ALSO always try to use the upgraded version, as of now is
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}
As every incremental version has some bugs fixes or up-gradations as mentioned here
Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.
-
is the 'binary operator' your error is referencing, and either CurrentDay
or MA
(or both) are non-numeric.
A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). +
is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).
R only knows how to apply +
(and other binary operators, such as -
) to numeric arguments:
> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator
When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.
EDIT:
Your error lies in the use of [
instead of [[
. Because Day
is a list, subsetting with [
will return a list, not a numeric vector. [[
, however, returns an object of the class of the item contained in the list:
> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator
> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3
Transaction
, as you've defined it, returns a list of two vectors. Above, Day
is a list contain one vector. Day2
, however, is simply a vector.
You may simply use both as per the specification kindly provided by Oli.
I always use border:0 none;
.
Though there is no harm in specifying them seperately and some browsers will parse the CSS faster if you do use the legacy CSS1 property calls.
Though border:0;
will normally default the border style to none
, I have however noticed some browsers enforcing their default border style which can strangely overwrite border:0;
.
I have the same issue and my solution is change a little thing in Build Settings
SWIFT_COMPILATION_MODE = singlefile;
SWIFT_OPTIMIZATION_LEVEL = "-O";
The answer I would provide is that a keystore file is to authenticate yourself to anyone who is asking. It isn't restricted to just signing .apk files, you can use it to store personal certificates, sign data to be transmitted and a whole variety of authentication.
In terms of what you do with it for Android and probably what you're looking for since you mention signing apk's, it is your certificate. You are branding your application with your credentials. You can brand multiple applications with the same key, in fact, it is recommended that you use one certificate to brand multiple applications that you write. It easier to keep track of what applications belong to you.
I'm not sure what you mean by implications. I suppose it means that no one but the holder of your certificate can update your application. That means that if you release it into the wild, lose the cert you used to sign the application, then you cannot release updates so keep that cert safe and backed up if need be.
But apart from signing apks to release into the wild, you can use it to authenticate your device to a server over SSL if you so desire, (also Android related) among other functions.
Add pointer-events: none;
to the overlay.
Original answer: My suggestion would be that you could capture the click event with the overlay, hide the overlay, then refire the click event, then display the overlay again. I'm not sure if you'd get a flicker effect though.
[Update] Exactly this problem and exactly my solution just appeared in this post: "Forwarding Mouse Events Through Layers". I know its probably a little late for the OP, but for the sake of somebody having this problem in the future, I though I would include it.
ClsConectaBanco bd = new ClsConectaBanco();
StringBuilder sb = new StringBuilder();
sb.Append(" INSERT INTO FAT_BALANCETE ");
sb.Append(" ([DT_LANCAMENTO] ");
sb.Append(" ,[ID_LANCAMENTO_CONTABIL] ");
sb.Append(" ,[NR_DOC_CONTABIL] ");
sb.Append(" ,[TP_LANCAMENTO_GERADO] ");
sb.Append(" ,[VL_LANCAMENTO] ");
sb.Append(" ,[TP_NATUREZA] ");
sb.Append(" ,[CD_EMPRESA] ");
sb.Append(" ,[CD_FILIAL] ");
sb.Append(" ,[CD_CONTA_CONTABIL] ");
sb.Append(" ,[DS_CONTA_CONTABIL] ");
sb.Append(" ,[ID_CONTA_CONTABIL] ");
sb.Append(" ,[DS_TRIMESTRE] ");
sb.Append(" ,[DS_SEMESTRE] ");
sb.Append(" ,[NR_TRIMESTRE] ");
sb.Append(" ,[NR_SEMESTRE] ");
sb.Append(" ,[NR_ANO] ");
sb.Append(" ,[NR_MES] ");
sb.Append(" ,[NM_FILIAL]) ");
sb.Append(" VALUES ");
sb.Append(" (@DT_LANCAMENTO ");
sb.Append(" ,@ID_LANCAMENTO_CONTABIL ");
sb.Append(" ,@NR_DOC_CONTABIL ");
sb.Append(" ,@TP_LANCAMENTO_GERADO ");
sb.Append(" ,@VL_LANCAMENTO ");
sb.Append(" ,@TP_NATUREZA ");
sb.Append(" ,@CD_EMPRESA ");
sb.Append(" ,@CD_FILIAL ");
sb.Append(" ,@CD_CONTA_CONTABIL ");
sb.Append(" ,@DS_CONTA_CONTABIL ");
sb.Append(" ,@ID_CONTA_CONTABIL ");
sb.Append(" ,@DS_TRIMESTRE ");
sb.Append(" ,@DS_SEMESTRE ");
sb.Append(" ,@NR_TRIMESTRE ");
sb.Append(" ,@NR_SEMESTRE ");
sb.Append(" ,@NR_ANO ");
sb.Append(" ,@NR_MES ");
sb.Append(" ,@NM_FILIAL) ");
SqlCommand cmd = new SqlCommand(sb.ToString(), bd.CriaConexaoSQL());
bd.AbrirConexao();
cmd.Parameters.Add("@DT_LANCAMENTO", SqlDbType.Date);
cmd.Parameters.Add("@ID_LANCAMENTO_CONTABIL", SqlDbType.Int);
cmd.Parameters.Add("@NR_DOC_CONTABIL", SqlDbType.VarChar,255);
cmd.Parameters.Add("@TP_LANCAMENTO_GERADO", SqlDbType.VarChar,255);
cmd.Parameters.Add("@VL_LANCAMENTO", SqlDbType.Decimal);
cmd.Parameters["@VL_LANCAMENTO"].Precision = 15;
cmd.Parameters["@VL_LANCAMENTO"].Scale = 2;
cmd.Parameters.Add("@TP_NATUREZA", SqlDbType.VarChar, 1);
cmd.Parameters.Add("@CD_EMPRESA",SqlDbType.Int);
cmd.Parameters.Add("@CD_FILIAL", SqlDbType.Int);
cmd.Parameters.Add("@CD_CONTA_CONTABIL", SqlDbType.VarChar, 255);
cmd.Parameters.Add("@DS_CONTA_CONTABIL", SqlDbType.VarChar, 255);
cmd.Parameters.Add("@ID_CONTA_CONTABIL", SqlDbType.VarChar,50);
cmd.Parameters.Add("@DS_TRIMESTRE", SqlDbType.VarChar, 4);
cmd.Parameters.Add("@DS_SEMESTRE", SqlDbType.VarChar, 4);
cmd.Parameters.Add("@NR_TRIMESTRE", SqlDbType.Int);
cmd.Parameters.Add("@NR_SEMESTRE", SqlDbType.Int);
cmd.Parameters.Add("@NR_ANO", SqlDbType.Int);
cmd.Parameters.Add("@NR_MES", SqlDbType.Int);
cmd.Parameters.Add("@NM_FILIAL", SqlDbType.VarChar, 255);
cmd.Prepare();
foreach (dtoVisaoBenner obj in lista)
{
cmd.Parameters["@DT_LANCAMENTO"].Value = obj.CTLDATA;
cmd.Parameters["@ID_LANCAMENTO_CONTABIL"].Value = obj.CTLHANDLE.ToString();
cmd.Parameters["@NR_DOC_CONTABIL"].Value = obj.CTLDOCTO.ToString();
cmd.Parameters["@TP_LANCAMENTO_GERADO"].Value = obj.LANCAMENTOGERADO;
cmd.Parameters["@VL_LANCAMENTO"].Value = obj.CTLANVALORF;
cmd.Parameters["@TP_NATUREZA"].Value = obj.NATUREZA;
cmd.Parameters["@CD_EMPRESA"].Value = obj.EMPRESA;
cmd.Parameters["@CD_FILIAL"].Value = obj.FILIAL;
cmd.Parameters["@CD_CONTA_CONTABIL"].Value = obj.CONTAHANDLE.ToString();
cmd.Parameters["@DS_CONTA_CONTABIL"].Value = obj.CONTANOME.ToString();
cmd.Parameters["@ID_CONTA_CONTABIL"].Value = obj.CONTA;
cmd.Parameters["@DS_TRIMESTRE"].Value = obj.TRIMESTRE;
cmd.Parameters["@DS_SEMESTRE"].Value = obj.SEMESTRE;
cmd.Parameters["@NR_TRIMESTRE"].Value = obj.NRTRIMESTRE;
cmd.Parameters["@NR_SEMESTRE"].Value = obj.NRSEMESTRE;
cmd.Parameters["@NR_ANO"].Value = obj.NRANO;
cmd.Parameters["@NR_MES"].Value = obj.NRMES;
cmd.Parameters["@NM_FILIAL"].Value = obj.NOME;
cmd.ExecuteNonQuery();
rowAffected++;
}
For kotlin I use the following
val fcmtoken = FirebaseMessaging.getInstance().token.await()
and for the extension functions
public suspend fun <T> Task<T>.await(): T {
// fast path
if (isComplete) {
val e = exception
return if (e == null) {
if (isCanceled) {
throw CancellationException("Task $this was cancelled normally.")
} else {
@Suppress("UNCHECKED_CAST")
result as T
}
} else {
throw e
}
}
return suspendCancellableCoroutine { cont ->
addOnCompleteListener {
val e = exception
if (e == null) {
@Suppress("UNCHECKED_CAST")
if (isCanceled) cont.cancel() else cont.resume(result as T)
} else {
cont.resumeWithException(e)
}
}
}
}
Unix and Windows both have things called "Named pipes", but they behave differently. On Unix, a named pipe is a one-way street which typically has just one reader and one writer - the writer writes, and the reader reads, you get it?
On Windows, the thing called a "Named pipe" is an IPC object more like a TCP socket - things can flow both ways and there is some metadata (You can obtain the credentials of the thing on the other end etc).
Unix named pipes appear as a special file in the filesystem and can be accessed with normal file IO commands including the shell. Windows ones don't, and need to be opened with a special system call (after which they behave mostly like a normal win32 handle).
Even more confusing, Unix has something called a "Unix socket" or AF_UNIX socket, which works more like (but not completely like) a win32 "named pipe", being bidirectional.
here's non-paste methods
awk
awk 'BEGIN {OFS=" "}{
getline line < "file2"
print $0,line
} ' file1
Bash
exec 6<"file2"
while read -r line
do
read -r f2line <&6
echo "${line}${f2line}"
done <"file1"
exec 6<&-
Just provide another implementation of Jason's answer by C.
After discussing with my classmates, based on Jason's explanation, I like the recursive version more if you don't care about the performance very much:
For example:
#include<stdio.h>
int mypow( int base, int pow, int mod ){
if( pow == 0 ) return 1;
if( pow % 2 == 0 ){
int tmp = mypow( base, pow >> 1, mod );
return tmp * tmp % mod;
}
else{
return base * mypow( base, pow - 1, mod ) % mod;
}
}
int main(){
printf("%d", mypow(5,55,221));
return 0;
}
In your viewDidLoad
, register at notification center to listen to this opened from background action
NotificationCenter.default.addObserver(self, selector:#selector(doSomething), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
Then add this function and perform needed action
func doSomething(){
//...
}
Finally add this function to clean up the notification observer when your view controller is destroyed.
deinit {
NotificationCenter.default.removeObserver(self)
}
You can try something that I've been working on called 'xeno'. It will allow you to open up files/folders in Sublime Text (or any local editor really) over an SSH connection and automatically synchronize changes to the remote machine. It should work on almost all POSIX systems (I myself use it from OS X to connect to Linux machines and edit files in Sublime Text). It's free and open source. I'd love some feedback.
For more information: it's basically a Git/SSH mashup written in Python that allows you to edit files and folders on a remote machine in a local editor. You don't have to configure kernel modules, you don't need to have a persistent connection, it's all automatic, and it won't interfere with existing source control because it uses an out-of-worktree Git repository. Also, because it's built on Git, it's extremely fast and supports automatic merging of files that might be changing on both ends, unlike SSHFS/SFTP which will just clobber any files with older timestamps.
Since JavaScript does not support passing parameters by reference, you'll need to make the variable an object instead:
var x = {Value: 0};_x000D_
_x000D_
function a(obj)_x000D_
{_x000D_
obj.Value++;_x000D_
}_x000D_
_x000D_
a(x);_x000D_
document.write(x.Value); //Here i want to have 1 instead of 0
_x000D_
In this case, x
is a reference to an object. When x
is passed to the function a
, that reference is copied over to obj
. Thus, obj
and x
refer to the same thing in memory. Changing the Value
property of obj
affects the Value
property of x
.
Javascript will always pass function parameters by value. That's simply a specification of the language. You could create x
in a scope local to both functions, and not pass the variable at all.
One of my real favorites may not count as a keyboard shortcut exactly. But the "iter" smart template is really great.
basically if you want to iterate though something using a for loop type "iter" then tab to use the live template
itertab
it will figure out the most likely variable you want to iterate over and generate a for loop for it. I'm pretty sure it uses the nearest reference to an object which supports iteration.
<>
is equal to !=
i.e, both are used to represent the NOT EQUAL operation. For instance, email <> ''
and email != ''
are same.
Assuming it's the user's address, some mail servers do allow the SMTP VRFY command to actually verify the email address against its mailboxes. Most of the major site won't give you much information; the gmail response is "if you try to mail it, we'll try to deliver it" or something clever like that.
You can save the best model using keras.callbacks.ModelCheckpoint()
Example:
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model_checkpoint_callback = keras.callbacks.ModelCheckpoint("best_Model.h5",save_best_only=True)
history = model.fit(x_train,y_train,
epochs=10,
validation_data=(x_valid,y_valid),
callbacks=[model_checkpoint_callback])
This will save the best model in your working directory.
For one-way data binding from parent to child, use the @Input
decorator (as recommended by the style guide) to specify an input property on the child component
@Input() model: any; // instead of any, specify your type
and use template property binding in the parent template
<child [model]="parentModel"></child>
Since you are passing an object (a JavaScript reference type) any changes you make to object properties in the parent or the child component will be reflected in the other component, since both components have a reference to the same object. I show this in the Plunker.
If you reassign the object in the parent component
this.model = someNewModel;
Angular will propagate the new object reference to the child component (automatically, as part of change detection).
The only thing you shouldn't do is reassign the object in the child component. If you do this, the parent will still reference the original object. (If you do need two-way data binding, see https://stackoverflow.com/a/34616530/215945).
@Component({
selector: 'child',
template: `<h3>child</h3>
<div>{{model.prop1}}</div>
<button (click)="updateModel()">update model</button>`
})
class Child {
@Input() model: any; // instead of any, specify your type
updateModel() {
this.model.prop1 += ' child';
}
}
@Component({
selector: 'my-app',
directives: [Child],
template: `
<h3>Parent</h3>
<div>{{parentModel.prop1}}</div>
<button (click)="updateModel()">update model</button>
<child [model]="parentModel"></child>`
})
export class AppComponent {
parentModel = { prop1: '1st prop', prop2: '2nd prop' };
constructor() {}
updateModel() { this.parentModel.prop1 += ' parent'; }
}
Plunker - Angular RC.2
Possibly browser returns String representation of some integer value? Actually int can't be null. May be you could check for null, if value is not null, then transform String representation to int.
For a super succinct with jQuery approach try:
<div onclick="$(this).toggleClass('newclass')">click me</div>
Or pure JS:
<div onclick="this.classList.toggle('newclass');">click me</div>
The simplest way is to get the width and height of an ImageView in onWindowFocusChanged method of the activity
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
height = mImageView.getHeight();
width = mImageView.getWidth();
}
First of all bar is not the only one pipe progress meter. The other (maybe even more known) is pv (pipe viewer).
Secondly bar and pv can be used for example like this:
$ bar file1 | wc -l
$ pv file1 | wc -l
or even:
$ tail -n 100 file1 | bar | wc -l
$ tail -n 100 file1 | pv | wc -l
one useful trick if you want to make use of bar and pv in commands that are working with files given in arguments, like e.g. copy file1 file2, is to use process substitution:
$ copy <(bar file1) file2
$ copy <(pv file1) file2
Process substitution is a bash magic thing that creates temporary fifo pipe files /dev/fd/ and connect stdout from runned process (inside parenthesis) through this pipe and copy sees it just like an ordinary file (with one exception, it can only read it forwards).
Update:
bar command itself allows also for copying. After man bar:
bar --in-file /dev/rmt/1cbn --out-file \
tape-restore.tar --size 2.4g --buffer-size 64k
But process substitution is in my opinion more generic way to do it. An it uses cp program itself.
This actually removes the contents from the list, but doesn't replace the old label with a new empty list:
del lst[:]
Here's an example:
lst1 = [1, 2, 3]
lst2 = lst1
del lst1[:]
print(lst2)
For the sake of completeness, the slice assignment has the same effect:
lst[:] = []
It can also be used to shrink a part of the list while replacing a part at the same time (but that is out of the scope of the question).
Note that doing lst = []
does not empty the list, just creates a new object and binds it to the variable lst
, but the old list will still have the same elements, and effect will be apparent if it had other variable bindings.
While the solutions here are workable, more recent technology has made for what I think is a better solution. CSS Grid Layout allows us to structure a more elegant solution.
The CSS below provides a 2-column "settings" structure, where the first column is expected to be a right-aligned label, followed by some content in the second column. More complicated content can be presented in the second column by wrapping it in a <div>.
[As a side-note: I use CSS to add the ':' that trails each label, as this is a stylistic element - my preference.]
/* CSS */_x000D_
_x000D_
div.settings {_x000D_
display:grid;_x000D_
grid-template-columns: max-content max-content;_x000D_
grid-gap:5px;_x000D_
}_x000D_
div.settings label { text-align:right; }_x000D_
div.settings label:after { content: ":"; }
_x000D_
<!-- HTML -->_x000D_
_x000D_
<div class="settings">_x000D_
<label>Label #1</label>_x000D_
<input type="text" />_x000D_
_x000D_
<label>Long Label #2</label>_x000D_
<span>Display content</span>_x000D_
_x000D_
<label>Label #3</label>_x000D_
<input type="text" />_x000D_
</div>
_x000D_
Change the button to
<button id="search">Search</button>
and add the following script
var url = '@Url.Action("DisplaySearchResults", "Search")';
$('#search').click(function() {
var keyWord = $('#Keyword').val();
$('#searchResults').load(url, { searchText: keyWord });
})
and modify the controller method to accept the search text
public ActionResult DisplaySearchResults(string searchText)
{
var model = // build list based on parameter searchText
return PartialView("SearchResults", model);
}
The jQuery .load
method calls your controller method, passing the value of the search text and updates the contents of the <div>
with the partial view.
Side note: The use of a <form>
tag and @Html.ValidationSummary()
and @Html.ValidationMessageFor()
are probably not necessary here. Your never returning the Index
view so ValidationSummary
makes no sense and I assume you want a null
search text to return all results, and in any case you do not have any validation attributes for property Keyword
so there is nothing to validate.
Edit
Based on OP's comments that SearchCriterionModel
will contain multiple properties with validation attributes, then the approach would be to include a submit button and handle the forms .submit()
event
<input type="submit" value="Search" />
var url = '@Url.Action("DisplaySearchResults", "Search")';
$('form').submit(function() {
if (!$(this).valid()) {
return false; // prevent the ajax call if validation errors
}
var form = $(this).serialize();
$('#searchResults').load(url, form);
return false; // prevent the default submit action
})
and the controller method would be
public ActionResult DisplaySearchResults(SearchCriterionModel criteria)
{
var model = // build list based on the properties of criteria
return PartialView("SearchResults", model);
}
The accepted answer is correct, but I prefer:
@{int count = 0;}
@foreach (var item in Model.Resources)
{
@Html.Raw(count <= 3 ? "<div class=\"resource-row\">" : "")
// some code
@Html.Raw(count <= 3 ? "</div>" : "")
@(count++)
}
I hope this inspires someone, even though I'm late to the party.
Here is a one liner linq version of the accepted answer:
Enumerable.Range(0, reader.FieldCount).Any(i => reader.GetName(i) == "COLUMN_NAME_GOES_HERE")
for the records since this is an old post and since nobody mentioned it, check if you forgot (as I did) to set the android.permission.INTERNET flag in AndroidManifest.xml as, i.e.:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.android.webviewdemo">
<uses-permission android:name="android.permission.INTERNET"/>
<application android:icon="@drawable/icon">
<activity android:name=".WebViewDemo" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Duration.ofMinutes( 260L )
.toString()
PT4H20M
… or …
LocalTime.MIN.plus(
Duration.ofMinutes( 260L )
).toString()
04:20
Duration
The java.time classes include a pair of classes to represent spans of time. The Duration
class is for hours-minutes-seconds, and Period
is for years-months-days.
Duration d = Duration.ofMinutes( 260L );
Duration
partsAccess each part of the Duration
by calling to…Part
. These methods were added in Java 9 and later.
long days = d.toDaysPart() ;
int hours = d.toHoursPart() ;
int minutes = d.toMinutesPart() ;
int seconds = d.toSecondsPart() ;
int nanos = d.toNanosPart() ;
You can then assemble your own string from those parts.
The ISO 8601 standard defines textual formats for date-time values. For spans of time unattached to the timeline, the standard format is PnYnMnDTnHnMnS
. The P
marks the beginning, and the T
separates the years-month-days from the hours-minutes-seconds. So an hour and a half is PT1H30M
.
The java.time classes use ISO 8601 formats by default for parsing and generating strings. The Duration
and Period
classes use this particular standard format. So simply call toString
.
String output = d.toString();
PT4H20M
For alternate formatting, build your own String in Java 9 and later (not in Java 8) with the Duration::to…Part
methods. Or see this Answer for using regex to manipulate the ISO 8601 formatted string.
LocalTime
I strongly suggest using the standard ISO 8601 format instead of the extremely ambiguous and confusing clock format of 04:20
. But if you insist, you can get this effect by hacking with the LocalTime
class. This works if your duration is not over 24 hours.
LocalTime hackUseOfClockAsDuration = LocalTime.MIN.plus( d );
String output = hackUseOfClockAsDuration.toString();
04:20
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
You can change the case of String before using it, like this
String name1 = fname.getText().toString().toLowerCase();
String name2 = sname.getText().toString().toLowerCase();
Then continue with rest operation.
Use assertNotNull(obj)
. assert
means must be
.
Collapse to definitions
CTRL + M, O
Expand all outlining
CTRL + M, X
Expand or collapse everything
CTRL + M, L
This also works with other languages like TypeScript and JavaScript
Another option would be to use the chromestorage API. This allows storage of user data with optional syncing across sessions.
One downside is that it is asynchronous.
In my case the problem was because of conflicting Jars.
Here is the full list of jars which is working absolutely fine for me.
antlr-2.7.7.jar
byte-buddy-1.8.12.jar
c3p0-0.9.5.2.jar
classmate-1.3.4.jar
dom4j-1.6.1.jar
geolatte-geom-1.3.0.jar
hibernate-c3p0-5.3.1.Final.jar
hibernate-commons-annotations-5.0.3.Final.jar
hibernate-core-5.3.1.Final.jar
hibernate-envers-5.3.1.Final.jar
hibernate-jpamodelgen-5.3.1.Final.jar
hibernate-osgi-5.3.1.Final.jar
hibernate-proxool-5.3.1.Final.jar
hibernate-spatial-5.3.1.Final.jar
jandex-2.0.3.Final.jar
javassist-3.22.0-GA.jar
javax.interceptor-api-1.2.jar
javax.persistence-api-2.2.jar
jboss-logging-3.3.2.Final.jar
jboss-transaction-api_1.2_spec-1.1.1.Final.jar
jts-core-1.14.0.jar
mchange-commons-java-0.2.11.jar
mysql-connector-java-5.1.21.jar
org.osgi.compendium-4.3.1.jar
org.osgi.core-4.3.1.jar
postgresql-42.2.2.jar
proxool-0.8.3.jar
slf4j-api-1.6.1.jar
I had to COPY
and untar java package in my docker image.
When I compared the docker image size created using ADD it was 180MB bigger than the one created using COPY, tar -xzf *.tar.gz and rm *.tar.gz
This means that although ADD removes the tar file, it is still kept somewhere. And its making the image bigger!!
Java access modifies which you can use
Access modifier can be applicable for class
, field
[About], method
. Try to access, subclass or override this.
field
or method
is through a class
.class
(subclass) access modifier can be any.method
(override) access modifier should be the same or expand itTop level class(first level scope) can be public
and default
. Nested class
[About] can have any of them
package
is not applying for package hierarchy
You can try with ParseExact
method
Sample
Dim format As String
format = "d"
Dim provider As CultureInfo = CultureInfo.InvariantCulture
result = Date.ParseExact(DateString, format, provider)
With Xcode 7 you are no longer required to have a developer account in order to test your apps on your device:
Check it out here.
Please notice that this is the officially supported by Apple, so there's no need of jailbroken devices or testing on the simulator, but you'll have to use Xcode 7 (currently in beta by the time of this post) or later.
I successfully deployed an app to my iPhone without a developer account. You'll have to use your iCloud account to solve the provisioning profile issues. Just add your iCloud account and assign it in the Team dropdown (in the Identity menu) and the Fix Issue button should do the rest.
UPDATE:
Some people are having problems with iOS 8.4, here is how to fix it.
What everyone here is missing is Java's guarantee of definite assignment for final member variables.
For a class C with final member variable V, every possible execution path through every constructor of C must assign V exactly once - failing to assign V or assigning V two or more times will result in an error.
C#'s readonly keyword has no such guarantee - the compiler is more than happy to leave readonly members unassigned or allow you to assign them multiple times within a constructor.
So, final and readonly (at least with respect to member variables) are definitely not equivalent - final is much more strict.
JavaScript that allows for syntax checking
JSHint-Eclipse
and autosuggestions for .js files in Eclipse?
http://www.nodeclipse.org/updates/anide/
As Nodeclipse lead, I am always looking for what is available in Eclipse ecosystem. Nodeclipse site has even more links, and I am inviting to collaborate on the JavaScript tools on GitHub
I was having this problem on Windows but wasn't prepared to look into the ramifications of using config --global core.autocrlf false
I also wasn't prepared to abandon other private branches and goodies in my stash and start with a fresh clone. I just need to get something done. Now.
This worked for me, on the idea that you let git rewrite your working directory completely:
git rm --cached -r .
git reset --hard
(Note that running just git reset --hard
wasn't good enough nor was a plain rm
on the files before the reset
as are suggested in the comments to the original question)
You can try this rating bar with much better animations
A very late reply, but just in case someone needs a ready function for this:
i.e.
slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(x, y)
as in @Adam Marples's answer.
SELECT CAST(CAST(year AS varchar) + '/' + CAST(month AS varchar) + '/' + CAST(day as varchar) AS datetime) AS MyDateTime
FROM table
By adding a class to either the first tr
or the subsequent tr
s. There is no crossbrowser way of selecting the rows you want with CSS alone.
However, if you don't care about Internet Explorer 6, 7 or 8:
tr:not(:first-child) {
color: red;
}
if you just type
$ git update
on bash git will inform you that 'update' command is no longer working and will display the correct command which is 'update-git-for-windows'
but still the update will continue you just have to press " y "
if you are having issues on it run the bashh as administrator or add the 'git.exe' path to the "allowed apps through controlled folder access".
The backslash escapes the #, interpreting it as its literal character instead of a comment character.
Try This
div.circle {_x000D_
-moz-border-radius: 50px/50px;_x000D_
-webkit-border-radius: 50px 50px;_x000D_
border-radius: 50px/50px;_x000D_
border: solid 21px #f00;_x000D_
width: 50px;_x000D_
height: 50px;_x000D_
}_x000D_
_x000D_
div.square {_x000D_
border: solid 21px #f0f;_x000D_
width: 50px;_x000D_
height: 50px;_x000D_
}
_x000D_
<div class="circle">_x000D_
<img/>_x000D_
</div>_x000D_
<hr/>_x000D_
<div class="square">_x000D_
<img/>_x000D_
</div>
_x000D_
You can find the info here: http://www.php.net/manual/en/language.operators.comparison.php
It's scarce because it wasn't added until PHP4. What you have is fine though, if you know there may be a type difference then it's a much better comparison, since it's testing value and type in the comparison, not just value.
Consider a scenario where Test1, Test2 and Test3 are three classes. The Test3 class inherits Test2 and Test1 classes. If Test1 and Test2 classes have same method and you call it from child class object, there will be ambiguity to call method of Test1 or Test2 class but there is no such ambiguity for interface as in interface no implementation is there.
I don't think there's any way to get width of texts in variable-width fonts, especially in javascript.
The only way I can think is to make a hidden element that has variable width set by css, put text in its innerHTML, and get the width of that element. So you may be able to apply this method to cope with textarea auto-sizing problem.
I found this problem too. Because centos service depend on multi-user.target for none desktop Cenots 7.2. so I delete multi-user.target from my .service file. It had missed.
Split it on the ,
character;
var string = "0,1";
var array = string.split(",");
alert(array[0]);
If you are running a nginx + uwsgi setup vagrant then the main problem is the Virtual box bug with send file as mentioned in some of the answers. However to resolve it you have to disable sendfile in both nginx and uwsgi.
In nginx.conf sendfile off
uwsgi application / config --disable-sendfile
I also had the same problem, but gladelly I fixed this by changing the type like from type="submit"
to type="button"
and it worked.
string userName="";
string userId = "";
int uid = 0;
if (HttpContext.Current != null && HttpContext.Current.User != null
&& HttpContext.Current.User.Identity.Name != null)
{
userName = HttpContext.Current.User.Identity.Name;
}
using (DevEntities context = new DevEntities())
{
uid = context.Users.Where(x => x.UserName == userName).Select(x=>x.Id).FirstOrDefault();
return uid;
}
return uid;
Demo: http://www.jqueryscript.net/demo/jQuery-Plugin-For-Fixed-Table-Header-Footer-Columns-TableHeadFixer/
HTML
<h2>TableHeadFixer Fix Left Column</h2>
<div id="parent">
<table id="fixTable" class="table">
<thead>
<tr>
<th>Ano</th>
<th>Jan</th>
<th>Fev</th>
<th>Mar</th>
<th>Abr</th>
<th>Maio</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
</tbody>
</table>
</div>
JS
$(document).ready(function() {
$("#fixTable").tableHeadFixer({"head" : false, "right" : 1});
});
CSS
#parent {
height: 300px;
}
#fixTable {
width: 1800px !important;
}
If you know this when the page is rendered, which it sounds like you do because the database has a value, it's better to disable it when rendered instead of JavaScript. To do that, just add the readonly
attribute (or disabled
, if you want to remove it from the form submission as well) to the <input>
, like this:
<input type="text" disabled="disabled" />
//or...
<input type="text" readonly="readonly" />
Try following source code it worked for me
//Fetching id from shared preferences
SharedPreferences sharedPreferences;
sharedPreferences =getSharedPreferences(Constant.SHARED_PREF_NAME, Context.MODE_PRIVATE);
getUserLogin = sharedPreferences.getString(Constant.ID_SHARED_PREF, "");
For Eclipse, modify project.properties
like this: (your path please)
android.library.reference.1=../../../../workspace/appcompat_v7_22
And remove android-support-v4.jar
file in your project's libs
folder.
Create a wrapper around properties and assume your A value has keys A.1, A.2, etc. Then when asked for A your wrapper will read all the A.* items and build the list. HTH
height:100% works if the parent container has a specified height property else, it won't work
Note that it is now possible to use some of C++11 std::thread in the win32 threading mode. These header-only adapters worked out of the box for me: https://github.com/meganz/mingw-std-threads
From the revision history it looks like there is some recent attempt to make this a part of the mingw64 runtime.
I had to do recently something similar, I used this snippet:
const getNode = () =>
for (let el = this.$el; el && el.parentNode; el = el.parentNode){
if (/* insert your condition here */) return el;
}
return null
})
The function will returns the element that fulfills your condition. It was a CSS class on the element that I was looking for. If there isn't such element then it will return null
In case somebody would look for multiple elements it only returns closest parent to the element that you provided.
My example was:
if (el.classList?.contains('o-modal')) return el;
I used it in a vue component (this.$el) change that to your document.getElementById
function and you're good to go. Hope it will be useful for some people ??
I've written a Visual Studio Code extension for changing case (not only upper case, many other options): https://github.com/wmaurer/vscode-change-case
To map the upper case command to a keybinding (e.g. Ctrl+T U), click File -> Preferences -> Keyboard shortcuts, and insert the following into the json config:
{
"key": "ctrl+t u",
"command": "extension.changeCase.upper",
"when": "editorTextFocus"
}
EDIT:
With the November 2016 (release notes) update of VSCode, there is built-in support for converting to upper case and lower case via the commands editor.action.transformToUppercase
and editor.action.transformToLowercase
. These don't have default keybindings.
The change-case extension is still useful for other text transformations, e.g. camelCase, PascalCase, snake-case, etc.
python -m pip install -r requirements.txt
Referece: How to install packages using pip according to the requirements.txt file from a local directory?
If you're open to a Perl solution, here one similar to fedorqui's awk solution:
perl -F/ -lane 'print $F[-1]' input
-F/
specifies /
as the field separator
$F[-1]
is the last element in the @F
autosplit array
Basically if you want to set size and make it change then set it to state on layout like this:
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, View } from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'yellow',
},
View1: {
flex: 2,
margin: 10,
backgroundColor: 'red',
elevation: 1,
},
View2: {
position: 'absolute',
backgroundColor: 'orange',
zIndex: 3,
elevation: 3,
},
View3: {
flex: 3,
backgroundColor: 'green',
elevation: 2,
},
Text: {
fontSize: 25,
margin: 20,
color: 'white',
},
});
class Example extends Component {
constructor(props) {
super(props);
this.state = {
view2LayoutProps: {
left: 0,
top: 0,
width: 50,
height: 50,
}
};
}
onLayout(event) {
const {x, y, height, width} = event.nativeEvent.layout;
const newHeight = this.state.view2LayoutProps.height + 1;
const newLayout = {
height: newHeight ,
width: width,
left: x,
top: y,
};
this.setState({ view2LayoutProps: newLayout });
}
render() {
return (
<View style={styles.container}>
<View style={styles.View1}>
<Text>{this.state.view2LayoutProps.height}</Text>
</View>
<View onLayout={(event) => this.onLayout(event)}
style={[styles.View2, this.state.view2LayoutProps]} />
<View style={styles.View3} />
</View>
);
}
}
AppRegistry.registerComponent(Example);
You can create many more variation of how it should be modified, by using this in another component which has Another view as wrapper and create an onResponderRelease callback, which could pass the touch event location into the state, which could be then passed to child component as property, which could override onLayout updated state, by placing {[styles.View2, this.state.view2LayoutProps, this.props.touchEventTopLeft]}
and so on.
Another better option is to not depend on PRINT or RAISERROR and just load your "print" statements into a ##Temp table in TempDB or a permanent table in your database which will give you visibility to the data immediately via a SELECT statement from another window. This works the best for me. Using a permanent table then also serves as a log to what happened in the past. The print statements are handy for errors, but using the log table you can also determine the exact point of failure based on the last logged value for that particular execution (assuming you track the overall execution start time in your log table.)
I was able to do this by selecting "All" located under the "Keys" header from the left column
Then I clicked the plus button in the top right corner to add a new key
Enter a name for your key and check "APNs"
Then scroll down and select Continue. You will then be brought to a screen presenting you with the option to download your .p8 now or later. In my case, I was presented with a warning that it could only be downloaded once so keep the file safe.
Mix-in annotations work pretty well here as already mentioned. Another possibility beyond per-property @JsonIgnore is to use @JsonIgnoreType if you have a type that should never be included (i.e. if all instances of GeometryCollection properties should be ignored). You can then either add it directly (if you control the type), or using mix-in, like:
@JsonIgnoreType abstract class MixIn { }
// and then register mix-in, either via SerializationConfig, or by using SimpleModule
This can be more convenient if you have lots of classes that all have a single 'IgnoredType getContext()' accessor or so (which is the case for many frameworks)
First of all.
You can use JSON to Kotlin Data class converter plugin in Android Studio for JSON mapping to POJO classes (kotlin data class). This plugin will annotate your Kotlin data class according to JSON.
Then you can use GSON converter to convert JSON to Kotlin.
Follow this Complete tutorial: Kotlin Android JSON Parsing Tutorial
If you want to parse json manually.
val **sampleJson** = """
[
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio
reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita"
}]
"""
Code to Parse above JSON Array and its object at index 0.
var jsonArray = JSONArray(sampleJson)
for (jsonIndex in 0..(jsonArray.length() - 1)) {
Log.d("JSON", jsonArray.getJSONObject(jsonIndex).getString("title"))
}
The nested generics-problem can be avoided with the @Captor annotation:
public class Test{
@Mock
private Service service;
@Captor
private ArgumentCaptor<ArrayList<SomeType>> captor;
@Before
public void init(){
MockitoAnnotations.initMocks(this);
}
@Test
public void shouldDoStuffWithListValues() {
//...
verify(service).doStuff(captor.capture()));
}
}
The correct answer to this particular questions is "don't select". Sometimes you have to select or activate, but 99% of the time you don't. If your code looks like
Select something
Do something to the selection
Select something else
Do something to the selection
You probably need to refactor and consider not selecting.
The error, Method 'Range' of object '_Worksheet' failed, error 1004, that you're getting is because the sheet with the button on it doesn't have a range named "Result". Most (maybe all) properties that return an object have a default Parent object. In this case, you're using the Range property to return a Range object. Because you don't qualify the Range property, Excel uses the default.
The default Parent object can be different based on the circumstances. If your code were in a standard module, then the ActiveSheet would be the default Parent and Excel would try to resolve ActiveSheet.Range("Result"). Your code is in a sheet's class module (the sheet with the button on it). When the unqualified reference is used there, the default Parent is the sheet that's attached to that module. In this case they're the same because the sheet has to be active to click the button, but that isn't always the case.
When Excel gives the error that includes text like '_Object' (yours said '_Worksheet') it's always referring to the default Parent object - the underscore gives that away. Generally the way to fix that is to qualify the reference by being explicit about the parent. But in the case of selecting and activating when you don't need to, it's better to just refactor the code.
Here's one way to write your code without any selecting or activating.
Private Sub cmdRecord_Click()
Dim shSource As Worksheet
Dim shDest As Worksheet
Dim rNext As Range
'Me refers to the sheet whose class module you're in
'Me.Parent refers to the workbook
Set shSource = Me.Parent.Worksheets("BxWsn Simulation")
Set shDest = Me.Parent.Worksheets("Reslt Record")
Set rNext = shDest.Cells(shDest.Rows.Count, 1).End(xlUp).Offset(1, 0)
shSource.Range("Result").Copy
rNext.PasteSpecial xlPasteFormulasAndNumberFormats
Application.CutCopyMode = False
End Sub
When I'm in a class module, like the sheet's class module that you're working in, I always try to do things in terms of that class. So I use Me.Parent instead of ActiveWorkbook. It makes the code more portable and prevents unexpected problems when things change.
I'm sure the code you have now runs in milliseconds, so you may not care, but avoiding selecting will definitely speed up your code and you don't have to set ScreenUpdating. That may become important as your code grows or in a different situation.
Looking at the source code for dumpsys and service, you can get the list of services available by executing the following:
adb shell service -l
You can then supply the service name you are interested in to dumpsys to get the specific information. For example (note that not all services provide dump info):
adb shell dumpsys activity
adb shell dumpsys cpuinfo
adb shell dumpsys battery
As you can see in the code (and in K_Anas's answer), if you call dumpsys without any service name, it will dump the info on all services in one big dump:
adb shell dumpsys
Some services can receive additional arguments on what to show which normally is explained if you supplied a -h
argument, for example:
adb shell dumpsys activity -h
adb shell dumpsys window -h
adb shell dumpsys meminfo -h
adb shell dumpsys package -h
adb shell dumpsys batteryinfo -h
Nexus 5 with Win7 x64
-USB computer connection : Uncheck MTP and PTP
-Use a 2.0 USB port.
-Try to use the original USB cable.
Now device manager will detect nexus 5 as an androide device with ADB driver.
For any non-trivial application (I.E. the application must receive and handle different kinds of messages with different lengths), the solution to your particular problem isn't necessarily just a programming solution - it's a convention, I.E. a protocol.
In order to determine how many bytes you should pass to your read
call, you should establish a common prefix, or header, that your application receives. That way, when a socket first has reads available, you can make decisions about what to expect.
A binary example might look like this:
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <arpa/inet.h>
enum MessageType {
MESSAGE_FOO,
MESSAGE_BAR,
};
struct MessageHeader {
uint32_t type;
uint32_t length;
};
/**
* Attempts to continue reading a `socket` until `bytes` number
* of bytes are read. Returns truthy on success, falsy on failure.
*
* Similar to @grieve's ReadXBytes.
*/
int readExpected(int socket, void *destination, size_t bytes)
{
/*
* Can't increment a void pointer, as incrementing
* is done by the width of the pointed-to type -
* and void doesn't have a width
*
* You can in GCC but it's not very portable
*/
char *destinationBytes = destination;
while (bytes) {
ssize_t readBytes = read(socket, destinationBytes, bytes);
if (readBytes < 1)
return 0;
destinationBytes += readBytes;
bytes -= readBytes;
}
return 1;
}
int main(int argc, char **argv)
{
int selectedFd;
// use `select` or `poll` to wait on sockets
// received a message on `selectedFd`, start reading
char *fooMessage;
struct {
uint32_t a;
uint32_t b;
} barMessage;
struct MessageHeader received;
if (!readExpected (selectedFd, &received, sizeof(received))) {
// handle error
}
// handle network/host byte order differences maybe
received.type = ntohl(received.type);
received.length = ntohl(received.length);
switch (received.type) {
case MESSAGE_FOO:
// "foo" sends an ASCII string or something
fooMessage = calloc(received.length + 1, 1);
if (readExpected (selectedFd, fooMessage, received.length))
puts(fooMessage);
free(fooMessage);
break;
case MESSAGE_BAR:
// "bar" sends a message of a fixed size
if (readExpected (selectedFd, &barMessage, sizeof(barMessage))) {
barMessage.a = ntohl(barMessage.a);
barMessage.b = ntohl(barMessage.b);
printf("a + b = %d\n", barMessage.a + barMessage.b);
}
break;
default:
puts("Malformed type received");
// kick the client out probably
}
}
You can likely already see one disadvantage of using a binary format - for each attribute greater than a char
you read, you will have to ensure its byte order is correct using the ntohl
or ntohs
functions.
An alternative is to use byte-encoded messages, such as simple ASCII or UTF-8 strings, which avoid byte-order issues entirely but require extra effort to parse and validate.
There are two final considerations for network data in C.
The first is that some C types do not have fixed widths. For example, the humble int
is defined as the word size of the processor, so 32 bit processors will produce 32 bit int
s, while 64 bit processors will produces 64 bit int
s. Good, portable code should have network data use fixed-width types, like those defined in stdint.h
.
The second is struct padding. A struct with different-widthed members will add data in between some members to maintain memory alignment, making the struct faster to use in the program but sometimes producing confusing results.
#include <stdio.h>
#include <stdint.h>
int main()
{
struct A {
char a;
uint32_t b;
} A;
printf("sizeof(A): %ld\n", sizeof(A));
}
In this example, its actual width won't be 1 char
+ 4 uint32_t
= 5 bytes, it'll be 8:
mharrison@mharrison-KATANA:~$ gcc -o padding padding.c
mharrison@mharrison-KATANA:~$ ./padding
sizeof(A): 8
This is because 3 bytes are added after char a
to make sure uint32_t b
is memory-aligned.
So if you write
a struct A
, then attempt to read a char
and a uint32_t
on the other side, you'll get char a
, and a uint32_t where the first three bytes are garbage and the last byte is the first byte of the actual integer you wrote.
Either document your data format explicitly as C struct types or, better yet, document any padding bytes they might contain.
You have an incorrect ON
clause at the join, this works:
inner join Employees m on e.mgr = m.EmpId;
The mgr
column references the EmpId
column.
This was the only thing that worked for me from https://github.com/zsh-users/zsh-completions/issues/433#issuecomment-600582607. Thanks https://github.com/malaquiasdev!
$ cd /usr/local/share/
$ sudo chmod -R 755 zsh
$ sudo chown -R root:staff zsh
The accepted answer is invalid with the double EXEC (only need the first EXEC):
DECLARE @returnvalue int;
EXEC @returnvalue = SP_SomeProc
PRINT @returnvalue
And you still need to call PRINT (at least in Visual Studio).
Question = [67, 121, 98, 101, 114, 71, 105, 114, 108, 122]
print(''.join(chr(number) for number in Question))
I like this, so that you can add whatever fields you want and print it that way.
function printPage() {
var w = window.open();
var headers = $("#headers").html();
var field= $("#field1").html();
var field2= $("#field2").html();
var html = "<!DOCTYPE HTML>";
html += '<html lang="en-us">';
html += '<head><style></style></head>';
html += "<body>";
//check to see if they are null so "undefined" doesnt print on the page. <br>s optional, just to give space
if(headers != null) html += headers + "<br/><br/>";
if(field != null) html += field + "<br/><br/>";
if(field2 != null) html += field2 + "<br/><br/>";
html += "</body>";
w.document.write(html);
w.window.print();
w.document.close();
};
You can also do what the "Service Reference" generated code does
public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
public ServiceXClient() { }
public ServiceXClient(string endpointConfigurationName) :
base(endpointConfigurationName) { }
public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) { }
public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) { }
public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
base(binding, remoteAddress) { }
public bool ServiceXWork(string data, string otherParam)
{
return base.Channel.ServiceXWork(data, otherParam);
}
}
Where IServiceX is your WCF Service Contract
Then your client code:
var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");
pde is extesion for:
Processing: Java derived language
Wiring: C/C++ derived language (Wiring is derived from Processing)
Early versions of Arduino: C/C++ derived (Arduino IDE is derived from Wiring)
For Arduino for example the IDE preprocessor is adding some #defines and some C/C++ files before giving all to gcc.
You can use the .some
method referenced here.
The
some()
method tests whether at least one element in the array passes the test implemented by the provided function.
// test cases
var str1 = 'hi, how do you do?';
var str2 = 'regular string';
// do the test strings contain these terms?
var conditions = ["hello", "hi", "howdy"];
// run the tests against every element in the array
var test1 = conditions.some(el => str1.includes(el));
var test2 = conditions.some(el => str2.includes(el));
// display results
console.log(str1, ' ===> ', test1);
console.log(str2, ' ===> ', test2);
_x000D_
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
window.location.href = marker.url;
}
})(marker, i));
http://docs.ansible.com/ansible/latest/plugins/lookup/dig.html
so in template, for e. g.:
{{ lookup('dig', ansible_host) }}
Notes:
But still it serves 99 % (figuratively speaking) of use cases.
If you want a string mm/dd/yyyy
instead of the datetime
object, you can use strftime
(string format time):
>>> dt.datetime.today().strftime("%m/%d/%Y")
# ^ note parentheses
'02/12/2014'
You need to use setInterval
to trigger the change, but you also need to clear the timer when the component unmounts to prevent it leaving errors and leaking memory:
componentDidMount() {
this.interval = setInterval(() => this.setState({ time: Date.now() }), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
Always better to start with an example :).
Let's assume you have two modules A and B.
You want module A to be notified when some event/condition occurs in module B. However, module B has no idea about your module A. All it knows is an address to a particular function (of module A) through a function pointer that is provided to it by module A.
So all B has to do now, is "callback" into module A when a particular event/condition occurs by using the function pointer. A can do further processing inside the callback function.
*) A clear advantage here is that you are abstracting out everything about module A from module B. Module B does not have to care who/what module A is.
Instead of "w"
use "a"
(append) mode with open
function:
with open("games.txt", "a") as text_file:
Make a virtual enviroment using python3
virtualenv env_name --python="python3"
and run the following command
pip3 install opencv-python
Probably because of optimizations. Excel 2007 can have a maximum of 16 384 columns and 1 048 576 rows. Strange numbers?
14 bits = 16 384, 20 bits = 1 048 576
14 + 20 = 34 bits = more than one 32 bit register can hold.
But they also need to store the format of the cell (text, number etc) and formatting (colors, borders etc). Assuming they use two 32-bit words (64 bit) they use 34 bits for the cell number and have 30 bits for other things.
Why is that important? In memory they don't need to allocate all the memory needed for the whole spreadsheet but only the memory necessary for your data, and every data is tagged with in what cell it is supposed to be in.
Update 2016:
Found a link to Microsoft's specification for Excel 2013 & 2016
You can use <hr>
for a vertical line as well.
Set the width
to 1
and the size(height) as long as you want.
I used 500 in my example(demo):
With <hr width="1" size="500">
Add readonly
:
<input type="text" value="3" class="field left" readonly>
If you want the value to be not submitted in a form, instead add the disabled
attribute.
<input type="text" value="3" class="field left" disabled>
There is no way to use CSS that always works to do this.
Why? CSS can't "disable" anything. You can still turn off display or visibility and use pointer-events: none
but pointer-events
doesn't work on versions of IE that came out earlier than IE 11.
You can use map
. Here is an example implementation:
case 'SOME_ACTION':
return {
...state,
contents: state.contents.map(
(content, i) => i === 1 ? {...content, text: action.payload}
: content
)
}
-- i use something like this, with concepts and some code stolen from asktom.
-- suggestions for improvements are welcome
WITH
sess AS
(
SELECT *
FROM V$SESSION
WHERE USERNAME = USER
ORDER BY SID
)
SELECT si.SID,
si.LOCKWAIT,
si.OSUSER,
si.PROGRAM,
si.LOGON_TIME,
si.STATUS,
(
SELECT ROUND(USED_UBLK*8/1024,1)
FROM V$TRANSACTION,
sess
WHERE sess.TADDR = V$TRANSACTION.ADDR
AND sess.SID = si.SID
) rollback_remaining,
(
SELECT (MAX(DECODE(PIECE, 0,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 1,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 2,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 3,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 4,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 5,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 6,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 7,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 8,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 9,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 10,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 11,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 12,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 13,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 14,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 15,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 16,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 17,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 18,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 19,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 20,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 21,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 22,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 23,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 24,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 25,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 26,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 27,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 28,SQL_TEXT,NULL)) ||
MAX(DECODE(PIECE, 29,SQL_TEXT,NULL)))
FROM V$SQLTEXT_WITH_NEWLINES
WHERE ADDRESS = SI.SQL_ADDRESS AND
PIECE < 30
) SQL_TEXT
FROM sess si;
As stated in a comment at
with System.Net.Mail, use port 25 instead of 465:
You must set SSL=true and Port=25. Server responds to your request from unprotected 25 and then throws connection to protected 465.
Vague as the question seems to me, I would probably create a map from the ID to the actual object. In pseudo-java (I didn't check whether it works/compiles), it might be something like:
Map<ID, FlatObject> flatObjectMap = new HashMap<ID, FlatObject>();
for (FlatObject object: flatStructure) {
flatObjectMap.put(object.ID, object);
}
And to look up each parent:
private FlatObject getParent(FlatObject object) {
getRealObject(object.ParentID);
}
private FlatObject getRealObject(ID objectID) {
flatObjectMap.get(objectID);
}
By reusing getRealObject(ID)
and doing a map from object to a collection of objects (or their IDs), you get a parent->children map too.
For symfony 4 users:
$query = $request->query->get('query');
In my app, user experience is better if more memory is used, so I have to decide if I really should free all the memory I can in didReceiveMemoryWarning
. Based on Split's and Jasper Pol's answer, using a maximum of 45% of the total device memory appears to be a safe threshold (thanks guys).
In case someone wants to look at my actual implementation:
#import "mach/mach.h"
- (void)didReceiveMemoryWarning
{
// Remember to call super
[super didReceiveMemoryWarning];
// If we are using more than 45% of the memory, free even important resources,
// because the app might be killed by the OS if we don't
if ([self __getMemoryUsedPer1] > 0.45)
{
// Free important resources here
}
// Free regular unimportant resources always here
}
- (float)__getMemoryUsedPer1
{
struct mach_task_basic_info info;
mach_msg_type_number_t size = sizeof(info);
kern_return_t kerr = task_info(mach_task_self(), MACH_TASK_BASIC_INFO, (task_info_t)&info, &size);
if (kerr == KERN_SUCCESS)
{
float used_bytes = info.resident_size;
float total_bytes = [NSProcessInfo processInfo].physicalMemory;
//NSLog(@"Used: %f MB out of %f MB (%f%%)", used_bytes / 1024.0f / 1024.0f, total_bytes / 1024.0f / 1024.0f, used_bytes * 100.0f / total_bytes);
return used_bytes / total_bytes;
}
return 1;
}
Swift (based on this answer):
func __getMemoryUsedPer1() -> Float
{
let MACH_TASK_BASIC_INFO_COUNT = (sizeof(mach_task_basic_info_data_t) / sizeof(natural_t))
let name = mach_task_self_
let flavor = task_flavor_t(MACH_TASK_BASIC_INFO)
var size = mach_msg_type_number_t(MACH_TASK_BASIC_INFO_COUNT)
var infoPointer = UnsafeMutablePointer<mach_task_basic_info>.alloc(1)
let kerr = task_info(name, flavor, UnsafeMutablePointer(infoPointer), &size)
let info = infoPointer.move()
infoPointer.dealloc(1)
if kerr == KERN_SUCCESS
{
var used_bytes: Float = Float(info.resident_size)
var total_bytes: Float = Float(NSProcessInfo.processInfo().physicalMemory)
println("Used: \(used_bytes / 1024.0 / 1024.0) MB out of \(total_bytes / 1024.0 / 1024.0) MB (\(used_bytes * 100.0 / total_bytes)%%)")
return used_bytes / total_bytes
}
return 1
}
the right ways
const getUser = user => {return { name: user.name, age: user.age };};
const user = { name: "xgqfrms", age: 21 };
console.log(getUser(user));
// {name: "xgqfrms", age: 21}
const getUser = user => ({ name: user.name, age: user.age });
const user = { name: "xgqfrms", age: 21 };
console.log(getUser(user));
// {name: "xgqfrms", age: 21}
https://github.com/lydiahallie/javascript-questions/issues/220
https://mariusschulz.com/blog/returning-object-literals-from-arrow-functions-in-javascript
According to this post, you should enable it in XCode.
//Data Table
protected DataTable tblDynamic
{
get
{
return (DataTable)ViewState["tblDynamic"];
}
set
{
ViewState["tblDynamic"] = value;
}
}
//DynamicReport_GetUserType() function for getting data from DB
System.Data.DataSet ds = manage.DynamicReport_GetUserType();
tblDynamic = ds.Tables[13];
//Add Column as "TypeName"
tblDynamic.Columns.Add(new DataColumn("TypeName", typeof(string)));
//fill column data against ds.Tables[13]
for (int i = 0; i < tblDynamic.Rows.Count; i++)
{
if (tblDynamic.Rows[i]["Type"].ToString()=="A")
{
tblDynamic.Rows[i]["TypeName"] = "Apple";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "B")
{
tblDynamic.Rows[i]["TypeName"] = "Ball";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "C")
{
tblDynamic.Rows[i]["TypeName"] = "Cat";
}
if (tblDynamic.Rows[i]["Type"].ToString() == "D")
{
tblDynamic.Rows[i]["TypeName"] = "Dog;
}
}
Following Romain Guy's comment, here's how I fixed it. Hopefully it'll help anyone else who also had this problem.
I was indeed trying to get the positions of the views before they had been laid out on the screen but it wasn't at all obvious that was happening. Those lines had been placed after the initilisation code ran, so I assumed everything was ready. However, this code was still in onCreate(); by experimenting with Thread.sleep() I discovered that the layout is not actually finalised until after onCreate() all the way to onResume() had finished executing. So indeed, the code was trying to run before the layout had finished being positioned on the screen. By adding the code to an OnClickListener (or some other Listener) the correct values were obtained because it could only be fired after the layout had finished.
The line below was suggested as a community edit:
please use onWindowfocuschanged(boolean hasFocus)
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
const PASSENGER_API = 'api/passengers';
getPassengers(): Observable<Passenger[]> {
return this.http
.get<Passenger[]>(PASSENGER_API)
.pipe(catchError((error: HttpErrorResponse) => throwError(error)));
}
(new to nginx) In my case it was wrong folder name
For config
upstream serv {
server ex2_app_1:3000;
}
make sure the app folder is in ex2 folder:
ex2/app/...
You don't need to convert NumPy
array to Mat
because OpenCV cv2
module can accept NumPy
array.
The only thing you need to care for is that {0,1} is mapped to {0,255} and any value bigger than 1 in NumPy
array is equal to 255. So you should divide by 255 in your code, as shown below.
img = numpy.zeros([5,5,3])
img[:,:,0] = numpy.ones([5,5])*64/255.0
img[:,:,1] = numpy.ones([5,5])*128/255.0
img[:,:,2] = numpy.ones([5,5])*192/255.0
cv2.imwrite('color_img.jpg', img)
cv2.imshow("image", img)
cv2.waitKey()
My tests with git-2.0.0 today indicate that the --mirror option does not copy hooks, the config file, the description file, the info/exclude file, and at least in my test case a few refs (which I don't understand.) I would not call it a "functionally identical copy, interchangeable with the original."
-bash-3.2$ git --version
git version 2.0.0
-bash-3.2$ git clone --mirror /git/hooks
Cloning into bare repository 'hooks.git'...
done.
-bash-3.2$ diff --brief -r /git/hooks.git hooks.git
Files /git/hooks.git/config and hooks.git/config differ
Files /git/hooks.git/description and hooks.git/description differ
...
Only in hooks.git/hooks: applypatch-msg.sample
...
Only in /git/hooks.git/hooks: post-receive
...
Files /git/hooks.git/info/exclude and hooks.git/info/exclude differ
...
Files /git/hooks.git/packed-refs and hooks.git/packed-refs differ
Only in /git/hooks.git/refs/heads: fake_branch
Only in /git/hooks.git/refs/heads: master
Only in /git/hooks.git/refs: meta
I have handled this as below:
try {
response = restTemplate.postForEntity(requestUrl, new HttpEntity<>(requestBody, headers), String.class);
} catch (HttpStatusCodeException ex) {
response = new ResponseEntity<String>(ex.getResponseBodyAsString(), ex.getResponseHeaders(), ex.getStatusCode());
}
NOTE: This answer obviously defeats the purpose of SSL and should be used sparingly as a last resort.
For those having issues with scripts that download scripts that download scripts and want a quick fix, create a file called ~/.curlrc
With the contents
--insecure
This will cause curl to ignore SSL certificate problems by default.
Make sure you delete the file when done.
UPDATE
12 days later I got notified of an upvote on this answer, which made me go "Hmmm, did I follow my own advice remember to delete that .curlrc
?", and discovered I hadn't. So that really underscores how easy it is to leave your curl insecure by following this method.
In more explanation for n. 'pronouns' m.
's answer,
Public-key crypto is not for encrypting arbitrarily long files. One uses a symmetric cipher (say AES) to do the normal encryption. Each time a new random symmetric key is generated, used, and then encrypted with the RSA cipher (public key). The ciphertext together with the encrypted symmetric key is transferred to the recipient. The recipient decrypts the symmetric key using his private key, and then uses the symmetric key to decrypt the message.
There is the flow of Encryption:
+---------------------+ +--------------------+
| | | |
| generate random key | | the large file |
| (R) | | (F) |
| | | |
+--------+--------+---+ +----------+---------+
| | |
| +------------------+ |
| | |
v v v
+--------+------------+ +--------+--+------------+
| | | |
| encrypt (R) with | | encrypt (F) |
| your RSA public key | | with symmetric key (R) |
| | | |
| ASym(PublicKey, R) | | EF = Sym(F, R) |
| | | |
+----------+----------+ +------------+-----------+
| |
+------------+ +--------------+
| |
v v
+--------------+-+---------------+
| |
| send this files to the peer |
| |
| ASym(PublicKey, R) + EF |
| |
+--------------------------------+
And the flow of Decryption:
+----------------+ +--------------------+
| | | |
| EF = Sym(F, R) | | ASym(PublicKey, R) |
| | | |
+-----+----------+ +---------+----------+
| |
| |
| v
| +-------------------------+-----------------+
| | |
| | restore key (R) |
| | |
| | R <= ASym(PrivateKey, ASym(PublicKey, R)) |
| | |
| +---------------------+---------------------+
| |
v v
+---+-------------------------+---+
| |
| restore the file (F) |
| |
| F <= Sym(Sym(F, R), R) |
| |
+---------------------------------+
Besides, you can use this commands:
# generate random symmetric key
openssl rand -base64 32 > /config/key.bin
# encryption
openssl rsautl -encrypt -pubin -inkey /config/public_key.pem -in /config/key.bin -out /config/key.bin.enc
openssl aes-256-cbc -a -pbkdf2 -salt -in $file_name -out $file_name.enc -k $(cat /config/key.bin)
# now you can send this files: $file_name.enc + /config/key.bin.enc
# decryption
openssl rsautl -decrypt -inkey /config/private_key.pem -in /config/key.bin.enc -out /config/key.bin
openssl aes-256-cbc -d -a -in $file_name.enc -out $file_name -k $(cat /config/key.bin)
You can use @WebFilter javax.servlet.annotation.WebFilter on a class that implements javax.servlet.Filter
@WebFilter(urlPatterns = "/*")
public class MyFilter implements Filter {}
Then use @ServletComponentScan to register
Method overriding is when a child class redefines the same method as a parent class, with the same parameters. For example, the standard Java class java.util.LinkedHashSet
extends java.util.HashSet
. The method add()
is overridden in LinkedHashSet
. If you have a variable that is of type HashSet
, and you call its add()
method, it will call the appropriate implementation of add()
, based on whether it is a HashSet
or a LinkedHashSet
. This is called polymorphism.
Method overloading is defining several methods in the same class, that accept different numbers and types of parameters. In this case, the actual method called is decided at compile-time, based on the number and types of arguments. For instance, the method System.out.println()
is overloaded, so that you can pass ints as well as Strings, and it will call a different version of the method.
Here is my Scala solution:
def combinations[A](s: List[A], k: Int): List[List[A]] =
if (k > s.length) Nil
else if (k == 1) s.map(List(_))
else combinations(s.tail, k - 1).map(s.head :: _) ::: combinations(s.tail, k)
You can use window.scrollTo()
, like this:
window.scrollTo(0, 0); // values are x,y-offset
#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29
1.open the terminal.
2.backup your database with following command
your postgres bin - /opt/PostgreSQL/9.1/bin/
your source database server - 192.168.1.111
your backup file location and name - /home/dinesh/db/mydb.backup
your source db name - mydatabase
/opt/PostgreSQL/9.1/bin/pg_dump --host '192.168.1.111' --port 5432 --username "postgres" --no-password --format custom --blobs --file "/home/dinesh/db/mydb.backup" "mydatabase"
3.restore mydb.backup file into destination.
your destination server - localhost
your destination database name - mydatabase
create database for restore the backup.
/opt/PostgreSQL/9.1/bin/psql -h 'localhost' -p 5432 -U postgres -c "CREATE DATABASE mydatabase"
restore the backup.
/opt/PostgreSQL/9.1/bin/pg_restore --host 'localhost' --port 5432 --username "postgres" --dbname "mydatabase" --no-password --clean "/home/dinesh/db/mydb.backup"
I use $(date +"%Y-%m-%d")
or $(date +"%Y-%m-%d %T")
with time and hours.
C# 7 introduced tuples which enables swapping two variables without a temporary one:
int a = 10;
int b = 2;
(a, b) = (b, a);
This assigns b
to a
and a
to b
.
I found it far easier to use a non-editable UITextView
and set the contentOffset
uiTextView.contentOffset = CGPointMake(8, 7);
Some people posted options for Linux and Mac, and the Windows (free) equivalent is, if you can deal with it globally:
Set Windows desktop appearance theme window background color. You can keep current/desired theme, just modify the background color of windows. By default, it is set to white. I change it to a shade of grey. I tried dark grey and black before, but then you have to change text font colors globally, and all that's painful.
But a simple shade of grey as background does the trick globally, works with any color text font as long as the shade of grey is not too dark.
It's not the best solution for all editors/IDEs, as I prefer black, but it's the next best free & global workaround on Windows.
Assuming there is one number per line:
sort <file> | uniq -c
You can use the more verbose --count
flag too with the GNU version, e.g., on Linux:
sort <file> | uniq --count
Based on @Sid's good answer.
Before concatenating, you can load csv files into an intermediate dictionary which gives access to each data set based on the file name (in the form dict_of_df['filename.csv']
). Such a dictionary can help you identify issues with heterogeneous data formats, when column names are not aligned for example.
import os
import glob
import pandas
from collections import OrderedDict
path =r'C:\DRO\DCL_rawdata_files'
filenames = glob.glob(path + "/*.csv")
Note: OrderedDict
is not necessary,
but it'll keep the order of files which might be useful for analysis.
dict_of_df = OrderedDict((f, pandas.read_csv(f)) for f in filenames)
pandas.concat(dict_of_df, sort=True)
Keys are file names f
and values are the data frame content of csv files.
Instead of using f
as a dictionary key, you can also use os.path.basename(f)
or other os.path methods to reduce the size of the key in the dictionary to only the smaller part that is relevant.
I've created the following LinkedList code with many features. It is available for public under the CodeBase github public repo.
Classes:
Node
and LinkedList
Getters and Setters: First
and Last
Functions:
AddFirst(data), AddFirst(node), AddLast(data), RemoveLast(), AddAfter(node, data), RemoveBefore(node), Find(node), Remove(foundNode), Print(LinkedList)
using System;
using System.Collections.Generic;
namespace Codebase
{
public class Node
{
public object Data { get; set; }
public Node Next { get; set; }
public Node()
{
}
public Node(object Data, Node Next = null)
{
this.Data = Data;
this.Next = Next;
}
}
public class LinkedList
{
private Node Head;
public Node First
{
get => Head;
set
{
First.Data = value.Data;
First.Next = value.Next;
}
}
public Node Last
{
get
{
Node p = Head;
//Based partially on https://en.wikipedia.org/wiki/Linked_list
while (p.Next != null)
p = p.Next; //traverse the list until p is the last node.The last node always points to NULL.
return p;
}
set
{
Last.Data = value.Data;
Last.Next = value.Next;
}
}
public void AddFirst(Object data, bool verbose = true)
{
Head = new Node(data, Head);
if (verbose) Print();
}
public void AddFirst(Node node, bool verbose = true)
{
node.Next = Head;
Head = node;
if (verbose) Print();
}
public void AddLast(Object data, bool Verbose = true)
{
Last.Next = new Node(data);
if (Verbose) Print();
}
public Node RemoveFirst(bool verbose = true)
{
Node temp = First;
Head = First.Next;
if (verbose) Print();
return temp;
}
public Node RemoveLast(bool verbose = true)
{
Node p = Head;
Node temp = Last;
while (p.Next != temp)
p = p.Next;
p.Next = null;
if (verbose) Print();
return temp;
}
public void AddAfter(Node node, object data, bool verbose = true)
{
Node temp = new Node(data);
temp.Next = node.Next;
node.Next = temp;
if (verbose) Print();
}
public void AddBefore(Node node, object data, bool verbose = true)
{
Node temp = new Node(data);
Node p = Head;
while (p.Next != node) //Finding the node before
{
p = p.Next;
}
temp.Next = p.Next; //same as = node
p.Next = temp;
if (verbose) Print();
}
public Node Find(object data)
{
Node p = Head;
while (p != null)
{
if (p.Data == data)
return p;
p = p.Next;
}
return null;
}
public void Remove(Node node, bool verbose = true)
{
Node p = Head;
while (p.Next != node)
{
p = p.Next;
}
p.Next = node.Next;
if (verbose) Print();
}
public void Print()
{
Node p = Head;
while (p != null) //LinkedList iterator
{
Console.Write(p.Data + " ");
p = p.Next; //traverse the list until p is the last node.The last node always points to NULL.
}
Console.WriteLine();
}
}
}
Using @yogihosting answer when she used the Microsoft built-in LinkedList and LinkedListNode to answer the question, you can achieve the same results:
using System;
using System.Collections.Generic;
using Codebase;
namespace Cmd
{
static class Program
{
static void Main(string[] args)
{
var tune = new LinkedList(); //Using custom code instead of the built-in LinkedList<T>
tune.AddFirst("do"); // do
tune.AddLast("so"); // do - so
tune.AddAfter(tune.First, "re"); // do - re- so
tune.AddAfter(tune.First.Next, "mi"); // do - re - mi- so
tune.AddBefore(tune.Last, "fa"); // do - re - mi - fa- so
tune.RemoveFirst(); // re - mi - fa - so
tune.RemoveLast(); // re - mi - fa
Node miNode = tune.Find("mi"); //Using custom code instead of the built in LinkedListNode
tune.Remove(miNode); // re - fa
tune.AddFirst(miNode); // mi- re - fa
}
}
Since I spent a lot of time on this issue, I thought I'd share my solution. Since spring 3.0.4, there is a configuration parameter that is called <mvc:resources/>
(more about that on the reference documentation website) which can be used to serve static resources while still using the DispatchServlet on your site's root.
In order to use this, use a directory structure that looks like the following:
src/
springmvc/
web/
MyController.java
WebContent/
resources/
img/
image.jpg
WEB-INF/
jsp/
index.jsp
web.xml
springmvc-servlet.xml
The contents of the files should look like:
src/springmvc/web/HelloWorldController.java:
package springmvc.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloWorldController {
@RequestMapping(value="/")
public String index() {
return "index";
}
}
WebContent/WEB-INF/web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
WebContent/WEB-INF/springmvc-servlet.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- not strictly necessary for this example, but still useful, see http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-controller for more information -->
<context:component-scan base-package="springmvc.web" />
<!-- the mvc resources tag does the magic -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- also add the following beans to get rid of some exceptions -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
</bean>
<!-- JSTL resolver -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
WebContent/jsp/index.jsp:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<h1>Page with image</h1>
<!-- use c:url to get the correct absolute path -->
<img src="<c:url value="/resources/img/image.jpg" />" />
Hope this helps :-)
We can calculate using mid point of line formula,
centre (x,y) = new Point((boundRect.tl().x+boundRect.br().x)/2,(boundRect.tl().y+boundRect.br().y)/2)
Basically, "assert true" will pass and "assert false" will fail. Let's looks at how this will work:
public static void main(String[] args)
{
String s1 = "Hello";
assert checkInteger(s1);
}
private static boolean checkInteger(String s)
{
try {
Integer.parseInt(s);
return true;
}
catch(Exception e)
{
return false;
}
}
Now try to run git commands on terminal.
It might ask you to do a two-step verification the first time, just follow the steps and you're done!
I received this same error in the following Linq statement regarding DailyReport. The problem was that DailyReport had no default constructor. Apparently, it instantiates the object before populating the properties.
var sums = reports
.GroupBy(r => r.CountryRegion)
.Select(cr => new DailyReport
{
CountryRegion = cr.Key,
ProvinceState = "All",
RecordDate = cr.First().RecordDate,
Confirmed = cr.Sum(c => c.Confirmed),
Recovered = cr.Sum(c => c.Recovered),
Deaths = cr.Sum(c => c.Deaths)
});
The best approach for this sort of thing is probably git rebase
. It allows you to pull changes from master into your development branch, but leave all of your development work "on top of" (later in the commit log) the stuff from master. When your new work is complete, the merge back to master is then very straightforward.
Relocation R_X86_64_PC32 against undefined symbol , usually happens when LDFLAGS are set with hardening and CFLAGS not .
Maybe just user error:
If you are using -specs=/usr/lib/rpm/redhat/redhat-hardened-ld at link time,
you also need to use -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 at compile time, and as you are compiling and linking at the same time, you need either both, or drop the -specs=/usr/lib/rpm/redhat/redhat-hardened-ld .
Common fixes :
https://bugzilla.redhat.com/show_bug.cgi?id=1304277#c3
https://github.com/rpmfusion/lxdream/blob/master/lxdream-0.9.1-implicit.patch
Since it appears you are using jQuery, here is a jQuery solution.
$(function() {
$('#Eframe').on("mousewheel", function() {
alert($(document).scrollTop());
});
});
Not much to explain here. If you want, here is the jQuery documentation.
selectedIndex is a JavaScript Select Property. For jQuery you can use this code:
jQuery(document).ready(function($) {
$("#dropDownMenuKategorie").change(function() {
// I personally prefer using console.log(), but if you want you can still go with the alert().
console.log($(this).children('option:selected').index());
});
});
I don't think you can skip rows in a different format with BULK INSERT
/BCP
.
When I run this:
TRUNCATE TABLE so1029384
BULK INSERT so1029384
FROM 'C:\Data\test\so1029384.txt'
WITH
(
--FIRSTROW = 2,
FIELDTERMINATOR= '|',
ROWTERMINATOR = '\n'
)
SELECT * FROM so1029384
I get:
col1 col2 col3
-------------------------------------------------- -------------------------------------------------- --------------------------------------------------
***A NICE HEADER HERE***
0000001234 SSNV 00013893-03JUN09
0000005678 ABCD 00013893-03JUN09
0000009112 0000 00013893-03JUN09
0000009112 0000 00013893-03JUN09
It looks like it requires the '|' even in the header data, because it reads up to that into the first column - swallowing up a newline into the first column. Obviously if you include a field terminator parameter, it expects that every row MUST have one.
You could strip the row with a pre-processing step. Another possibility is to select only complete rows, then process them (exluding the header). Or use a tool which can handle this, like SSIS.
Lets suppose there is a table with following describe command for table (hello)- name char(100), id integer, count integer, city char(100).
we have following basic commands for MySQL -
select * from hello;
select name, city from hello;
etc
select name from hello where id = 8;
select id from hello where name = 'GAURAV';
now lets see multiple where condition -
select name from hello where id = 3 or id = 4 or id = 8 or id = 22;
select name from hello where id =3 and count = 3 city = 'Delhi';
This is how we can use multiple where commands in MySQL.
If you define the ListView
in XAML:
<ListView x:Name="listView"/>
Then you can add columns and populate it in C#:
public Window()
{
// Initialize
this.InitializeComponent();
// Add columns
var gridView = new GridView();
this.listView.View = gridView;
gridView.Columns.Add(new GridViewColumn {
Header = "Id", DisplayMemberBinding = new Binding("Id") });
gridView.Columns.Add(new GridViewColumn {
Header = "Name", DisplayMemberBinding = new Binding("Name") });
// Populate list
this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}
See definition of MyItem
below.
However, it's easier to define the columns in XAML (inside the ListView
definition):
<ListView x:Name="listView">
<ListView.View>
<GridView>
<GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
</GridView>
</ListView.View>
</ListView>
And then just populate the list in C#:
public Window()
{
// Initialize
this.InitializeComponent();
// Populate list
this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}
See definition of MyItem
below.
MyItem
DefinitionMyItem
is defined like this:
public class MyItem
{
public int Id { get; set; }
public string Name { get; set; }
}
I used PdfSharp. It's free, open source and quite convenient to use, but I can't say whether it is the best or not, because I haven't really used anything else.
An alternative is to call the pip
module by using python2.7, as below:
python2.7 -m pip <commands>
For example, you could run python2.7 -m pip install <package>
to install your favorite python modules. Here is a reference: https://stackoverflow.com/a/50017310/4256346.
In case the pip module has not yet been installed for this version of python, you can run the following:
python2.7 -m ensurepip
Running this command will "bootstrap the pip installer". Note that running this may require administrative privileges (i.e. sudo
). Here is a reference: https://docs.python.org/2.7/library/ensurepip.html and another reference https://stackoverflow.com/a/46631019/4256346.
The email addresses I want to validate are going to be used by an ASP.NET web application using the System.Net.Mail
namespace to send emails to a list of people.
So, rather than using some very complex regular expression, I just try to create a MailAddress
instance from the address. The MailAddress
constructor will throw an exception if the address is not formed properly. This way, I know I can at least get the email out of the door. Of course this is server-side validation, but at a minimum you need that anyway.
protected void emailValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
try
{
var a = new MailAddress(txtEmail.Text);
}
catch (Exception ex)
{
args.IsValid = false;
emailValidator.ErrorMessage = "email: " + ex.Message;
}
}
Applies to Ubuntu 14.04 and later releases. Make sure to backup following files before making any changes.
1.Open /etc/apache2/apache2.conf
and search for <Directory /var/www/>
directive and replace path with /home/<USERNAME>/public_html
. You can use * instead of .
2.Open /etc/apache2/sites-available/000-default.conf
and replace DocumentRoot
value property from /var/www/html
to /home/<USERNAME>/public_html
.
Also <Directory /var/www/html>
to <Directory /home/<USERNAME>/public_html
.
3.Open /etc/mods-available/php7.1.conf
. Find and comment following code
<IfModule mod_userdir.c>
<Directory /home/*/public_html>
php_admin_flag engine Off
</Directory>
</IfModule>
Do not turn ON php_admin_flag engine OFF
flag as reason is mentioned in comment above Directive code. Also php version can be 5.0, 7.0 or anything which you have installed.
Create public_html
directory in home/<USERNAME>
.
Restart apache service by executing command sudo service apache2 restart
.
Test by running sample script on server.
Try this:
$.each(result,function(index, value){
console.log('My array has at position ' + index + ', this value: ' + value);
});
Demo :
<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
Based on your question:
<connectionStrings>
<add name="itmall" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True" />
</connectionStrings>
Refer links:
http://www.connectionstrings.com/store-connection-string-in-webconfig/
Retrive connection string from web.config file:
write the below code in your file where you want;
string connstring=ConfigurationManager.ConnectionStrings["itmall"].ConnectionString;
SqlConnection con = new SqlConnection(connstring);
or you can go in your way like
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["itmall"].ConnectionString);
Note:
The "name" which you gave in web.config file and name which you used in connection string must be same(like "itmall" in this solution.)
Try:
DateTime.TryParseExact(txtStartDate.Text, formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out startDate)
There are three options:
results = Model.objects.exclude(a=True).filter(x=5)
Use Q()
objects and the ~
operator
from django.db.models import Q
object_list = QuerySet.filter(~Q(a=True), x=5)
Register a custom lookup function
from django.db.models import Lookup
from django.db.models import Field
@Field.register_lookup
class NotEqual(Lookup):
lookup_name = 'ne'
def as_sql(self, compiler, connection):
lhs, lhs_params = self.process_lhs(compiler, connection)
rhs, rhs_params = self.process_rhs(compiler, connection)
params = lhs_params + rhs_params
return '%s <> %s' % (lhs, rhs), params
Which can the be used as usual:
results = Model.objects.exclude(a=True, x__ne=5)
The Jenkinsfile is written in groovy which uses the Java (and C) form of comments:
/* this
is a
multi-line comment */
// this is a single line comment
You need to have it converted to a Date, where you can then add a number of seconds, and convert it back to a string.
The easiest way is to make the "button image" as a separate image. Then place it over the main image (using "style="position: absolute;". Assign the URL link to "button image". and smile :)
Take another way:
var distinctValues = myCustomerList.
Select(x => x._myCaustomerProperty).Distinct();
The sequence return distinct elements compare them by property '_myCaustomerProperty' .
date -d "yesterday" '+%Y-%m-%d'
or
date=$(date -d "yesterday" '+%Y-%m-%d')
echo $date
Parenthesis ()
are used to enable grouping of regex phrases.
The group(1)
contains the string that is between parenthesis (.*)
so .*
in this case
And group(0)
contains whole matched string.
If you would have more groups (read (...)
) it would be put into groups with next indexes (2, 3 and so on).
Old question; but I always try to use fastest code!
I had a huge list with 69 millions of uint64. np.array() was fastest for me.
df['hashes'] = hashes
Time spent: 17.034842014312744
df['hashes'] = pd.Series(hashes).values
Time spent: 17.141014337539673
df['key'] = np.array(hashes)
Time spent: 10.724546194076538
I would use the built-in ngInclude
directive. In the example below, you don't even need to write any javascript. The templates can just as easily live at a remote url.
Here's a working demo: http://plnkr.co/edit/5ImqWj65YllaCYD5kX5E?p=preview
<p>Select page content template via dropdown</p>
<select ng-model="template">
<option value="page1">Page 1</option>
<option value="page2">Page 2</option>
</select>
<p>Set page content template via button click</p>
<button ng-click="template='page2'">Show Page 2 Content</button>
<ng-include src="template"></ng-include>
<script type="text/ng-template" id="page1">
<h1 style="color: blue;">This is the page 1 content</h1>
</script>
<script type="text/ng-template" id="page2">
<h1 style="color:green;">This is the page 2 content</h1>
</script>
If you don't want to list the fields, and the structure of the tables is the same, you can do:
INSERT INTO `table2` SELECT * FROM `table1`;
or if you want to create a new table with the same structure:
CREATE TABLE new_tbl [AS] SELECT * FROM orig_tbl;
Reference for insert select; Reference for create table select
just recap:
$(document).ready(function() {_x000D_
_x000D_
$('button').on( "click", function() {_x000D_
_x000D_
showAlert( "OK", "alert-success" );_x000D_
_x000D_
} );_x000D_
_x000D_
});_x000D_
_x000D_
function showAlert( message, alerttype ) {_x000D_
_x000D_
$('#alert_placeholder').append( $('#alert_placeholder').append(_x000D_
'<div id="alertdiv" class="alert alert-dismissible fade in ' + alerttype + '">' +_x000D_
'<a class="close" data-dismiss="alert" aria-label="close" >×</a>' +_x000D_
'<span>' + message + '</span>' + _x000D_
'</div>' )_x000D_
);_x000D_
_x000D_
// close it in 3 secs_x000D_
setTimeout( function() {_x000D_
$("#alertdiv").remove();_x000D_
}, 3000 );_x000D_
_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" />_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
<button onClick="" >Show Alert</button>_x000D_
_x000D_
<div id="alert_placeholder" class="container" ></div>
_x000D_
What you can do is set specific width and height to your iframe (for example these could be equal to your window dimensions) and then applying a scale transformation to it. The scale value will be the ratio between your window width and the dimension you wanted to set to your iframe.
E.g.
<iframe width="1024" height="768" src="http://www.bbc.com" style="-webkit-transform:scale(0.5);-moz-transform-scale(0.5);"></iframe>
Just to make searching easier, as mentioned in comments, this is not possible since 3.1
https://stackoverflow.com/a/19856367/6505257
Current working version as of Oct 2020, updated to use maven-antrun-plugin 3.0.0.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>prepare</id>
<phase>package</phase>
<configuration>
<target>
<unzip src="target/shaded-jar/shade-test.jar"
dest="target/unpacked-shade/"/>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
I have below solution which works correctly for me(After doing some Test cases). Extra Test cases are acceptable.
public class DateDiffernce
{
private int m_nDays = -1;
private int m_nWeek;
private int m_nMonth = -1;
private int m_nYear;
public int Days
{
get
{
return m_nDays;
}
}
public int Weeks
{
get
{
return m_nWeek;
}
}
public int Months
{
get
{
return m_nMonth;
}
}
public int Years
{
get
{
return m_nYear;
}
}
public void GetDifferenceBetwwenTwoDate(DateTime objDateTimeFromDate, DateTime objDateTimeToDate)
{
if (objDateTimeFromDate.Date > objDateTimeToDate.Date)
{
DateTime objDateTimeTemp = objDateTimeFromDate;
objDateTimeFromDate = objDateTimeToDate;
objDateTimeToDate = objDateTimeTemp;
}
if (objDateTimeFromDate == objDateTimeToDate)
{
//textBoxDifferenceDays.Text = " Same dates";
//textBoxAllDifference.Text = " Same dates";
return;
}
// If From Date's Day is bigger than borrow days from previous month
// & then subtract.
if (objDateTimeFromDate.Day > objDateTimeToDate.Day)
{
objDateTimeToDate = objDateTimeToDate.AddMonths(-1);
int nMonthDays = DateTime.DaysInMonth(objDateTimeToDate.Year, objDateTimeToDate.Month);
m_nDays = objDateTimeToDate.Day + nMonthDays - objDateTimeFromDate.Day;
}
// If From Date's Month is bigger than borrow 12 Month
// & then subtract.
if (objDateTimeFromDate.Month > objDateTimeToDate.Month)
{
objDateTimeToDate = objDateTimeToDate.AddYears(-1);
m_nMonth = objDateTimeToDate.Month + 12 - objDateTimeFromDate.Month;
}
//Below are best cases - simple subtraction
if (m_nDays == -1)
{
m_nDays = objDateTimeToDate.Day - objDateTimeFromDate.Day;
}
if (m_nMonth == -1)
{
m_nMonth = objDateTimeToDate.Month - objDateTimeFromDate.Month;
}
m_nYear = objDateTimeToDate.Year - objDateTimeFromDate.Year;
m_nWeek = m_nDays / 7;
m_nDays = m_nDays % 7;
}
}
Query syntax:
var count = (from o in context.MyContainer
where o.ID == '1'
from t in o.MyTable
select t).Count();
Method syntax:
var count = context.MyContainer
.Where(o => o.ID == '1')
.SelectMany(o => o.MyTable)
.Count()
Both generate the same SQL query.