So when you call EntityManager.persist()
, it only makes the entity get managed by the EntityManager
and adds it (entity instance) to the Persistence Context
. An Explicit flush()
will make the entity now residing in the Persistence Context
to be moved to the database (using a SQL).
Without flush(), this (moving of entity from Persistence Context
to the database) will happen when the Transaction to which this Persistence Context
is associated is committed.
To ensure that a cell will return a date value and not just a string that looks like a date, first you must set the NumberFormat property to a Date format, then put a real date into the cell's content.
Sub test_date_or_String()
Set c = ActiveCell
c.NumberFormat = "@"
c.Value = CDate("03/04/2014")
Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a String
c.NumberFormat = "m/d/yyyy"
Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is still a String
c.Value = CDate("03/04/2014")
Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a date
End Sub
Wikipedia's Segmentation_fault page has a very nice description about it, just pointing out the causes and reasons. Have a look into the wiki for a detailed description.
In computing, a segmentation fault (often shortened to segfault) or access violation is a fault raised by hardware with memory protection, notifying an operating system (OS) about a memory access violation.
The following are some typical causes of a segmentation fault:
These in turn are often caused by programming errors that result in invalid memory access:
Dereferencing or assigning to an uninitialized pointer (wild pointer, which points to a random memory address)
Dereferencing or assigning to a freed pointer (dangling pointer, which points to memory that has been freed/deallocated/deleted)
A buffer overflow.
A stack overflow.
Attempting to execute a program that does not compile correctly. (Some compilers will output an executable file despite the presence of compile-time errors.)
The way that Java Swing UIs work is that for each JPanel there is always a LayoutManager that decides on where to exactly place your components. Each layout managers works differently, so if you use for example a BorderLayout, setBounds() is not used by the LayoutManager, instead component placement is decided by East,West,South,North,Center.
For the NullLayoutManager (in case you used new JPanel(null)
) however, each component has to have an x and y coordinate. Stupid Sidenote: if your UI would be three-dimensional there would also be a z coordinate.
So with public void Component.setBounds(int x, int y, int width, int height)
you specify where your component is placed and how many pixel it is wide and high.
Here's an example:
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JTableInNullLayout
{
public static void main(String[] argv) throws Exception {
JPanel panel = new JPanel(null);
JLabel helloLabel = new JLabel("Hello world!");
helloLabel.setBounds( 10, 50, 60, 20 ); // x, y, width, height
panel.add(helloLabel);
JFrame frame = new JFrame();
frame.add(panel);
frame.setPreferredSize( new Dimension(200,200));
frame.pack();
frame.setVisible(true);
}
}
You may use jQuery in it like
$('#yesh').click(function(){
*****HERE GOES THE FUNCTION*****
});
Besides jQuery is easy to use.
You can make changes in colors etc using simple jQUery or Javascript.
I solved this by referring properties of login user under the security, logins. then go to User Mapping and select the database then check db_datareader and db_dataweriter options.
Below given some information about fav Icon
What Is FavIcon? ? FavIcon is nothing but small image which appears top left along with the application address bar title.Standard size specification for favicon.ico is 16 by 16 pixel. Please see below attached figure.
How It Works ? ? Usually we add our FavIcon.ico image in the route solution folder and automatically application picks it while running. But most of the time we might have to use below both link reference.
<link rel="icon" href="favicon.ico" type="image/ico"/>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>
Some browser expect one (rel="icon") Some other browser expect other rel="shortcut icon"
? Type=”image/x-icon” OR Type=”image/ico”: once expect exact ico image and one expect any image even formatted from .jpg or .pn ..etc.
? We have to use above two tags to the common pages like – Master page , Main frame which is getting used in all the pages
As I said in comments - you should always use parameters in your query - NEVER EVER concatenate together your SQL statements yourself.
Also: I would recommend to separate the click event handler from the actual code to insert the data.
So I would rewrite your code to be something like
In your web page's code-behind file (yourpage.aspx.cs
)
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=DELL-PC;initial catalog=AdventureWorks2008R2 ; User ID=sa;Password=sqlpass;Integrated Security=SSPI;";
InsertData(connectionString,
textBox1.Text.Trim(), -- first name
textBox2.Text.Trim(), -- last name
textBox3.Text.Trim(), -- user name
textBox4.Text.Trim(), -- password
Convert.ToInt32(comboBox1.Text), -- age
comboBox2.Text.Trim(), -- gender
textBox7.Text.Trim() ); -- contact
}
In some other code (e.g. a databaselayer.cs
):
private void InsertData(string connectionString, string firstName, string lastname, string username, string password
int Age, string gender, string contact)
{
// define INSERT query with parameters
string query = "INSERT INTO dbo.regist (FirstName, Lastname, Username, Password, Age, Gender,Contact) " +
"VALUES (@FirstName, @Lastname, @Username, @Password, @Age, @Gender, @Contact) ";
// create connection and command
using(SqlConnection cn = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(query, cn))
{
// define parameters and their values
cmd.Parameters.Add("@FirstName", SqlDbType.VarChar, 50).Value = firstName;
cmd.Parameters.Add("@Lastname", SqlDbType.VarChar, 50).Value = lastName;
cmd.Parameters.Add("@Username", SqlDbType.VarChar, 50).Value = userName;
cmd.Parameters.Add("@Password", SqlDbType.VarChar, 50).Value = password;
cmd.Parameters.Add("@Age", SqlDbType.Int).Value = age;
cmd.Parameters.Add("@Gender", SqlDbType.VarChar, 50).Value = gender;
cmd.Parameters.Add("@Contact", SqlDbType.VarChar, 50).Value = contact;
// open connection, execute INSERT, close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
Code like this:
I think the OP is asking the wrong question. The code below will show that it not necessary to manually raise the PropertyChanged
EVENT from a dependency property to achieve the desired result. The way to do it is handle the PropertyChanged
CALLBACK on the dependency property and set values for other dependency properties there. The following is a working example.
In the code below, MyControl
has two dependency properties - ActiveTabInt
and ActiveTabString
. When the user clicks the button on the host (MainWindow
), ActiveTabString
is modified. The PropertyChanged
CALLBACK on the dependency property sets the value of ActiveTabInt
. The PropertyChanged
EVENT is not manually raised by MyControl
.
MainWindow.xaml.cs
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
ActiveTabString = "zero";
}
private string _ActiveTabString;
public string ActiveTabString
{
get { return _ActiveTabString; }
set
{
if (_ActiveTabString != value)
{
_ActiveTabString = value;
RaisePropertyChanged("ActiveTabString");
}
}
}
private int _ActiveTabInt;
public int ActiveTabInt
{
get { return _ActiveTabInt; }
set
{
if (_ActiveTabInt != value)
{
_ActiveTabInt = value;
RaisePropertyChanged("ActiveTabInt");
}
}
}
#region INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
private void Button_Click(object sender, RoutedEventArgs e)
{
ActiveTabString = (ActiveTabString == "zero") ? "one" : "zero";
}
}
public class MyControl : Control
{
public static List<string> Indexmap = new List<string>(new string[] { "zero", "one" });
public string ActiveTabString
{
get { return (string)GetValue(ActiveTabStringProperty); }
set { SetValue(ActiveTabStringProperty, value); }
}
public static readonly DependencyProperty ActiveTabStringProperty = DependencyProperty.Register(
"ActiveTabString",
typeof(string),
typeof(MyControl), new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
ActiveTabStringChanged));
public int ActiveTabInt
{
get { return (int)GetValue(ActiveTabIntProperty); }
set { SetValue(ActiveTabIntProperty, value); }
}
public static readonly DependencyProperty ActiveTabIntProperty = DependencyProperty.Register(
"ActiveTabInt",
typeof(Int32),
typeof(MyControl), new FrameworkPropertyMetadata(
new Int32(),
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
static MyControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
}
private static void ActiveTabStringChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
MyControl thiscontrol = sender as MyControl;
if (Indexmap[thiscontrol.ActiveTabInt] != thiscontrol.ActiveTabString)
thiscontrol.ActiveTabInt = Indexmap.IndexOf(e.NewValue.ToString());
}
}
MainWindow.xaml
<StackPanel Orientation="Vertical">
<Button Content="Change Tab Index" Click="Button_Click" Width="110" Height="30"></Button>
<local:MyControl x:Name="myControl" ActiveTabInt="{Binding ActiveTabInt, Mode=TwoWay}" ActiveTabString="{Binding ActiveTabString}"></local:MyControl>
</StackPanel>
App.xaml
<Style TargetType="local:MyControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MyControl">
<TabControl SelectedIndex="{Binding ActiveTabInt, Mode=TwoWay}">
<TabItem Header="Tab Zero">
<TextBlock Text="{Binding ActiveTabInt}"></TextBlock>
</TabItem>
<TabItem Header="Tab One">
<TextBlock Text="{Binding ActiveTabInt}"></TextBlock>
</TabItem>
</TabControl>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
In my case i has include .m file thats why compiler shows this type of error.
you should check the latest file import that is not .m file " Sometime i"
try this out :)
public static HashMap HashMapFrom(String s){
HashMap base = new HashMap(); //result
int dismiss = 0; //dismiss tracker
StringBuilder tmpVal = new StringBuilder(); //each val holder
StringBuilder tmpKey = new StringBuilder(); //each key holder
for (String next:s.split("")){ //each of vale
if(dismiss==0){ //if not writing value
if (next.equals("=")) //start writing value
dismiss=1; //update tracker
else
tmpKey.append(next); //writing key
} else {
if (next.equals("{")) //if it's value so need to dismiss
dismiss++;
else if (next.equals("}")) //value closed so need to focus
dismiss--;
else if (next.equals(",") //declaration ends
&& dismiss==1) {
//by the way you have to create something to correct the type
Object ObjVal = object.valueOf(tmpVal.toString()); //correct the type of object
base.put(tmpKey.toString(),ObjVal);//declaring
tmpKey = new StringBuilder();
tmpVal = new StringBuilder();
dismiss--;
continue; //next :)
}
tmpVal.append(next); //writing value
}
}
Object objVal = object.valueOf(tmpVal.toString()); //same as here
base.put(tmpKey.toString(), objVal); //leftovers
return base;
}
examples input : "a=0,b={a=1},c={ew={qw=2}},0=a" output : {0=a,a=0,b={a=1},c={ew={qw=2}}}
FWIW,
Poor mans security folder (to protect a public shared folder from little prying eyes ;) )
mkdir -p {0..9}/{0..9}/{0..9}/{0..9}
Now you can put your files in a pin numbered folder. Not exactly waterproof, but it's a barrier for the youngest.
You need to use the TO_DATE
function.
SELECT TO_DATE('01/01/2004', 'MM/DD/YYYY') FROM DUAL;
Here's a jquery plugin to do the same: http://s.technabled.com/jquery-foggle
You want the following:
ALTER TABLE mytable MODIFY mycolumn VARCHAR(255);
Columns are nullable by default. As long as the column is not declared UNIQUE
or NOT NULL
, there shouldn't be any problems.
This works for me on all browsers (included Firefox)
https://gist.github.com/jaydson/1780598
https://jsfiddle.net/sidanmor/v6m9exsw/
var myConfObj = {_x000D_
iframeMouseOver : false_x000D_
}_x000D_
window.addEventListener('blur',function(){_x000D_
if(myConfObj.iframeMouseOver){_x000D_
console.log('Wow! Iframe Click!');_x000D_
}_x000D_
});_x000D_
_x000D_
document.getElementById('idanmorblog').addEventListener('mouseover',function(){_x000D_
myConfObj.iframeMouseOver = true;_x000D_
});_x000D_
document.getElementById('idanmorblog').addEventListener('mouseout',function(){_x000D_
myConfObj.iframeMouseOver = false;_x000D_
});
_x000D_
<iframe id="idanmorblog" src="https://sidanmor.com/" style="width:400px;height:600px" ></iframe>
_x000D_
<iframe id="idanmorblog" src="https://sidanmor.com/" style="width:400px;height:600px" ></iframe>
First add the collections and then apply lookup on these collections. Don't use $unwind
as unwind will simply separate all the documents of each collections. So apply simple lookup and then use $project
for projection.
Here is mongoDB query:
db.userInfo.aggregate([
{
$lookup: {
from: "userRole",
localField: "userId",
foreignField: "userId",
as: "userRole"
}
},
{
$lookup: {
from: "userInfo",
localField: "userId",
foreignField: "userId",
as: "userInfo"
}
},
{$project: {
"_id":0,
"userRole._id":0,
"userInfo._id":0
}
} ])
Here is the output:
/* 1 */ {
"userId" : "AD",
"phone" : "0000000000",
"userRole" : [
{
"userId" : "AD",
"role" : "admin"
}
],
"userInfo" : [
{
"userId" : "AD",
"phone" : "0000000000"
}
] }
Thanks.
The basic idea will be using a nested query with count aggregation:
select * from yourTable ou
where (select count(*) from yourTable inr
where inr.sid = ou.sid) > 1
You can adjust the where clause in the inner query to narrow the search.
There is another good solution for that mentioned in the comments, (but not everyone reads them):
select Column1, Column2, count(*)
from yourTable
group by Column1, Column2
HAVING count(*) > 1
Or shorter:
SELECT (yourTable.*)::text, count(*)
FROM yourTable
GROUP BY yourTable.*
HAVING count(*) > 1
When using this safari-only filter I could target Safari (iOS and Mac), but exclude Chrome (and other browsers):
@supports (-webkit-backdrop-filter: blur(1px)) {
.safari-only {
background-color: rgb(76,80,84);
}
}
$( "#foo" ).slideUp( 300 ).delay( 5000 ).fadeIn( 400 );
The colon is a built-in command that does nothing, but returns 0 (success). Thus, it's shorter (and faster) than calling an actual command to do the same thing.
Depending on your privileges, this query might work:
SELECT sqltext.TEXT,
req.session_id,
req.status,
req.command,
req.cpu_time,
req.total_elapsed_time
FROM sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext
Ref: http://blog.sqlauthority.com/2009/01/07/sql-server-find-currently-running-query-t-sql
Is your BitLocker disk encryption running? In my case, it locked the whole drive of the disk for encryption, and SVN failed with this error.
You can't. It's not a trusted event.
Events that are generated by the user agent, either as a result of user interaction, or as a direct result of changes to the DOM, are trusted by the user agent with privileges that are not afforded to events generated by script through the DocumentEvent.createEvent("Event") method, modified using the Event.initEvent() method, or dispatched via the EventTarget.dispatchEvent() method. The isTrusted attribute of trusted events has a value of true, while untrusted events have a isTrusted attribute value of false.
Most untrusted events should not trigger default actions, with the exception of click or DOMActivate events.
You have to add a class and add/remove that on the mouseover/mouseout events manually.
Side note, I'm answering this here after I marked this as a duplicate since no answer here really covers the issue from what I see. Hopefully, one day it'll be merged.
the bottom cell will grow as you enter more text ... setting the table width will help too
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<table id="content" style="min-height:525px; height:525px; width:100%; border:0px; margin:0; padding:0; border-collapse:collapse;">
<tr><td style="height:10px; background-color:#900;">Upper</td></tr>
<tr><td style="min-height:515px; height:515px; background-color:#909;">lower<br/>
</td></tr>
</table>
</body>
</html>
You can't create arrays with a generic component type.
Create an array of an explicit type, like Object[]
, instead. You can then cast this to PCB[]
if you want, but I don't recommend it in most cases.
PCB[] res = (PCB[]) new Object[list.size()]; /* Not type-safe. */
If you want type safety, use a collection like java.util.List<PCB>
instead of an array.
By the way, if list
is already a java.util.List
, you should use one of its toArray()
methods, instead of duplicating them in your code. This doesn't get your around the type-safety problem though.
Use Volley as suggested above. Add following into build.gradle (Module: app)
implementation 'com.android.volley:volley:1.1.1'
Add following into AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
And add following to you Activity code:
public void httpCall(String url) {
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// enjoy your response
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// enjoy your error status
}
});
queue.add(stringRequest);
}
It replaces http client and it is very simple.
$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');
will add a new row to the first TBODY
of the table, without depending of any THEAD
or TFOOT
present.
(I didn't find information from which version of jQuery .append()
this behavior is present.)
You may try it in these examples:
<table class="t"> <!-- table with THEAD, TBODY and TFOOT -->
<thead>
<tr><th>h1</th><th>h2</th></tr>
</thead>
<tbody>
<tr><td>1</td><td>2</td></tr>
</tbody>
<tfoot>
<tr><th>f1</th><th>f2</th></tr>
</tfoot>
</table><br>
<table class="t"> <!-- table with two TBODYs -->
<thead>
<tr><th>h1</th><th>h2</th></tr>
</thead>
<tbody>
<tr><td>1</td><td>2</td></tr>
</tbody>
<tbody>
<tr><td>3</td><td>4</td></tr>
</tbody>
<tfoot>
<tr><th>f1</th><th>f2</th></tr>
</tfoot>
</table><br>
<table class="t"> <!-- table without TBODY -->
<thead>
<tr><th>h1</th><th>h2</th></tr>
</thead>
</table><br>
<table class="t"> <!-- table with TR not in TBODY -->
<tr><td>1</td><td>2</td></tr>
</table>
<br>
<table class="t">
</table>
<script>
$('.t').append('<tr><td>a</td><td>a</td></tr>');
</script>
In which example a b
row is inserted after 1 2
, not after 3 4
in second example. If the table were empty, jQuery creates TBODY
for a new row.
I have come across this with the Hero, using what I thought was a published API. In the end, I used a test to see if the intent could be received:
private boolean isCallable(Intent intent) {
List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
In use when I would usually just start the activity:
final Intent intent = new Intent("com.android.camera.action.CROP");
intent.setClassName("com.android.camera", "com.android.camera.CropImage");
if (isCallable(intent)) {
// call the intent as you intended.
} else {
// make alternative arrangements.
}
obvious: If you go down this route - using non-public APIs - you must absolutely provide a fallback which you know definitely works. It doesn't have to be perfect, it can be a Toast saying that this is unsupported for this handset/device, but you should avoid an uncaught exception. end obvious.
I find the Open Intents Registry of Intents Protocols quite useful, but I haven't found the equivalent of a TCK type list of intents which absolutely must be supported, and examples of what apps do different handsets.
Delays can be also implemented by using the following methods.
The first method:
import time
time.sleep(5) # Delay for 5 seconds.
The second method to delay would be using the implicit wait method:
driver.implicitly_wait(5)
The third method is more useful when you have to wait until a particular action is completed or until an element is found:
self.wait.until(EC.presence_of_element_located((By.ID, 'UserName'))
Integer Types:
short -> signed short
signed short
unsigned short
int -> signed int
signed int
unsigned int
signed -> signed int
unsigned -> unsigned int
long -> signed long
signed long
unsigned long
Be careful of char:
char (is signed or unsigned depending on the implmentation)
signed char
unsigned char
Try following these steps:
It's called String#start_with?
, not String#startswith
: In Ruby, the names of boolean-ish methods end with ?
and the words in method names are separated with an _
. Not sure where the s
went, personally, I'd prefer String#starts_with?
over the actual String#start_with?
Make SymbolIndexer( const SymbolIndexer& )
private. If you're assigning to a reference, you're not copying.
If your web application is configured to impersonate a client, then using a trusted connection will potentially have a negative performance impact. This is because each client must use a different connection pool (with the client's credentials).
Most web applications don't use impersonation / delegation, and hence don't have this problem.
See this MSDN article for more information.
You need to inject mock inside the class you're testing. At the moment you're interacting with the real object, not with the mock one. You can fix the code in a following way:
void testAbc(){
myClass.myObj = myInteface;
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
although it would be a wiser choice to extract all initialization code into @Before
@Before
void setUp(){
myClass = new myClass();
myClass.myObj = myInteface;
}
@Test
void testAbc(){
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
First of all check the declaration of both the methods.
1) OrElse: Execute logic and pass result as argument.
public T orElse(T other) {
return value != null ? value : other;
}
2) OrElseGet: Execute logic if value inside the optional is null
public T orElseGet(Supplier<? extends T> other) {
return value != null ? value : other.get();
}
Some explanation on above declaration: The argument of “Optional.orElse” always gets executed irrespective of the value of the object in optional (null, empty or with value). Always consider the above-mentioned point in mind while using “Optional.orElse”, otherwise use of “Optional.orElse” can be very risky in the following situation.
Risk-1) Logging Issue: If content inside orElse contains any log statement: In this case, you will end up logging it every time.
Optional.of(getModel())
.map(x -> {
//some logic
})
.orElse(getDefaultAndLogError());
getDefaultAndLogError() {
log.error("No Data found, Returning default");
return defaultValue;
}
Risk-2) Performance Issue: If content inside orElse is time-intensive: Time intensive content can be any i/o operations DB call, API call, file reading. If we put such content in orElse(), the system will end up executing a code of no use.
Optional.of(getModel())
.map(x -> //some logic)
.orElse(getDefaultFromDb());
getDefaultFromDb() {
return dataBaseServe.getDefaultValue(); //api call, db call.
}
Risk-3) Illegal State or Bug Issue: If content inside orElse is mutating some object state: We might be using the same object at another place let say inside Optional.map function and it can put us in a critical bug.
List<Model> list = new ArrayList<>();
Optional.of(getModel())
.map(x -> {
})
.orElse(get(list));
get(List < String > list) {
log.error("No Data found, Returning default");
list.add(defaultValue);
return defaultValue;
}
Then, When can we go with orElse()? Prefer using orElse when the default value is some constant object, enum. In all above cases we can go with Optional.orElseGet() (which only executes when Optional contains non empty value)instead of Optional.orElse(). Why?? In orElse, we pass default result value, but in orElseGet we pass Supplier and method of Supplier only executes if the value in Optional is null.
Key takeaways from this:
I have explained this in point-2 (“Optional.map/Optional.orElse” != “if/else”) my medium blog. Use Java8 as a programmer not as a coder
I copied this from one of my apps, so there's prob a few extra attributes, but should give you the idea. This is from the layout that has the progress bar:
<ProgressBar
android:id="@+id/ProgressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:indeterminate="false"
android:maxHeight="10dip"
android:minHeight="10dip"
android:progress="50"
android:progressDrawable="@drawable/greenprogress" />
Then create a new drawable with something similar to the following (In this case greenprogress.xml
):
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
<shape>
<corners android:radius="5dip" />
<gradient
android:angle="270"
android:centerColor="#ff5a5d5a"
android:centerY="0.75"
android:endColor="#ff747674"
android:startColor="#ff9d9e9d" />
</shape>
</item>
<item android:id="@android:id/secondaryProgress">
<clip>
<shape>
<corners android:radius="5dip" />
<gradient
android:angle="270"
android:centerColor="#80ffb600"
android:centerY="0.75"
android:endColor="#a0ffcb00"
android:startColor="#80ffd300" />
</shape>
</clip>
</item>
<item android:id="@android:id/progress">
<clip>
<shape>
<corners android:radius="5dip" />
<gradient
android:angle="270"
android:endColor="#008000"
android:startColor="#33FF33" />
</shape>
</clip>
</item>
</layer-list>
You can change up the colors as needed, this will give you a green progress bar.
DataView view = new DataView();
view.Table = DataSet1.Tables["Suppliers"];
view.RowFilter = "City = 'Berlin'";
view.RowStateFilter = DataViewRowState.ModifiedCurrent;
view.Sort = "CompanyName DESC";
// Simple-bind to a TextBox control
Text1.DataBindings.Add("Text", view, "CompanyName");
Ref: http://www.csharp-examples.net/dataview-rowfilter/
http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx
It's Hebrew for "double colon".
If you are using python 3 use py
in front of cmd code, like this
py manage.py runserver
You should be able to do this just fine:
$.ajax({
url: 'controller/myaction',
data: JSON.stringify({
myKey: myArray
}),
success: function(data) { /* Whatever */ }
});
Then your action method would be like so:
public ActionResult(List<int> myKey)
{
// Do Stuff
}
For you, it looks like you just need to stringify your values. The JSONValueProvider in MVC will convert that back into an IEnumerable for you.
A code that works for any sign in dividend and divisor:
int divRoundClosest(const int n, const int d)
{
return ((n < 0) ^ (d < 0)) ? ((n - d/2)/d) : ((n + d/2)/d);
}
In response to a comment "Why is this actually working?", we can break this apart. First, observe that n/d
would be the quotient, but it is truncated towards zero, not rounded. You get a rounded result if you add half of the denominator to the numerator before dividing, but only if numerator and denominator have the same sign. If the signs differ, you must subtract half of the denominator before dividing. Putting all that together:
(n < 0) is false (zero) if n is non-negative
(d < 0) is false (zero) if d is non-negative
((n < 0) ^ (d < 0)) is true if n and d have opposite signs
(n + d/2)/d is the rounded quotient when n and d have the same sign
(n - d/2)/d is the rounded quotient when n and d have opposite signs
If you prefer a macro:
#define DIV_ROUND_CLOSEST(n, d) ((((n) < 0) ^ ((d) < 0)) ? (((n) - (d)/2)/(d)) : (((n) + (d)/2)/(d)))
The linux kernel macro DIV_ROUND_CLOSEST doesn't work for negative divisors!
EDIT: This will work without overflow:
int divRoundClosest( int A, int B )
{
if(A<0)
if(B<0)
return (A + (-B+1)/2) / B + 1;
else
return (A + ( B+1)/2) / B - 1;
else
if(B<0)
return (A - (-B+1)/2) / B - 1;
else
return (A - ( B+1)/2) / B + 1;
}
BigDecimal b = BigDecimal.valueOf(d);
import java.math.*;
public class Test {
public static void main(String[] args)
{
// Creating a Double Object
Double d = new Double("785.254");
/// Assigning the bigdecimal value of ln to b
BigDecimal b = BigDecimal.valueOf(d);
// Displaying BigDecimal value
System.out.println("The Converted BigDecimal value is: " + b);
}
}
Support, unfortunately, is brutal at best. Here's a post on the topic:
https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/
And the post content:
To get the currently logged in user:
System.getProperty("user.name"); //platform independent
and the hostname of the machine:
java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
System.out.println("Hostname of local machine: " + localMachine.getHostName());
Use the Database menu and "Set Datasource Location" menu option to change the name or location of each table in a report.
This works for changing the location of a database, changing to a new database, and changing the location or name of an individual table being used in your report.
To change the datasource connection, go the Database menu and click Set Datasource Location.
And try running the report again.
The key is to change the datasource connection first, then any tables you need to update, then the other stuff. The connection won't automatically change the tables underneath. Those tables are like goslings that've imprinted on the first large goose-like animal they see. They'll continue to bypass all reason and logic and go to where they've always gone unless you specifically manually change them.
To make it more convenient, here's a tip: You can "Show SQL Query" in the Database menu, and you'll see table names qualified with the database (like "Sales"."dbo"."Customers") for any tables that go straight to a specific database. That might make the hunting easier if you have a lot of stuff going on. When I tackled this problem I had to change each and every table to point to the new table in the new database.
In addition to the simple addition shown by others, you can also use seq.Date
or seq.POSIXt
to find other increments or decrements (the POSIXt version does seconds, minutes, hours, etc.):
> seq.Date( Sys.Date(), length=2, by='3 months' )[2]
[1] "2012-07-25"
Unfortunately, no. You will have to cast each value individually.
You can use this:
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
// Actions to do after 10 seconds
}
}, 10000);
For Stop the Handler, You can try this:
handler.removeCallbacksAndMessages(null);
column(1)
is your friend.
$ column -t <<< '"option-y" yank-pop
> "option-z" execute-last-named-cmd
> "option-|" vi-goto-column
> "option-~" _bash_complete-word
> "option-control-?" backward-kill-word
> "control-_" undo
> "control-?" backward-delete-char
> '
"option-y" yank-pop
"option-z" execute-last-named-cmd
"option-|" vi-goto-column
"option-~" _bash_complete-word
"option-control-?" backward-kill-word
"control-_" undo
"control-?" backward-delete-char
File f = new File("C:/aaa/bbb/ccc/ddd/test.java");
System.out.println(f.getParentFile().getName())
f.getParentFile()
can be null, so you should check it.
Instead of extrapolating off the ends, you could return the extents of the y_list
. Most of the time your application is well behaved, and the Interpolate[x]
will be in the x_list
. The (presumably) linear affects of extrapolating off the ends may mislead you to believe that your data is well behaved.
Returning a non-linear result (bounded by the contents of x_list
and y_list
) your program's behavior may alert you to an issue for values greatly outside x_list
. (Linear behavior goes bananas when given non-linear inputs!)
Returning the extents of the y_list
for Interpolate[x]
outside of x_list
also means you know the range of your output value. If you extrapolate based on x
much, much less than x_list[0]
or x
much, much greater than x_list[-1]
, your return result could be outside of the range of values you expected.
def __getitem__(self, x):
if x <= self.x_list[0]:
return self.y_list[0]
elif x >= self.x_list[-1]:
return self.y_list[-1]
else:
i = bisect_left(self.x_list, x) - 1
return self.y_list[i] + self.slopes[i] * (x - self.x_list[i])
The base way to handle it in Kotlin is:
edittext.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
callback.invoke()
true
}
false
}
Use this to just call edittext.onDone{/*action*/}
in your main code. Makes your code far more readable and maintainable
fun EditText.onDone(callback: () -> Unit) {
setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
callback.invoke()
true
}
false
}
}
<EditText ...
android:imeOptions="actionDone"
android:inputType="text"/>
If you need
inputType="textMultiLine"
support, read this post
Here is a few ways to do it (Just assume I'm using Dependency Injection for the DbConext)
public class Example
{
private readonly DbContext Context;
public Example(DbContext context)
{
Context = context;
}
public DbSetSampleOne[] DbSamples { get; set; }
public void ExampleMethod DoSomething()
{
// Example 1: This will select everything from the entity you want to select
DbSamples = Context.DbSetSampleOne.ToArray();
// Example 2: If you want to apply some filtering use the following example
DbSamples = Context.DbSetSampleOne.ToArray().Where(p => p.Field.Equals("some filter"))
}
You can map another entity based on this class (you should use entity-name in order to distinct the two) and the second one will be kind of dto (dont forget that dto has design issues ). you should define the second one as readonly and give it a good name in order to be clear that this is not a regular entity. by the way select only few columns is called projection , so google with it will be easier.
alternative - you can create named query with the list of fields that you need (you put them in the select ) or use criteria with projection
FLAG_ACTIVITY_REORDER_TO_FRONT: If set in an Intent passed to Context.startActivity(), this flag will cause the launched activity to be brought to the front of its task's history stack if it is already running.
Intent i = new Intent(context, AActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<div class="row">
<div class="col-sm-6"><p class="float-start">left</p></div>
<div class="col-sm-6"><p class="float-end">right</p></div>
</div>
_x000D_
A whole column can accommodate 12, 6 (col-sm-6
) is exactly half, and in this half, one to the left(float-start
) and one to the right(float-end
).
fontawesome-button
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w==" crossorigin="anonymous" />
<div class="row">
<div class=col-sm-6>
<p class="float-start text-center"> <!-- text-center can help you put the icon at the center -->
<a class="text-decoration-none" href="https://www.google.com/"
><i class="fas fa-arrow-circle-left fa-3x"></i><br>Left
</a>
</p>
</div>
<div class=col-sm-6>
<p class="float-end text-center">
<a class="text-decoration-none" href="https://www.google.com/"
><i class="fas fa-arrow-circle-right fa-3x"></i><br>Right
</a>
</p>
</div>
_x000D_
It does not work because your script in JSFiddle is running inside it's own scope (see the "OnLoad" drop down on the left?).
One way around this is to bind your event handler in javascript (where it should be):
document.getElementById('optionID').onchange = function () {
document.getElementById("message").innerHTML = "Having a Baby!!";
};
Another way is to modify your code for the fiddle environment and explicitly declare your function as global so it can be found by your inline event handler:
window.changeMessage() {
document.getElementById("message").innerHTML = "Having a Baby!!";
};
?
Set the default console colors and fonts:
http://poshcode.org/2220
From Windows PowerShell Cookbook (O'Reilly)
by Lee Holmes (http://www.leeholmes.com/guide)
Set-StrictMode -Version Latest
Push-Location
Set-Location HKCU:\Console
New-Item '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'
Set-Location '.\%SystemRoot%_system32_WindowsPowerShell_v1.0_powershell.exe'
New-ItemProperty . ColorTable00 -type DWORD -value 0x00562401
New-ItemProperty . ColorTable07 -type DWORD -value 0x00f0edee
New-ItemProperty . FaceName -type STRING -value "Lucida Console"
New-ItemProperty . FontFamily -type DWORD -value 0x00000036
New-ItemProperty . FontSize -type DWORD -value 0x000c0000
New-ItemProperty . FontWeight -type DWORD -value 0x00000190
New-ItemProperty . HistoryNoDup -type DWORD -value 0x00000000
New-ItemProperty . QuickEdit -type DWORD -value 0x00000001
New-ItemProperty . ScreenBufferSize -type DWORD -value 0x0bb80078
New-ItemProperty . WindowSize -type DWORD -value 0x00320078
Pop-Location
Calling window.setTimeout(function, delay)
will allow you to accomplish this. Here's an example that will automatically close the alert 2 seconds (or 2000 milliseconds) after it is displayed.
$(".alert-message").alert();
window.setTimeout(function() { $(".alert-message").alert('close'); }, 2000);
If you want to wrap it in a nifty function you could do this.
function createAutoClosingAlert(selector, delay) {
var alert = $(selector).alert();
window.setTimeout(function() { alert.alert('close') }, delay);
}
Then you could use it like so...
createAutoClosingAlert(".alert-message", 2000);
I am certain there are more elegant ways to accomplish this.
This is a modern Promise
version of the previous one, using a Promise.all
approach to resolve all promises when all files have been read:
/**
* Promise all
* @author Loreto Parisi (loretoparisi at gmail dot com)
*/
function promiseAllP(items, block) {
var promises = [];
items.forEach(function(item,index) {
promises.push( function(item,i) {
return new Promise(function(resolve, reject) {
return block.apply(this,[item,index,resolve,reject]);
});
}(item,index))
});
return Promise.all(promises);
} //promiseAll
/**
* read files
* @param dirname string
* @return Promise
* @author Loreto Parisi (loretoparisi at gmail dot com)
* @see http://stackoverflow.com/questions/10049557/reading-all-files-in-a-directory-store-them-in-objects-and-send-the-object
*/
function readFiles(dirname) {
return new Promise((resolve, reject) => {
fs.readdir(dirname, function(err, filenames) {
if (err) return reject(err);
promiseAllP(filenames,
(filename,index,resolve,reject) => {
fs.readFile(path.resolve(dirname, filename), 'utf-8', function(err, content) {
if (err) return reject(err);
return resolve({filename: filename, contents: content});
});
})
.then(results => {
return resolve(results);
})
.catch(error => {
return reject(error);
});
});
});
}
How to Use It:
Just as simple as doing:
readFiles( EMAIL_ROOT + '/' + folder)
.then(files => {
console.log( "loaded ", files.length );
files.forEach( (item, index) => {
console.log( "item",index, "size ", item.contents.length);
});
})
.catch( error => {
console.log( error );
});
Supposed that you have another list of folders you can as well iterate over this list, since the internal promise.all will resolve each of then asynchronously:
var folders=['spam','ham'];
folders.forEach( folder => {
readFiles( EMAIL_ROOT + '/' + folder)
.then(files => {
console.log( "loaded ", files.length );
files.forEach( (item, index) => {
console.log( "item",index, "size ", item.contents.length);
});
})
.catch( error => {
console.log( error );
});
});
How it Works
The promiseAll
does the magic. It takes a function block of signature function(item,index,resolve,reject)
, where item
is the current item in the array, index
its position in the array, and resolve
and reject
the Promise
callback functions.
Each promise will be pushed in a array at the current index
and with the current item
as arguments through a anonymous function call:
promises.push( function(item,i) {
return new Promise(function(resolve, reject) {
return block.apply(this,[item,index,resolve,reject]);
});
}(item,index))
Then all promises will be resolved:
return Promise.all(promises);
I'll mention the more obvious way of dealing with duplicates in lists. In terms of complexity, dictionaries are the way to go because each lookup is O(1). You can be more clever if you're only interested in duplicates...
my_list = [1,1,2,3,4,5,5]
my_dict = {}
for (ind,elem) in enumerate(my_list):
if elem in my_dict:
my_dict[elem].append(ind)
else:
my_dict.update({elem:[ind]})
for key,value in my_dict.iteritems():
if len(value) > 1:
print "key(%s) has indices (%s)" %(key,value)
which prints the following:
key(1) has indices ([0, 1])
key(5) has indices ([5, 6])
DECLARE @COMBINED_STRINGS AS VARCHAR(50),
@STRING1 AS VARCHAR(20),
@STRING2 AS VARCHAR(20);
SET @STRING1 = 'rupesh''s';
SET @STRING2 = 'malviya';
SET @COMBINED_STRINGS = @STRING1 + @STRING2;
SELECT @COMBINED_STRINGS;
SELECT '2' + '3';
I typed this in a sql file named TEST.sql and I run it. I got the following out put.
+-------------------+
| @COMBINED_STRINGS |
+-------------------+
| 0 |
+-------------------+
1 row in set (0.00 sec)
+-----------+
| '2' + '3' |
+-----------+
| 5 |
+-----------+
1 row in set (0.00 sec)
After looking into this issue a bit more I found the best and sure sort way for string concatenation in SQL is by using CONCAT method. So I made the following changes in the same file.
#DECLARE @COMBINED_STRINGS AS VARCHAR(50),
# @STRING1 AS VARCHAR(20),
# @STRING2 AS VARCHAR(20);
SET @STRING1 = 'rupesh''s';
SET @STRING2 = 'malviya';
#SET @COMBINED_STRINGS = @STRING1 + @STRING2;
SET @COMBINED_STRINGS = (SELECT CONCAT(@STRING1, @STRING2));
SELECT @COMBINED_STRINGS;
#SELECT '2' + '3';
SELECT CONCAT('2','3');
and after executing the file this was the output.
+-------------------+
| @COMBINED_STRINGS |
+-------------------+
| rupesh'smalviya |
+-------------------+
1 row in set (0.00 sec)
+-----------------+
| CONCAT('2','3') |
+-----------------+
| 23 |
+-----------------+
1 row in set (0.00 sec)
SQL version I am using is: 14.14
I faced the same problem while testing the changes in Symfony 4.3.2
I lowered the log level to INFO
And ran the test again
And the logged showed this:
console.ERROR: Error thrown while running command "doctrine:schema:create". Message: "[Semantical Error] The annotation "@ORM\Id" in property App\Entity\Common::$id was never imported. Did you maybe forget to add a "use" statement for this annotation?" {"exception":"[object] (Doctrine\\Common\\Annotations\\AnnotationException(code: 0): [Semantical Error] The annotation \"@ORM\\Id\" in property App\\Entity\\Common::$id was never imported. Did you maybe forget to add a \"use\" statement for this annotation? at C:\\xampp\\htdocs\\dirty7s\\vendor\\doctrine\\annotations\\lib\\Doctrine\\Common\\Annotations\\AnnotationException.php:54)","command":"doctrine:schema:create","message":"[Semantical Error] The annotation \"@ORM\\Id\" in property App\\Entity\\Common::$id was never imported. Did you maybe forget to add a \"use\" statement for this annotation?"} []
This means that some error in the code causes the:
Doctrine\ORM\ORMException: The EntityManager is closed.
So it is a good idea to check the log
Just add this line
sFileName = "C:\someotherfilelocation"
right before this line
Open sFileName For Output As iFileNum
The idea is to open and write to a different file than the one you read earlier (C:\filelocation
).
If you want to get fancy and show a real "Save As" dialog box, you could do this instead:
sFileName = Application.GetSaveAsFilename()
I felt a like I needed to share this manipulated code to the accepted answer - as I have no reputation, I'm unable to comment..
using System;
using System.Xml.Serialization;
using System.IO;
namespace ObjectSerialization
{
public static class ObjectSerialization
{
// THIS: (C): https://stackoverflow.com/questions/2434534/serialize-an-object-to-string
/// <summary>
/// A helper to serialize an object to a string containing XML data of the object.
/// </summary>
/// <typeparam name="T">An object to serialize to a XML data string.</typeparam>
/// <param name="toSerialize">A helper method for any type of object to be serialized to a XML data string.</param>
/// <returns>A string containing XML data of the object.</returns>
public static string SerializeObject<T>(this T toSerialize)
{
// create an instance of a XmlSerializer class with the typeof(T)..
XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
// using is necessary with classes which implement the IDisposable interface..
using (StringWriter stringWriter = new StringWriter())
{
// serialize a class to a StringWriter class instance..
xmlSerializer.Serialize(stringWriter, toSerialize); // a base class of the StringWriter instance is TextWriter..
return stringWriter.ToString(); // return the value..
}
}
// THIS: (C): VPKSoft, 2018, https://www.vpksoft.net
/// <summary>
/// Deserializes an object which is saved to an XML data string. If the object has no instance a new object will be constructed if possible.
/// <note type="note">An exception will occur if a null reference is called an no valid constructor of the class is available.</note>
/// </summary>
/// <typeparam name="T">An object to deserialize from a XML data string.</typeparam>
/// <param name="toDeserialize">An object of which XML data to deserialize. If the object is null a a default constructor is called.</param>
/// <param name="xmlData">A string containing a serialized XML data do deserialize.</param>
/// <returns>An object which is deserialized from the XML data string.</returns>
public static T DeserializeObject<T>(this T toDeserialize, string xmlData)
{
// if a null instance of an object called this try to create a "default" instance for it with typeof(T),
// this will throw an exception no useful constructor is found..
object voidInstance = toDeserialize == null ? Activator.CreateInstance(typeof(T)) : toDeserialize;
// create an instance of a XmlSerializer class with the typeof(T)..
XmlSerializer xmlSerializer = new XmlSerializer(voidInstance.GetType());
// construct a StringReader class instance of the given xmlData parameter to be deserialized by the XmlSerializer class instance..
using (StringReader stringReader = new StringReader(xmlData))
{
// return the "new" object deserialized via the XmlSerializer class instance..
return (T)xmlSerializer.Deserialize(stringReader);
}
}
// THIS: (C): VPKSoft, 2018, https://www.vpksoft.net
/// <summary>
/// Deserializes an object which is saved to an XML data string.
/// </summary>
/// <param name="toDeserialize">A type of an object of which XML data to deserialize.</param>
/// <param name="xmlData">A string containing a serialized XML data do deserialize.</param>
/// <returns>An object which is deserialized from the XML data string.</returns>
public static object DeserializeObject(Type toDeserialize, string xmlData)
{
// create an instance of a XmlSerializer class with the given type toDeserialize..
XmlSerializer xmlSerializer = new XmlSerializer(toDeserialize);
// construct a StringReader class instance of the given xmlData parameter to be deserialized by the XmlSerializer class instance..
using (StringReader stringReader = new StringReader(xmlData))
{
// return the "new" object deserialized via the XmlSerializer class instance..
return xmlSerializer.Deserialize(stringReader);
}
}
}
}
I had the same problem, I removed "@ManagedBean" from my bean class now working.
UPDATE My Answer here is now outdated. The Joda-Time project is now in maintenance mode, advising migration to the java.time classes. See the modern solution in the Answer by Ole V.V..
The accepted answer by NidhishKrishnan is correct.
For fun, here is the same kind of code in Joda-Time 2.3.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
java.util.Date date = new Date(); // A Date object coming from other code.
// Pass the java.util.Date object to constructor of Joda-Time DateTime object.
DateTimeZone kolkataTimeZone = DateTimeZone.forID( "Asia/Kolkata" );
DateTime dateTimeInKolkata = new DateTime( date, kolkataTimeZone );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "yyyy-MM-dd");
System.out.println( "dateTimeInKolkata formatted for date: " + formatter.print( dateTimeInKolkata ) );
System.out.println( "dateTimeInKolkata formatted for ISO 8601: " + dateTimeInKolkata );
When run…
dateTimeInKolkata formatted for date: 2013-12-17
dateTimeInKolkata formatted for ISO 8601: 2013-12-17T14:56:46.658+05:30
From the Python glossary:
An object is hashable if it has a hash value which never changes during its lifetime (it needs a
__hash__()
method), and can be compared to other objects (it needs an__eq__()
or__cmp__()
method). Hashable objects which compare equal must have the same hash value.Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.
All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their
id()
.
Please try this following steps.
1) Create AsyncTask in class or adapter(if you want to change the list item image).
public class AsyncTaskLoadImage extends AsyncTask<String, String, Bitmap> {
private final static String TAG = "AsyncTaskLoadImage";
private ImageView imageView;
public AsyncTaskLoadImage(ImageView imageView) {
this.imageView = imageView;
}
@Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = null;
try {
URL url = new URL(params[0]);
bitmap = BitmapFactory.decodeStream((InputStream) url.getContent());
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
try {
int width, height;
height = bitmap.getHeight();
width = bitmap.getWidth();
Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bmpGrayscale);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bitmap, 0, 0, paint);
imageView.setImageBitmap(bmpGrayscale);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2) Call the AsyncTask from your activity, fragment or adapter(inside onBindViewHolder).
2.a) For adapter:
String src = current.getProductImage();
new AsyncTaskLoadImage(holder.icon).execute(src);
2.b) For activity and fragment:
**Activity:**
ImageView imagview= (ImageView) findViewById(R.Id.imageview);
String src = (your image string);
new AsyncTaskLoadImage(imagview).execute(src);
**Fragment:**
ImageView imagview= (ImageView)view.findViewById(R.Id.imageview);
String src = (your image string);
new AsyncTaskLoadImage(imagview).execute(src);
3) Kindly run the app and check the image.
Happy coding....:)
The direct answer to your question is String.Join
as others have mentioned.
However, if you need some manipulations, you can use Aggregate
:
List<string> employees = new List<string>();
employees.Add("e1");
employees.Add("e2");
employees.Add("e3");
string employeesString = "'" + employees.Aggregate((x, y) => x + "','" + y) + "'";
Console.WriteLine(employeesString);
Console.ReadLine();
Imagine the DOM (HTML page) as a tree right. The HTML elements are the nodes of this tree.
The append()
adds a new node to the child
of the node you called it on.
Example:$("#mydiv").append("<p>Hello there</p>")
creates a child node <p> to <div>
The after()
adds a new node as a sibling or at the same level or child to the parent of the node you called it on.
andorid-support-v4.jar is an external jar file that you have to import into your project.
This is how you do it in Android Studio:
Go to File -> Project Structure
Go to "Dependencies" Tab -> Click on the Plus sign -> Go to "Library dependency"
Select the support library "support-v4 (com.android.support:support-v4:23.0.1)"
Now to go your "build.gradle" file in your app and make sure the android support library has been added to your dependencies. Alternatively, you could've also just typed compile 'com.android.support:support-v4:23.0.1'
directly into your dependencies{}
instead of doing it through the GUI.
Open command prompt and give the platform-tools path of the sdk. Eg:- C:\Android\sdk\platform-tools> Then type 'adb push' command like below,
C:\Android\sdk\platform-tools>adb push C:\MyFiles\fileName.txt /sdcard/fileName.txt
This command push the file to the root folder of the emulator.
Edit 7/17/2020: I cannot delete this accepted answer. It used to be good, but now it isn't. Beware really old posts, guys. I'm removing the link.
[Linqer] is a SQL to LINQ converter tool. It helps you to learn LINQ and convert your existing SQL statements.
Not every SQL statement can be converted to LINQ, but Linqer covers many different types of SQL expressions. Linqer supports both .NET languages - C# and Visual Basic.
I've found that for my use-cases I don't always want the entire outerHTML. Many nodes just have too many children to show.
Here's a function (minimally tested in Chrome):
/**
* Stringifies a DOM node.
* @param {Object} el - A DOM node.
* @param {Number} truncate - How much to truncate innerHTML of element.
* @returns {String} - A stringified node with attributes
* retained.
*/
function stringifyEl(el, truncate) {
var truncateLen = truncate || 50;
var outerHTML = el.outerHTML;
var ret = outerHTML;
ret = ret.substring(0, truncateLen);
// If we've truncated, add an elipsis.
if (outerHTML.length > truncateLen) {
ret += "...";
}
return ret;
}
https://gist.github.com/kahunacohen/467f5cc259b5d4a85eb201518dcb15ec
Actually, Guido vetoed the idea: http://bugs.python.org/issue1093
But, as noted in that issue, you can make one pretty easily:
from functools import reduce # Valid in Python 2.6+, required in Python 3
import operator
reduce(operator.mul, (3, 4, 5), 1)
select * from tbl
where exists (select 1 from all_likes where all_likes.value = substr(tbl.my_col,0, length(tbl.my_col)))
Looking at the "effective POM" will probably help too. For instance, if you wanted to know what the path is for ${project.build.sourceDirectory}
you would find the related XML in the effective POM, such as:
<project>
<build>
<sourceDirectory>/my/path</sourceDirectory>
Also helpful - you can do a real time evaluation of properties via the command line execution of mvn help:evaluate
while in the same dir as the POM.
JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.
var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
//red
textBox.style.backgroundColor = "#FF0000";
}
else
{
//green
textBox.style.backgroundColor = "#00FF00";
}
One of the best semi solutions is to copy %1
into a variable and then use delayed expansion, as delayedExp. is always safe against any content.
set "param1=%~1"
setlocal EnableDelayedExpansion
if "!param1!"=="" ( echo it is empty )
rem ... or use the DEFINED keyword now
if defined param1 echo There is something
The advantage of this is that dealing with param1 is absolutly safe.
And the setting of param1 will work in many cases, like
test.bat hello"this is"a"test
test.bat you^&me
But it still fails with strange contents like
test.bat ^&"&
It detects if %1
is empty, but for some content it can't fetch the content.
This can be also be useful to distinguish between an empty %1
and one with ""
.
It uses the ability of the CALL
command to fail without aborting the batch file.
@echo off
setlocal EnableDelayedExpansion
set "arg1="
call set "arg1=%%1"
if defined arg1 goto :arg_exists
set "arg1=#"
call set "arg1=%%1"
if "!arg1!" EQU "#" (
echo arg1 exists, but can't assigned to a variable
REM Try to fetch it a second time without quotes
(call set arg1=%%1)
goto :arg_exists
)
echo arg1 is missing
exit /b
:arg_exists
echo arg1 exists, perhaps the content is '!arg1!'
If you want to be 100% bullet proof to fetch the content, you could read How to receive even the strangest command line parameters?
I just the changed the langversion
to default
and it worked for me. VS 2015
<system.codedom>
<compilers>
<compiler language=”c#;cs;csharp” extension=”.cs” type=”Microsoft.CSharp.CSharpCodeProvider, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel=”4" compilerOptions=”/langversion:default /nowarn:1659;1699;1701">
<providerOption name=”CompilerVersion” value=”v4.0"/>
</compiler>
<compiler language=”vb;vbs;visualbasic;vbscript” extension=”.vb” type=”Microsoft.VisualBasic.VBCodeProvider, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel=”4" compilerOptions=”/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+”>
<providerOption name=”CompilerVersion” value=”v4.0"/>
</compiler>
</compilers>
You can use assertThrows()
, which allows you to test multiple exceptions within the same test. With support for lambdas in Java 8, this is the canonical way to test for exceptions in JUnit.
Per the JUnit docs:
import static org.junit.jupiter.api.Assertions.assertThrows;
@Test
void exceptionTesting() {
MyException thrown = assertThrows(
MyException.class,
() -> myObject.doThing(),
"Expected doThing() to throw, but it didn't"
);
assertTrue(thrown.getMessage().contains("Stuff"));
}
You didn't open the file in binary mode.
open("Fruits.obj",'rb')
Should work.
For your second error, the file is most likely empty, which mean you inadvertently emptied it or used the wrong filename or something.
(This is assuming you really did close your session. If not, then it's because you didn't close the file between the write and the read).
I tested your code, and it works.
Start at node X and check for all child nodes (parent and child nodes are equivalent if undirected). Mark those child nodes as being children of X. From any such child node A, mark it's children of being children of A, X', where X' is marked as being 2 steps away.). If you later hit X and mark it as being a child of X'', that means X is in a 3 node cycle. Backtracking to it's parent is easy (as-is, the algorithm has no support for this so you'd find whichever parent has X').
Note: If graph is undirected or has any bidirectional edges, this algorithm gets more complicated, assuming you don't want to traverse the same edge twice for a cycle.
When you want to access an element, you have to first dereference your pointer, and then index the element you want (which is also dereferncing). i.e. you need to do:
printf("\nvalue:%c", (*ptr)[0]);
, which is the same as *((*ptr)+0)
Note that working with pointer to arrays are not very common in C. instead, one just use a pointer to the first element in an array, and either deal with the length as a separate element, or place a senitel value at the end of the array, so one can learn when the array ends, e.g.
char arr[5] = {'a','b','c','d','e',0};
char *ptr = arr; //same as char *ptr = &arr[0]
printf("\nvalue:%c", ptr[0]);
This app is just awesome. It is essentially a virtual keyboard that immediately shows you the keycode pressed on a standard US keyboard.
The nice thing about the IN expression is that if you have repeated values, it does not change the result. So, just duplicate the first item and process the entire list. This assumes that there is at least one item in the list. If there are no items, I'd suggest checking for that first and then not executing the SQL at all.
This will do the trick, is obvious in what it is doing and does not rely on any external libraries:
StringBuffer inString = new StringBuffer(listOfIDs.get(0).toString());
for (Long currentID : listOfIDs) {
inString.append(",").append(currentID);
}
You can use dapper library:
conn2.Execute(@"INSERT INTO klant(klant_id,naam,voornaam) VALUES (@p1,@p2,@p3)",
new { p1 = klantId, p2 = klantNaam, p3 = klantVoornaam });
BTW Dapper is a Stack Overflow project :)
UPDATE: I believe you can't do it simpler without something like EF. Also try to use using
statements when you are working with database connections. This will close connection automatically, even in case of exception. And connection will be returned to connections pool.
private readonly string _spionshopConnectionString;
private void Form1_Load(object sender, EventArgs e)
{
_spionshopConnectionString = ConfigurationManager
.ConnectionStrings["connSpionshopString"].ConnectionString;
}
private void button4_Click(object sender, EventArgs e)
{
using(var connection = new SqlConnection(_spionshopConnectionString))
{
connection.Execute(@"INSERT INTO klant(klant_id,naam,voornaam)
VALUES (@klantId,@klantNaam,@klantVoornaam)",
new {
klantId = Convert.ToInt32(textBox1.Text),
klantNaam = textBox2.Text,
klantVoornaam = textBox3.Text
});
}
}
If an item is child of an item that is hidden is(":visible") will return true, which is incorrect.
I just fixed this by added "display:inherit" to the child item. This will fixed it for me:
<div class="parent">
<div class="child">
</div>
<div>
and the CSS:
.parent{
display: hidden;
}
.child{
display: inherit;
}
Now the item can be effectively switched on and off by changing the visibility of the parent, and $(element).is(":visible") will return the visibility of the parent item
When you use GNU AWK since version 4.1, you can load the time library and do:
$ awk '@load "time"; BEGIN{printf "%.6f", gettimeofday()}'
This will print the current time in seconds since 1970-01-01T00:00:00 in sub second accuracy.
the_time = gettimeofday()
Return the time in seconds that has elapsed since 1970-01-01 UTC as a floating-point value. If the time is unavailable on this platform, return-1
and setERRNO
. The returned time should have sub-second precision, but the actual precision may vary based on the platform. If the standard Cgettimeofday()
system call is available on this platform, then it simply returns the value. Otherwise, if on MS-Windows, it tries to useGetSystemTimeAsFileTime()
.source: GNU awk manual
On Linux systems, the standard C function getimeofday()
returns the time in microsecond accuracy.
Here is what I did and I'm happy to say that this worked for me. I too wanted a 2x2, 3x3 etc. grid of items to cover the entire screen. Gridlayouts do not adhere to the width of the screen. LinearLayouts kind of work but you cant use nested weights.
The best option for me was to use Fragments I used this tutorial to get started with what I wanted to do.
Here is some code:
Main Activity:
public class GridHolderActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_6);
}
}
activity_main_6 XML (inflates 3 fragments)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment
android:id="@+id/frag1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:name=".TwoHorizontalGridFragment"
tools:layout="@layout/two_horiz" />
<fragment
android:id="@+id/frag2"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:name=".TwoHorizontalGridFragment"
tools:layout="@layout/two_horiz" />
<fragment
android:id="@+id/frag3"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:name=".Grid.TwoHorizontalGridFragment"
tools:layout="@layout/two_horiz" />
Base fragment layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:layout_height="match_parent">
<ImageQueue
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/img1"
android:layout_weight="1"/>
<ImageQueue
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/img2"
android:layout_weight="1"/>
</LinearLayout>
Fragment Class (only handles initialization of a custom view) inflates 2 tiles per fragment
public class TwoHorizontalGridFragment extends Fragment {
private View rootView;
private ImageQueue imageQueue1;
private ImageQueue imageQueue2;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
/**
* Inflate the layout for this fragment
*/
rootView = inflater.inflate(
R.layout.two_horiz, container, false);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
imageQueue1 = (ImageQueue)rootView.findViewById(R.id.img1);
imageQueue2 = (ImageQueue)rootView.findViewById(R.id.img2);
imageQueue1.updateFiles();
imageQueue2.updateFiles();
}
}
Thats it!
This is a weird work around to using nested weights, essentially. It gives me a perfect 2x3 grid that fills the entire screen of both my 10 inch tablet and my HTC droid DNA. Let me know how it goes for you!
function changeImage(a)
so there is no such thing as a.src
=> just use a
.
demo here
To expound on cletus' answer, at runtime all record of the generic types is removed. Generics are processed only in the compiler and are used to provide additional type safety. They are really just shorthand that allows the compiler to insert typecasts at the appropriate places. For example, previously you'd have to do the following:
List x = new ArrayList();
x.add(new SomeClass());
Iterator i = x.iterator();
SomeClass z = (SomeClass) i.next();
becomes
List<SomeClass> x = new ArrayList<SomeClass>();
x.add(new SomeClass());
Iterator<SomeClass> i = x.iterator();
SomeClass z = i.next();
This allows the compiler to check your code at compile-time, but at runtime it still looks like the first example.
I did a combination of what others have posted. Its simple and smooth
$('#myButton').click(function(){
$('html, body').animate({
scrollTop: $('#scroll-to-this-element').position().top },
1000
);
});
If you really want, you could always compile with Cython. This will generate C code, which you can then compile with any C compiler such as GCC.
See the docs:
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression
expr1 ?: expr3
returnsexpr1
ifexpr1
evaluates toTRUE
, andexpr3
otherwise.
There are so many possibilities of this error some other possibilities are also on add page or edit page. In my case I was trying to save a object AdvanceSalary. The problem is that in edit the AdvanceSalary employee.employee_id is null Because on edit I was not set the employee.employee_id. I have make a hidden field and set it. my code working absolutely fine.
@Entity(name = "ic_advance_salary")
@Table(name = "ic_advance_salary")
public class AdvanceSalary extends BaseDO{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Integer id;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "employee_id", nullable = false)
private Employee employee;
@Column(name = "employee_id", insertable=false, updatable=false)
@NotNull(message="Please enter employee Id")
private Long employee_id;
@Column(name = "advance_date")
@DateTimeFormat(pattern = "dd-MMM-yyyy")
@NotNull(message="Please enter advance date")
private Date advance_date;
@Column(name = "amount")
@NotNull(message="Please enter Paid Amount")
private Double amount;
@Column(name = "cheque_date")
@DateTimeFormat(pattern = "dd-MMM-yyyy")
private Date cheque_date;
@Column(name = "cheque_no")
private String cheque_no;
@Column(name = "remarks")
private String remarks;
public AdvanceSalary() {
}
public AdvanceSalary(Integer advance_salary_id) {
this.id = advance_salary_id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public Long getEmployee_id() {
return employee_id;
}
public void setEmployee_id(Long employee_id) {
this.employee_id = employee_id;
}
}
Pillow is released with installation wheels on Windows:
We provide Pillow binaries for Windows compiled for the matrix of supported Pythons in both 32 and 64-bit versions in wheel, egg, and executable installers. These binaries have all of the optional libraries included
https://pillow.readthedocs.io/en/3.3.x/installation.html#basic-installation
Update: Python 3.6 is now supported by Pillow. Install with pip install pillow
and check https://pillow.readthedocs.io/en/latest/installation.html for more information.
However, Python 3.6 is still in alpha and not officially supported yet, although the tests do all pass for the nightly Python builds (currently 3.6a4).
https://travis-ci.org/python-pillow/Pillow/jobs/155605577
If it's somehow possible to install the 3.5 wheel for 3.6, that's your best bet. Otherwise, zlib notwithstanding, you'll need to build from source, requiring an MS Visual C++ compiler, and which isn't straightforward. For tips see:
https://pillow.readthedocs.io/en/3.3.x/installation.html#building-from-source
And also see how it's built for Windows on AppVeyor CI (but not yet 3.5 or 3.6):
https://github.com/python-pillow/Pillow/tree/master/winbuild
Failing that, downgrade to Python 3.5 or wait until 3.6 is supported by Pillow, probably closer to the 3.6's official release.
If you have the stats toolbox, then you can compute
Z = zscore(S);
Example. To find number of vowels within the string
var word='Web Development Tutorial';
var vowels='[aeiou]';
var re = new RegExp(vowels, 'gi');
var arr = word.match(re);
document.write(arr.length);
Pandas merge
offers a naive, fast solution to the problem:
# given the lists
x, y, z = [1, 2, 3], [4, 5], [6, 7]
# get dfs with same, constant index
x = pd.DataFrame({'x': x}, index=np.repeat(0, len(x))
y = pd.DataFrame({'y': y}, index=np.repeat(0, len(y))
z = pd.DataFrame({'z': z}, index=np.repeat(0, len(z))
# get all permutations stored in a new df
df = pd.merge(x, pd.merge(y, z, left_index=True, righ_index=True),
left_index=True, right_index=True)
I tried svn rm --force /path/to/dir
to no avail but ended up just running svn up
and it fixed it for me.
There are a million duplicates of this question on here, but here goes again anyway:
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.keyCode || evt.which;
var charStr = String.fromCharCode(charCode);
alert(charStr);
};
The best reference on key events I've seen is http://unixpapa.com/js/key.html.
No one seems to love mac re-indentation, So here How I do it:
[
{ "keys": ["command+shift+i"], "command": "reindent"}
]
In Preferences > Key Binding - User
One more extra tip: add
{ "keys": ["command+0"], "command": "focus_side_bar" }
to have sidebar file tree view navigation using keyboard.
Note: Add , at the end of each {}, if you have more than one {} set of objects
Simply copy the entire working directory contents (including the hidden .git
directory). This will move the entire working directory to the new directory and will not affect the remote repository on GitHub.
If you are using GitHub for Windows, you may move the repository using the method as above. However, when you click on the repository in the application it will be unable to find it. To resolve this simply click on the blue circle with the !, select Find It and then browse to the new directory.
An alternative implementation in pure powershell (without Add-Type
of c# source):
#requires -Version 5
#requires -PSEdition Desktop
class TrustAllCertsPolicy : System.Net.ICertificatePolicy {
[bool] CheckValidationResult([System.Net.ServicePoint] $a,
[System.Security.Cryptography.X509Certificates.X509Certificate] $b,
[System.Net.WebRequest] $c,
[int] $d) {
return $true
}
}
[System.Net.ServicePointManager]::CertificatePolicy = [TrustAllCertsPolicy]::new()
There is no float
type. Looks like you want float64
. You could also use float32
if you only need a single-precision floating point value.
package main
import "fmt"
func main() {
i := 5
f := float64(i)
fmt.Printf("f is %f\n", f)
}
The command for listing all triggers is:
show triggers;
or you can access the INFORMATION_SCHEMA
table directly by:
select trigger_schema, trigger_name, action_statement
from information_schema.triggers
TRIGGERS
table is here.You have here available an example of DNS Caching in Debian using dnsmasq.
Configuration summary:
# Ensure you add this line
DNSMASQ_OPTS="-r /etc/resolv.dnsmasq"
# Your preferred servers
nameserver 1.1.1.1
nameserver 8.8.8.8
nameserver 2001:4860:4860::8888
nameserver 127.0.0.1
Then just restart dnsmasq.
Benchmark test using DNS 1.1.1.1:
for i in {1..100}; do time dig slashdot.org @1.1.1.1; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'
Benchmark test using you local cached DNS:
for i in {1..100}; do time dig slashdot.org; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'
Assuming you're asking about the common "index hinting" feature found in many databases, PostgreSQL doesn't provide such a feature. This was a conscious decision made by the PostgreSQL team. A good overview of why and what you can do instead can be found here. The reasons are basically that it's a performance hack that tends to cause more problems later down the line as your data changes, whereas PostgreSQL's optimizer can re-evaluate the plan based on the statistics. In other words, what might be a good query plan today probably won't be a good query plan for all time, and index hints force a particular query plan for all time.
As a very blunt hammer, useful for testing, you can use the enable_seqscan
and enable_indexscan
parameters. See:
These are not suitable for ongoing production use. If you have issues with query plan choice, you should see the documentation for tracking down query performance issues. Don't just set enable_
params and walk away.
Unless you have a very good reason for using the index, Postgres may be making the correct choice. Why?
See also this old newsgroup post.
$('#myiframe').contents().find('html').html(s);
you can check from here http://jsfiddle.net/Y9beh/
Simply you can use the following SQL Script to delete the index in MySQL:
alter table fuinfo drop index email;
Here is a link from developer.nokia.com wiki pages, which explains how to install Windows Phone 8 SDK on a Virtual Machine with Working Emulator
And another link here
AFAIK, it is not possible to directly install WP8 SDK in Windows 7, because WP8 sdk is VS 2012 supported and also its emulator works on a Hyper-V (which is integrated into the Windows 8).
You can use a serialize() function of JQuery:
var datastring = $("#preview_form").serialize();
$.ajax({
type: "POST",
url: "your url.php",
data: datastring,
success: function(data) {
alert('Data send');
}
});
And read in PHP:
echo $_POST['datastring']['dialog_box_textarea_1'];
echo $_POST['datastring']['radiobutton_1'];
........
And get ***data-**** to tag HTML5 you can see this example:
<div id="texto" data-author="Ricardo Miranda" data-date="2012-06-21">
<h4>Lorem ipsum</h4>
<p>
Lorem ipsum dolor sit amet, ius integre eligendi et,
sea ut expetendis conclusionemque,
mel at ornatus invenire. His ad moderatius definiebas omittantur,
liber saepe albucius sea cu.
Audire tamquam dolores vis ne, mediocrem consulatu eum ex.
Duo te agam saepe convenire, et fugit iisque his.
</p>
<script type="text/javascript">
$(function() {
alert("The text is write " + $('#texto').data('author'));
});
And
<div id="texto" data-author='{"nombre":"Ricardo","apellido":"Miranda"}' data-date="2012-06-21">
...
</div>
<script type="text/javascript">
$(function() {
alert("The text is write " + $('#texto').data('author').apellido + ", " +
('#texto').data('author').nombre);
});
</script>
another version of this situation can occur when there are duplicates in the Headers build phase.
to fix this …
Build Phases
Headers
build phase+|-
boxes in the lower left corner-
buttonI'd use absolute positioning:
#play_button {
position:absolute;
transition: .5s ease;
left: 202px;
top: 198px;
}
I would recommend using a Double not a double as your type then you check against null.
The exception occurs due to this statement,
called_from.equalsIgnoreCase("add")
It seem that the previous statement
String called_from = getIntent().getStringExtra("called");
returned a null reference.
You can check whether the intent to start this activity contains such a key "called".
1)Yes it is, when there is style then it is styling your code(css).2) is belong to html it is like a container that keep your css.
Got the error in Mac after the update to Mojave. Probably you have an older version of virtual box.
Update to a recent version of virtualbox. (5.2 at the time of wrting this post)
Edit: adding @lsimonetti's comment.
In addition to that upgrade to Virtualbox 5.2, you need Vagrant >= 2.0.1
You can verify your SSH key passphrase by attempting to load it into your SSH agent. With OpenSSH this is done via ssh-add
.
Once you're done, remember to unload your SSH passphrase from the terminal by running ssh-add -d
.
From docs TWIG docs:
Unlike in PHP, it's not possible to break or continue in a loop.
But still:
You can however filter the sequence during iteration which allows you to skip items.
Example 1 (for huge lists you can filter posts using slice, slice(start, length)
):
{% for post in posts|slice(0,10) %}
<h2>{{ post.heading }}</h2>
{% endfor %}
Example 2:
{% for post in posts if post.id < 10 %}
<h2>{{ post.heading }}</h2>
{% endfor %}
You can even use own TWIG filters for more complexed conditions, like:
{% for post in posts|onlySuperPosts %}
<h2>{{ post.heading }}</h2>
{% endfor %}
VB6:
Listview1.selecteditem
VB10:
Listview1.FocusedItem.Text
Here another solution what i am using frequently. However I am not sure is good practice or not, please comment below if not.
/// Interface
export default interface BookInterface {
title: string,
author: string,
id: any
}
/// Creating Class
export class BookClass implements BookInterface {
title: string;
author: string;
id: any;
constructor(title: string, author: string, id: any) {
this.title = title;
this.author = author;
this.id = id;
}
}
/// How to use it
let book: BookInterface = new BookClass(title, author, id);
Thanks :)
Based on the error you showed ('footballforum' is missing required Java project: 'ApiDemos'), I would check your build path. Right-click the footballforum project and choose Build Path > Configure Build Path. Make sure ApiDemos is on the projects tab of the build path options.
I was looking for a nice and complete example of how to bind multiple query parameters dynamically to any SELECT, INSERT, UPDATE and DELETE query. Alec mentions in his answer a way of how to bind result, for me the get_result() after execute() function for SELECT queries works just fine, and am able to retrieve all the selected results into an array of associative arrays.
Anyway, I ended up creating a function where I am able to dynamically bind any amount of parameters to a parametrized query ( using call_user_func_array function) and obtain a result of the query execution. Below is the function with its documentation (please read before it before using - especially the $paremetersTypes - Type specification chars parameter is important to understand)
/**
* Prepares and executes a parametrized QUERY (SELECT, INSERT, UPDATE, DELETE)
*
* @param[in] $dbConnection mysqli database connection to be used for query execution
* @param[in] $dbQuery parametrized query to be bind parameters for and then execute
* @param[in] $isDMQ boolean value, should be set to TRUE for (DELETE, INSERT, UPDATE - Data manipulaiton queries), FALSE for SELECT queries
* @param[in] $paremetersTypes String representation for input parametrs' types as per http://php.net/manual/en/mysqli-stmt.bind-param.php
* @param[in] $errorOut A variable to be passed by reference where a string representation of an error will be present if a FAUILURE occurs
* @param[in] $arrayOfParemetersToBind Parameters to be bind to the parametrized query, parameters need to be specified in an array in the correct order
* @return array of feched records associative arrays for SELECT query on SUCCESS, TRUE for INSERT, UPDATE, DELETE queries on SUCCESS, on FAIL sets the error and returns NULL
*/
function ExecuteMySQLParametrizedQuery($dbConnection, $dbQuery, $isDMQ, $paremetersTypes, &$errorOut, $arrayOfParemetersToBind)
{
$stmt = $dbConnection->prepare($dbQuery);
$outValue = NULL;
if ($stmt === FALSE)
$errorOut = 'Failed to prepare statement for query: ' . $dbQuery;
else if ( call_user_func_array(array($stmt, "bind_param"), array_merge(array($paremetersTypes), $arrayOfParemetersToBind)) === FALSE)
$errorOut = 'Failed to bind required parameters to query: ' . $dbQuery . ' , parameters :' . json_encode($arrayOfParemetersToBind);
else if (!$stmt->execute())
$errorOut = "Failed to execute query [$dbQuery] , erorr:" . $stmt->error;
else
{
if ($isDMQ)
$outValue = TRUE;
else
{
$result = $stmt->get_result();
if ($result === FALSE)
$errorOut = 'Failed to obtain result from statement for query ' . $dbQuery;
else
$outValue = $result->fetch_all(MYSQLI_ASSOC);
}
}
$stmt->close();
return $outValue;
}
usage:
$param1 = "128989";
$param2 = "some passcode";
$insertQuery = "INSERT INTO Cards (Serial, UserPin) VALUES (?, ?)";
$rowsInserted = ExecuteMySQLParametrizedQuery($dbConnection, $insertQuery, TRUE, 'ss', $errorOut, array(&$param1, &$param2) ); // Make sure the parameters in an array are passed by reference
if ($rowsInserted === NULL)
echo 'error ' . $errorOut;
else
echo "successfully inserted row";
$selectQuery = "SELECT CardID FROM Cards WHERE Serial like ? AND UserPin like ?";
$arrayOfCardIDs = ExecuteMySQLParametrizedQuery($dbConnection, $selectQuery, FALSE, 'ss', $errorOut, array(&$param1, &$param2) ); // Make sure the parameters in an array are passed by reference
if ($arrayOfCardIDs === NULL)
echo 'error ' . $errorOut;
else
{
echo 'obtained result array of ' . count($arrayOfCardIDs) . 'selected rows';
if (count($arrayOfCardIDs) > 0)
echo 'obtained card id = ' . $arrayOfCardIDs[0]['CardID'];
}
Maybe the problem is the configuration of the mail server. To avoid this type of problems or you do not have to worry about the mail server problem, I recommend you use PHPMailer.
It is a plugin that has everything necessary to send mail, and the only thing you have to take into account is to have the SMTP port (Port: 25 and 465), enabled.
require_once 'PHPMailer/PHPMailer.php';
require_once '/servicios/PHPMailer/SMTP.php';
require_once '/servicios/PHPMailer/Exception.php';
$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 0;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->SMTPAuth = true;
$mail->Username = '[email protected]';
$mail->Password = 'contrasenia';
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
// Recipients
$mail->setFrom('[email protected]', 'my name');
$mail->addAddress('[email protected]');
// Attachments
$mail->addAttachment('optional file'); // Add files, is optional
// Content
$mail->isHTML(true);// Set email format to HTML
$mail->Subject = utf8_decode("subject");
$mail->Body = utf8_decode("mail content");
$mail->AltBody = '';
$mail->send();
}
catch (Exception $e) {
$error = $mail->ErrorInfo;
}
If you assume just one result you could do this as in Edwin suggested by using specific users id.
$someUserId = 'abc123';
$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss WHERE user_id = ?");
$stmt->bind_param('s', $someUserId);
$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();
ChromePhp::log($ssfullname, $ssemail); //log result in chrome if ChromePhp is used.
OR as "Your Common Sense" which selects just one user.
$stmt = $mysqli->prepare("SELECT ssfullname, ssemail FROM userss ORDER BY ssid LIMIT 1");
$stmt->execute();
$stmt->bind_result($ssfullname, $ssemail);
$stmt->store_result();
$stmt->fetch();
Nothing really different from the above except for PHP v.5
You could try:
$('input.class').removeAttr('value');
$('#inputID').removeAttr('value');
If you're using Radiant CMS, simply add
require 'thread'
to the top of config/boot.rb
.
(Kudos to Aaron's and nathanvda's responses.)
As HungryDB said the easier way for do that is:
$mystring = json_encode($my_json,JSON_UNESCAPED_SLASHES);
Have a look at your php version because this parameter has been added in version 5.4.0
Look up the new HTML5 Input Types. These instruct browsers to perform client-side filtering of data, but the implementation is incomplete across different browsers. The pattern
attribute will do regex-style filtering, but, again, browsers don't fully (or at all) support it.
However, these won't block the input itself, it will simply prevent submitting the form with the invalid data. You'll still need to trap the onkeydown
event to block key input before it displays on the screen.
Use get_browser()
From Manual:
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";
$browser = get_browser(null, true);
print_r($browser);
Will return:
Array
(
[browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
[browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*/
[parent] => Firefox 0.9
[platform] => WinXP
[browser] => Firefox
[version] => 0.9
[majorver] => 0
[minorver] => 9
[cssversion] => 2
[frames] => 1
[iframes] => 1
[tables] => 1
[cookies] => 1
[backgroundsounds] =>
[vbscript] =>
[javascript] => 1
[javaapplets] => 1
[activexcontrols] =>
[cdf] =>
[aol] =>
[beta] => 1
[win16] =>
[crawler] =>
[stripper] =>
[wap] =>
[netclr] =>
)
You need to do this on each word after you split
into an array
of words.
public String reverse(String word) {
char[] chs = word.toCharArray();
int i=0, j=chs.length-1;
while (i < j) {
// swap chs[i] and chs[j]
char t = chs[i];
chs[i] = chs[j];
chs[j] = t;
i++; j--;
}
return String.valueOf(chs);
}
Here's a way of obtaining a square root using trigonometry. It's not the fastest algorithm by a longshot, but it is precise. Code is in javascript:
var n = 5; //number to get the square root of
var icr = ((n+1)/2); //intersecting circle radius
var sqrt = Math.cos(Math.asin((icr-1)/icr))*icr; //square root of n
alert(sqrt);
Since the glyphicons image is a sprite, you really can't do that: fundamentally what you want is to limit the size of the background, but there's no way to specify how big the background is. Either you cut out the icon you want, size it down and use it, or use something like the input field prepend/append option (http://twitter.github.io/bootstrap/base-css.html#forms and then search for prepended inputs).
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
int mSec = calendar.get(Calendar.MILLISECOND);
You are echoing outside the body tag of your HTML. Put your echos there, and you should be fine.
Also, remove the onclick="alert()"
from your submit. This is the cause for your first undefined
message.
<?php
$posted = false;
if( $_POST ) {
$posted = true;
// Database stuff here...
// $result = mysql_query( ... )
$result = $_POST['name'] == "danny"; // Dummy result
}
?>
<html>
<head></head>
<body>
<?php
if( $posted ) {
if( $result )
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
else
echo "<script type='text/javascript'>alert('failed!')</script>";
}
?>
<form action="" method="post">
Name:<input type="text" id="name" name="name"/>
<input type="submit" value="submit" name="submit"/>
</form>
</body>
</html>
Yet another method - create a filter function that returns True
for all desired tags:
def my_filter(tag):
return (tag.name == 'a' and
tag.parent.name == 'li' and
'test' in tag.parent['class'])
Then just call find_all
with the argument:
for a in soup(my_filter): # or soup.find_all(my_filter)
print a
ONLY BLOCK SUBMIT but not other, important functionality of enter key, such as creating a new paragraph in a <textarea>
:
window.addEventListener('keydown', function(event) {_x000D_
//set default value for variable that will hold the status of keypress_x000D_
pressedEnter = false;_x000D_
_x000D_
//if user pressed enter, set the variable to true_x000D_
if (event.keyCode == 13)_x000D_
pressedEnter = true;_x000D_
_x000D_
//we want forms to disable submit for a tenth of a second only_x000D_
setTimeout(function() {_x000D_
pressedEnter = false;_x000D_
}, 100)_x000D_
_x000D_
})_x000D_
_x000D_
//find all forms_x000D_
var forms = document.getElementsByTagName('form')_x000D_
_x000D_
//loop through forms_x000D_
for (i = 0; i < forms.length; i++) {_x000D_
//listen to submit event_x000D_
forms[i].addEventListener('submit', function(e) {_x000D_
//if user just pressed enter, stop the submit event_x000D_
if (pressedEnter == true) {_x000D_
updateLog('Form prevented from submit.')_x000D_
e.preventDefault();_x000D_
return false;_x000D_
}_x000D_
_x000D_
updateLog('Form submitted.')_x000D_
})_x000D_
}_x000D_
_x000D_
var log = document.getElementById('log')_x000D_
updateLog = function(msg) {_x000D_
log.innerText = msg_x000D_
}
_x000D_
input,_x000D_
textarea {_x000D_
display: inline-block;_x000D_
margin-bottom: 1em;_x000D_
border: 1px solid #6f6f6f;_x000D_
padding: 5px;_x000D_
border-radius: 2px;_x000D_
width: 90%;_x000D_
font-size: 14px;_x000D_
}_x000D_
_x000D_
input[type=submit] {_x000D_
background: lightblue;_x000D_
color: #fff;_x000D_
}
_x000D_
<form>_x000D_
<p>Sample textarea (try enter key):</p>_x000D_
<textarea rows="4">Hit enter, a new line will be added. But the form won't submit</textarea><br/>_x000D_
<p>Sample textfield (try enter key):</p>_x000D_
<input type="text" placeholder="" />_x000D_
<br/>_x000D_
<input type="submit" value="Save" />_x000D_
<h3 id="log"></h3>_x000D_
</form>
_x000D_
I got this error resolved by doing 2 things in chrome browser:
This site has this information and other options as well : https://www.thesslstore.com/blog/fix-err-ssl-protocol-error/
String s = "prefix/dir1/dir2/dir3/dir4"
String parts[] = s.split("/");
System.out.println(s[0]); // "prefix"
System.out.println(s[1]); // "dir1"
...
Since I prefer to list required arguments before optional, I hack around it via:
parser = argparse.ArgumentParser()
parser._action_groups.pop()
required = parser.add_argument_group('required arguments')
optional = parser.add_argument_group('optional arguments')
required.add_argument('--required_arg', required=True)
optional.add_argument('--optional_arg')
return parser.parse_args()
and this outputs:
usage: main.py [-h] [--required_arg REQUIRED_ARG]
[--optional_arg OPTIONAL_ARG]
required arguments:
--required_arg REQUIRED_ARG
optional arguments:
--optional_arg OPTIONAL_ARG
I can live without 'help' showing up in the optional arguments group.
Try this
<script>
$().ready(function(){
$('.coupon_question').live('click',function()
{
if ($('.coupon_question').is(':checked')) {
$(".answer").show();
} else {
$(".answer").hide();
}
});
});
</script>
inside the Android manifest file of your project, find the activity declaration of whose you want to fix the orientation and add the following piece of code ,
android:screenOrientation="landscape"
for landscape orientation and for portrait add the following code,
android:screenOrientation="portrait"
I haven't tried it but if you put a div in your table cell set so that it will have scrollbars if needed, then you could insert in there, with a fixed height on the div and it should keep your table row to a fixed height.
Shared preferences introduced a getStringSet
and putStringSet
methods in API Level 11, but that's not compatible with older versions of Android (which are still popular), and also is limited to sets of strings.
Android does not provide better methods, and looping over maps and arrays for saving and loading them is not very easy and clean, specially for arrays. But a better implementation isn't that hard:
package com.example.utils;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Context;
import android.content.SharedPreferences;
public class JSONSharedPreferences {
private static final String PREFIX = "json";
public static void saveJSONObject(Context c, String prefName, String key, JSONObject object) {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(JSONSharedPreferences.PREFIX+key, object.toString());
editor.commit();
}
public static void saveJSONArray(Context c, String prefName, String key, JSONArray array) {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(JSONSharedPreferences.PREFIX+key, array.toString());
editor.commit();
}
public static JSONObject loadJSONObject(Context c, String prefName, String key) throws JSONException {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
return new JSONObject(settings.getString(JSONSharedPreferences.PREFIX+key, "{}"));
}
public static JSONArray loadJSONArray(Context c, String prefName, String key) throws JSONException {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
return new JSONArray(settings.getString(JSONSharedPreferences.PREFIX+key, "[]"));
}
public static void remove(Context c, String prefName, String key) {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
if (settings.contains(JSONSharedPreferences.PREFIX+key)) {
SharedPreferences.Editor editor = settings.edit();
editor.remove(JSONSharedPreferences.PREFIX+key);
editor.commit();
}
}
}
Now you can save any collection in shared preferences with this five methods. Working with JSONObject
and JSONArray
is very easy. You can use JSONArray (Collection copyFrom)
public constructor to make a JSONArray
out of any Java collection and use JSONArray
's get
methods to access the elements.
There is no size limit for shared preferences (besides device's storage limits), so these methods can work for most of usual cases where you want a quick and easy storage for some collection in your app. But JSON parsing happens here, and preferences in Android are stored as XMLs internally, so I recommend using other persistent data store mechanisms when you're dealing with megabytes of data.
I am using this:
<div key={+new Date() + Math.random()}>
Change this line:
mMyListView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
listItems));
to:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
listItems)
mMyListView.setAdapter(adapter);
and after updating the value of a list item, call:
adapter.notifyDataSetChanged();
I use this website and this pattern do leap year validation as well.
<input type="text" pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))" required />
To create simple hover enlarge plugin, try this. (DEMO)
HTML
<div id="content">
<img src="http://www.freevectorgallery.com/wp-content/uploads/2011/10/Vintage-Microphone- 11395-large.jpg" style="width:50%;" />
</div>
js
$(function () {
$('#content img').hover(function () {
$(this).toggle(function () {
$(this).width('70%');
});
});
});
Scope(s) can be used to propagate, dispatch event to the scope children or parent.
$emit - propagates the event to parent. $broadcast - propagates the event to children. $on - method to listen the events, propagated by $emit and $broadcast.
example index.html:
<div ng-app="appExample" ng-controller="EventCtrl">
Root(Parent) scope count: {{count}}
<div>
<button ng-click="$emit('MyEvent')">$emit('MyEvent')</button>
<button ng-click="$broadcast('MyEvent')">$broadcast('MyEvent')</button><br>
Childrent scope count: {{count}}
</div>
</div>
example app.js:
angular.module('appExample', [])
.controller('EventCtrl', ['$scope', function($scope) {
$scope.count = 0;
$scope.$on('MyEvent', function() {
$scope.count++;
});
}]);
Here u can test code: http://jsfiddle.net/zp6v0rut/41/
Draw a circle with text in middle with HTML Tag and without CSS
HTML having SVG tag for this. You can follow this standard approach if you don't want to go for CSS.
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="white" />
Sorry, your browser does not support inline SVG.
<text fill="#000000" font-size="18" font-family="Verdana"
x="15" y="60">ASHISH</text>
</svg>
This what you need to do.
@Url.Action(action,controller, null, Request.Url.Scheme)
Sessions are stored on the server and are set from server side code, not client side code such as JavaScript.
What you want is a cookie, someone's given a brilliant explanation in this Stack Overflow question here: How do I set/unset cookie with jQuery?
You could potentially use sessions and set/retrieve them with jQuery and AJAX, but it's complete overkill if Cookies will do the trick.
I know this question is 5 years old, but for anybody wondering how to do this without re-rendering the main page. This solution uses the dart editor/scripting language.
You could have an <object>
tag that contains a data
attribute. Make the <object>
1px by 1px and then use something like dart to dynamically change the <object>
's data
attribute which re-renders the data
in the 1px by 1px object.
HTML Script:
<object id="external_source" type="text/html" data="" width="1px" height="1px">
</object>
<button id="button1" type="button">Start Script</button>
<script async type="application/dart" src="dartScript.dart"></script>
<script async src="packages/browser/dart.js"></script>
someScript.php:
<?php
echo 'hello world';
?>
dartScript.dart:
import 'dart:html';
InputElement button1;
ObjectElement externalSource;
void main() {
button1 = querySelector('#button1')
..onClick.listen(runExternalSource);
externalSource = querySelector('#external_source');
}
void runExternalSource(Event e) {
externalSource.setAttribute('data', 'someScript.php');
}
So long as you aren't posting any information and you are just looking to run a script, this should work just fine.
Just build the dart script using "pub Build(generate JS)" and then upload the package onto your server.
Git add .
Git status //Check file that being modified
// git reset HEAD --- replace to which file you want to ignore
git reset HEAD .idea/ <-- Those who wanted to exclude .idea from before commit // git check status and the idea file will be gone, and you're ready to go!
git commit -m ''
git push
I solved this by clearing the jboss-x.y.z/server[config]/tmp and jboss-x.y.z/server/[config]/work directories.
You can overwrite the classes in your own css using !important, e.g. if you want to get rid of the rounded corners.
.ui-corner-all
{
border-radius: 0px !important;
}
Hide text on load and show on hover
.hide-text {
width: 70px;
display: inline-block;
white-space: nowrap;
overflow: hidden !important;
text-overflow: ellipsis;
}
span:hover {
white-space: unset;
text-overflow: unset;
}
_x000D_
<span class="hide-text"> How to hide text by dots and show text on hover</span>
_x000D_
It is very complex to invoke Win32 from C#.
You should use the tool Handle.exe.
After that your C# code have to be the following:
string fileName = @"c:\aaa.doc";//Path to locked file
Process tool = new Process();
tool.StartInfo.FileName = "handle.exe";
tool.StartInfo.Arguments = fileName+" /accepteula";
tool.StartInfo.UseShellExecute = false;
tool.StartInfo.RedirectStandardOutput = true;
tool.Start();
tool.WaitForExit();
string outputTool = tool.StandardOutput.ReadToEnd();
string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
foreach(Match match in Regex.Matches(outputTool, matchPattern))
{
Process.GetProcessById(int.Parse(match.Value)).Kill();
}
You need to use brackets when using the fileExists
step in an if
condition or assign the returned value to a variable
Using variable:
def exists = fileExists 'file'
if (exists) {
echo 'Yes'
} else {
echo 'No'
}
Using brackets:
if (fileExists('file')) {
echo 'Yes'
} else {
echo 'No'
}
If you want to compile and run Java/C/C++ apps directly on your Android device, I recommend the Terminal IDE environment from Google Play. It's a very slick package to develop and compile Android APKs, Java, C and C++ directly on your device. The interface is all command line and "vi" based, so it has real Linux feel. It comes with the gnu C/C++ implementation.
Additionally, there is a telnet and telnet server application built in, so you can do all the programming with your PC and big keyboard, but working on the device. No root permission is needed.
Why not doing it in two lines?
var a, b, c, d; // All in the same scope
a = b = c = d = 1; // Set value to all.
The reason why, is to preserve the local scope on variable declarations, as this:
var a = b = c = d = 1;
will lead to the implicit declarations of b
, c
and d
on the window scope.
I have tried all solution. The -lopencv_core -lopencv_imgproc -lopencv_highgui
in comments solved my problem. And know my command line looks like this in geany:
g++ -lopencv_core -lopencv_imgproc -lopencv_highgui -o "%e" "%f"
When I build:
g++ -lopencv_core -lopencv_imgproc -lopencv_highgui -o "opencv" "opencv.cpp" (in directory: /home/fedora/Desktop/Implementations)
The headers are:
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
Here is a complete screenshot example that works with chrome in 2021. The end result is a blob ready to be transmitted. Flow is: request media > grab frame > draw to canvas > transfer to blob. If you want to do it more memory efficient explore OffscreenCanvas or possibly ImageBitmapRenderingContext
https://jsfiddle.net/v24hyd3q/1/
// Request media
navigator.mediaDevices.getDisplayMedia().then(stream =>
{
// Grab frame from stream
let track = stream.getVideoTracks()[0];
let capture = new ImageCapture(track);
capture.grabFrame().then(bitmap =>
{
// Stop sharing
track.stop();
// Draw the bitmap to canvas
canvas.width = bitmap.width;
canvas.height = bitmap.height;
canvas.getContext('2d').drawImage(bitmap, 0, 0);
// Grab blob from canvas
canvas.toBlob(blob => {
// Do things with blob here
console.log('output blob:', blob);
});
});
})
.catch(e => console.log(e));
Update: As Roko C.Bulijan pointed out.. you need to use .insertAfter to insert it after the selected div. Also see updated code if you want it appended to the end instead of beginning when cloned multiple times. DEMO
Code:
var cloneCount = 1;;
$("button").click(function(){
$('#id')
.clone()
.attr('id', 'id'+ cloneCount++)
.insertAfter('[id^=id]:last')
// ^-- Use '#id' if you want to insert the cloned
// element in the beginning
.text('Cloned ' + (cloneCount-1)); //<--For DEMO
});
Try,
$("#id").clone().attr('id', 'id1').after("#id");
If you want a automatic counter, then see below,
var cloneCount = 1;
$("button").click(function(){
$("#id").clone().attr('id', 'id'+ cloneCount++).insertAfter("#id");
});
This answer is for TextInputEditText :
In the layout XML file set your input method options to your required type. for example done.
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/textInputLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.textfield.TextInputEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionGo"/>
</com.google.android.material.textfield.TextInputLayout>
Similarly, you can also set imeOptions to actionSubmit, actionSearch, etc
In the java add the editor action listener.
TextInputLayout textInputLayout = findViewById(R.id.textInputLayout);
textInputLayout.getEditText().setOnEditorActionListener(new
TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_GO) {
performYourAction();
return true;
}
return false;
}
});
If you're using kotlin :
textInputLayout.editText.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_GO) {
performYourAction()
}
true
}
The Python with
statement is built-in language support of the Resource Acquisition Is Initialization
idiom commonly used in C++. It is intended to allow safe acquisition and release of operating system resources.
The with
statement creates resources within a scope/block. You write your code using the resources within the block. When the block exits the resources are cleanly released regardless of the outcome of the code in the block (that is whether the block exits normally or because of an exception).
Many resources in the Python library that obey the protocol required by the with
statement and so can used with it out-of-the-box. However anyone can make resources that can be used in a with statement by implementing the well documented protocol: PEP 0343
Use it whenever you acquire resources in your application that must be explicitly relinquished such as files, network connections, locks and the like.
If you have a typescript file, you have to instruct the webpack to resolve them by using below code in webpack.config.js
module.exports={
...
resolve:{
extensions:['.ts','.tsx';]
}
}
possibly if you want to just transfer data to be used by JavaScript then you can use Hash Tags like this
http://localhost/project/index.html#exist
so once when you are done retriving the data show the message and change the
window.location.hash to a suitable value.. now whenever you ll refresh the page the hashtag
wont be present
NOTE: when you will use this instead ot query strings the data being sent cannot be retrived/read by the server
For me adding this in the web.config
resolved the problem
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" >
<remove name="UrlRoutingModule"/>
</modules>
</system.webServer>
First you have to get the localVisible rectangle of the view
For eg:
Rect rectf = new Rect();
//For coordinates location relative to the parent
anyView.getLocalVisibleRect(rectf);
//For coordinates location relative to the screen/display
anyView.getGlobalVisibleRect(rectf);
Log.d("WIDTH :", String.valueOf(rectf.width()));
Log.d("HEIGHT :", String.valueOf(rectf.height()));
Log.d("left :", String.valueOf(rectf.left));
Log.d("right :", String.valueOf(rectf.right));
Log.d("top :", String.valueOf(rectf.top));
Log.d("bottom :", String.valueOf(rectf.bottom));
Hope this will help
You can also go ahead and import via good old require, ie:
const _get: any = require('lodash.get');
This is the only thing that worked for us. Of course, make sure any require() calls come after imports.
Pseudo-random number generators work by performing some operation on a value. Generally this value is the previous number generated by the generator. However, the first time you use the generator, there is no previous value.
Seeding a pseudo-random number generator gives it its first "previous" value. Each seed value will correspond to a sequence of generated values for a given random number generator. That is, if you provide the same seed twice, you get the same sequence of numbers twice.
Generally, you want to seed your random number generator with some value that will change each execution of the program. For instance, the current time is a frequently-used seed. The reason why this doesn't happen automatically is so that if you want, you can provide a specific seed to get a known sequence of numbers.
I have recently installed dlib on python 3.7.
First I have installed cmake from anaconda navigator (cmake version 3.14.0)
Next i installed visual studio 2019 and installed Desktop development with C++ .
Then I do pip install dlib
and now its working
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null
, neither of which would seem to be what you want. If status
is null, Elvis says true
. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find
calls, just use an intermediate variable.
This method does not need to modify dtype or ravel your numpy array.
The core idea is: 1.initialize with one extra row. 2.change the list(which has one more row) to array 3.delete the extra row in the result array e.g.
>>> a = [np.zeros((10,224)), np.zeros((10,))]
>>> np.array(a)
# this will raise error,
ValueError: could not broadcast input array from shape (10,224) into shape (10)
# but below method works
>>> a = [np.zeros((11,224)), np.zeros((10,))]
>>> b = np.array(a)
>>> b[0] = np.delete(b[0],0,0)
>>> print(b.shape,b[0].shape,b[1].shape)
# print result:(2,) (10,224) (10,)
Indeed, it's not necessarily to add one more row, as long as you can escape from the gap stated in @aravk33 and @user707650 's answer and delete the extra item later, it will be fine.
in my case, this error is raised due to sequence was not created..
CREATE SEQUENCE J.SOME_SEQ MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER NOCYCLE ;
Some generic help:
gdb start GDB, with no debugging les
gdb program begin debugging program
gdb program core debug coredump core produced by program
gdb --help describe command line options
First of all, find the directory where the corefile is generated.
Then use ls -ltr
command in the directory to find the latest generated corefile.
To load the corefile use
gdb binary path of corefile
This will load the corefile.
Then you can get the information using the bt
command.
For a detailed backtrace use bt full
.
To print the variables, use print variable-name
or p variable-name
To get any help on GDB, use the help
option or use apropos search-topic
Use frame frame-number
to go to the desired frame number.
Use up n
and down n
commands to select frame n frames up and select frame n frames down respectively.
To stop GDB, use quit
or q
.
Assuming you are using VSTS run vsts-npm-auth -config .npmrc
to generate new .npmrc file with the auth token
Here is a different view or solution for the original problem. Here I show that we have an option to write a code that will process only a valid subset of values with an option to detect and handle caseses when the exception was thrown.
@Test
public void getClasses() {
String[] classNames = {"java.lang.Object", "java.lang.Integer", "java.lang.Foo"};
List<Class> classes =
Stream.of(classNames)
.map(className -> {
try {
return Class.forName(className);
} catch (ClassNotFoundException e) {
// log the error
return null;
}
})
.filter(c -> c != null)
.collect(Collectors.toList());
if (classes.size() != classNames.length) {
// add your error handling here if needed or process only the resulting list
System.out.println("Did not process all class names");
}
classes.forEach(System.out::println);
}
That's odd. Does your program compile and run successfully and only fail on 'Publish' or does it fail on every compile now?
Also, have you perhaps changed the file's properties' Build Action
to something other than Compile
?
I found a solution in the guide here:
http://www.samontab.com/web/2014/06/installing-opencv-2-4-9-in-ubuntu-14-04-lts/
I resorted to compiling and installing from source. The process was very smooth, had I known, I would have started with that instead of trying to find a more simple way to install. Hopefully this information is helpful to someone.
#!/bin/sed -f
1,/^#include/ {
/^#include/i\
#include "newfile.h"
}
How this script works: For lines between 1 and the first #include
(after line 1), if the line starts with #include
, then prepend the specified line.
However, if the first #include
is in line 1, then both line 1 and the next subsequent #include
will have the line prepended. If you are using GNU sed
, it has an extension where 0,/^#include/
(instead of 1,
) will do the right thing.
After migrating from Turbo Pascal to C++ back in the day, I used to do this in order to have an equivalent for the Turbo Pascal "inherited" keyword, which works the same way. However, after programming in C++ for a few years I stopped doing it. I found I just didn't need it very much.
Got the solution and it's working fine. Set the environment variables as:
CATALINA_HOME=C:\Program Files\Java\apache-tomcat-7.0.59\apache-tomcat-7.0.59
(path where your Apache Tomcat is)JAVA_HOME=C:\Program Files\Java\jdk1.8.0_25;
(path where your JDK is)JRE_Home=C:\Program Files\Java\jre1.8.0_25;
(path where your JRE is)CLASSPATH=%JAVA_HOME%\bin;%JRE_HOME%\bin;%CATALINA_HOME%\lib
Resolve this issue by installing Microsoft SQL Server Compact 4.0
A lot of these answers entirely forgot to mention hypermedia controls (HATEOAS) which is completely fundamental to REST. A few others touched on it, but didn't really explain it so well.
This article should explain the difference between the concepts, without getting into the weeds on specific SOAP features.
If the error message only occurs locally, try opening the sql file and press the play button.
In Python 2.7 with iPython:
>>> import os
>>> os.getenv??
Signature: os.getenv(key, default=None)
Source:
def getenv(key, default=None):
"""Get an environment variable, return None if it doesn't exist.
The optional second argument can specify an alternate default."""
return environ.get(key, default)
File: ~/venv/lib/python2.7/os.py
Type: function
So we can conclude os.getenv
is just a simple wrapper around os.environ.get
.
If you want to simply hide the errors:
$("#clearButton").click(function() {
$("label.error").hide();
$(".error").removeClass("error");
});
If you specified the errorClass
, call that class to hide instead error
(the default) I used above.
The best way to get good control over the colorbar position is to give it its own axis. Like so:
# What I imagine your plotting looks like so far
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(your_data)
# Now adding the colorbar
cbaxes = fig.add_axes([0.8, 0.1, 0.03, 0.8])
cb = plt.colorbar(ax1, cax = cbaxes)
The numbers in the square brackets of add_axes refer to [left, bottom, width, height], where the coordinates are just fractions that go from 0 to 1 of the plotting area.