Try this:
create your table on the target server using your scripts from the Script Table As / Create Script
step
on the target server, you can then issue a T-SQL statement:
INSERT INTO dbo.YourTableNameHere
SELECT *
FROM [SourceServer].[SourceDatabase].dbo.YourTableNameHere
This should work just fine.
Try this one IntentChooser. Just add some lines of code, I did the rest for you.
private void startImageChooserActivity() {
Intent intent = ImageChooserMaker.newChooser(MainActivity.this)
.add(new ImageChooser(true))
.create("Select Image");
startActivityForResult(intent, REQUEST_IMAGE_CHOOSER);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CHOOSER && resultCode == RESULT_OK) {
List<Uri> imageUris = ImageChooserMaker.getPickMultipleImageResultUris(this, data);
}
}
PS: as mentioned at the answers above, EXTRA_ALLOW_MULTIPLE is only available for API >= 18. And some gallery apps don't make this feature available (Google Photos and Documents (com.android.documentsui
) work.
I've spent 2 days attempting to convert layouts to ConstraintLayout
in the so-called "stable" release Android Studio 2.2 and I've not got ScrollView
to work in the designer. I'm not going to start down the route of adding constraints in XML for Views
that are further down the scroll. After all this is supposed to be a visual design tool.
And the number of rendering errors, stack overflows and theme issues I've had has led me to conclude that the whole ConstraintLayout
implementation is still riddled with bugs. Unless you are developing simple layouts then I'd leave it well alone until it's had a few more iterations at least.
That's 2 days I'm not going to get back.
IIS 7 or more
Use this code, but you need to be the admin on the server
public bool CheckMimeMapExtension(string fileExtension)
{
try
{
using (
ServerManager serverManager = new ServerManager())
{
// connects to default app.config
var config = serverManager.GetApplicationHostConfiguration();
var staticContent = config.GetSection("system.webServer/staticContent");
var mimeMap = staticContent.GetCollection();
foreach (var mimeType in mimeMap)
{
if (((String)mimeType["fileExtension"]).Equals(fileExtension, StringComparison.OrdinalIgnoreCase))
return true;
}
}
return false;
}
catch (Exception ex)
{
Console.WriteLine("An exception has occurred: \n{0}", ex.Message);
Console.Read();
}
return false;
}
try this:
var c=document.getElementById("alpha");
var d=c.toDataURL("image/png");
var w=window.open('about:blank','image from canvas');
w.document.write("<img src='"+d+"' alt='from canvas'/>");
This shows image from canvas on new page, but if you have open popup in new tab
setting it shows about:blank
in address bar.
EDIT:- though window.open("<img src='"+ c.toDataURL('image/png') +"'/>")
does not work in FF or Chrome, following works though rendering is somewhat different from what is shown on canvas, I think transparency is the issue:
window.open(c.toDataURL('image/png'));
Just throwing the library I'm using into the mix: https://github.com/lukencode/FluentEmail
It renders emails using RazorLight, uses the fluent style to build emails, and supports multiple senders out of the box. It comes with extension methods for ASP.NET DI too. Simple to use, little setup, with plain text and HTML support.
/*
*The Options Menu (the one that pops up on pressing the menu button on the emulator)
* can be customized to change the background of the menu
*@primalpop
*/
package com.pop.menu;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.LayoutInflater.Factory;
public class Options_Menu extends Activity {
private static final String TAG = "DEBUG";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
/* Invoked when the menu button is pressed */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
MenuInflater inflater = new MenuInflater(getApplicationContext());
inflater.inflate(R.menu.options_menu, menu);
setMenuBackground();
return true;
}
/*IconMenuItemView is the class that creates and controls the options menu
* which is derived from basic View class. So We can use a LayoutInflater
* object to create a view and apply the background.
*/
protected void setMenuBackground(){
Log.d(TAG, "Enterting setMenuBackGround");
getLayoutInflater().setFactory( new Factory() {
@Override
public View onCreateView ( String name, Context context, AttributeSet attrs ) {
if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) {
try { // Ask our inflater to create the view
LayoutInflater f = getLayoutInflater();
final View view = f.createView( name, null, attrs );
/*
* The background gets refreshed each time a new item is added the options menu.
* So each time Android applies the default background we need to set our own
* background. This is done using a thread giving the background change as runnable
* object
*/
new Handler().post( new Runnable() {
public void run () {
view.setBackgroundResource( R.drawable.background);
}
} );
return view;
}
catch ( InflateException e ) {}
catch ( ClassNotFoundException e ) {}
}
return null;
}
});
}
}
I've tested this and it works. What's the problem? Just put the new function inside your javascript element and then call it. It will work.
It has advantage when you use ASP.Net MVC. When you use HTML helper to build some control in view it uses property names in name attribure of html input:
@Html.TextBoxFor(m => m.CanBeRenamed)
It makes something like that:
<input type="text" name="CanBeRenamed" />
So now, if you need to validate your property in Validate method you can do this:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
if (IsNotValid(CanBeRenamed)) {
yield return new ValidationResult(
$"Property {nameof(CanBeRenamed)} is not valid",
new [] { $"{nameof(CanBeRenamed)}" })
}
}
In case if you rename you property using refactoring tools, your validation will not be broken.
Like this:
>>> s='1\t2\t3\t4\t5'
>>> [x for x in s.split('\t')]
['1', '2', '3', '4', '5']
For a file:
# create test file:
>>> with open('tabs.txt','w') as o:
... s='\n'.join(['\t'.join(map(str,range(i,i+10))) for i in [0,10,20,30]])
... print >>o, s
#read that file:
>>> with open('tabs.txt','r') as f:
... LoL=[x.strip().split('\t') for x in f]
...
>>> LoL
[['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
['10', '11', '12', '13', '14', '15', '16', '17', '18', '19'],
['20', '21', '22', '23', '24', '25', '26', '27', '28', '29'],
['30', '31', '32', '33', '34', '35', '36', '37', '38', '39']]
>>> LoL[2][3]
23
If you want the input transposed:
>>> with open('tabs.txt','r') as f:
... LoT=zip(*(line.strip().split('\t') for line in f))
...
>>> LoT[2][3]
'32'
Or (better still) use the csv module in the default distribution...
What worked for me was:
Created a new project.
Found that the R is wokring!
Found that difference in gradle file: compile 'com.android.support:appcompat-v7:23.4.0'
Sync, and it worked again!
If you are using in NodeJS then you can set timeout in package.json
"test": "mocha --timeout 10000"
then you can run using npm like:
npm test
I'm a little late to the party, but I think my approach has the advantage that it lacks the use of EventEmitters and Subjects.
So, here's my approach. We can't get away from subscribe(), and we don't want to. In that vein, our service will return an Observable<T>
with an observer that has our precious cargo. From the caller, we'll initialize a variable, Observable<T>
, and it will get the service's Observable<T>
. Next, we'll subscribe to this object. Finally, you get your "T"! from your service.
First, our people service, but yours doesnt pass parameters, that's more realistic:
people(hairColor: string): Observable<People> {
this.url = "api/" + hairColor + "/people.json";
return Observable.create(observer => {
http.get(this.url)
.map(res => res.json())
.subscribe((data) => {
this._people = data
observer.next(this._people);
observer.complete();
});
});
}
Ok, as you can see, we're returning an Observable
of type "people". The signature of the method, even says so! We tuck-in the _people
object into our observer. We'll access this type from our caller in the Component, next!
In the Component:
private _peopleObservable: Observable<people>;
constructor(private peopleService: PeopleService){}
getPeople(hairColor:string) {
this._peopleObservable = this.peopleService.people(hairColor);
this._peopleObservable.subscribe((data) => {
this.people = data;
});
}
We initialize our _peopleObservable
by returning that Observable<people>
from our PeopleService
. Then, we subscribe to this property. Finally, we set this.people
to our data(people
) response.
Architecting the service in this fashion has one, major advantage over the typical service: map(...) and component: "subscribe(...)" pattern. In the real world, we need to map the json to our properties in our class and, sometimes, we do some custom stuff there. So this mapping can occur in our service. And, typically, because our service call will be used not once, but, probably, in other places in our code, we don't have to perform that mapping in some component, again. Moreover, what if we add a new field to people?....
If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.
//javascript file
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);
doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
window.console.log(result);
});
//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
int userID = int.Parse(queryJson.UserID.Value);
string userName = queryJson.UserName.Value;
}
//utility function:
public static dynamic ParseHttpGetJson(string query)
{
if (!string.IsNullOrEmpty(query))
{
try
{
var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
json = System.Web.HttpUtility.UrlDecode(json);
dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);
return queryJson;
}
catch (System.Exception e)
{
throw new ApplicationException("can't deserialize object as wrong string content!", e);
}
}
else
{
return null;
}
}
I would like to attract attention to the following specifics of the as operator:
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/as
Note that the as operator performs only reference conversions, nullable conversions, and boxing conversions. The as operator can't perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.
Microsoft listed the following methods for getting the a View definition: http://technet.microsoft.com/en-us/library/ms175067.aspx
USE AdventureWorks2012;
GO
SELECT definition, uses_ansi_nulls, uses_quoted_identifier, is_schema_bound
FROM sys.sql_modules
WHERE object_id = OBJECT_ID('HumanResources.vEmployee');
GO
USE AdventureWorks2012;
GO
SELECT OBJECT_DEFINITION (OBJECT_ID('HumanResources.vEmployee'))
AS ObjectDefinition;
GO
EXEC sp_helptext 'HumanResources.vEmployee';
As mentioned, the JDK does not have a close match. However, my team occasionally has a use for such an exception as well. We could have gone with UnsupportedOperationException
as suggested by other answers, but we prefer a custom exception class in our base library that has deprecated constructors:
public class NotYetImplementedException extends RuntimeException
{
/**
* @deprecated Deprecated to remind you to implement the corresponding code
* before releasing the software.
*/
@Deprecated
public NotYetImplementedException()
{
}
/**
* @deprecated Deprecated to remind you to implement the corresponding code
* before releasing the software.
*/
@Deprecated
public NotYetImplementedException(String message)
{
super(message);
}
}
This approach has the following benefits:
NotYetImplementedException
, they know that an implementation was planned and was either forgotten or is still in progress, whereas UnsupportedOperationException
says (in line with collection contracts) that something will never be implemented. That's why we have the word "yet" in the class name. Also, an IDE can easily list the call sites.import
line (JDK 9 fixed this, though).I faced the same problem and here's the solution I implemented with ES6
code
let id = 0; // This is a kind of global variable accessible for every instance
class Animal {
constructor(name){
this.name = name;
this.id = id++;
}
foo(){}
// Executes some cool stuff
}
cat = new Animal("Catty");
console.log(cat.id) // 1
Delete Multiple checkbox using PHP Code
<input type="checkbox" name="chkbox[] value=".$row[0]."/>
<input type="submit" name="delete" value="delete"/>
<?php
if(isset($_POST['delete']))
{
$cnt=array();
$cnt=count($_POST['chkbox']);
for($i=0;$i<$cnt;$i++)
{
$del_id=$_POST['chkbox'][$i];
$query="delete from $tablename where Id=".$del_id;
mysql_query($query);
}
}
The D-Bus error can be fixed with dbus-launch :
dbus-launch command
The best way I've found is to use a combination "IF" and "ISERROR" statement:
=IF(ISERROR(COUNTIF(E5:E356,1)),"---",COUNTIF(E5:E356,1)
This formula will either fill the cell with three dashes (---) if there would be an error (if there is no data in the cells to count/average/etc), or with the count (if there was data in the cells)
The nice part about this logical query is that it will exclude entirely blank rows/columns by making them textual values of "---", so if you have a row counting (or averaging), which was then counted (or averaged) in another spot in your formula, the second formula won't respond with an error because it will ignore the "---" cell.
Guys use this code in Your main activity. Very Efficient Method
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.users_list);
UsersAdapter adapter = new UsersAdapter(users, this);
recyclerView.setAdapter(adapter);
adapter.setOnCardClickListner(this);
Here is your Adapter class.
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.UserViewHolder> {
private ArrayList<User> mDataSet;
OnCardClickListner onCardClickListner;
public UsersAdapter(ArrayList<User> mDataSet) {
this.mDataSet = mDataSet;
}
@Override
public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_row_layout, parent, false);
UserViewHolder userViewHolder = new UserViewHolder(v);
return userViewHolder;
}
@Override
public void onBindViewHolder(UserViewHolder holder, final int position) {
holder.name_entry.setText(mDataSet.get(position).getUser_name());
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onCardClickListner.OnCardClicked(v, position);
}
});
}
@Override
public int getItemCount() {
return mDataSet.size();
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
public static class UserViewHolder extends RecyclerView.ViewHolder {
CardView cardView;
TextView name_entry;
public UserViewHolder(View itemView) {
super(itemView);
cardView = (CardView) itemView.findViewById(R.id.user_layout);
name_entry = (TextView) itemView.findViewById(R.id.name_entry);
}
}
public interface OnCardClickListner {
void OnCardClicked(View view, int position);
}
public void setOnCardClickListner(OnCardClickListner onCardClickListner) {
this.onCardClickListner = onCardClickListner;
}
}
After this you will get this override method in your activity.
@Override
public void OnCardClicked(View view, int position) {
Log.d("OnClick", "Card Position" + position);
}
from
is a keyword in SQL. You may not used it as a column name without quoting it. In MySQL, things like column names are quoted using backticks, i.e. `from`
.
Personally, I wouldn't bother; I'd just rename the column.
PS. as pointed out in the comments, to
is another SQL keyword so it needs to be quoted, too. Conveniently, the folks at drupal.org maintain a list of reserved words in SQL.
The problem is the import of ProjectsListComponent
in your ProjectsModule
. You should not import that, but add it to the export array, if you want to use it outside of your ProjectsModule
.
Other issues are your project routes. You should add these to an exportable variable, otherwise it's not AOT compatible. And you should -never- import the BrowserModule
anywhere else but in your AppModule
. Use the CommonModule
to get access to the *ngIf, *ngFor...etc
directives:
@NgModule({
declarations: [
ProjectsListComponent
],
imports: [
CommonModule,
RouterModule.forChild(ProjectRoutes)
],
exports: [
ProjectsListComponent
]
})
export class ProjectsModule {}
project.routes.ts
export const ProjectRoutes: Routes = [
{ path: 'projects', component: ProjectsListComponent }
]
For your first array example use,
a = numpy.arange(5)
To initialize big_array, use
big_array = numpy.zeros((10,4))
This assumes you want to initialize with zeros, which is pretty typical, but there are many other ways to initialize an array in numpy.
Edit:
If you don't know the size of big_array in advance, it's generally best to first build a Python list using append, and when you have everything collected in the list, convert this list to a numpy array using numpy.array(mylist)
. The reason for this is that lists are meant to grow very efficiently and quickly, whereas numpy.concatenate would be very inefficient since numpy arrays don't change size easily. But once everything is collected in a list, and you know the final array size, a numpy array can be efficiently constructed.
This is the benchmark I have run after finding some articles around the net.
With 2.4.0 the winner is re.match?(str)
(as suggested by @wiktor-stribizew), on previous versions, re =~ str
seems to be fastest, although str =~ re
is almost as fast.
#!/usr/bin/env ruby
require 'benchmark'
str = "aacaabc"
re = Regexp.new('a+b').freeze
N = 4_000_000
Benchmark.bm do |b|
b.report("str.match re\t") { N.times { str.match re } }
b.report("str =~ re\t") { N.times { str =~ re } }
b.report("str[re] \t") { N.times { str[re] } }
b.report("re =~ str\t") { N.times { re =~ str } }
b.report("re.match str\t") { N.times { re.match str } }
if re.respond_to?(:match?)
b.report("re.match? str\t") { N.times { re.match? str } }
end
end
Results MRI 1.9.3-o551:
$ ./bench-re.rb | sort -t $'\t' -k 2
user system total real
re =~ str 2.390000 0.000000 2.390000 ( 2.397331)
str =~ re 2.450000 0.000000 2.450000 ( 2.446893)
str[re] 2.940000 0.010000 2.950000 ( 2.941666)
re.match str 3.620000 0.000000 3.620000 ( 3.619922)
str.match re 4.180000 0.000000 4.180000 ( 4.180083)
Results MRI 2.1.5:
$ ./bench-re.rb | sort -t $'\t' -k 2
user system total real
re =~ str 1.150000 0.000000 1.150000 ( 1.144880)
str =~ re 1.160000 0.000000 1.160000 ( 1.150691)
str[re] 1.330000 0.000000 1.330000 ( 1.337064)
re.match str 2.250000 0.000000 2.250000 ( 2.255142)
str.match re 2.270000 0.000000 2.270000 ( 2.270948)
Results MRI 2.3.3 (there is a regression in regex matching, it seems):
$ ./bench-re.rb | sort -t $'\t' -k 2
user system total real
re =~ str 3.540000 0.000000 3.540000 ( 3.535881)
str =~ re 3.560000 0.000000 3.560000 ( 3.560657)
str[re] 4.300000 0.000000 4.300000 ( 4.299403)
re.match str 5.210000 0.010000 5.220000 ( 5.213041)
str.match re 6.000000 0.000000 6.000000 ( 6.000465)
Results MRI 2.4.0:
$ ./bench-re.rb | sort -t $'\t' -k 2
user system total real
re.match? str 0.690000 0.010000 0.700000 ( 0.682934)
re =~ str 1.040000 0.000000 1.040000 ( 1.035863)
str =~ re 1.040000 0.000000 1.040000 ( 1.042963)
str[re] 1.340000 0.000000 1.340000 ( 1.339704)
re.match str 2.040000 0.000000 2.040000 ( 2.046464)
str.match re 2.180000 0.000000 2.180000 ( 2.174691)
Your DateFormat
pattern does not match you input date String
. You could use
new SimpleDateFormat("dd-MMM-yyyy")
This eventually helped me:
var x = 0;
var buttonText = 'LOADING';
$('#startbutton').click(function(){
$(this).text(buttonText);
window.setTimeout(addDotToButton,2000);
})
function addDotToButton(){
x++;
buttonText += '.';
$('#startbutton').text(buttonText);
if (x < 4) window.setTimeout(addDotToButton, 2000);
else location.reload(true);
}
if it is becoming repetitive work ; i think you shud do code reuse ! why dont you simply write functions that "write" small building blocks of HTML. get the idea? see Eg. you can have a function to which you could pass a string and it would automatically put that into a paragraph tag and present it. Of course you would also need to write some kind of a basic parser to do this (how would the function know where to attach the paragraph!). i dont think you are a beginner .. so i am not elaborating ... do tell me if you do not understand..
This error happens because of your Jre version of Eclipse and Tomcat are mismatched ..either change eclipse one to tomcat one or ViceVersa..
Both should be same ..Java version
mismatched ..Check it
It depends what you want to do with each line. awk is a useful utility for this type of processing. Example:
ls -l | awk '{print $9, $5}'
.. on my system prints the name and size of each item in the directory.
Since my system (like so many other systems) had various network interfaces.InetAddress.getLocalHost()
or Inet4Address.getLocalHost()
simply returned one that I did not desire.
Therefore I had to use this naive approach.
InetAddress[] allAddresses = Inet4Address.getAllByName("YourComputerHostName");
InetAddress desiredAddress;
//In order to find the desired Ip to be routed by other modules (WiFi adapter)
for (InetAddress address :
allAddresses) {
if (address.getHostAddress().startsWith("192.168.2")) {
desiredAddress = address;
}
}
// Use the desired address for whatever purpose.
Just be careful that in this approach I already knew that my desired IP address is in 192.168.2
subnet.
I had a problem with this kind of sql, I was giving empty list in IN clause(always check the list if it is not empty). Maybe my practice will help somebody.
I believe you can also accomplish this quite simply as follows:
e.g. #1:
# Libraries to import
import pandas as pd
import nump as np
#N x N numpy array (dimensions dont matter)
corr_mat #your numpy array
my_df = pd.DataFrame(corr_mat) #converting it to a pandas dataframe
e.g. #2:
#save as csv
my_df.to_csv('foo.csv', index=False) # "foo" is the name you want to give
# to csv file. Make sure to add ".csv"
# after whatever name like in the code
It used to be possible to disable the Home button, but now it isn't. It's due to malicious software that would trap the user.
You can see more detailes here: Disable Home button in Android 4.0+
Finally, the Back button can be disabled, as you can see in this other question: Disable back button in android
You're using Python 2.x, where integer divisions will truncate instead of becoming a floating point number.
>>> 1 / 2
0
You should make one of them a float
:
>>> float(10 - 20) / (100 - 10)
-0.1111111111111111
or from __future__ import division
, which the forces /
to adopt Python 3.x's behavior that always returns a float.
>>> from __future__ import division
>>> (10 - 20) / (100 - 10)
-0.1111111111111111
In Access, you will probably find a Join is quicker unless your tables are very small:
SELECT DISTINCT Table1.Column1
FROM Table1
LEFT JOIN Table2
ON Table1.Column1 = Table2.Column1
WHERE Table2.Column1 Is Null
This will exclude from the list all records with a match in Table2.
Is it possible to add onclick to a div and have it occur if any area of the div is clicked.
Yes … although it should be done with caution. Make sure there is some mechanism that allows keyboard access. Build on things that work
If yes then why is the onclick method not going through to my div.
You are assigning a string where a function is expected.
divTag.onclick = printWorking;
There are nicer ways to assign event handlers though, although older versions of Internet Explorer are sufficiently different that you should use a library to abstract it. There are plenty of very small event libraries and every major library jQuery) has event handling functionality.
That said, now it is 2019, older versions of Internet Explorer no longer exist in practice so you can go direct to addEventListener
Try using the -Force
parameter on Remove-Item
.
This may be created sql injection point "SQL Injection Piggy-backed Queries". attackers able to append multiple malicious sql statements. so do not append user inputs directly to the queries.
Security considerations
The API functions mysqli_query() and mysqli_real_query() do not set a connection flag necessary for activating multi queries in the server. An extra API call is used for multiple statements to reduce the likeliness of accidental SQL injection attacks. An attacker may try to add statements such as ; DROP DATABASE mysql or ; SELECT SLEEP(999). If the attacker succeeds in adding SQL to the statement string but mysqli_multi_query is not used, the server will not execute the second, injected and malicious SQL statement.
Use this instead:
string objTextBox = t.Text;
The object t
is the TextBox
. The object you call objTextBox
is assigned the ID
property of the TextBox
.
So better code would be:
TextBox objTextBox = (TextBox)sender;
string theText = objTextBox.Text;
2018 here, this is what I do:
$(inputs).on('change keydown paste input propertychange click keyup blur',handler);
If you can point out flaws in this approach, I would be grateful.
The way to approach this is to tell the tableView to remove and add rows and sections with the
insertRowsAtIndexPaths:withRowAnimation:
,
deleteRowsAtIndexPaths:withRowAnimation:
,
insertSections:withRowAnimation:
and
deleteSections:withRowAnimation:
methods of UITableView.
When you call these methods, the table will animate in/out the items you requested, then call reloadData on itself so you can update the state after this animation. This part is important - if you animate away everything but don't change the data returned by the table's dataSource, the rows will appear again after the animation completes.
So, your application flow would be:
[self setTableIsInSecondState:YES];
[myTable deleteSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:YES]];
As long as your table's dataSource methods return the correct new set of sections and rows by checking [self tableIsInSecondState]
(or whatever), this will achieve the effect you're looking for.
You can generate the WS proxy classes using WSCF (Web Services Contract First) tool from thinktecture.com. So essentially, YOU CAN create webservices from wsdl's. Creating the asmx's, maybe not, but that's the easy bit isn't it? This tool integrates brilliantly into VS2005-8 (new version for 2010/WCF called WSCF-blue). I've used it loads and always found it to be really good.
Like this for the server ip:
$_SERVER['SERVER_ADDR'];
and this for the port
$_SERVER['SERVER_PORT'];
int value = 1;
string description = Enumerations.GetEnumDescription((MyEnum)value);
The default underlying data type for an enum
in C# is an int
, you can just cast it.
Try this
$client = new \GuzzleHttp\Client();
$client->post(
'http://www.example.com/user/create',
array(
'form_params' => array(
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword'
)
)
);
I found an easy way to do this -
Just enter a command like this -
>mvn -Dtest=TestClassName#methodname -Dmaven.surefire.debug test
It will start listening to 5005 port. Now just create a remote debugging in Eclipse through Debug Configurations for localhost(any host) and port 5005.
Source - https://doc.nuxeo.com/display/CORG/How+to+Debug+a+Test+Run+with+Maven
In Python2, we had .items()
and .iteritems()
in dictionaries. dict.items()
returned list of tuples in dictionary [(k1,v1),(k2,v2),...]
. It copied all tuples in dictionary and created new list. If dictionary is very big, there is very big memory impact.
So they created dict.iteritems()
in later versions of Python2. This returned iterator object. Whole dictionary was not copied so there is lesser memory consumption. People using Python2
are taught to use dict.iteritems()
instead of .items()
for efficiency as explained in following code.
import timeit
d = {i:i*2 for i in xrange(10000000)}
start = timeit.default_timer()
for key,value in d.items():
tmp = key + value #do something like print
t1 = timeit.default_timer() - start
start = timeit.default_timer()
for key,value in d.iteritems():
tmp = key + value
t2 = timeit.default_timer() - start
Output:
Time with d.items(): 9.04773592949
Time with d.iteritems(): 2.17707300186
In Python3, they wanted to make it more efficient, so moved dictionary.iteritems()
to dict.items()
, and removed .iteritems()
as it was no longer needed.
You have used dict.iteritems()
in Python3
so it has failed. Try using dict.items()
which has the same functionality as dict.iteritems()
of Python2
. This is a tiny bit migration issue from Python2
to Python3
.
I believe that using a combination of interfaces and base classes could work for you. It will enforce behavioral requirements at compile time (rq_ post "below" refers to a post above, which is not this one).
The interface sets the behavioral API that isn't met by the base class. You will not be able to set base class methods to call on methods defined in the interface (because you will not be able to implement that interface in the base class without having to define those behaviors). Maybe someone can come up with a safe trick to allow calling of the interface methods in the parent.
You have to remember to extend and implement in the class you will instantiate. It satisfies concerns about defining runtime-fail code. You also won't even be able to call the methods that would puke if you haven't implemented the interface (such as if you try to instantiate the Animal class). I tried having the interface extend the BaseAnimal below, but it hid the constructor and the 'name' field of BaseAnimal from Snake. If I had been able to do that, the use of a module and exports could have prevented accidental direct instantiation of the BaseAnimal class.
Paste this in here to see if it works for you: http://www.typescriptlang.org/Playground/
// The behavioral interface also needs to extend base for substitutability
interface AbstractAnimal extends BaseAnimal {
// encapsulates animal behaviors that must be implemented
makeSound(input : string): string;
}
class BaseAnimal {
constructor(public name) { }
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
// If concrete class doesn't extend both, it cannot use super methods.
class Snake extends BaseAnimal implements AbstractAnimal {
constructor(name) { super(name); }
makeSound(input : string): string {
var utterance = "sssss"+input;
alert(utterance);
return utterance;
}
move() {
alert("Slithering...");
super.move(5);
}
}
var longMover = new Snake("windy man");
longMover.makeSound("...am I nothing?");
longMover.move();
var fulture = new BaseAnimal("bob fossil");
// compile error on makeSound() because it is not defined.
// fulture.makeSound("you know, like a...")
fulture.move(1);
I came across FristvanCampen's answer as linked below. He says abstract classes are an anti-pattern, and suggests that one instantiate base 'abstract' classes using an injected instance of an implementing class. This is fair, but there are counter arguments made. Read for yourself: https://typescript.codeplex.com/discussions/449920
Part 2: I had another case where I wanted an abstract class, but I was prevented from using my solution above, because the defined methods in the "abstract class" needed to refer to the methods defined in the matching interface. So, I tool FristvanCampen's advice, sort of. I have the incomplete "abstract" class, with method implementations. I have the interface with the unimplemented methods; this interface extends the "abstract" class. I then have a class that extends the first and implements the second (it must extend both because the super constructor is inaccessible otherwise). See the (non-runnable) sample below:
export class OntologyConceptFilter extends FilterWidget.FilterWidget<ConceptGraph.Node, ConceptGraph.Link> implements FilterWidget.IFilterWidget<ConceptGraph.Node, ConceptGraph.Link> {
subMenuTitle = "Ontologies Rendered"; // overload or overshadow?
constructor(
public conceptGraph: ConceptGraph.ConceptGraph,
graphView: PathToRoot.ConceptPathsToRoot,
implementation: FilterWidget.IFilterWidget<ConceptGraph.Node, ConceptGraph.Link>
){
super(graphView);
this.implementation = this;
}
}
and
export class FilterWidget<N extends GraphView.BaseNode, L extends GraphView.BaseLink<GraphView.BaseNode>> {
public implementation: IFilterWidget<N, L>
filterContainer: JQuery;
public subMenuTitle : string; // Given value in children
constructor(
public graphView: GraphView.GraphView<N, L>
){
}
doStuff(node: N){
this.implementation.generateStuff(thing);
}
}
export interface IFilterWidget<N extends GraphView.BaseNode, L extends GraphView.BaseLink<GraphView.BaseNode>> extends FilterWidget<N, L> {
generateStuff(node: N): string;
}
How about you store it like this? Maybe in username:password format, so
sebastion:password123
anotheruser:password321
Then you can use list($username,$password) = explode(':',file_get_contents('users.txt'));
to parse the data on your end.
After running eclipse:clean eclipse:eclipse its worked for me.
For Swift3
let theString = "<h1>H1 title</h1><b>Logo</b><img src='http://www.aver.com/Images/Shared/logo-color.png'><br>~end~"
let theAttributedString = try! NSAttributedString(data: theString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
UITextView_Message.attributedText = theAttributedString
The first argument must be one of type string or Buffer. Received type object
at write_
I was getting like the above error while I passing body data to the request module.
I have passed another parameter that is JSON: true and its working.
var option={
url:"https://myfirstwebsite/v1/appdata",
json:true,
body:{name:'xyz',age:30},
headers://my credential
}
rp(option)
.then((res)=>{
res.send({response:res});})
.catch((error)=>{
res.send({response:error});})
If you'd like to set this globally for all users of a machine, you can create the following directory and file structures:
mkdir %windir%\Sun\Java\Deployment
Create a file deployment.config with the content:
deployment.system.config=file:///c:/windows/Sun/Java/Deployment/deployment.properties
deployment.system.config.mandatory=TRUE
Create a file deployment.properties
deployment.user.security.exception.sites=C\:/WINDOWS/Sun/Java/Deployment/exception.sites
Create a file exception.sites
http://example1.com
http://example2.com/path/to/specific/directory/
Reference https://blogs.oracle.com/java-platform-group/entry/upcoming_exception_site_list_in
I just provide a little tuning to the solution by tfe. In particular, I added some additional control to ensure that there is no shifting of the page content (aka page shift) when the scrollbar is set to hidden
.
Two Javascript functions lockScroll()
and unlockScroll()
can be defined, respectively, to lock and unlock the page scroll.
function lockScroll(){
$html = $('html');
$body = $('body');
var initWidth = $body.outerWidth();
var initHeight = $body.outerHeight();
var scrollPosition = [
self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
];
$html.data('scroll-position', scrollPosition);
$html.data('previous-overflow', $html.css('overflow'));
$html.css('overflow', 'hidden');
window.scrollTo(scrollPosition[0], scrollPosition[1]);
var marginR = $body.outerWidth()-initWidth;
var marginB = $body.outerHeight()-initHeight;
$body.css({'margin-right': marginR,'margin-bottom': marginB});
}
function unlockScroll(){
$html = $('html');
$body = $('body');
$html.css('overflow', $html.data('previous-overflow'));
var scrollPosition = $html.data('scroll-position');
window.scrollTo(scrollPosition[0], scrollPosition[1]);
$body.css({'margin-right': 0, 'margin-bottom': 0});
}
where I assumed that the <body>
has no initial margin.
Notice that, while the above solution works in most of the practical cases, it is not definitive since it needs some further customization for pages that include, for instance, an header with position:fixed
. Let's go into this special case with an example. Suppose to have
<body>
<div id="header">My fixedheader</div>
<!--- OTHER CONTENT -->
</body>
with
#header{position:fixed; padding:0; margin:0; width:100%}
Then, one should add the following in functions lockScroll()
and unlockScroll()
:
function lockScroll(){
//Omissis
$('#header').css('margin-right', marginR);
}
function unlockScroll(){
//Omissis
$('#header').css('margin-right', 0);
}
Finally, take care of some possible initial value for the margins or paddings.
While the chosen answer is correct and more concise, I'd argue for the structure noted in other answers:
SELECT * FROM your_table
WHERE UNIX_TIMESTAMP(DateVisited) >= UNIX_TIMESTAMP(CAST(NOW() - INTERVAL 1 DAY AS DATE))
AND UNIX_TIMESTAMP(DateVisited) <= UNIX_TIMESTAMP(CAST(NOW() AS DATE));
If you just need a bare date without timestamp you could also write it as the following:
SELECT * FROM your_table
WHERE DateVisited >= CAST(NOW() - INTERVAL 1 DAY AS DATE)
AND DateVisited <= CAST(NOW() AS DATE);
The reason for using CAST
versus SUBDATE
is CAST
is ANSI SQL syntax. SUBDATE
is a MySQL specific implementation of the date arithmetic component of CAST
. Getting into the habit of using ANSI syntax can reduce headaches should you ever have to migrate to a different database. It's also good to be in the habit as a professional practice as you'll almost certainly work with other DBMS' in the future.
None of the major DBMS systems are fully ANSI compliant, but most of them implement the broad set of ANSI syntax whereas nearly none of them outside of MySQL and its descendants (MariaDB, Percona, etc) will implement MySQL-specific syntax.
Today things have changed a little.
Now we avoid use ProgressDialog to show spinning progress:
If you want to put in your app a spinning progress you should use an Activity indicators:
http://developer.android.com/design/building-blocks/progress.html#activity
Latest phpMyAdmin versions require mysqli extension and will no longer work with mysql one (note the extra "i" at the end of its name).
For PHP 5
sudo apt-get install php5-mysqli
For PHP 7.3
sudo apt-get install php7.3-mysqli
Will install package containing both old one and the new one, so afterwards all you need to do is to add
extension=mysqli.so
in your php.ini, under the subject Dynamic Extensions.
Restart apache:
sudo systemctl restart apache2
Authenitacate and press enter.
Should be done! If problem still occurs remove the browser cache.
already their is enough help full answers but if you want to see the process then
[ click here ]
Steps in Short
update php.ini file with following lines :
[XDebug]
xdebug.remote_enable = 1
xdebug.remote_autostart = 1
zend_extension=path/to/xdebug
[ good to go ]
To understand pid files, refer this DOC
Some times there are certain applications that require additional support of extra plugins and utilities. So it keeps track of these utilities and plugin process running ids using this pid file for reference.
That is why whenever you restart an application all necessary plugins and dependant apps must be restarted since the pid file will become stale.
Three ways in android studio for adding a external library.
if you want to add libarary project dependency in your project :
A. In file menu click new and choose import module choose your library project path and click ok, library project automatically add in your android studio project .
B. Now open your main module(like app) gradle file and add project dependency in dependency section dependencies {
compile project(':library project name')
if you want to add jar file : A. add jar file in libs folder. B. And Add dependency
compile fileTree(dir: 'libs', include: '*.jar') // add all jar file from libs folder, if you want to add particular jar from libs add below dependency.
compile files('libs/abc.jar')
Add Dependency from url (recommended). like
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
Candidate Key: The candidate key can be defined as minimal set of attribute which can uniquely identify a tuple is known as candidate key. For Example, STUD_NO in below STUDENT relation.
- The value of Candidate Key is unique and non-null for every tuple.
- There can be more than one candidate key in a relation. For Example, STUD_NO as well as STUD_PHONE both are candidate keys for relation STUDENT.
- The candidate key can be simple (having only one attribute) or composite as well. For Example, {STUD_NO, COURSE_NO} is a composite
candidate key for relation STUDENT_COURSE.
Super Key: The set of attributes which can uniquely identify a tuple is known as Super Key. For Example, STUD_NO, (STUD_NO, STUD_NAME) etc. Adding zero or more attributes to candidate key generates super key. A candidate key is a super key but vice versa is not true. Primary Key: There can be more than one candidate key in a relation out of which one can be chosen as primary key. For Example, STUD_NO as well as STUD_PHONE both are candidate keys for relation STUDENT but STUD_NO can be chosen as primary key (only one out of many candidate keys).
Alternate Key: The candidate key other than primary key is called as alternate key. For Example, STUD_NO as well as STUD_PHONE both are candidate keys for relation STUDENT but STUD_PHONE will be alternate key (only one out of many candidate keys).
Foreign Key: If an attribute can only take the values which are present as values of some other attribute, it will be foreign key to the attribute to which it refers. The relation which is being referenced is called referenced relation and corresponding attribute is called referenced attribute and the relation which refers to referenced relation is called referencing relation and corresponding attribute is called referencing attribute. Referenced attribute of referencing attribute should be primary key. For Example, STUD_NO in STUDENT_COURSE is a foreign key to STUD_NO in STUDENT relation.
When used in conjunction with the optional (nonstandard) attribute ZEROFILL, the default padding of spaces is replaced with zeros. For example, for a column declared as INT(4) ZEROFILL, a value of 5 is retrieved as 0005.
my css
TR.gray-t {background:#949494;}
h3{
padding-top:3px;
font:bold 12px/2px Arial;
}
my html
<TR class='gray-t'>
<TD colspan='3'><h3>KAJANG</h3>
I decrease the 2nd size in font.
padding-top
is used to fix the size in IE7.
There are answers with big number of votes, but when I read your question, I thought you wanted to know the directory where the script is, not that where the script is running. You can get the information with powershell's auto variables
$PSScriptRoot - the directory where the script exists, not the target directory the script is running in
$PSCommandPath - the full path of the script
For example, I have $profile script that finds visual studio solution file and start it. I wanted to store the full path, once a solution file is started. But I wanted to save the file where the original script exists. So I used $PsScriptRoot.
I think it is more pythonic:
aList.remove(123)
aList.insert(0, 2014)
more useful:
def shuffle(list, to_delete, to_shuffle, index):
list.remove(to_delete)
list.insert(index, to_shuffle)
return
list = ['a', 'b']
shuffle(list, 'a', 'c', 0)
print list
>> ['c', 'b']
This worked for me :
document.getElementById('yourDivID').scrollIntoView();
I fixed mine by adding these lines on my IIS webconfig.
<httpErrors>
<remove statusCode="405" subStatusCode="-1" />
<error statusCode="405" prefixLanguageFilePath="" path="/my-page.htm" responseMode="ExecuteURL" />
</httpErrors>
for regular Joins, it doesn't. TableA join TableB
will produce the same execution plan as TableB join TableA
(so your C and D examples would be the same)
for left and right joins it does. TableA left Join TableB
is different than TableB left Join TableA
, BUT its the same than TableB right Join TableA
Best solution is to use this jquery plugin:
https://github.com/jmosbech/StickyTableHeaders
This plugin worked great for us and we tried a lot other solutions. We tested it in IE, Chrome and Firefox
sed
solution:
echo "a b c" | sed 's/ \+/\n/g'
Result:
a
b
c
What about Microsoft's Visual Studio Express? http://www.microsoft.com/express/default.aspx SQL Server Express is also at that link...
I've found Tomcat to be rather finicky in that a running process or an open port doesn't necessarily mean it's actually handling requests. I usually try to grab a known page and compare its contents with a precomputed expected value.
This option seems to me more straightforward and readable:
pip install -U `pip list --outdated | awk 'NR>2 {print $1}'`
The explanation is that pip list --outdated
outputs a list of all the outdated packages in this format:
Package Version Latest Type
--------- ------- ------ -----
fonttools 3.31.0 3.32.0 wheel
urllib3 1.24 1.24.1 wheel
requests 2.20.0 2.20.1 wheel
In the awk command, NR>2
skips the first two records (lines) and {print $1}
selects the first word of each line (as suggested by SergioAraujo, I removed tail -n +3
since awk
can indeed handle skipping records).
Here's a solution using that ggplot
package (version 3.x) in addition to what you've gotten so far.
We use the position
argument of geom_bar
set to position = "fill"
. You may also use position = position_fill()
if you want to use the arguments of position_fill()
(vjust
and reverse
).
Note that your data is in a 'wide' format, whereas ggplot2
requires it to be in a 'long' format. Thus, we first need to gather
the data.
library(ggplot2)
library(dplyr)
library(tidyr)
dat <- read.table(text = " ONE TWO THREE
1 23 234 324
2 34 534 12
3 56 324 124
4 34 234 124
5 123 534 654",sep = "",header = TRUE)
# Add an id variable for the filled regions and reshape
datm <- dat %>%
mutate(ind = factor(row_number())) %>%
gather(variable, value, -ind)
ggplot(datm, aes(x = variable, y = value, fill = ind)) +
geom_bar(position = "fill",stat = "identity") +
# or:
# geom_bar(position = position_fill(), stat = "identity")
scale_y_continuous(labels = scales::percent_format())
The msg['To']
needs to be a string:
msg['To'] = "[email protected], [email protected], [email protected]"
While the recipients
in sendmail(sender, recipients, message)
needs to be a list:
sendmail("[email protected]", ["[email protected]", "[email protected]", "[email protected]"], "Howdy")
In your Html page please add
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test the multiselect with ajax</title>
<!-- Bootstrap -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- Bootstrap multiselect -->
<link rel="stylesheet" href="http://davidstutz.github.io/bootstrap-multiselect/dist/css/bootstrap-multiselect.css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.2/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<br>
<form method="post" id="myForm">
<!-- Build your select: -->
<select name="categories[]" id="example-getting-started" multiple="multiple" class="col-md-12">
<option value="A">Cheese</option>
<option value="B">Tomatoes</option>
<option value="C">Mozzarella</option>
<option value="D">Mushrooms</option>
<option value="E">Pepperoni</option>
<option value="F">Onions</option>
<option value="G">10</option>
<option value="H">11</option>
<option value="I">12</option>
</select>
<br><br>
<button type="button" class="btnSubmit"> Send </button>
</form>
<br><br>
<div id="result">result</div>
</div><!--container-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<!-- Bootstrap multiselect -->
<script src="http://davidstutz.github.io/bootstrap-multiselect/dist/js/bootstrap-multiselect.js"></script>
<!-- Bootstrap multiselect -->
<script src="ajax.js"></script>
<!-- Initialize the plugin: -->
<script type="text/javascript">
$(document).ready(function() {
$('#example-getting-started').multiselect();
});
</script>
</body>
</html>
In your ajax.js page please add
$(document).ready(function () {
$(".btnSubmit").on('click',(function(event) {
var formData = new FormData($('#myForm')[0]);
$.ajax({
url: "action.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#result").html(data);
// To clear the selected options
var select = $("#example-getting-started");
select.children().remove();
if (data.d) {
$(data.d).each(function(key,value) {
$("#example-getting-started").append($("<option></option>").val(value.State_id).html(value.State_name));
});
}
$('#example-getting-started').multiselect({includeSelectAllOption: true});
$("#example-getting-started").multiselect('refresh');
},
error: function()
{
console.log("failed to send the data");
}
});
}));
});
In your action.php page add
echo "<b>You selected :</b>";
for($i=0;$i<=count($_POST['categories']);$i++){
echo $_POST['categories'][$i]."<br>";
}
Shorter way:
var queue = function (args){
typeof variableToCheck !== "undefined"? doSomething(args) : setTimeout(function () {queue(args)}, 2000);
};
You can also pass arguments
One correct way to get selected value would be
var selected_value = $('#fruit_name').val()
And then you should do
if(selected_value) { ... }
Can't load library: /home/tom/.swt/lib/linux/x86_64/libswt-gtk-3740.so Can't load library: /home/tom/.swt/lib/linux/x86_64/libswt-gtk.so
looks like the libraries should be at .swt/lib/linux/x86_64/ if there are not there you can try this command:
locate libswt-gtk.so
this should find the libraries copy the entire directory to /home/tom/.swt/lib/linux/x86_64
What you need is the function strftime:
Time.now.strftime("%Y-%d-%m %H:%M:%S %Z")
Pass re.IGNORECASE
to the flags
param of search
, match
, or sub
:
re.search('test', 'TeSt', re.IGNORECASE)
re.match('test', 'TeSt', re.IGNORECASE)
re.sub('test', 'xxxx', 'Testing', flags=re.IGNORECASE)
Simply
function goodbye(e) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
}
window.onbeforeunload=goodbye;
RJSONIO from Omegahat is another package which provides facilities for reading and writing data in JSON format.
rjson does not use S4/S3 methods and so is not readily extensible, but still useful. Unfortunately, it does not used vectorized operations and so is too slow for non-trivial data. Similarly, for reading JSON data into R, it is somewhat slow and so does not scale to large data, should this be an issue.
Update (new Package 2013-12-03):
jsonlite: This package is a fork of the RJSONIO
package. It builds on the parser from RJSONIO
but implements a different mapping between R objects and JSON strings. The C code in this package is mostly from the RJSONIO
Package, the R code has been rewritten from scratch. In addition to drop-in replacements for fromJSON
and toJSON
, the package has functions to serialize objects. Furthermore, the package contains a lot of unit tests to make sure that all edge cases are encoded and decoded consistently for use with dynamic data in systems and applications.
const arr = ['1', '2', '3'];
// Old way
const cloneArr = arr.slice();
// ES6 way
const cloneArrES6 = [...arr];
// But problem with 3rd approach is that if you are using muti-dimensional
// array, then only first level is copied
const nums = [
[1, 2],
[10],
];
const cloneNums = [...nums];
// Let's change the first item in the first nested item in our cloned array.
cloneNums[0][0] = '8';
console.log(cloneNums);
// [ [ '8', 2 ], [ 10 ], [ 300 ] ]
// NOOooo, the original is also affected
console.log(nums);
// [ [ '8', 2 ], [ 10 ], [ 300 ] ]
So, in order to avoid these scenarios to happen, use
const arr = ['1', '2', '3'];
const cloneArr = Array.from(arr);
An alternative solution to floats is to use absolute positioning:
.title {
position: relative;
}
.title span:last-child {
position: absolute;
right: 6px; /* must be equal to parent's right padding */
}
See also the fiddle.
List<T> batch = collection.subList(i,i+nextInc);
->
List<T> batch = collection.subList(i, i = i + nextInc);
http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html covers catching multiple exceptions in the same block.
try {
// your code
} catch (Exception1 | Exception2 ex) {
// Handle 2 exceptions in Java 7
}
I'm making study cards, and this thread was helpful, just wanted to put in my two cents.
$("#linkid").trigger("click");
Instead of
paste
(default spaces), paste0
(force the inclusion of missing NA
as character) or unite
(constrained to 2 columns and 1 separator), I'd suggest an alternative as flexible as paste0
but more careful with NA
: stringr::str_c
library(tidyverse)
# check the missing value!!
df <- tibble(
n = c(2, 2, 8),
s = c("aa", "aa", NA_character_),
b = c(TRUE, FALSE, TRUE)
)
df %>%
mutate(
paste = paste(n,"-",s,".",b),
paste0 = paste0(n,"-",s,".",b),
str_c = str_c(n,"-",s,".",b)
) %>%
# convert missing value to ""
mutate(
s_2=str_replace_na(s,replacement = "")
) %>%
mutate(
str_c_2 = str_c(n,"-",s_2,".",b)
)
#> # A tibble: 3 x 8
#> n s b paste paste0 str_c s_2 str_c_2
#> <dbl> <chr> <lgl> <chr> <chr> <chr> <chr> <chr>
#> 1 2 aa TRUE 2 - aa . TRUE 2-aa.TRUE 2-aa.TRUE "aa" 2-aa.TRUE
#> 2 2 aa FALSE 2 - aa . FALSE 2-aa.FALSE 2-aa.FALSE "aa" 2-aa.FALSE
#> 3 8 <NA> TRUE 8 - NA . TRUE 8-NA.TRUE <NA> "" 8-.TRUE
Created on 2020-04-10 by the reprex package (v0.3.0)
extra note from str_c
documentation
Like most other R functions, missing values are "infectious": whenever a missing value is combined with another string the result will always be missing. Use
str_replace_na()
to convertNA
to"NA"
You also can lead your initial string, which you are going to check for pattern matching, to lower case. And using in your pattern lower case symbols respectively .
The main problem is that operator [] is used to insert and read a value into and from the map, so it cannot be const. If the key does not exist, it will create a new entry with a default value in it, incrementing the size of the map, that will contain a new key with an empty string ,in this particular case, as a value if the key does not exist yet. You should avoid operator[] when reading from a map and use, as was mention before, "map.at(key)" to ensure bound checking. This is one of the most common mistakes people often do with maps. You should use "insert" and "at" unless your code is aware of this fact. Check this talk about common bugs Curiously Recurring C++ Bugs at Facebook
The corruption in this question is isolated to a single substring at the end of the serialized string with was probably manually replaced by someone who lazily wanted to update the image
filename. This fact will be apparent in my demonstration link below using the OP's posted data -- in short, C:fakepath100.jpg
does not have a length of 19
, it should be 17
.
Since the serialized string corruption is limited to an incorrect byte/character count number, the following will do a fine job of updating the corrupted string with the correct byte count value.
It looks like many of the earlier posts are just copy-pasting a regex pattern from someone else. There is no reason to capture the potentially corrupted byte count number if it isn't going to be used in the replacement. Also, adding the s
pattern modifier is a reasonable inclusion in case a string value contains newlines/line returns.
*For those that are not aware of the treatment of multibyte characters with serializing, you must not use mb_strlen()
in the custom callback because it is the byte count that is stored not the character count, see my output...
Code: (Demo with OP's data) (Demo with arbitrary sample data) (Demo with condition replacing)
$corrupted = <<<STRING
a:4:{i:0;s:3:"three";i:1;s:5:"five";i:2;s:2:"newline1
newline2";i:3;s:6:"garçon";}
STRING;
$repaired = preg_replace_callback(
'/s:\d+:"(.*?)";/s',
// ^^^- matched/consumed but not captured because not used in replacement
function ($m) {
return "s:" . strlen($m[1]) . ":\"{$m[1]}\";";
},
$corrupted
);
echo $corrupted , "\n" , $repaired;
echo "\n---\n";
var_export(unserialize($repaired));
Output:
a:4:{i:0;s:3:"three";i:1;s:5:"five";i:2;s:2:"newline1
Newline2";i:3;s:6:"garçon";}
a:4:{i:0;s:5:"three";i:1;s:4:"five";i:2;s:17:"newline1
Newline2";i:3;s:7:"garçon";}
---
array (
0 => 'three',
1 => 'five',
2 => 'newline1
Newline2',
3 => 'garçon',
)
One leg down the rabbit hole... The above works fine even if double quotes occur in a string value, but if a string value contains ";
or some other monkeywrenching sbustring, you'll need to go a little further and implement "lookarounds". My new pattern
checks that the leading s
is:
;
and checks that the ";
is:
}
ors:
or i:
I haven't test each and every possibility; in fact, I am relatively unfamiliar with all of the possibilities in a serialized string because I never elect to work with serialized data -- always json in modern applications. If there are additional possible leading or trailing characters, leave a comment and I'll extend the lookarounds.
Extended snippet: (Demo)
$corrupted_byte_counts = <<<STRING
a:12:{i:0;s:3:"three";i:1;s:5:"five";i:2;s:2:"newline1
newline2";i:3;s:6:"garçon";i:4;s:111:"double " quote \"escaped";i:5;s:1:"a,comma";i:6;s:9:"a:colon";i:7;s:0:"single 'quote";i:8;s:999:"semi;colon";s:5:"assoc";s:3:"yes";i:9;s:1:"monkey";wrenching doublequote-semicolon";s:3:"s:";s:9:"val s: val";}
STRING;
$repaired = preg_replace_callback(
'/(?<=^|;)s:\d+:"(.*?)";(?=$|}|[si]:)/s',
//^^^^^^^^--------------^^^^^^^^^^^^^-- some additional validation
function ($m) {
return 's:' . strlen($m[1]) . ":\"{$m[1]}\";";
},
$corrupted_byte_counts
);
echo "corrupted serialized array:\n$corrupted_byte_counts";
echo "\n---\n";
echo "repaired serialized array:\n$repaired";
echo "\n---\n";
print_r(unserialize($repaired));
Output:
corrupted serialized array:
a:12:{i:0;s:3:"three";i:1;s:5:"five";i:2;s:2:"newline1
newline2";i:3;s:6:"garçon";i:4;s:111:"double " quote \"escaped";i:5;s:1:"a,comma";i:6;s:9:"a:colon";i:7;s:0:"single 'quote";i:8;s:999:"semi;colon";s:5:"assoc";s:3:"yes";i:9;s:1:"monkey";wrenching doublequote-semicolon";s:3:"s:";s:9:"val s: val";}
---
repaired serialized array:
a:12:{i:0;s:5:"three";i:1;s:4:"five";i:2;s:17:"newline1
newline2";i:3;s:7:"garçon";i:4;s:24:"double " quote \"escaped";i:5;s:7:"a,comma";i:6;s:7:"a:colon";i:7;s:13:"single 'quote";i:8;s:10:"semi;colon";s:5:"assoc";s:3:"yes";i:9;s:39:"monkey";wrenching doublequote-semicolon";s:2:"s:";s:10:"val s: val";}
---
Array
(
[0] => three
[1] => five
[2] => newline1
newline2
[3] => garçon
[4] => double " quote \"escaped
[5] => a,comma
[6] => a:colon
[7] => single 'quote
[8] => semi;colon
[assoc] => yes
[9] => monkey";wrenching doublequote-semicolon
[s:] => val s: val
)
by creating an absolute-positioned link inside relative-positioned div.. You need set the link width & height as button dimensions, and left&top coordinates for the left-top corner of button within the wrapping div.
<div style="position:relative">
<img src="" width="??" height="??" />
<a href="#" style="display:block; width:247px; height:66px; position:absolute; left: 48px; top: 275px;"></a>
</div>
I am not sure if this is the best solution or not, but it is what I need.
Please tell me if you know what is need to be changed for better performance or quality. In my case, I have a button.
Custom item on my menu - main.xml
<item
android:id="@+id/badge"
android:actionLayout="@layout/feed_update_count"
android:icon="@drawable/shape_notification"
android:showAsAction="always">
</item>
Custom shape drawable (background square) - shape_notification.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke android:color="#22000000" android:width="2dp"/>
<corners android:radius="5dp" />
<solid android:color="#CC0001"/>
</shape>
Layout for my view - feed_update_count.xml
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/notif_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="32dp"
android:minHeight="32dp"
android:background="@drawable/shape_notification"
android:text="0"
android:textSize="16sp"
android:textColor="@android:color/white"
android:gravity="center"
android:padding="2dp"
android:singleLine="true">
</Button>
MainActivity - setting and updating my view
static Button notifCount;
static int mNotifCount = 0;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
View count = menu.findItem(R.id.badge).getActionView();
notifCount = (Button) count.findViewById(R.id.notif_count);
notifCount.setText(String.valueOf(mNotifCount));
return super.onCreateOptionsMenu(menu);
}
private void setNotifCount(int count){
mNotifCount = count;
invalidateOptionsMenu();
}
You can also do it this way.
Create the following named ranges:
nList = the list of original values
nRow = ROW(nList)-ROW(OFFSET(nList,0,0,1,1))+1
nUnique = IF(COUNTIF(OFFSET(nList,nRow,0),nList)=0,COUNTIF(nList, "<"&nList),"")
With these 3 named ranges you can generate the ordered list of unique values with the formula below. It will be sorted in ascending order.
IFERROR(INDEX(nList,MATCH(SMALL(nUnique,ROW()-?),nUnique,0)),"")
You will need to substitute the row number of the cell just above the first element of your unique ordered list for the '?' character.
eg. If your unique ordered list begins in cell B5 then the formula will be:
IFERROR(INDEX(nList,MATCH(SMALL(nUnique,ROW()-4),nUnique,0)),"")
If you get the server response as a String, without using a third party library you can do
JSONObject json = new JSONObject(response);
JSONObject jsonResponse = json.getJSONObject("response");
String team = jsonResponse.getString("Team");
Here is the documentation
Otherwise to parse json you can use Gson or Jackson
EDIT without libraries (not tested)
class retrievedata extends AsyncTask<Void, Void, String>{
@Override
protected String doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
URL url;
try {
url = new URL("http://myurlhere.com");
urlConnection.setRequestMethod("GET"); //Your method here
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null)
buffer.append(line + "\n");
if (buffer.length() == 0)
return null;
return buffer.toString();
} catch (IOException e) {
Log.e(TAG, "IO Exception", e);
exception = e;
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
exception = e;
Log.e(TAG, "Error closing stream", e);
}
}
}
}
@Override
protected void onPostExecute(String response) {
if(response != null) {
JSONObject json = new JSONObject(response);
JSONObject jsonResponse = json.getJSONObject("response");
String team = jsonResponse.getString("Team");
}
}
}
You may use Apache Commons IO:
try (OutputStream outputStream = ...) {
IOUtils.write("data", outputStream, "UTF-8");
}
$ cat /tmp/so.json | underscore select '.Messages .Body'
["172.16.1.42|/home/480/1234/5-12-2013/1234.toSort"]
You can use Javascript CLI tools like
Select all name
children of a addons
:
underscore select ".addons > .name"
The underscore-cli
provide others real world examples as well as the json:select() doc.
I know that this question is about 6+ years old, but the answer by @Kyle doesn't work.
Using this
setSize(width - (getInsets().left + getInsets().right), height - (getInsets().top + getInsets().bottom));
But this always work in any size:
setSize(width + 14, height + 7);
If you don't want the border to border, and only want the white area, here:
setSize(width + 16, height + 39);
Also this only works on Windows 10, for MacOS users, use @ben's answer.
On Ubuntu you can install it for the system Python with
sudo apt install python3-opencv
Thanks HansUp for your answer, it is very helpful and it works!
I found three patterns working in Access, yours is the best, because it works in all cases.
INNER JOIN, your variant. I will call it "closed set pattern". It is possible to join more than two tables to the same table with good performance only with this pattern.
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM
((class
INNER JOIN person AS cr
ON class.C_P_ClassRep=cr.P_Nr
)
INNER JOIN person AS cr2
ON class.C_P_ClassRep2nd=cr2.P_Nr
)
;
INNER JOIN "chained-set pattern"
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM person AS cr
INNER JOIN ( class
INNER JOIN ( person AS cr2
) ON class.C_P_ClassRep2nd=cr2.P_Nr
) ON class.C_P_ClassRep=cr.P_Nr
;
CROSS JOIN with WHERE
SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
FROM class, person AS cr, person AS cr2
WHERE class.C_P_ClassRep=cr.P_Nr AND class.C_P_ClassRep2nd=cr2.P_Nr
;
XSLT 1.0 does not have an integer data type, only double. You can use number()
to convert a string to a number.
$ svn copy http://svn.example.com/repos/calc/trunk@192 \
http://svn.example.com/repos/calc/branches/my-calc-branch \
-m "Creating a private branch of /calc/trunk."
Where 192 is the revision you specify
You can find this information from the SVN Book, specifically here on the page about svn copy
Just add this one-line class in your CSS, and use the bootstrap label
component.
.label-as-badge {
border-radius: 1em;
}
Compare this label
and badge
side by side:
<span class="label label-default label-as-badge">hello</span>
<span class="badge">world</span>
They appear the same. But in the CSS, label
uses em
so it scales nicely, and it still has all the "-color" classes. So the label will scale to bigger font sizes better, and can be colored with label-success, label-warning, etc. Here are two examples:
<span class="label label-success label-as-badge">Yay! Rah!</span>
Or where things are bigger:
<div style="font-size: 36px"><!-- pretend an enclosing class has big font size -->
<span class="label label-success label-as-badge">Yay! Rah!</span>
</div>
11/16/2015: Looking at how we'll do this in Bootstrap 4
Looks like .badge
classes are completely gone. But there's a built-in .label-pill
class (here) that looks like what we want.
.label-pill {
padding-right: .6em;
padding-left: .6em;
border-radius: 10rem;
}
In use it looks like this:
<span class="label label-pill label-default">Default</span>
<span class="label label-pill label-primary">Primary</span>
<span class="label label-pill label-success">Success</span>
<span class="label label-pill label-info">Info</span>
<span class="label label-pill label-warning">Warning</span>
<span class="label label-pill label-danger">Danger</span>
11/04/2014: Here's an update on why cross-pollinating alert classes with .badge
is not so great. I think this picture sums it up:
Those alert classes were not designed to go with badges. It renders them with a "hint" of the intended colors, but in the end consistency is thrown out the window and readability is questionable. Those alert-hacked badges are not visually cohesive.
The .label-as-badge
solution is only extending the bootstrap design. We are keeping intact all the decision making made by the bootstrap designers, namely the consideration they gave for readability and cohesion across all the possible colors, as well as the color choices themselves. The .label-as-badge
class only adds rounded corners, and nothing else. There are no color definitions introduced. Thus, a single line of CSS.
Yep, it is easier to just hack away and drop in those .alert-xxxxx
classes -- you don't have to add any lines of CSS. Or you could care more about the little things and add one line.
There's also str_pad
<?php
$input = "Alien";
echo str_pad($input, 10); // produces "Alien "
echo str_pad($input, 10, "-=", STR_PAD_LEFT); // produces "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH); // produces "__Alien___"
echo str_pad($input, 6 , "___"); // produces "Alien_"
?>
Create two partial indexes:
CREATE UNIQUE INDEX favo_3col_uni_idx ON favorites (user_id, menu_id, recipe_id)
WHERE menu_id IS NOT NULL;
CREATE UNIQUE INDEX favo_2col_uni_idx ON favorites (user_id, recipe_id)
WHERE menu_id IS NULL;
This way, there can only be one combination of (user_id, recipe_id)
where menu_id IS NULL
, effectively implementing the desired constraint.
Possible drawbacks: you cannot have a foreign key referencing (user_id, menu_id, recipe_id)
, you cannot base CLUSTER
on a partial index, and queries without a matching WHERE
condition cannot use the partial index. (It seems unlikely you'd want a FK reference three columns wide - use the PK column instead).
If you need a complete index, you can alternatively drop the WHERE
condition from favo_3col_uni_idx
and your requirements are still enforced.
The index, now comprising the whole table, overlaps with the other one and gets bigger. Depending on typical queries and the percentage of NULL
values, this may or may not be useful. In extreme situations it might even help to maintain all three indexes (the two partial ones and a total on top).
Aside: I advise not to use mixed case identifiers in PostgreSQL.
You can run Postgres this way (map a port):
docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d -p 5432:5432 postgres
So now you have mapped the port 5432 of your container to port 5432 of your server. -p <host_port>:<container_port>
.So now your postgres is accessible from your public-server-ip:5432
To test: Run the postgres database (command above)
docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
05b3a3471f6f postgres "/docker-entrypoint.s" 1 seconds ago Up 1 seconds 0.0.0.0:5432->5432/tcp some-postgres
Go inside your container and create a database:
docker exec -it 05b3a3471f6f bash
root@05b3a3471f6f:/# psql -U postgres
postgres-# CREATE DATABASE mytest;
postgres-# \q
Go to your localhost (where you have some tool or the psql client).
psql -h public-ip-server -p 5432 -U postgres
(password mysecretpassword)
postgres=# \l
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+----------+----------+------------+------------+-----------------------
mytest | postgres | UTF8 | en_US.utf8 | en_US.utf8 |
postgres | postgres | UTF8 | en_US.utf8 | en_US.utf8 |
template0 | postgres | UTF8 | en_US.utf8 | en_US.utf8 | =c/postgres
So you're accessing the database (which is running in docker on a server) from your localhost.
In this post it's expained in detail.
For all example below you need to import fs and path modules:
const fs = require('fs');
const path = require('path');
function readFiles(dir, processFile) {
// read directory
fs.readdir(dir, (error, fileNames) => {
if (error) throw error;
fileNames.forEach(filename => {
// get current file name
const name = path.parse(filename).name;
// get current file extension
const ext = path.parse(filename).ext;
// get current file path
const filepath = path.resolve(dir, filename);
// get information about the file
fs.stat(filepath, function(error, stat) {
if (error) throw error;
// check if the current path is a file or a folder
const isFile = stat.isFile();
// exclude folders
if (isFile) {
// callback, do something with the file
processFile(filepath, name, ext, stat);
}
});
});
});
}
Usage:
// use an absolute path to the folder where files are located
readFiles('absolute/path/to/directory/', (filepath, name, ext, stat) => {
console.log('file path:', filepath);
console.log('file name:', name);
console.log('file extension:', ext);
console.log('file information:', stat);
});
/**
* @description Read files synchronously from a folder, with natural sorting
* @param {String} dir Absolute path to directory
* @returns {Object[]} List of object, each object represent a file
* structured like so: `{ filepath, name, ext, stat }`
*/
function readFilesSync(dir) {
const files = [];
fs.readdirSync(dir).forEach(filename => {
const name = path.parse(filename).name;
const ext = path.parse(filename).ext;
const filepath = path.resolve(dir, filename);
const stat = fs.statSync(filepath);
const isFile = stat.isFile();
if (isFile) files.push({ filepath, name, ext, stat });
});
files.sort((a, b) => {
// natural sort alphanumeric strings
// https://stackoverflow.com/a/38641281
return a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' });
});
return files;
}
Usage:
// return an array list of objects
// each object represent a file
const files = readFilesSync('absolute/path/to/directory/');
More info on promisify in this article.
const { promisify } = require('util');
const readdir_promise = promisify(fs.readdir);
const stat_promise = promisify(fs.stat);
function readFilesAsync(dir) {
return readdir_promise(dir, { encoding: 'utf8' })
.then(filenames => {
const files = getFiles(dir, filenames);
return Promise.all(files);
})
.catch(err => console.error(err));
}
function getFiles(dir, filenames) {
return filenames.map(filename => {
const name = path.parse(filename).name;
const ext = path.parse(filename).ext;
const filepath = path.resolve(dir, filename);
return stat({ name, ext, filepath });
});
}
function stat({ name, ext, filepath }) {
return stat_promise(filepath)
.then(stat => {
const isFile = stat.isFile();
if (isFile) return { name, ext, filepath, stat };
})
.catch(err => console.error(err));
}
Usage:
readFiles('absolute/path/to/directory/')
// return an array list of objects
// each object is a file
// with those properties: { name, ext, filepath, stat }
.then(files => console.log(files))
.catch(err => console.log(err));
Note: return undefined
for folders, if you want you can filter them out:
readFiles('absolute/path/to/directory/')
.then(files => files.filter(file => file !== undefined))
.catch(err => console.log(err));
Ok, this might be either a hack or error-prone, but somehow this is working as well-
SELECT id, MAX(user) as user, MAX(time) as time, MAX(io) as io FROM lms_attendance GROUP BY id;
You can't, you either need to keep the index separately:
int index = 0;
for(Element song : question) {
System.out.println("Current index is: " + (index++));
}
or use a normal for loop:
for(int i = 0; i < question.length; i++) {
System.out.println("Current index is: " + i);
}
The reason is you can use the condensed for syntax to loop over any Iterable, and it's not guaranteed that the values actually have an "index"
As far as I know, shouldOverrideUrlLoading is not called for images but rather for hyperlinks... I think the appropriate method is
@Override
public void onLoadResource(WebView view, String url)
This method is called for every resource (image, styleesheet, script) that's loaded by the webview, but since it's a void, I haven't found a way to change that url and replace it so that it loads a local resource ...
The difference between Func
and Action
is simply whether you want the delegate to return a value (use Func
) or not (use Action
).
Func
is probably most commonly used in LINQ - for example in projections:
list.Select(x => x.SomeProperty)
or filtering:
list.Where(x => x.SomeValue == someOtherValue)
or key selection:
list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)
Action
is more commonly used for things like List<T>.ForEach
: execute the given action for each item in the list. I use this less often than Func
, although I do sometimes use the parameterless version for things like Control.BeginInvoke
and Dispatcher.BeginInvoke
.
Predicate
is just a special cased Func<T, bool>
really, introduced before all of the Func
and most of the Action
delegates came along. I suspect that if we'd already had Func
and Action
in their various guises, Predicate
wouldn't have been introduced... although it does impart a certain meaning to the use of the delegate, whereas Func
and Action
are used for widely disparate purposes.
Predicate
is mostly used in List<T>
for methods like FindAll
and RemoveAll
.
Just another good looking table. I added "table-hover" class because it gives a nice hovering effect.
<h3>NATO Phonetic Alphabet</h3>
<table class="table table-striped table-bordered table-condensed table-hover">
<thead>
<tr>
<th>Letter</th>
<th>Phonetic Letter</th>
</tr>
</thead>
<tr>
<th>A</th>
<th>Alpha</th>
</tr>
<tr>
<td>B</td>
<td>Bravo</td>
</tr>
<tr>
<td>C</td>
<td>Charlie</td>
</tr>
</table>
Because I had the same problem, I want to stress that actually the first comment by Brian Cain is the solution to the "IOError: [Errno 13]"-problem:
If executed in the temp directory (cd /tmp
), the IOError does not occur anymore if I run sudo pip install foo
.
Per the jQuery documentation, try this:
$('input[inputName\\[\\]=someValue]')
[EDIT] However, I'm not sure that's the right syntax for your selector. You probably want:
$('input[name="inputName[]"][value="someValue"]')
I read through this question, and feel the best way to implement useEffect is not mentioned in the answers. Let's say you have a network call, and would like to do something once you have the response. For the sake of simplicity, let's store the network response in a state variable. One might want to use action/reducer to update the store with the network response.
const [data, setData] = useState(null);
/* This would be called on initial page load */
useEffect(()=>{
fetch(`https://www.reddit.com/r/${subreddit}.json`)
.then(data => {
setData(data);
})
.catch(err => {
/* perform error handling if desired */
});
}, [])
/* This would be called when store/state data is updated */
useEffect(()=>{
if (data) {
setPosts(data.children.map(it => {
/* do what you want */
}));
}
}, [data]);
Reference => https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
This is how I did grouping by multiple fields branchCode and prdId, Just posting it for someone in need
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
*
* @author charudatta.joshi
*/
public class Product1 {
public BigInteger branchCode;
public BigInteger prdId;
public String accountCode;
public BigDecimal actualBalance;
public BigDecimal sumActBal;
public BigInteger countOfAccts;
public Product1() {
}
public Product1(BigInteger branchCode, BigInteger prdId, String accountCode, BigDecimal actualBalance) {
this.branchCode = branchCode;
this.prdId = prdId;
this.accountCode = accountCode;
this.actualBalance = actualBalance;
}
public BigInteger getCountOfAccts() {
return countOfAccts;
}
public void setCountOfAccts(BigInteger countOfAccts) {
this.countOfAccts = countOfAccts;
}
public BigDecimal getSumActBal() {
return sumActBal;
}
public void setSumActBal(BigDecimal sumActBal) {
this.sumActBal = sumActBal;
}
public BigInteger getBranchCode() {
return branchCode;
}
public void setBranchCode(BigInteger branchCode) {
this.branchCode = branchCode;
}
public BigInteger getPrdId() {
return prdId;
}
public void setPrdId(BigInteger prdId) {
this.prdId = prdId;
}
public String getAccountCode() {
return accountCode;
}
public void setAccountCode(String accountCode) {
this.accountCode = accountCode;
}
public BigDecimal getActualBalance() {
return actualBalance;
}
public void setActualBalance(BigDecimal actualBalance) {
this.actualBalance = actualBalance;
}
@Override
public String toString() {
return "Product{" + "branchCode:" + branchCode + ", prdId:" + prdId + ", accountCode:" + accountCode + ", actualBalance:" + actualBalance + ", sumActBal:" + sumActBal + ", countOfAccts:" + countOfAccts + '}';
}
public static void main(String[] args) {
List<Product1> al = new ArrayList<Product1>();
System.out.println(al);
al.add(new Product1(new BigInteger("01"), new BigInteger("11"), "001", new BigDecimal("10")));
al.add(new Product1(new BigInteger("01"), new BigInteger("11"), "002", new BigDecimal("10")));
al.add(new Product1(new BigInteger("01"), new BigInteger("12"), "003", new BigDecimal("10")));
al.add(new Product1(new BigInteger("01"), new BigInteger("12"), "004", new BigDecimal("10")));
al.add(new Product1(new BigInteger("01"), new BigInteger("12"), "005", new BigDecimal("10")));
al.add(new Product1(new BigInteger("01"), new BigInteger("13"), "006", new BigDecimal("10")));
al.add(new Product1(new BigInteger("02"), new BigInteger("11"), "007", new BigDecimal("10")));
al.add(new Product1(new BigInteger("02"), new BigInteger("11"), "008", new BigDecimal("10")));
al.add(new Product1(new BigInteger("02"), new BigInteger("12"), "009", new BigDecimal("10")));
al.add(new Product1(new BigInteger("02"), new BigInteger("12"), "010", new BigDecimal("10")));
al.add(new Product1(new BigInteger("02"), new BigInteger("12"), "011", new BigDecimal("10")));
al.add(new Product1(new BigInteger("02"), new BigInteger("13"), "012", new BigDecimal("10")));
//Map<BigInteger, Long> counting = al.stream().collect(Collectors.groupingBy(Product1::getBranchCode, Collectors.counting()));
// System.out.println(counting);
//group by branch code
Map<BigInteger, List<Product1>> groupByBrCd = al.stream().collect(Collectors.groupingBy(Product1::getBranchCode, Collectors.toList()));
System.out.println("\n\n\n" + groupByBrCd);
Map<BigInteger, List<Product1>> groupByPrId = null;
// Create a final List to show for output containing one element of each group
List<Product> finalOutputList = new LinkedList<Product>();
Product newPrd = null;
// Iterate over resultant Map Of List
Iterator<BigInteger> brItr = groupByBrCd.keySet().iterator();
Iterator<BigInteger> prdidItr = null;
BigInteger brCode = null;
BigInteger prdId = null;
Map<BigInteger, List<Product>> tempMap = null;
List<Product1> accListPerBr = null;
List<Product1> accListPerBrPerPrd = null;
Product1 tempPrd = null;
Double sum = null;
while (brItr.hasNext()) {
brCode = brItr.next();
//get list per branch
accListPerBr = groupByBrCd.get(brCode);
// group by br wise product wise
groupByPrId=accListPerBr.stream().collect(Collectors.groupingBy(Product1::getPrdId, Collectors.toList()));
System.out.println("====================");
System.out.println(groupByPrId);
prdidItr = groupByPrId.keySet().iterator();
while(prdidItr.hasNext()){
prdId=prdidItr.next();
// get list per brcode+product code
accListPerBrPerPrd=groupByPrId.get(prdId);
newPrd = new Product();
// Extract zeroth element to put in Output List to represent this group
tempPrd = accListPerBrPerPrd.get(0);
newPrd.setBranchCode(tempPrd.getBranchCode());
newPrd.setPrdId(tempPrd.getPrdId());
//Set accCOunt by using size of list of our group
newPrd.setCountOfAccts(BigInteger.valueOf(accListPerBrPerPrd.size()));
//Sum actual balance of our of list of our group
sum = accListPerBrPerPrd.stream().filter(o -> o.getActualBalance() != null).mapToDouble(o -> o.getActualBalance().doubleValue()).sum();
newPrd.setSumActBal(BigDecimal.valueOf(sum));
// Add product element in final output list
finalOutputList.add(newPrd);
}
}
System.out.println("+++++++++++++++++++++++");
System.out.println(finalOutputList);
}
}
Output is as below:
+++++++++++++++++++++++
[Product{branchCode:1, prdId:11, accountCode:null, actualBalance:null, sumActBal:20.0, countOfAccts:2}, Product{branchCode:1, prdId:12, accountCode:null, actualBalance:null, sumActBal:30.0, countOfAccts:3}, Product{branchCode:1, prdId:13, accountCode:null, actualBalance:null, sumActBal:10.0, countOfAccts:1}, Product{branchCode:2, prdId:11, accountCode:null, actualBalance:null, sumActBal:20.0, countOfAccts:2}, Product{branchCode:2, prdId:12, accountCode:null, actualBalance:null, sumActBal:30.0, countOfAccts:3}, Product{branchCode:2, prdId:13, accountCode:null, actualBalance:null, sumActBal:10.0, countOfAccts:1}]
After Formatting it :
[
Product{branchCode:1, prdId:11, accountCode:null, actualBalance:null, sumActBal:20.0, countOfAccts:2},
Product{branchCode:1, prdId:12, accountCode:null, actualBalance:null, sumActBal:30.0, countOfAccts:3},
Product{branchCode:1, prdId:13, accountCode:null, actualBalance:null, sumActBal:10.0, countOfAccts:1},
Product{branchCode:2, prdId:11, accountCode:null, actualBalance:null, sumActBal:20.0, countOfAccts:2},
Product{branchCode:2, prdId:12, accountCode:null, actualBalance:null, sumActBal:30.0, countOfAccts:3},
Product{branchCode:2, prdId:13, accountCode:null, actualBalance:null, sumActBal:10.0, countOfAccts:1}
]
Looks like you have <authentication mode="Windows" />
in your web.config file but your hosting provider won't let you use that. Just remove that line.
This link: Creating the Sample Database in Oracle 11g Release 2 is a good example of creating a sample database.
This link: Newbie Guide to Oracle 11g Database Common Problems should help you if you come across some common problems creating your database.
Best of luck!
EDIT: As you are using XE, you should have a DB already created, to connect using SQL*Plus and SQL Developer etc. the info is here: Connecting to Oracle Database Express Edition and Exploring It.
Extract:
Connecting to Oracle Database XE from SQL Developer SQL Developer is a client program with which you can access Oracle Database XE. With Oracle Database XE 11g Release 2 (11.2), you must use SQL Developer version 3.0. This section assumes that SQL Developer is installed on your system, and shows how to start it and connect to Oracle Database XE. If SQL Developer is not installed on your system, see Oracle Database SQL Developer User's Guide for installation instructions.
Note:
For the following procedure: The first time you start SQL Developer on your system, you must provide the full path to java.exe in step 1.
For step 4, you need a user name and password.
For step 6, you need a host name and port.
To connect to Oracle Database XE from SQL Developer:
Start SQL Developer.
For instructions, see Oracle Database SQL Developer User's Guide.
If this is the first time you have started SQL Developer on your system, you are prompted to enter the full path to java.exe (for example, C:\jdk1.5.0\bin\java.exe). Either type the full path after the prompt or browse to it, and then press the key Enter.
The Oracle SQL Developer window opens.
In the navigation frame of the window, click Connections.
The Connections pane appears.
In the Connections pane, click the icon New Connection.
The New/Select Database Connection window opens.
In the New/Select Database Connection window, type the appropriate values in the fields Connection Name, Username, and Password.
For security, the password characters that you type appear as asterisks.
Near the Password field is the check box Save Password. By default, it is deselected. Oracle recommends accepting the default.
In the New/Select Database Connection window, click the tab Oracle.
The Oracle pane appears.
In the Oracle pane:
For Connection Type, accept the default (Basic).
For Role, accept the default.
In the fields Hostname and Port, either accept the defaults or type the appropriate values.
Select the option SID.
In the SID field, type accept the default (xe).
In the New/Select Database Connection window, click the button Test.
The connection is tested. If the connection succeeds, the Status indicator changes from blank to Success.
Description of the illustration success.gif
If the test succeeded, click the button Connect.
The New/Select Database Connection window closes. The Connections pane shows the connection whose name you entered in the Connection Name field in step 4.
You are in the SQL Developer environment.
To exit SQL Developer, select Exit from the File menu.
The lower the loss, the better a model (unless the model has over-fitted to the training data). The loss is calculated on training and validation and its interperation is how well the model is doing for these two sets. Unlike accuracy, loss is not a percentage. It is a summation of the errors made for each example in training or validation sets.
In the case of neural networks, the loss is usually negative log-likelihood and residual sum of squares for classification and regression respectively. Then naturally, the main objective in a learning model is to reduce (minimize) the loss function's value with respect to the model's parameters by changing the weight vector values through different optimization methods, such as backpropagation in neural networks.
Loss value implies how well or poorly a certain model behaves after each iteration of optimization. Ideally, one would expect the reduction of loss after each, or several, iteration(s).
The accuracy of a model is usually determined after the model parameters are learned and fixed and no learning is taking place. Then the test samples are fed to the model and the number of mistakes (zero-one loss) the model makes are recorded, after comparison to the true targets. Then the percentage of misclassification is calculated.
For example, if the number of test samples is 1000 and model classifies 952 of those correctly, then the model's accuracy is 95.2%.
There are also some subtleties while reducing the loss value. For instance, you may run into the problem of over-fitting in which the model "memorizes" the training examples and becomes kind of ineffective for the test set. Over-fitting also occurs in cases where you do not employ a regularization, you have a very complex model (the number of free parameters W
is large) or the number of data points N
is very low.
Use a colon:
: ${A:=hello}
The colon is a null command that does nothing and ignores its arguments. It is built into bash so a new process is not created.
for i in range(0,128):
print chr(i)
Try this!
Add this to your package.json
:
"browser": {
"[module-name]": false
},
Here's a batch file, called base64encode.bat, that encodes base64.
@echo off
if not "%1" == "" goto :arg1exists
echo usage: base64encode input-file [output-file]
goto :eof
:arg1exists
set base64out=%2
if "%base64out%" == "" set base64out=con
(
set base64tmp=base64.tmp
certutil -encode "%1" %base64tmp% > nul
findstr /v /c:- %base64tmp%
erase %base64tmp%
) > %base64out%
If you are doing in code then first check for table in database by using query SELECT table_name FROM user_tables WHERE table_name = 'XYZ'
if record found then truncate table otherwise create Table
Work like Create or Replace.
IOS 11.2 Swift 3.1- 4
let webView = WKWebView()
override func viewDidLoad() {
super.viewDidLoad()
guard let url = URL(string: "https://www.google.com") else { return }
webView.frame = view.bounds
webView.navigationDelegate = self
webView.load(URLRequest(url: url))
webView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
view.addSubview(webView)
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .linkActivated {
if let url = navigationAction.request.url,
let host = url.host, !host.hasPrefix("www.google.com"),
UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url)
print(url)
print("Redirected to browser. No need to open it locally")
decisionHandler(.cancel)
} else {
print("Open it locally")
decisionHandler(.allow)
}
} else {
print("not a user click")
decisionHandler(.allow)
}
}
Be careful with some answers...
UPDATE 2019-0829, I also included Microsoft decompiled code which should be far better than mine.
1 - You could easily represent any number with 15 significatives digits in memory with a double. See Wikipedia.
2 - The problem come from calculation of floating numbers where you could loose some precision. I mean that a number like .1 could become something like .1000000000000001 ==> after calculation. When you do some calculation, results could be truncated in order to be represented in a double. That truncation brings the error you could get.
3 - To prevent the problem when comparing double values, people introduce an error margin often called epsilon. If 2 floating numbers only have a contextual epsilon as difference, then they are considered equals. double.Epsilon is the smallest number between a double value and its neigbor (next or previous) value.
4 - The difference betwen 2 double values could be more than double.epsilon. The difference between the real double value and the one computed depends on how many calculation you have done and which ones. Many peoples think that it is always double.Epsilon but they are really wrong. To have a great answer please see: Hans Passant answer. The epsilon is based on your context where it depends on the biggest number you reach during your calculation and on the number of calculation you are doing (truncation error accumulate).
5 - This is the code that I use. Be careful that I use my epsilon only for few calculations. Otherwise I multiply my epsilon by 10 or 100.
6 - As noted by SvenL, it is possible that my epsilon is not big enough. I suggest to read SvenL comment. Also, perhaps "decimal" could do the job for your case?
Microsoft decompiled code:
// Decompiled with JetBrains decompiler
// Type: MS.Internal.DoubleUtil
// Assembly: WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
// MVID: 33C590FB-77D1-4FFD-B11B-3D104CA038E5
// Assembly location: C:\Windows\Microsoft.NET\assembly\GAC_MSIL\WindowsBase\v4.0_4.0.0.0__31bf3856ad364e35\WindowsBase.dll
using MS.Internal.WindowsBase;
using System;
using System.Runtime.InteropServices;
using System.Windows;
namespace MS.Internal
{
[FriendAccessAllowed]
internal static class DoubleUtil
{
internal const double DBL_EPSILON = 2.22044604925031E-16;
internal const float FLT_MIN = 1.175494E-38f;
public static bool AreClose(double value1, double value2)
{
if (value1 == value2)
return true;
double num1 = (Math.Abs(value1) + Math.Abs(value2) + 10.0) * 2.22044604925031E-16;
double num2 = value1 - value2;
if (-num1 < num2)
return num1 > num2;
return false;
}
public static bool LessThan(double value1, double value2)
{
if (value1 < value2)
return !DoubleUtil.AreClose(value1, value2);
return false;
}
public static bool GreaterThan(double value1, double value2)
{
if (value1 > value2)
return !DoubleUtil.AreClose(value1, value2);
return false;
}
public static bool LessThanOrClose(double value1, double value2)
{
if (value1 >= value2)
return DoubleUtil.AreClose(value1, value2);
return true;
}
public static bool GreaterThanOrClose(double value1, double value2)
{
if (value1 <= value2)
return DoubleUtil.AreClose(value1, value2);
return true;
}
public static bool IsOne(double value)
{
return Math.Abs(value - 1.0) < 2.22044604925031E-15;
}
public static bool IsZero(double value)
{
return Math.Abs(value) < 2.22044604925031E-15;
}
public static bool AreClose(Point point1, Point point2)
{
if (DoubleUtil.AreClose(point1.X, point2.X))
return DoubleUtil.AreClose(point1.Y, point2.Y);
return false;
}
public static bool AreClose(Size size1, Size size2)
{
if (DoubleUtil.AreClose(size1.Width, size2.Width))
return DoubleUtil.AreClose(size1.Height, size2.Height);
return false;
}
public static bool AreClose(Vector vector1, Vector vector2)
{
if (DoubleUtil.AreClose(vector1.X, vector2.X))
return DoubleUtil.AreClose(vector1.Y, vector2.Y);
return false;
}
public static bool AreClose(Rect rect1, Rect rect2)
{
if (rect1.IsEmpty)
return rect2.IsEmpty;
if (!rect2.IsEmpty && DoubleUtil.AreClose(rect1.X, rect2.X) && (DoubleUtil.AreClose(rect1.Y, rect2.Y) && DoubleUtil.AreClose(rect1.Height, rect2.Height)))
return DoubleUtil.AreClose(rect1.Width, rect2.Width);
return false;
}
public static bool IsBetweenZeroAndOne(double val)
{
if (DoubleUtil.GreaterThanOrClose(val, 0.0))
return DoubleUtil.LessThanOrClose(val, 1.0);
return false;
}
public static int DoubleToInt(double val)
{
if (0.0 >= val)
return (int) (val - 0.5);
return (int) (val + 0.5);
}
public static bool RectHasNaN(Rect r)
{
return DoubleUtil.IsNaN(r.X) || DoubleUtil.IsNaN(r.Y) || (DoubleUtil.IsNaN(r.Height) || DoubleUtil.IsNaN(r.Width));
}
public static bool IsNaN(double value)
{
DoubleUtil.NanUnion nanUnion = new DoubleUtil.NanUnion();
nanUnion.DoubleValue = value;
ulong num1 = nanUnion.UintValue & 18442240474082181120UL;
ulong num2 = nanUnion.UintValue & 4503599627370495UL;
if (num1 == 9218868437227405312UL || num1 == 18442240474082181120UL)
return num2 > 0UL;
return false;
}
[StructLayout(LayoutKind.Explicit)]
private struct NanUnion
{
[FieldOffset(0)]
internal double DoubleValue;
[FieldOffset(0)]
internal ulong UintValue;
}
}
}
My code:
public static class DoubleExtension
{
// ******************************************************************
// Base on Hans Passant Answer on:
// https://stackoverflow.com/questions/2411392/double-epsilon-for-equality-greater-than-less-than-less-than-or-equal-to-gre
/// <summary>
/// Compare two double taking in account the double precision potential error.
/// Take care: truncation errors accumulate on calculation. More you do, more you should increase the epsilon.
public static bool AboutEquals(this double value1, double value2)
{
double epsilon = Math.Max(Math.Abs(value1), Math.Abs(value2)) * 1E-15;
return Math.Abs(value1 - value2) <= epsilon;
}
// ******************************************************************
// Base on Hans Passant Answer on:
// https://stackoverflow.com/questions/2411392/double-epsilon-for-equality-greater-than-less-than-less-than-or-equal-to-gre
/// <summary>
/// Compare two double taking in account the double precision potential error.
/// Take care: truncation errors accumulate on calculation. More you do, more you should increase the epsilon.
/// You get really better performance when you can determine the contextual epsilon first.
/// </summary>
/// <param name="value1"></param>
/// <param name="value2"></param>
/// <param name="precalculatedContextualEpsilon"></param>
/// <returns></returns>
public static bool AboutEquals(this double value1, double value2, double precalculatedContextualEpsilon)
{
return Math.Abs(value1 - value2) <= precalculatedContextualEpsilon;
}
// ******************************************************************
public static double GetContextualEpsilon(this double biggestPossibleContextualValue)
{
return biggestPossibleContextualValue * 1E-15;
}
// ******************************************************************
/// <summary>
/// Mathlab equivalent
/// </summary>
/// <param name="dividend"></param>
/// <param name="divisor"></param>
/// <returns></returns>
public static double Mod(this double dividend, double divisor)
{
return dividend - System.Math.Floor(dividend / divisor) * divisor;
}
// ******************************************************************
}
Responding to the Forum Thread for the sake of completeness. Amazon has stopped using the the ECU - Elastic Compute Units and moved on to a vCPU based measure. So ignoring the ECU you pretty much can start comparing the EC2 Instances' sizes as CPU (Clock Speed), number of CPUs, RAM, storage etc.
Every instance families' instance configurations are published as number of vCPU and what is the physical processor. Detailed info and screenshot obstained from here http://aws.amazon.com/ec2/instance-types/#instance-type-matrix
Reading the file
import h5py
f = h5py.File(file_name, mode)
Studying the structure of the file by printing what HDF5 groups are present
for key in f.keys():
print(key) #Names of the groups in HDF5 file.
Extracting the data
#Get the HDF5 group
group = f[key]
#Checkout what keys are inside that group.
for key in group.keys():
print(key)
data = group[some_key_inside_the_group].value
#Do whatever you want with data
#After you are done
f.close()
Use the following jquery to submit a selectbox with out a submit button. Use "change" instead of click as shown above.
$("selectbox").change(function() {
document.forms["form"].submit();
});
Cheers!
The read_sql
docs say this params
argument can be a list, tuple or dict (see docs).
To pass the values in the sql query, there are different syntaxes possible: ?
, :1
, :name
, %s
, %(name)s
(see PEP249).
But not all of these possibilities are supported by all database drivers, which syntax is supported depends on the driver you are using (psycopg2
in your case I suppose).
In your second case, when using a dict, you are using 'named arguments', and according to the psycopg2
documentation, they support the %(name)s
style (and so not the :name
I suppose), see http://initd.org/psycopg/docs/usage.html#query-parameters.
So using that style should work:
df = psql.read_sql(('select "Timestamp","Value" from "MyTable" '
'where "Timestamp" BETWEEN %(dstart)s AND %(dfinish)s'),
db,params={"dstart":datetime(2014,6,24,16,0),"dfinish":datetime(2014,6,24,17,0)},
index_col=['Timestamp'])
use below
UIImageView *imageView = ((UIImageView *)(barButtonItem.customView.subviews.lastObject));
file_name = imageView.accessibilityLabel;
now Nuget Package Manager Console in Visual Studio 2012 gives you a "Restore" button automatically as soon it find any package not installed but in there in package.config. Awesome Feature!
You can also use df.assign
:
In [1559]: df
Out[1559]:
A B C
0 0 NaN NaN
1 4 NaN NaN
2 5 NaN NaN
3 6 NaN NaN
4 7 NaN NaN
5 7 NaN NaN
6 6 NaN NaN
7 5 NaN NaN
In [1560]: mylist = [2,5,6,8,12,16,26,32]
In [1567]: df = df.assign(D=mylist)
In [1568]: df
Out[1568]:
A B C D
0 0 NaN NaN 2
1 4 NaN NaN 5
2 5 NaN NaN 6
3 6 NaN NaN 8
4 7 NaN NaN 12
5 7 NaN NaN 16
6 6 NaN NaN 26
7 5 NaN NaN 32
Another alternative way to achieve the same is to use the tail calls. But, we don’t have anything like that in JavaScript. So generally, the goto is accomplished in JS using the below two keywords. break and continue, reference: Goto Statement in JavaScript
Here is an example:
var number = 0;
start_position: while(true) {
document.write("Anything you want to print");
number++;
if(number < 100) continue start_position;
break;
}
In case of a very large stream length there is the hazard of memory leak due to Large Object Heap. i.e. The byte buffer created by stream.ToArray creates a copy of memory stream in Heap memory leading to duplication of reserved memory. I would suggest to use a StreamReader
, a TextWriter
and read the stream in chunks of char
buffers.
In netstandard2.0 System.IO.StreamReader
has a method ReadBlock
you can use this method in order to read the instance of a Stream (a MemoryStream instance as well since Stream is the super of MemoryStream):
private static string ReadStreamInChunks(Stream stream, int chunkLength)
{
stream.Seek(0, SeekOrigin.Begin);
string result;
using(var textWriter = new StringWriter())
using (var reader = new StreamReader(stream))
{
var readChunk = new char[chunkLength];
int readChunkLength;
//do while: is useful for the last iteration in case readChunkLength < chunkLength
do
{
readChunkLength = reader.ReadBlock(readChunk, 0, chunkLength);
textWriter.Write(readChunk,0,readChunkLength);
} while (readChunkLength > 0);
result = textWriter.ToString();
}
return result;
}
NB. The hazard of memory leak is not fully eradicated, due to the usage of MemoryStream, that can lead to memory leak for large memory stream instance (memoryStreamInstance.Size >85000 bytes). You can use Recyclable Memory stream, in order to avoid LOH. This is the relevant library
I found no solid answers that didn't either break accessibility or subvert functionality.
Perhaps combining a few will work better overall.
<h1
onmousedown="this.style.outline='none';"
onclick="this.blur(); runFn(this);"
onmouseup="this.style.outline=null;"
>Hello</h1>
function runFn(thisElem) { console.log('Hello: ', thisElem); }
The approved solution doesn't work in my case, so my solution is the following one:
''' The column name in the example case is "Unnamed: 7"
but it works with any other name ("Unnamed: 0" for example). '''
df.rename({"Unnamed: 7":"a"}, axis="columns", inplace=True)
# Then, drop the column as usual.
df.drop(["a"], axis=1, inplace=True)
Hope it helps others.
In my case it was because i was connecting to HTTP and it was running on HTTPS
Just to give a complete answer:
filename_queue = tf.train.string_input_producer(['/Users/HANEL/Desktop/tf.png']) # list of files to read
reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)
my_img = tf.image.decode_png(value) # use png or jpg decoder based on your files.
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init_op)
# Start populating the filename queue.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
for i in range(1): #length of your filename list
image = my_img.eval() #here is your image Tensor :)
print(image.shape)
Image.fromarray(np.asarray(image)).show()
coord.request_stop()
coord.join(threads)
Or if you have a directory of images you can add them all via this Github source file
@mttk and @salvador-dali: I hope it is what you need
Old post but ES6 now handles this out of the box with the includes
method.
let files = ['file.json', 'other.js'];
let jsonFiles = files.filter(file => file.includes('.json'));
console.log("Files: ", jsonFiles) ==> //file.json
if You have The JAVA_HOME environment variable is not defined correctly This environment variable is needed to run this program NB: JAVA_HOME should point to a JDK not a JRE Error so do one thing ...type C:>dir/x and you will see the PROGRA~1 or May ~2 and After int Environment Variable Chang The JAVA_HOME Dir Like This JAVA_HOME:- C:\PROGRA~1\Java\jdk1.8.0_144\ also Set In Path :-%JAVA_HOME%\bin; And it Works
Thanks for the links, but it does seem as if the actual text highlighting just isn't exposed.
As far as the actual issue at hand, I ended up opting for a different approach by eliminating the need for a text input altogether and using innerHTML with some JavaScript. Not only does it get around the text highlighting, it actually looks much cleaner.
This granular of a tweak to an HTML form control is just another good argument for eliminating form controls altogether. Haha!
The memory associated with arr
is freed automatically when arr
goes out of scope. It is either a local variable, or allocated statically, but it is not dynamically allocated.
A simple rule for you to follow is that you must only every call free()
on a pointer that was returned by a call to malloc
, calloc
or realloc
.
so I also had the same problem. This is probably happening because your computer has an older version of ruby. So you need to first update your ruby. Mine worked for ruby 2.6.3 version.I got this solution from sStackOverflow,
You need to first open terminal and put this code
curl -L https://get.rvm.io | bash -s stable
Then put this command
rvm install ruby-2.6
This would install the ruby for you if it hasn' t been installed.After this just update the ruby to the new version
rvm use ruby-2.6.3
After this just make ruby 2.6.3 your default
rvm --default use 2.6.3
This would possibly fix your issue. You can now put the command
sudo gem install cocoapods
And the command
pod setup
I hope this was useful
strlist =[{}]*10
strlist[0] = set()
strlist[0].add("Beef")
strlist[0].add("Fish")
strlist[1] = {"Apple", "Banana"}
strlist[1].add("Cherry")
print(strlist[0])
print(strlist[1])
print(strlist[2])
print("Array size:", len(strlist))
print(strlist)
.border-blue.background { ... }
is for one item with multiple classes.
.border-blue, .background { ... }
is for multiple items each with their own class.
.border-blue .background { ... }
is for one item where '.background' is the child of '.border-blue'.
See Chris' answer for a more thorough explanation.
I agree that using jQuery is the best option. You should also avoid using body's onload function and use jQuery's ready function instead. As for the event listeners, they should be functions that take one argument:
document.getElementById("foo").onclick = function (event){alert('foo');};
or in jQuery:
$('#foo').click(function(event) { alert('foo'); }
np.mean
always computes an arithmetic mean, and has some additional options for input and output (e.g. what datatypes to use, where to place the result).
np.average
can compute a weighted average if the weights
parameter is supplied.
Explaining State Transitions in the official doc: https://developer.apple.com/library/ios/documentation/uikit/reference/UIViewController_Class/index.html
This image shows the valid state transitions between various view ‘will’ and ‘did’ callback methods
Valid State Transitions:
Taken from: https://developer.apple.com/library/ios/documentation/uikit/reference/UIViewController_Class/Art/UIViewController Class Reference_2x.png
In addition mysql passwords when not using the IDENTIFIED BY
clause, may be blank values, if non-blank, they may be encrypted. But yes USAGE
is used to modify an account by granting simple resource limiters such as MAX_QUERIES_PER_HOUR
, again this can be specified by also
using the WITH clause, in conjuction with GRANT USAGE
(no privileges added) or GRANT ALL
, you can also specify GRANT USAGE
at the global level, database level, table level,etc....
when search field is timestamp and you want find records from 0 hours yesterday and 0 hour today use construction
MY_DATE_TIME_FIELD between makedate(year(now()), date_format(now(),'%j')-1) and makedate(year(now()), date_format(now(),'%j'))
instead
now() - interval 1 day
I like Tom Faust's answer the best. Here's a C# version of his solution, but simplifying things a bit.
var codecs = ImageCodecInfo.GetImageEncoders();
var codecFilter = "Image Files|";
foreach (var codec in codecs)
{
codecFilter += codec.FilenameExtension + ";";
}
dialog.Filter = codecFilter;
Use div.section > div
.
Better yet, use an <h1>
tag for the heading and div.section h1
in your CSS, so as to support older browsers (that don't know about the >
) and keep your markup semantic.
check the command : NA!=NA
: you'll get the result NA
, hence the error message.
You have to use the function is.na
for your if
statement to work (in general, it is always better to use this function to check for NA
values) :
comments = c("no","yes",NA)
for (l in 1:length(comments)) {
if (!is.na(comments[l])) print(comments[l])
}
[1] "no"
[1] "yes"
$(document).ready(function(){
$('input.checkD[type="checkbox"]').click(function(){
if($(this).prop("checked") == true){
$(this).val('true');
}
else if($(this).prop("checked") == false){
$(this).val('false');
}
});
});
Use the "Edit top 200" option, then click on "Show SQL panel", modify your query with your WHERE clause, and execute the query. You'll be able to edit the results.
That should work via HTTPRewriteModule.
Example rewrite from www.example.com to example.com:
server {
server_name www.example.com;
rewrite ^ http://example.com$request_uri? permanent;
}
I have faced the same issue. And this save my life: https://gist.github.com/jtdp/5443498
git diff -p -R --no-color \
| grep -E "^(diff|(old|new) mode)" --color=never \
| git apply`
Hope you can Successfully remove your project. Happy Coding :)
Yes, #id
selectors combined with a multiple selector (comma) is perfectly valid in both jQuery and CSS.
However, for your example, since <script>
comes before the elements, you need a document.ready
handler, so it waits until the elements are in the DOM to go looking for them, like this:
<script>
$(function() {
$("#segement1,#segement2,#segement3").hide()
});
</script>
<div id="segement1"></div>
<div id="segement2"></div>
<div id="segement3"></div>
The curly braces mean concatenation, from most significant bit (MSB) on the left down to the least significant bit (LSB) on the right. You are creating a 32-bit bus (result) whose 16 most significant bits consist of 16 copies of bit 15 (the MSB) of the a bus, and whose 16 least significant bits consist of just the a bus (this particular construction is known as sign extension, which is needed e.g. to right-shift a negative number in two's complement form and keep it negative rather than introduce zeros into the MSBits).
There is a tutorial here*, but it doesn't explain too much more than the above paragraph.
For what it's worth, the nested curly braces around a[15:0]
are superfluous.
*Beware: the example within the tutorial link contains a typo when demonstrating multiple concatenations - the (2{C}}
should be a {2{2}}
.
A version that will continue to work with both IE10 and IE11:
preg_match('/MSIE (.*?);/', $_SERVER['HTTP_USER_AGENT'], $matches);
if(count($matches)<2){
preg_match('/Trident\/\d{1,2}.\d{1,2}; rv:([0-9]*)/', $_SERVER['HTTP_USER_AGENT'], $matches);
}
if (count($matches)>1){
//Then we're using IE
$version = $matches[1];
switch(true){
case ($version<=8):
//IE 8 or under!
break;
case ($version==9 || $version==10):
//IE9 & IE10!
break;
case ($version==11):
//Version 11!
break;
default:
//You get the idea
}
}
One thing that adds confusion to this subject is the idea of decorators is not made very clear, and when we consider something like...
@HostBinding('attr.something')
get something() {
return this.somethingElse;
}
It works, because it is a get
accessor. You couldn't use a function equivalent:
@HostBinding('attr.something')
something() {
return this.somethingElse;
}
Otherwise, the benefit of using @HostBinding
is it assures change detection is run when the bound value changes.
In addition to the other suggestions - you can also wrap the flag in a control class and make a final instance of it in your parent class:
public class Test {
class Control {
public volatile boolean flag = false;
}
final Control control = new Control();
class T1 implements Runnable {
@Override
public void run() {
while ( !control.flag ) {
}
}
}
class T2 implements Runnable {
@Override
public void run() {
while ( !control.flag ) {
}
}
}
private void test() {
T1 main = new T1();
T2 help = new T2();
new Thread(main).start();
new Thread(help).start();
}
public static void main(String[] args) throws InterruptedException {
try {
Test test = new Test();
test.test();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have the same problem. I avoid it with remove.packages("Package making this confusion")
and it works. In my case, I don't need the second package, so that is not a very good idea.
I understand that its been answered already. but I hope this will help someone in future and saves so much time and pain.
complete code is below: This one I did for a textbox to make it Autocomplete in CiviCRM. Hope it helps someone
CRM.$( 'input[id^=custom_78]' ).autocomplete({
autoFill: true,
select: function (event, ui) {
var label = ui.item.label;
var value = ui.item.value;
// Update subject field to add book year and book product
var book_year_value = CRM.$('select[id^=custom_77] option:selected').text().replace('Book Year ','');
//book_year_value.replace('Book Year ','');
var subject_value = book_year_value + '/' + ui.item.label;
CRM.$('#subject').val(subject_value);
CRM.$( 'input[name=product_select_id]' ).val(ui.item.value);
CRM.$('input[id^=custom_78]').val(ui.item.label);
return false;
},
source: function(request, response) {
CRM.$.ajax({
url: productUrl,
data: {
'subCategory' : cj('select[id^=custom_77]').val(),
's': request.term,
},
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
},
success: function(result){
result = jQuery.parseJSON( result);
//console.log(result);
response(CRM.$.map(result, function (val,key) {
//console.log(key);
//console.log(val);
return {
label: val,
value: key
};
}));
}
})
.done(function( data ) {
if ( console && console.log ) {
// console.log( "Sample of dataas:", data.slice( 0, 100 ) );
}
});
}
});
PHP code on how I'm returning data to this jquery ajax call in autocomplete:
/**
* This class contains all product related functions that are called using AJAX (jQuery)
*/
class CRM_Civicrmactivitiesproductlink_Page_AJAX {
static function getProductList() {
$name = CRM_Utils_Array::value( 's', $_GET );
$name = CRM_Utils_Type::escape( $name, 'String' );
$limit = '10';
$strSearch = "description LIKE '%$name%'";
$subCategory = CRM_Utils_Array::value( 'subCategory', $_GET );
$subCategory = CRM_Utils_Type::escape( $subCategory, 'String' );
if (!empty($subCategory))
{
$strSearch .= " AND sub_category = ".$subCategory;
}
$query = "SELECT id , description as data FROM abc_books WHERE $strSearch";
$resultArray = array();
$dao = CRM_Core_DAO::executeQuery( $query );
while ( $dao->fetch( ) ) {
$resultArray[$dao->id] = $dao->data;//creating the array to send id as key and data as value
}
echo json_encode($resultArray);
CRM_Utils_System::civiExit();
}
}
Many answers here say the same (order by your auto increment), which is OK, provided you have an autoincremented column that is indexed.
On a side note, if you have such field and it is the primary key, there is no performance penalty for using order by
versus select max(id)
. The primary key is how data is ordered in the database files (for InnoDB at least), and the RDBMS knows where that data ends, and it can optimize order by id + limit 1
to be the same as reach the max(id)
Now the road less traveled is when you don't have an autoincremented primary key. Maybe the primary key is a natural key, which is a composite of 3 fields... Not all is lost, though. From a programming language you can first get the number of rows with
SELECT Count(*) - 1 AS rowcount FROM <yourTable>;
and then use the obtained number in the LIMIT
clause
SELECT * FROM orderbook2
LIMIT <number_from_rowcount>, 1
Unfortunately, MySQL will not allow for a sub-query, or user variable in the LIMIT
clause
If you need to be checking external pages, you won't be able to get away with a pure javascript solution, since any requests to external URLs are blocked. You can get away with it by using JSONP, but that won't work unless the page you're requesting only serves up JSON.
You need to have a proxy on your own server to get the external links for you. This is actually rather simple with any server-side language.
<?php
$contents = file_get_contents($_GET['url']); // please do some sanitation here...
// i'm just showing an example.
echo $contents;
?>
If you needed to check server response codes (eg: 404, 301, etc), then using a library such as cURL in your server-side script could retrieve that information and then pass it onto your javascript app.
Thinking about it now, there probably could be JSONP-enabled proxies out there for you to use, should the "setting up my own proxy" option not be viable.
Made a simple implementation of what I believe to be what you want to achieve. You can use the class later
with the following arguments:
You can change std::chrono::milliseconds
to std::chrono::nanoseconds
or microseconds
for even higher precision and add a second int and a for loop to specify for how many times to run the code.
Here you go, enjoy:
#include <functional>
#include <chrono>
#include <future>
#include <cstdio>
class later
{
public:
template <class callable, class... arguments>
later(int after, bool async, callable&& f, arguments&&... args)
{
std::function<typename std::result_of<callable(arguments...)>::type()> task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));
if (async)
{
std::thread([after, task]() {
std::this_thread::sleep_for(std::chrono::milliseconds(after));
task();
}).detach();
}
else
{
std::this_thread::sleep_for(std::chrono::milliseconds(after));
task();
}
}
};
void test1(void)
{
return;
}
void test2(int a)
{
printf("%i\n", a);
return;
}
int main()
{
later later_test1(1000, false, &test1);
later later_test2(1000, false, &test2, 101);
return 0;
}
Outputs after two seconds:
101
In Python 3, map
returns an iterable object of type map
, and not a subscriptible list, which would allow you to write map[i]
. To force a list result, write
payIntList = list(map(int,payList))
However, in many cases, you can write out your code way nicer by not using indices. For example, with list comprehensions:
payIntList = [pi + 1000 for pi in payList]
for pi in payIntList:
print(pi)
The latest version of core-js lib provides the polyfills from a different path. so use the following in the polyfills.js. And also change the target
value to es5
in the tsconfig.base.json
/** IE9, IE10 and IE11 requires all of the following polyfills. **/
import 'core-js/es/symbol';
import 'core-js/es/object';
import 'core-js/es/function';
import 'core-js/es/parse-int';
import 'core-js/es/parse-float';
import 'core-js/es/number';
import 'core-js/es/math';
import 'core-js/es/string';
import 'core-js/es/date';
import 'core-js/es/array';
import 'core-js/es/regexp';
import 'core-js/es/map';
When using request
for an http POST you can add parameters this way:
var request = require('request');
request.post({
url: 'http://localhost/test2.php',
form: { mes: "heydude" }
}, function(error, response, body){
console.log(body);
});
If you are in a web application which already uses Spring and if you do not want to include Apache Commons IO for simple file copying, you can use FileCopyUtils of the Spring framework.
Make the class public.
class NewClass
{
}
is the same as:
internal class NewClass
{
}
so the class has to be public
One main reason we went with Workstation over Player at my job is because we need to run VMs that use a physical disk as their hard drive instead of a virtual disk. Workstation supports using physical disks while Player does not.
Table A
+--------+-----------+
| A-num | text |
| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
+--------+-----------+
Table B
+------+------+--------------+
| B-num| date | A-num |
| 22 | 01.08.2003 | 2 |
| 23 | 02.08.2003 | 2 |
| 24 | 03.08.2003 | 1 |
| 25 | 04.08.2003 | 4 |
| 26 | 05.03.2003 | 4 |
I will update field text in table A with
UPDATE `Table A`,`Table B`
SET `Table A`.`text`=concat_ws('',`Table A`.`text`,`Table B`.`B-num`," from
",`Table B`.`date`,'/')
WHERE `Table A`.`A-num` = `Table B`.`A-num`
and come to this result:
Table A
+--------+------------------------+
| A-num | text |
| 1 | 24 from 03 08 2003 / |
| 2 | 22 from 01 08 2003 / |
| 3 | |
| 4 | 25 from 04 08 2003 / |
| 5 | |
--------+-------------------------+
where only one field from Table B is accepted, but I will come to this result:
Table A
+--------+--------------------------------------------+
| A-num | text |
| 1 | 24 from 03 08 2003 |
| 2 | 22 from 01 08 2003 / 23 from 02 08 2003 / |
| 3 | |
| 4 | 25 from 04 08 2003 / 26 from 05 03 2003 / |
| 5 | |
+--------+--------------------------------------------+
Let's assume our application uses the following Post
, PostComment
, PostDetails
, and Tag
entities, which form a one-to-many, one-to-one, and many-to-many table relationships:
The hibernate-jpamodelgen
tool provided by Hibernate ORM can be used to scan the project entities and generate the JPA Criteria Metamodel. All you need to do is add the following annotationProcessorPath
to the maven-compiler-plugin
in the Maven pom.xml
configuration file:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<annotationProcessorPaths>
<annotationProcessorPath>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<version>${hibernate.version}</version>
</annotationProcessorPath>
</annotationProcessorPaths>
</configuration>
</plugin>
Now, when the project is compiled, you can see that in the target
folder, the following Java classes are generated:
> tree target/generated-sources/
target/generated-sources/
+-- annotations
+-- com
+-- vladmihalcea
+-- book
+-- hpjp
+-- hibernate
+-- forum
¦ +-- PostComment_.java
¦ +-- PostDetails_.java
¦ +-- Post_.java
¦ +-- Tag_.java
If the Tag
entity is mapped as follows:
@Entity
@Table(name = "tag")
public class Tag {
@Id
private Long id;
private String name;
//Getters and setters omitted for brevity
}
The Tag_
Metamodel class is generated like this:
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Tag.class)
public abstract class Tag_ {
public static volatile SingularAttribute<Tag, String> name;
public static volatile SingularAttribute<Tag, Long> id;
public static final String NAME = "name";
public static final String ID = "id";
}
The SingularAttribute
is used for the basic id
and name
Tag
JPA entity attributes.
The Post
entity is mapped like this:
@Entity
@Table(name = "post")
public class Post {
@Id
private Long id;
private String title;
@OneToMany(
mappedBy = "post",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<PostComment> comments = new ArrayList<>();
@OneToOne(
mappedBy = "post",
cascade = CascadeType.ALL,
fetch = FetchType.LAZY
)
@LazyToOne(LazyToOneOption.NO_PROXY)
private PostDetails details;
@ManyToMany
@JoinTable(
name = "post_tag",
joinColumns = @JoinColumn(name = "post_id"),
inverseJoinColumns = @JoinColumn(name = "tag_id")
)
private List<Tag> tags = new ArrayList<>();
//Getters and setters omitted for brevity
}
The Post
entity has two basic attributes, id
and title
, a one-to-many comments
collection, a one-to-one details
association, and a many-to-many tags
collection.
The Post_
Metamodel class is generated as follows:
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Post.class)
public abstract class Post_ {
public static volatile ListAttribute<Post, PostComment> comments;
public static volatile SingularAttribute<Post, PostDetails> details;
public static volatile SingularAttribute<Post, Long> id;
public static volatile SingularAttribute<Post, String> title;
public static volatile ListAttribute<Post, Tag> tags;
public static final String COMMENTS = "comments";
public static final String DETAILS = "details";
public static final String ID = "id";
public static final String TITLE = "title";
public static final String TAGS = "tags";
}
The basic id
and title
attributes, as well as the one-to-one details
association, are represented by a SingularAttribute
while the comments
and tags
collections are represented by the JPA ListAttribute
.
The PostDetails
entity is mapped like this:
@Entity
@Table(name = "post_details")
public class PostDetails {
@Id
@GeneratedValue
private Long id;
@Column(name = "created_on")
private Date createdOn;
@Column(name = "created_by")
private String createdBy;
@OneToOne(fetch = FetchType.LAZY)
@MapsId
@JoinColumn(name = "id")
private Post post;
//Getters and setters omitted for brevity
}
All entity attributes are going to be represented by the JPA SingularAttribute
in the associated PostDetails_
Metamodel class:
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(PostDetails.class)
public abstract class PostDetails_ {
public static volatile SingularAttribute<PostDetails, Post> post;
public static volatile SingularAttribute<PostDetails, String> createdBy;
public static volatile SingularAttribute<PostDetails, Long> id;
public static volatile SingularAttribute<PostDetails, Date> createdOn;
public static final String POST = "post";
public static final String CREATED_BY = "createdBy";
public static final String ID = "id";
public static final String CREATED_ON = "createdOn";
}
The PostComment
is mapped as follows:
@Entity
@Table(name = "post_comment")
public class PostComment {
@Id
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
private Post post;
private String review;
//Getters and setters omitted for brevity
}
And, all entity attributes are represented by the JPA SingularAttribute
in the associated PostComments_
Metamodel class:
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(PostComment.class)
public abstract class PostComment_ {
public static volatile SingularAttribute<PostComment, Post> post;
public static volatile SingularAttribute<PostComment, String> review;
public static volatile SingularAttribute<PostComment, Long> id;
public static final String POST = "post";
public static final String REVIEW = "review";
public static final String ID = "id";
}
Without the JPA Metamodel, a Criteria API query that needs to fetch the PostComment
entities filtered by their associated Post
title would look like this:
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<PostComment> query = builder.createQuery(PostComment.class);
Root<PostComment> postComment = query.from(PostComment.class);
Join<PostComment, Post> post = postComment.join("post");
query.where(
builder.equal(
post.get("title"),
"High-Performance Java Persistence"
)
);
List<PostComment> comments = entityManager
.createQuery(query)
.getResultList();
Notice that we used the post
String literal when creating the Join
instance, and we used the title
String literal when referencing the Post
title
.
The JPA Metamodel allows us to avoid hard-coding entity attributes, as illustrated by the following example:
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<PostComment> query = builder.createQuery(PostComment.class);
Root<PostComment> postComment = query.from(PostComment.class);
Join<PostComment, Post> post = postComment.join(PostComment_.post);
query.where(
builder.equal(
post.get(Post_.title),
"High-Performance Java Persistence"
)
);
List<PostComment> comments = entityManager
.createQuery(query)
.getResultList();
Or, let's say we want to fetch a DTO projection while filtering the Post
title
and the PostDetails
createdOn
attributes.
We can use the Metamodel when creating the join attributes, as well as when building the DTO projection column aliases or when referencing the entity attributes we need to filter:
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object[]> query = builder.createQuery(Object[].class);
Root<PostComment> postComment = query.from(PostComment.class);
Join<PostComment, Post> post = postComment.join(PostComment_.post);
query.multiselect(
postComment.get(PostComment_.id).alias(PostComment_.ID),
postComment.get(PostComment_.review).alias(PostComment_.REVIEW),
post.get(Post_.title).alias(Post_.TITLE)
);
query.where(
builder.and(
builder.like(
post.get(Post_.title),
"%Java Persistence%"
),
builder.equal(
post.get(Post_.details).get(PostDetails_.CREATED_BY),
"Vlad Mihalcea"
)
)
);
List<PostCommentSummary> comments = entityManager
.createQuery(query)
.unwrap(Query.class)
.setResultTransformer(Transformers.aliasToBean(PostCommentSummary.class))
.getResultList();
Cool, right?
Subset sum problem can be solved in O(sum*n) using dynamic programming. Optimal substructure for subset sum is as follows:
SubsetSum(A, n, sum) = SubsetSum(A, n-1, sum) || SubsetSum(A, n-1, sum-set[n-1])
SubsetSum(A, n, sum) = 0, if sum > 0 and n == 0 SubsetSum(A, n, sum) = 1, if sum == 0
Here A is array of elements, n is the number of elements of array A and sum is the sum of elements in the subset.
Using this dp, you can solve for the number of subsets for the sum.
For getting subset elements, we can use following algorithm:
After filling dp[n][sum] by calling SubsetSum(A, n, sum), we recursively traverse it from dp[n][sum]. For cell being traversed, we store path before reaching it and consider two possibilities for the element.
1) Element is included in current path.
2) Element is not included in current path.
Whenever sum becomes 0, we stop the recursive calls and print current path.
void findAllSubsets(int dp[], int A[], int i, int sum, vector<int>& p) {
if (sum == 0) {
print(p);
return;
}
// If sum can be formed without including current element
if (dp[i-1][sum])
{
// Create a new vector to store new subset
vector<int> b = p;
findAllSubsets(dp, A, i-1, sum, b);
}
// If given sum can be formed after including
// current element.
if (sum >= A[i] && dp[i-1][sum-A[i]])
{
p.push_back(A[i]);
findAllSubsets(dp, A, i-1, sum-A[i], p);
}
}
Though both the sorts are O(N^2).The hidden constants are much smaller in Insertion sort.Hidden constants refer to the actual number of primitive operations carried out.
When insertion sort has better running time?
Notice that insertion sort is not always better than bubble sort.To get the best of both worlds, you can use insertion sort if array is of small size, and probably merge sort(or quicksort) for larger arrays.
In order to export out the VAR variable first the most logical and seems working way is to source the variable:
. ./export.bash
or
source ./export.bash
Now when echoing from main shell it works
echo $VAR
HELLO, VARABLE
We will now reset VAR
export VAR=""
echo $VAR
Now we will execute a script to source the variable then unset it :
./test-export.sh
HELLO, VARABLE
--
.
the code: cat test-export.sh
#!/bin/bash
# Source env variable
source ./export.bash
# echo out the variable in test script
echo $VAR
# unset the variable
unset VAR
# echo a few dotted lines
echo "---"
# now return VAR which is blank
echo $VAR
Here is one way
PLEASE NOTE: The exports are limited to the script that execute the exports in your main console - so as far as a cron job I would add it like the console like below... for the command part still questionable: here is how you would run in from your shell:
On your command prompt (so long as the export.bash has multiple echo values)
IFS=$'\n'; for entries in $(./export.bash); do export $entries; done; ./v1.sh
HELLO THERE
HI THERE
cat v1.sh
#!/bin/bash
echo $VAR
echo $VAR1
Now so long as this is for your usage - you could make the variables available for your scripts at any time by doing a bash alias like this:
myvars ./v1.sh
HELLO THERE
HI THERE
echo $VAR
.
add this to your .bashrc
function myvars() {
IFS=$'\n';
for entries in $(./export.bash); do export $entries; done;
"$@";
for entries in $(./export.bash); do variable=$(echo $entries|awk -F"=" '{print $1}'); unset $variable;
done
}
source your bashrc file and you can do like above any time ...
Anyhow back to the rest of it..
This has made it available globally then executed the script..
simply echo it out then run export on the echo !
cat export.bash
#!/bin/bash
echo "VAR=HELLO THERE"
Now within script or your console run:
export "$(./export.bash)"
Try:
echo $VAR
HELLO THERE
Multiple values so long as you know what you are expecting in another script using above method:
cat export.bash
#!/bin/bash
echo "VAR=HELLO THERE"
echo "VAR1=HI THERE"
cat test-export.sh
#!/bin/bash
IFS=$'\n'
for entries in $(./export.bash); do
export $entries
done
echo "round 1"
echo $VAR
echo $VAR1
for entries in $(./export.bash); do
variable=$(echo $entries|awk -F"=" '{print $1}');
unset $variable
done
echo "round 2"
echo $VAR
echo $VAR1
Now the results
./test-export.sh
round 1
HELLO THERE
HI THERE
round 2
.
and the final final update to auto assign read the VARIABLES:
./test-export.sh
Round 0 - Export out then find variable name -
Set current variable to the variable exported then echo its value
$VAR has value of HELLO THERE
$VAR1 has value of HI THERE
round 1 - we know what was exported and we will echo out known variables
HELLO THERE
HI THERE
Round 2 - We will just return the variable names and unset them
round 3 - Now we get nothing back
The script: cat test-export.sh
#!/bin/bash
IFS=$'\n'
echo "Round 0 - Export out then find variable name - "
echo "Set current variable to the variable exported then echo its value"
for entries in $(./export.bash); do
variable=$(echo $entries|awk -F"=" '{print $1}');
export $entries
eval current_variable=\$$variable
echo "\$$variable has value of $current_variable"
done
echo "round 1 - we know what was exported and we will echo out known variables"
echo $VAR
echo $VAR1
echo "Round 2 - We will just return the variable names and unset them "
for entries in $(./export.bash); do
variable=$(echo $entries|awk -F"=" '{print $1}');
unset $variable
done
echo "round 3 - Now we get nothing back"
echo $VAR
echo $VAR1
Does using .live work for you?
$("#my-button").live("click", function(){ alert("yay!"); });
EDIT
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
I would say that the easiest way is to use transparent background image.
background: url("http://musescore.org/sites/musescore.org/files/blue-translucent.png") repeat top left;
Do you mean can you select them? If so, then yes:
$(":checkbox[myattr]")
Alternative to the nice head / tail way:
ls -al | awk 'NR==2'
or
ls -al | sed -n '2p'
Problem is caused by comma at the end of (in your case each) JSON object placed in the array:
{
"number": "...",
"title": ".." , //<- see that comma?
}
If you remove them your data will become
[
{
"number": "3",
"title": "hello_world"
}, {
"number": "2",
"title": "hello_world"
}
]
and
Wrapper[] data = gson.fromJson(jElement, Wrapper[].class);
should work fine.
Answered the same question here:
To repost:
After searching through many solutions I decided to blog about how to sort in jquery. In summary, steps to sort jquery "array-like" objects by data attribute...
Html
<div class="item" data-order="2">2</div> <div class="item" data-order="1">1</div> <div class="item" data-order="4">4</div> <div class="item" data-order="3">3</div>
Plain jquery selector
$('.item');
[<div class="item" data-order="2">2</div>, <div class="item" data-order="1">1</div>, <div class="item" data-order="4">4</div>, <div class="item" data-order="3">3</div> ]
Lets sort this by data-order
function getSorted(selector, attrName) { return $($(selector).toArray().sort(function(a, b){ var aVal = parseInt(a.getAttribute(attrName)), bVal = parseInt(b.getAttribute(attrName)); return aVal - bVal; })); }
> getSorted('.item', 'data-order')
[<div class="item" data-order="1">1</div>, <div class="item" data-order="2">2</div>, <div class="item" data-order="3">3</div>, <div class="item" data-order="4">4</div> ]
Hope this helps!
In the meantime (while you were updating your project), other commits have been made to the 'master' branch. Therefore, you must pull those changes first to be able to push your changes.
Deleting registry keys as suggested above got my service stuck in the stopping state. The following procedure worked for me:
open task manager > select services tab > select the service > right click and select "go to process" > right click on the process and select End process
Service should be gone after that
Just style the content with white-space: pre-wrap;
.
div {_x000D_
white-space: pre-wrap;_x000D_
}
_x000D_
<div>_x000D_
This is some text with some extra spacing and a_x000D_
few newlines along with some trailing spaces _x000D_
and five leading spaces thrown in_x000D_
for good_x000D_
measure _x000D_
</div>
_x000D_
To update @Sunil answer: Under Windows, Miniconda has a regular uninstaller. Go to the menu "Settings/Apps/Apps&Features", or click the Start button, type "uninstall", then click on "Add or Remove Programs" and finally on the Miniconda uninstaller.
In 2019 using ES6:
const ids = [1, 4, 5],_x000D_
data = {_x000D_
records: [{_x000D_
"empid": 1,_x000D_
"fname": "X",_x000D_
"lname": "Y"_x000D_
}, {_x000D_
"empid": 2,_x000D_
"fname": "A",_x000D_
"lname": "Y"_x000D_
}, {_x000D_
"empid": 3,_x000D_
"fname": "B",_x000D_
"lname": "Y"_x000D_
}, {_x000D_
"empid": 4,_x000D_
"fname": "C",_x000D_
"lname": "Y"_x000D_
}, {_x000D_
"empid": 5,_x000D_
"fname": "C",_x000D_
"lname": "Y"_x000D_
}]_x000D_
};_x000D_
_x000D_
_x000D_
data.records = data.records.filter( i => ids.includes( i.empid ) );_x000D_
_x000D_
console.info( data );
_x000D_
I had a similar problem with a new ASP.NET Core application a while ago. Turns out one of the referenced libraries used a version of Newtonsoft.Json that was lower than 9.0.0.0. So I upgraded the version for that library and the problem was solved. Not sure if you'll be able to do the same here
Calling a Sub Procedure – 3 Way technique
Once you have a procedure, whether you created it or it is part of the Visual Basic language, you can use it. Using a procedure is also referred to as calling it.
Before calling a procedure, you should first locate the section of code in which you want to use it. To call a simple procedure, type its name. Here is an example:
Sub CreateCustomer()
Dim strFullName As String
strFullName = "Paul Bertrand Yamaguchi"
msgbox strFullName
End Sub
Sub Exercise()
CreateCustomer
End Sub
Besides using the name of a procedure to call it, you can also precede it with the Call keyword. Here is an example:
Sub CreateCustomer()
Dim strFullName As String
strFullName = "Paul Bertrand Yamaguchi"
End Sub
Sub Exercise()
Call CreateCustomer
End Sub
When calling a procedure, without or without the Call keyword, you can optionally type an opening and a closing parentheses on the right side of its name. Here is an example:
Sub CreateCustomer()
Dim strFullName As String
strFullName = "Paul Bertrand Yamaguchi"
End Sub
Sub Exercise()
CreateCustomer()
End Sub
Procedures and Access Levels
Like a variable access, the access to a procedure can be controlled by an access level. A procedure can be made private or public. To specify the access level of a procedure, precede it with the Private or the Public keyword. Here is an example:
Private Sub CreateCustomer()
Dim strFullName As String
strFullName = "Paul Bertrand Yamaguchi"
End Sub
The rules that were applied to global variables are the same:
Private: If a procedure is made private, it can be called by other procedures of the same module. Procedures of outside modules cannot access such a procedure.
Also, when a procedure is private, its name does not appear in the Macros dialog box
Public: A procedure created as public can be called by procedures of the same module and by procedures of other modules.
Also, if a procedure was created as public, when you access the Macros dialog box, its name appears and you can run it from there
Expanding on betabandido's answer, you could write a function to inject the attributes as constants into the module:
def module_register_class_constants(klass, attr_prefix):
globals().update(
(name, getattr(klass, name)) for name in dir(klass) if name.startswith(attr_prefix)
)
class Animal(object):
SIZE_HUGE = "Huge"
SIZE_BIG = "Big"
module_register_class_constants(Animal, "SIZE_")
class Horse(Animal):
def printSize(self):
print SIZE_BIG