If you are using office 365 follow this steps:
Hope it helps!
With the introduction of Data Classes in Python 3.7 we get very close.
The following example is similar to the NamedTuple example below, but the resulting object is mutable and it allows for default values.
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
z: float = 0.0
p = Point(1.5, 2.5)
print(p) # Point(x=1.5, y=2.5, z=0.0)
This plays nicely with the new typing module in case you want to use more specific type annotations.
I've been waiting desperately for this! If you ask me, Data Classes and the new NamedTuple declaration, combined with the typing module are a godsend!
Since Python 3.6 it became quite simple and beautiful (IMHO), as long as you can live with immutability.
A new way of declaring NamedTuples was introduced, which allows for type annotations as well:
from typing import NamedTuple
class User(NamedTuple):
name: str
class MyStruct(NamedTuple):
foo: str
bar: int
baz: list
qux: User
my_item = MyStruct('foo', 0, ['baz'], User('peter'))
print(my_item) # MyStruct(foo='foo', bar=0, baz=['baz'], qux=User(name='peter'))
I don't think you should be returning any http error codes, rather custom exceptions that are useful to the client end of the application so the interface knows what had actually occurred. I wouldn't try and mask real issues with 404 error codes or something to that nature.
What is the type of c.PhysicalAddresses
? If it's Dictionary<TKey,TValue>
, then you can use the ContainsKey
method.
System.out.println(myList.size());
Since no elements are in the list
output => 0
myList.add("newString"); // use myList.add() to insert elements to the arraylist
System.out.println(myList.size());
Since one element is added to the list
output => 1
The key is "argument-less git-pull". When you do a git pull
from a branch, without specifying a source remote or branch, git looks at the branch.<name>.merge
setting to know where to pull from. git push -u
sets this information for the branch you're pushing.
To see the difference, let's use a new empty branch:
$ git checkout -b test
First, we push without -u
:
$ git push origin test
$ git pull
You asked me to pull without telling me which branch you
want to merge with, and 'branch.test.merge' in
your configuration file does not tell me, either. Please
specify which branch you want to use on the command line and
try again (e.g. 'git pull <repository> <refspec>').
See git-pull(1) for details.
If you often merge with the same branch, you may want to
use something like the following in your configuration file:
[branch "test"]
remote = <nickname>
merge = <remote-ref>
[remote "<nickname>"]
url = <url>
fetch = <refspec>
See git-config(1) for details.
Now if we add -u
:
$ git push -u origin test
Branch test set up to track remote branch test from origin.
Everything up-to-date
$ git pull
Already up-to-date.
Note that tracking information has been set up so that git pull
works as expected without specifying the remote or branch.
Update: Bonus tips:
git pull
this setting also affects default behavior of git push
. If you get in the habit of using -u
to capture the remote branch you intend to track, I recommend setting your push.default
config value to upstream
.git push -u <remote> HEAD
will push the current branch to a branch of the same name on <remote>
(and also set up tracking so you can do git push
after that).you must use import android.support.v7.app.ActionBarDrawerToggle;
and use the constructor
public CustomActionBarDrawerToggle(Activity mActivity,DrawerLayout mDrawerLayout)
{
super(mActivity, mDrawerLayout, R.string.ns_menu_open, R.string.ns_menu_close);
}
and if the drawer toggle button becomes dark then you must use the supportActionBar provided in the support library.
You can implement supportActionbar from this link: http://developer.android.com/training/basics/actionbar/setting-up.html
this code adds horizontal line to a linear layout
View view = new View(this);
LinearLayout.LayoutParams lpView = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 1); // --> horizontal
view.setLayoutParams(lpView);
view.setBackgroundColor(Color.DKGRAY);
linearLayout.addView(view);
It really depends on what level you mean. In Python 2.x, there are two integer types, int
(constrained to sys.maxint
) and long
(unlimited precision), for historical reasons. In Python code, this shouldn't make a bit of difference because the interpreter automatically converts to long when a number is too large. If you want to know about the actual data types used in the underlying interpreter, that's implementation dependent. (CPython's are located in Objects/intobject.c and Objects/longobject.c.) To find out about the systems types look at cdleary answer for using the struct module.
In Python, the 'null' object is the singleton None
.
The best way to check things for "Noneness" is to use the identity operator, is
:
if foo is None:
...
Demo_ListView_In_ScrollView
==============================
package com.app.custom_seekbar;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class Demo_ListView_In_ScrollView extends Activity
{
ListView listview;
ArrayList<String> data=null;
listview_adapter adapter=null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
super.setContentView(R.layout.demo_listview_in_scrollview_activity);
init();
set_data();
set_adapter();
}
public void init()
{
listview=(ListView)findViewById(R.id.listView1);
data=new ArrayList<String>();
}
public void set_data()
{
data.add("Meet");
data.add("prachi");
data.add("shailesh");
data.add("manoj");
data.add("sandip");
data.add("zala");
data.add("tushar");
data.add("Meet");
data.add("prachi");
data.add("shailesh");
data.add("manoj");
data.add("sandip");
data.add("zala");
data.add("tushar");
data.add("Meet");
data.add("prachi");
data.add("shailesh");
data.add("manoj");
data.add("sandip");
data.add("zala");
data.add("tushar");
data.add("Meet");
data.add("prachi");
data.add("shailesh");
data.add("manoj");
data.add("sandip");
data.add("zala");
data.add("tushar");
data.add("Meet");
data.add("prachi");
data.add("shailesh");
data.add("manoj");
data.add("sandip");
data.add("zala");
data.add("tushar");
data.add("Meet");
data.add("prachi");
data.add("shailesh");
data.add("manoj");
data.add("sandip");
data.add("zala");
data.add("tushar");
data.add("Meet");
data.add("prachi");
data.add("shailesh");
data.add("manoj");
data.add("sandip");
data.add("zala");
data.add("tushar");
data.add("Meet");
data.add("prachi");
data.add("shailesh");
data.add("manoj");
data.add("sandip");
data.add("zala");
data.add("tushar");
data.add("Meet");
data.add("prachi");
data.add("shailesh");
data.add("manoj");
data.add("sandip");
data.add("zala");
data.add("tushar");
data.add("Meet");
data.add("prachi");
data.add("shailesh");
data.add("manoj");
data.add("sandip");
data.add("zala");
data.add("tushar");
data.add("Meet");
data.add("prachi");
data.add("shailesh");
data.add("manoj");
data.add("sandip");
data.add("zala");
data.add("tushar");
data.add("Meet");
data.add("prachi");
data.add("shailesh");
data.add("manoj");
data.add("sandip");
data.add("zala");
data.add("tushar");
data.add("Meet");
data.add("prachi");
data.add("shailesh");
data.add("manoj");
data.add("sandip");
data.add("zala");
data.add("tushar");
}
public void set_adapter()
{
adapter=new listview_adapter(Demo_ListView_In_ScrollView.this,data);
listview.setAdapter(adapter);
Helper.getListViewSize(listview); // set height of listview according to Arraylist item
}
}
========================
listview_adapter
==========================
package com.app.custom_seekbar;
import java.util.ArrayList;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
public class listview_adapter extends ArrayAdapter<String>
{
private final Activity context;
ArrayList<String>data;
class ViewHolder
{
public TextView tv_name;
public ScrollView scroll;
public LinearLayout l1;
}
public listview_adapter(Activity context, ArrayList<String> all_data) {
super(context, R.layout.item_list_xml, all_data);
this.context = context;
data=all_data;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = convertView;
ViewHolder viewHolder;
if (rowView == null)
{
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.item_list_xml, null);
viewHolder = new ViewHolder();
viewHolder.tv_name=(TextView)rowView.findViewById(R.id.textView1);
rowView.setTag(viewHolder);
}
else
viewHolder = (ViewHolder) rowView.getTag();
viewHolder.tv_name.setText(data.get(position).toString());
return rowView;
}
}
===================================
Helper class
====================================
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
public class Helper {
public static void getListViewSize(ListView myListView) {
ListAdapter myListAdapter = myListView.getAdapter();
if (myListAdapter == null) {
//do nothing return null
return;
}
//set listAdapter in loop for getting final size
int totalHeight = 0;
for (int size = 0; size < myListAdapter.getCount(); size++) {
View listItem = myListAdapter.getView(size, null, myListView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
//setting listview item in adapter
ViewGroup.LayoutParams params = myListView.getLayoutParams();
params.height = totalHeight + (myListView.getDividerHeight() * (myListAdapter.getCount() - 1));
myListView.setLayoutParams(params);
// print height of adapter on log
Log.i("height of listItem:", String.valueOf(totalHeight));
}
}
========================
demo_listview_in_scrollview_activity.xml
========================
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ScrollView
android:id="@+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
</ScrollView>
</LinearLayout>
================
item_list_xml.xml
==================
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:text="TextView"
android:textSize="14sp" />
</LinearLayout>
You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.
To affect all flex-items of the container, choose this:
You have to set align-items: flex-start;
to div
and all flex-items of this container get the height of their content.
div {_x000D_
align-items: flex-start;_x000D_
background: tan;_x000D_
display: flex;_x000D_
height: 200px;_x000D_
}_x000D_
span {_x000D_
background: red;_x000D_
}
_x000D_
<div>_x000D_
<span>This is some text.</span>_x000D_
</div>
_x000D_
To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start;
to this flex-item. All other flex-items of the container aren't affected.
div {_x000D_
display: flex;_x000D_
height: 200px;_x000D_
background: tan;_x000D_
}_x000D_
span.only {_x000D_
background: red;_x000D_
align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
background:green;_x000D_
}
_x000D_
<div>_x000D_
<span class="only">This is some text.</span>_x000D_
<span>This is more text.</span>_x000D_
</div>
_x000D_
Why is this happening to the span
?
The default value of the property align-items
is stretch
. This is the reason why the span
fill the height of the div
.
Difference between baseline
and flex-start
?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start
the flex-item will be set to the top of the container (without space).
div {_x000D_
align-items: baseline;_x000D_
background: tan;_x000D_
display: flex;_x000D_
height: 200px;_x000D_
}_x000D_
span {_x000D_
background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
<span class="fontsize">This is some text.</span>_x000D_
<span>This is more text.</span>_x000D_
</div>
_x000D_
You can find more information about the difference between
baseline
andflex-start
here:
What's the difference between flex-start and baseline?
Maybe you included the .c
file in makefile multiple times.
A naming convention like this is useful when you are reading code, particularly code that is not your own. A strong naming convention helps indicate where a particular member is defined, what kind of member it is, etc. Most development teams adopt a simple naming convention, and simply prefix member fields with an underscore (_fieldName
). In the past, I have used the following naming convention for C# (which is based on Microsofts conventions for the .NET framework code, which can be seen with Reflector):
Instance Field: m_fieldName
Static Field: s_fieldName
Public/Protected/Internal Member: PascalCasedName()
Private Member: camelCasedName()
This helps people understand the structure, use, accessibility and location of members when reading unfamiliar code very rapidly.
thanks, try this instead
Select
STR(account_code) as account_code_Numeric,
descr
from account
where STR(account_code) = 1
I'm happy to help you
I'm setting up a dev server to play with that mirrors our outdated live one, I used The Perfect Server - Ubuntu 14.04 (nginx, BIND, MySQL, PHP, Postfix, Dovecot and ISPConfig 3)
After experiencing the same issue, I came across this post and nothing was working. I changed the value in every recommended file (nginx.conf, ispconfig.vhost, /sites-available/default, etc.)
Finally, changing client_max_body_size
in my /etc/nginx/sites-available/apps.vhost
and restarting nginx is what did the trick. Hopefully it helps someone else.
Seeing as this is the top result on Google for "static class java" and the best answer isn't here I figured I'd add it. I'm interpreting OP's question as concerning static classes in C#, which are known as singletons in the Java world. For those unaware, in C# the "static" keyword can be applied to a class declaration which means the resulting class can never be instantiated.
Excerpt from "Effective Java - Second Edition" by Joshua Bloch (widely considered to be one of the best Java style guides available):
As of release 1.5, there is a third approach to implementing singletons. Simply make an enum type with one element:
// Enum singleton - the preferred approach public enum Elvis { INSTANCE; public void leaveTheBuilding() { ... } }
This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free , and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton. (emphasis author's)
Bloch, Joshua (2008-05-08). Effective Java (Java Series) (p. 18). Pearson Education.
I think the implementation and justification are pretty self explanatory.
You need to write it this way
<div
className="player"
style={{ position: "absolute" }}
onKeyDown={this.onKeyPressed}
tabIndex="0"
>
If onKeyPressed
is not bound to this
, then try to rewrite it using arrow function or bind it in the component constructor
.
For windows machine: After trying alot of set path, remove path and etc.
What finally work is to located the folder C:\Users\johndoe\.android
and delete it. after that you can lunch your Android Studio, it will ask you to download and install a new AVD and it will override and create a fresh new folder and files. This solve the problem.
Just increasing max_connections
is bad idea. You need to increase shared_buffers
and kernel.shmmax
as well.
Considerations
max_connections
determines the maximum number of concurrent connections to the database server. The default is typically 100 connections.
Before increasing your connection count you might need to scale up your deployment. But before that, you should consider whether you really need an increased connection limit.
Each PostgreSQL connection consumes RAM for managing the connection or the client using it. The more connections you have, the more RAM you will be using that could instead be used to run the database.
A well-written app typically doesn't need a large number of connections. If you have an app that does need a large number of connections then consider using a tool such as pg_bouncer which can pool connections for you. As each connection consumes RAM, you should be looking to minimize their use.
How to increase max connections
1. Increase max_connection
and shared_buffers
in /var/lib/pgsql/{version_number}/data/postgresql.conf
change
max_connections = 100
shared_buffers = 24MB
to
max_connections = 300
shared_buffers = 80MB
The shared_buffers
configuration parameter determines how much memory is dedicated to PostgreSQL to use for caching data.
2. Change kernel.shmmax
You would need to increase kernel max segment size to be slightly larger
than the shared_buffers
.
In file /etc/sysctl.conf
set the parameter as shown below. It will take effect when postgresql
reboots (The following line makes the kernel max to 96Mb
)
kernel.shmmax=100663296
References
Darin Dimitrov's answer shows that OrderBy
is slightly faster than List.Sort
when faced with already-sorted input. I modified his code so it repeatedly sorts the unsorted data, and OrderBy
is in most cases slightly slower.
Furthermore, the OrderBy
test uses ToArray
to force enumeration of the Linq enumerator, but that obviously returns a type (Person[]
) which is different from the input type (List<Person>
). I therefore re-ran the test using ToList
rather than ToArray
and got an even bigger difference:
Sort: 25175ms
OrderBy: 30259ms
OrderByWithToList: 31458ms
The code:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
class Program
{
class NameComparer : IComparer<string>
{
public int Compare(string x, string y)
{
return string.Compare(x, y, true);
}
}
class Person
{
public Person(string id, string name)
{
Id = id;
Name = name;
}
public string Id { get; set; }
public string Name { get; set; }
public override string ToString()
{
return Id + ": " + Name;
}
}
private static Random randomSeed = new Random();
public static string RandomString(int size, bool lowerCase)
{
var sb = new StringBuilder(size);
int start = (lowerCase) ? 97 : 65;
for (int i = 0; i < size; i++)
{
sb.Append((char)(26 * randomSeed.NextDouble() + start));
}
return sb.ToString();
}
private class PersonList : List<Person>
{
public PersonList(IEnumerable<Person> persons)
: base(persons)
{
}
public PersonList()
{
}
public override string ToString()
{
var names = Math.Min(Count, 5);
var builder = new StringBuilder();
for (var i = 0; i < names; i++)
builder.Append(this[i]).Append(", ");
return builder.ToString();
}
}
static void Main()
{
var persons = new PersonList();
for (int i = 0; i < 100000; i++)
{
persons.Add(new Person("P" + i.ToString(), RandomString(5, true)));
}
var unsortedPersons = new PersonList(persons);
const int COUNT = 30;
Stopwatch watch = new Stopwatch();
for (int i = 0; i < COUNT; i++)
{
watch.Start();
Sort(persons);
watch.Stop();
persons.Clear();
persons.AddRange(unsortedPersons);
}
Console.WriteLine("Sort: {0}ms", watch.ElapsedMilliseconds);
watch = new Stopwatch();
for (int i = 0; i < COUNT; i++)
{
watch.Start();
OrderBy(persons);
watch.Stop();
persons.Clear();
persons.AddRange(unsortedPersons);
}
Console.WriteLine("OrderBy: {0}ms", watch.ElapsedMilliseconds);
watch = new Stopwatch();
for (int i = 0; i < COUNT; i++)
{
watch.Start();
OrderByWithToList(persons);
watch.Stop();
persons.Clear();
persons.AddRange(unsortedPersons);
}
Console.WriteLine("OrderByWithToList: {0}ms", watch.ElapsedMilliseconds);
}
static void Sort(List<Person> list)
{
list.Sort((p1, p2) => string.Compare(p1.Name, p2.Name, true));
}
static void OrderBy(List<Person> list)
{
var result = list.OrderBy(n => n.Name, new NameComparer()).ToArray();
}
static void OrderByWithToList(List<Person> list)
{
var result = list.OrderBy(n => n.Name, new NameComparer()).ToList();
}
}
Table2.Column2 => Table1.Column1
I realize this question is old but the accepted answer did not work for me. For future googlers, this is what worked for me:
UPDATE table1
SET column1 = (
SELECT column2
FROM table2
WHERE table2.id = table1.id
);
Whereby:
There is another way if all you want is the text up to the first line feed:
x='some
thing'
y=${x%$'\n'*}
After that y
will contain some
and nothing else (no line feed).
What is happening here?
We perform a parameter expansion substring removal (${PARAMETER%PATTERN}
) for the shortest match up to the first ANSI C line feed ($'\n'
) and drop everything that follows (*
).
In response to the good solution from macek. The solution didn't work for me. I have to bind the values of the datas to the export function. This solution works for me:
function exportToForm(a, b, c, d, e) {
console.log(a, b, c, d, e);
}
var images = document.getElementsByTagName("img");
for (var i=0, len=images.length, img; i<len; i++) {
var img = images[i];
var boundExportToForm = exportToForm.bind(undefined,
img.getAttribute("data-a"),
img.getAttribute("data-b"),
img.getAttribute("data-c"),
img.getAttribute("data-d"),
img.getAttribute("data-e"))
img.addEventListener("click", boundExportToForm);
}
Generally the most common mistake is not cleaning your build directory after adding new options. I have Boost installed from system packet manager. Its version is 1.49.
I also downloaded Boost 1.53 and "installed" it under $HOME/installs
.
The only thing that I had to do in my project was to (I keep sources in my_project_directory/src
):
cd my_project_directory
mkdir build
cd build
cmake -DCMAKE_INCLUDE_PATH=$HOME/installs/include -DCMAKE_LIBRARY_PATH=$HOME/installs/lib ../src
And that's it. Ta bum tss.
But if I'd make after cd build
-> cmake ../src
it would set Boost from the system path. Then doing cmake -DCMAKE_INCLUDE_PATH=$HOME/installs/include -DCMAKE_LIBRARY_PATH=$HOME/installs/lib ../src
would change nothing.
You have to clean your build directory ( cd build && rm -rf *
;) )
__all__
is used to document the public API of a Python module. Although it is optional, __all__
should be used.
Here is the relevant excerpt from the Python language reference:
The public names defined by a module are determined by checking the module’s namespace for a variable named
__all__
; if defined, it must be a sequence of strings which are names defined or imported by that module. The names given in__all__
are all considered public and are required to exist. If__all__
is not defined, the set of public names includes all names found in the module’s namespace which do not begin with an underscore character ('_').__all__
should contain the entire public API. It is intended to avoid accidentally exporting items that are not part of the API (such as library modules which were imported and used within the module).
PEP 8 uses similar wording, although it also makes it clear that imported names are not part of the public API when __all__
is absent:
To better support introspection, modules should explicitly declare the names in their public API using the
__all__
attribute. Setting__all__
to an empty list indicates that the module has no public API.[...]
Imported names should always be considered an implementation detail. Other modules must not rely on indirect access to such imported names unless they are an explicitly documented part of the containing module's API, such as
os.path
or a package's__init__
module that exposes functionality from submodules.
Furthermore, as pointed out in other answers, __all__
is used to enable wildcard importing for packages:
The import statement uses the following convention: if a package’s
__init__.py
code defines a list named__all__
, it is taken to be the list of module names that should be imported whenfrom package import *
is encountered.
//This is to convert a letter from upper case to lower case
import java.util.Scanner;
public class ChangeCase {
public static void main(String[]args) {
String input;
Scanner sc= new Scanner(System.in);
System.out.println("Enter Letter from upper case");
input=sc.next();
String result;
result= input.toLowerCase();
System.out.println(result);
}
}
This is an old question and asks a little bit less than what I needed so this answer actually solves more than this question asks. The answers in this question helped me solve the following:
All this combined with JSON makes for a pretty powerful configuration storage support.
The solution (also on github):
from collections import OrderedDict
from pprint import pprint
class izipDestinationMatching(object):
__slots__ = ("attr", "value", "index")
def __init__(self, attr, value, index):
self.attr, self.value, self.index = attr, value, index
def __repr__(self):
return "izip_destination_matching: found match by '%s' = '%s' @ %d" % (self.attr, self.value, self.index)
def izip_destination(a, b, attrs, addMarker=True):
"""
Returns zipped lists, but final size is equal to b with (if shorter) a padded with nulls
Additionally also tries to find item reallocations by searching child dicts (if they are dicts) for attribute, listed in attrs)
When addMarker == False (patching), final size will be the longer of a, b
"""
for idx, item in enumerate(b):
try:
attr = next((x for x in attrs if x in item), None) # See if the item has any of the ID attributes
match, matchIdx = next(((orgItm, idx) for idx, orgItm in enumerate(a) if attr in orgItm and orgItm[attr] == item[attr]), (None, None)) if attr else (None, None)
if match and matchIdx != idx and addMarker: item[izipDestinationMatching] = izipDestinationMatching(attr, item[attr], matchIdx)
except:
match = None
yield (match if match else a[idx] if len(a) > idx else None), item
if not addMarker and len(a) > len(b):
for item in a[len(b) - len(a):]:
yield item, item
def dictdiff(a, b, searchAttrs=[]):
"""
returns a dictionary which represents difference from a to b
the return dict is as short as possible:
equal items are removed
added / changed items are listed
removed items are listed with value=None
Also processes list values where the resulting list size will match that of b.
It can also search said list items (that are dicts) for identity values to detect changed positions.
In case such identity value is found, it is kept so that it can be re-found during the merge phase
@param a: original dict
@param b: new dict
@param searchAttrs: list of strings (keys to search for in sub-dicts)
@return: dict / list / whatever input is
"""
if not (isinstance(a, dict) and isinstance(b, dict)):
if isinstance(a, list) and isinstance(b, list):
return [dictdiff(v1, v2, searchAttrs) for v1, v2 in izip_destination(a, b, searchAttrs)]
return b
res = OrderedDict()
if izipDestinationMatching in b:
keepKey = b[izipDestinationMatching].attr
del b[izipDestinationMatching]
else:
keepKey = izipDestinationMatching
for key in sorted(set(a.keys() + b.keys())):
v1 = a.get(key, None)
v2 = b.get(key, None)
if keepKey == key or v1 != v2: res[key] = dictdiff(v1, v2, searchAttrs)
if len(res) <= 1: res = dict(res) # This is only here for pretty print (OrderedDict doesn't pprint nicely)
return res
def dictmerge(a, b, searchAttrs=[]):
"""
Returns a dictionary which merges differences recorded in b to base dictionary a
Also processes list values where the resulting list size will match that of a
It can also search said list items (that are dicts) for identity values to detect changed positions
@param a: original dict
@param b: diff dict to patch into a
@param searchAttrs: list of strings (keys to search for in sub-dicts)
@return: dict / list / whatever input is
"""
if not (isinstance(a, dict) and isinstance(b, dict)):
if isinstance(a, list) and isinstance(b, list):
return [dictmerge(v1, v2, searchAttrs) for v1, v2 in izip_destination(a, b, searchAttrs, False)]
return b
res = OrderedDict()
for key in sorted(set(a.keys() + b.keys())):
v1 = a.get(key, None)
v2 = b.get(key, None)
#print "processing", key, v1, v2, key not in b, dictmerge(v1, v2)
if v2 is not None: res[key] = dictmerge(v1, v2, searchAttrs)
elif key not in b: res[key] = v1
if len(res) <= 1: res = dict(res) # This is only here for pretty print (OrderedDict doesn't pprint nicely)
return res
You can generate scripts to a file via SQL Server Management Studio, here are the steps:
When generating the scripts, there is an area that will allow you to script, constraints, keys, etc. From SQL Server 2008 R2 there is an Advanced Option under scripting:
In my opinion the most readable version
public enum PIN_PULL_RESISTANCE {
PULL_UP {
@Override
public int getValue() {
return 1;
}
},
PULL_DOWN {
@Override
public int getValue() {
return 0;
}
};
public abstract int getValue();
}
I hope to provide more background knowledge here.
First, constructor signature of the of method threading::Thread:
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)
args is the argument tuple for the target invocation. Defaults to ().
Second, A quirk in Python about tuple
:
Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses).
On the other hand, a string is a sequence of characters, like 'abc'[1] == 'b'
. So if send a string to args
, even in parentheses (still a sting), each character will be treated as a single parameter.
However, Python is so integrated and is not like JavaScript where extra arguments can be tolerated. Instead, it throws an TypeError
to complain.
To make sure it does not fail for string
, date
and timestamp
columns:
import pyspark.sql.functions as F
def count_missings(spark_df,sort=True):
"""
Counts number of nulls and nans in each column
"""
df = spark_df.select([F.count(F.when(F.isnan(c) | F.isnull(c), c)).alias(c) for (c,c_type) in spark_df.dtypes if c_type not in ('timestamp', 'string', 'date')]).toPandas()
if len(df) == 0:
print("There are no any missing values!")
return None
if sort:
return df.rename(index={0: 'count'}).T.sort_values("count",ascending=False)
return df
If you want to see the columns sorted based on the number of nans and nulls in descending:
count_missings(spark_df)
# | Col_A | 10 |
# | Col_C | 2 |
# | Col_B | 1 |
If you don't want ordering and see them as a single row:
count_missings(spark_df, False)
# | Col_A | Col_B | Col_C |
# | 10 | 1 | 2 |
you may also place the followinng
<a href='javascript:alert("hello world!");'>Click me</a>
to your html-code, and when you click on 'Click me' hyperlink, javascript will appear in url-bar and Alert dialog will show
String str="004-034556"
String[] sTemp=str.split("-");// '-' is a delimiter
string1=004 // sTemp[0];
string2=034556//sTemp[1];
For me it was becuase I recently added
RequestTTY force
into .ssh/config
commenting this out allowed it to work
Change *.cs to .cs in the excludefileslist.txt
on Centos 7, this will do it, for Tomcat 7 : (my tomcat install dir: opt/apache-tomcat-7.0.79)
not sure the log link is necessary, the configuration is the critical one.
:
There is a CSS unit called viewport height / viewport width.
Example
.mainbody{height: 100vh;}
similarly html,body{width: 100vw;}
or 90vh = 90% of the viewport height.
**IE9+ and most modern browsers.
One of the reasons that C++ was designed was to make it easy to reuse code. In general, C++ should be written so that it works whether the class is instantiated on the heap, in an array, or on the stack. "Delete this" is a very bad coding practice because it will only work if a single instance is defined on the heap; and there had better not be another delete statement, which is typically used by most developers to clean up the heap. Doing this also assumes that no maintenance programmer in the future will cure a falsely perceived memory leak by adding a delete statement.
Even if you know in advance that your current plan is to only allocate a single instance on the heap, what if some happy-go-lucky developer comes along in the future and decides to create an instance on the stack? Or, what if he cuts and pastes certain portions of the class to a new class that he intends to use on the stack? When the code reaches "delete this" it will go off and delete it, but then when the object goes out of scope, it will call the destructor. The destructor will then try to delete it again and then you are hosed. In the past, doing something like this would screw up not only the program but the operating system and the computer would need to be rebooted. In any case, this is highly NOT recommended and should almost always be avoided. I would have to be desperate, seriously plastered, or really hate the company I worked for to write code that did this.
Easiest way:
+num.toFixed(2)
It converts it to a string, and then back into an integer / float.
Simple example in java
public class Driver {
static int x;
static int y;
public static void main(String[] args)
throws Exception {
System.out.println("using double pipe");
if(setX() || setY())
{System.out.println("x = "+x);
System.out.println("y = "+y);
}
System.out.println("using single pipe");
if(setX() | setY())
{System.out.println("x = "+x);
System.out.println("y = "+y);
}
}
static boolean setX(){
x=5;
return true;
}
static boolean setY(){
y=5;
return true;
}
}
output :
using double pipe
x = 5
y = 0
using single pipe
x = 5
y = 5
For the toast message in flutter use bot_toast library. This library provides Feature-rich, support for displaying notifications, text, loading, attachments, etc. Toast
Here is simple code. You must set an id for your input. Here call it 'myInput':
var myform = document.getElementById('myform');
myform.onsubmit = function(){
document.getElementById('myInput').value = '1';
myform.submit();
};
There are five ways to convert The First Way :
String str = " 123" ;
int i = Integer.parse(str);
output : 123
The second way :
String str = "hello123world";
int i = Integer.parse(str.replaceAll("[\\D]" , "" ) );
output : 123
The Third Way :
String str"123";
int i = new Integer(str);
output "123
The Fourth Way :
String str"123";
int i = Integer.valueOf(Str);
output "123
The Fifth Way :
String str"123";
int i = Integer.decode(str);
output "123
There could be other ways But that's what I remember now
Normally you would select IDs using the ID selector #
, but for more complex matches you can use the attribute-starts-with selector (as a jQuery selector, or as a CSS3 selector):
div[id^="player_"]
If you are able to modify that HTML, however, you should add a class to your player div
s then target that class. You'll lose the additional specificity offered by ID selectors anyway, as attribute selectors share the same specificity as class selectors. Plus, just using a class makes things much simpler.
Many description internet-wide don't mention that specifying Access-Control-Allow-Origin
is not enough. Here is a complete example that works for me:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, DELETE, PUT, PATCH, OPTIONS');
header('Access-Control-Allow-Headers: token, Content-Type');
header('Access-Control-Max-Age: 1728000');
header('Content-Length: 0');
header('Content-Type: text/plain');
die();
}
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
$ret = [
'result' => 'OK',
];
print json_encode($ret);
Imo, you should try MySQL Connector/Node.js which is the official Node.js driver for MySQL. See ref-1 and ref-2 for detailed explanation. I have tried mysqljs/mysql which is available here, but I don't find detailed documentation on classes, methods, properties of this library.
So I switched to the standard MySQL Connector/Node.js
with X DevAPI
, since it is an asynchronous Promise-based client library and provides good documentation.
Take a look at the following code snippet :
const mysqlx = require('@mysql/xdevapi');
const rows = [];
mysqlx.getSession('mysqlx://localhost:33060')
.then(session => {
const table = session.getSchema('testSchema').getTable('testTable');
// The criteria is defined through the expression.
return table.update().where('name = "bar"').set('age', 50)
.execute()
.then(() => {
return table.select().orderBy('name ASC')
.execute(row => rows.push(row));
});
})
.then(() => {
console.log(rows);
});
Recursion occurs when something contains, or uses, a similar version of itself.When talking specifically about computer programming, recursion occurs when a function calls itself.
The following link helps me to understand recursion better, even I consider this is the best so far what I've learned.
It comes with an example to understand how the inner(recursive) functions called while executing.
Please go through the article and I have pasted the test program in case if the article got trashed. You may please run the program in local server to see it in action.
https://www.elated.com/php-recursive-functions/
<?php
function factorial( $n ) {
// Base case
if ( $n == 0 ) {
echo "Base case: $n = 0. Returning 1...<br>";
return 1;
}
// Recursion
echo "$n = $n: Computing $n * factorial( " . ($n-1) . " )...<br>";
$result = ( $n * factorial( $n-1 ) );
echo "Result of $n * factorial( " . ($n-1) . " ) = $result. Returning $result...<br>";
return $result;
}
echo "The factorial of 5 is: " . factorial( 5 );
?>
My "convention": static before instance, public before private, constructor before methods, but main method at the bottom (if present).
Best way to find this is: create a php file and add the following code:
<?php phpinfo(); ?>
and open it in browser, it will show the file which is actually being read!
Updates by OP:
<?php echo php_ini_loaded_file(); ?>
mentioned in this answer.A relatively easy way of doing this is to write the entire sequence as a shell script.
out.tar:
set -e ;\
TMP=$$(mktemp -d) ;\
echo hi $$TMP/hi.txt ;\
tar -C $$TMP cf $@ . ;\
rm -rf $$TMP ;\
I have consolidated some related tips here: https://stackoverflow.com/a/29085684/86967
You can use Replace Function to replace comma easily. To Do this-
The syntax for the REPLACE function in SQL Server (Transact-SQL) is:
REPLACE( string, string_to_replace, replacement_string )
Parameters or Arguments
string : The source string from which a sequence of characters will be replaced by another set of characters.
string_to_replace : The string that will be searched for in string1.
replacement_string : The replacement string. All occurrences of string_to_replace will be replaced with replacement_string in string1.
Note :
The REPLACE function performs a replacement that is not case-sensitive. So all occurrences of string_to_replace will be replaced with replacement_string regardless of the case of string_to_replace or replacement_string
For Example :
SELECT REPLACE('Kapil,raj,chouhan', ',' , ' ') from DUAL;
Result : Kapil raj chouhan
SELECT REPLACE('I Live In India', ' ' , '-') from DUAL;
Result : I-Live-In-India
SELECT REPLACE('facebook.com', 'face' , 'friends') from DUAL;
Result : friendsbook.com
I Hope it will be usefull for you.
In the majority of project there are some implementation of object extending: underscore, jquery, lodash: extend.
There is also pure javascript implementation, that is a part of ECMAscript 6: Object.assign: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Adding my 2 cents .If you are using scala and sbt and scala-logging as dependency ;then this can happen because scala-logging's earlier version had the name scala-logging-api.So;essentially the dependency resolutions do not happen because of different names leading to runtime errors while launching the scala application.
Base class constructors are automatically called for you if they have no argument. If you want to call a superclass constructor with an argument, you must use the subclass's constructor initialization list. Unlike Java, C++ supports multiple inheritance (for better or worse), so the base class must be referred to by name, rather than "super()".
class SuperClass
{
public:
SuperClass(int foo)
{
// do something with foo
}
};
class SubClass : public SuperClass
{
public:
SubClass(int foo, int bar)
: SuperClass(foo) // Call the superclass constructor in the subclass' initialization list.
{
// do something with bar
}
};
More info on the constructor's initialization list here and here.
Perhaps your Apache is bounded to localhost only. Look in your apache configuration file for:
Listen 127.0.0.1:80
If you found it, replace it for:
Listen 80
With GNU Make, you can use shell
and eval
to store, run, and assign output from arbitrary command line invocations. The difference between the example below and those which use :=
is the :=
assignment happens once (when it is encountered) and for all. Recursively expanded variables set with =
are a bit more "lazy"; references to other variables remain until the variable itself is referenced, and the subsequent recursive expansion takes place each time the variable is referenced, which is desirable for making "consistent, callable, snippets". See the manual on setting variables for more info.
# Generate a random number.
# This is not run initially.
GENERATE_ID = $(shell od -vAn -N2 -tu2 < /dev/urandom)
# Generate a random number, and assign it to MY_ID
# This is not run initially.
SET_ID = $(eval MY_ID=$(GENERATE_ID))
# You can use .PHONY to tell make that we aren't building a target output file
.PHONY: mytarget
mytarget:
# This is empty when we begin
@echo $(MY_ID)
# This recursively expands SET_ID, which calls the shell command and sets MY_ID
$(SET_ID)
# This will now be a random number
@echo $(MY_ID)
# Recursively expand SET_ID again, which calls the shell command (again) and sets MY_ID (again)
$(SET_ID)
# This will now be a different random number
@echo $(MY_ID)
mime_content_type()
appears to be the way to go, notwithstanding the above comments saying it is deprecated. It is not -- or at least this incarnation of mime_content_type()
is not deprecated, according to http://php.net/manual/en/function.mime-content-type.php. It is part of the FileInfo extension, but the PHP documentation now tells us it is enabled by default as of PHP 5.3.0.
Use a comma to specify a port number with SQL Server:
mycomputer.test.xxx.com,1234
It's not necessary to specify an instance name when specifying the port.
Lots more examples at http://www.connectionstrings.com/. It's saved me a few times.
How does the server know that it should pull image.png from the /pictures folder when you visit the website and browse to the /system/files/images folder in your web browser? A so-called symbolic link is the guy that is responsible for this behavior. Somewhere in your system, there is a symlink that tells your server "If a visitor requests /system/files/images/image.png then show him /pictures/image.png."
And what is the role of the FollowSymLinks setting in this?
FollowSymLinks relates to server security. When dealing with web servers, you can't just leave things undefined. You have to tell who has access to what. The FollowSymLinks setting tells your server whether it should or should not follow symlinks. In other words, if FollowSymLinks was disabled in our case, browsing to the /system/files/images/image.png file would return depending on other settings either the 403 (access forbidden) or 404 (not found) error.
We can create alternative of implode of in javascript:
function my_implode_js(separator,array){
var temp = '';
for(var i=0;i<array.length;i++){
temp += array[i]
if(i!=array.length-1){
temp += separator ;
}
}//end of the for loop
return temp;
}//end of the function
var array = new Array("One", "Two", "Three");
var str = my_implode_js('-',array);
alert(str);
You can:
<input type="submit" ..>
, instead of that button.submit(..)
on it. Eg: form.submit()
. Attach this code to the button click event. This will serialise the form parameters and execute a GET or POST request as specified in the form's method attribute.Likewise, I saw this error as a result of too little RAM. I cranked up the RAM on the VM and the error disappeared.
You could just use VideoLAN. VideoLAN will work as a server (or you can wrap your own C# application around it for more control). There are also .NET wrappers for the viewer that you can use and thus embed in your C# client.
I liked @Andomar's answer best, but I needed the column descriptions also. Here is his query modified to include those also. (Uncomment the last part of the WHERE clause to return only rows where either description is non-null).
SELECT
TableName = tbl.table_schema + '.' + tbl.table_name,
TableDescription = tableProp.value,
ColumnName = col.column_name,
ColumnDataType = col.data_type,
ColumnDescription = colDesc.ColumnDescription
FROM information_schema.tables tbl
INNER JOIN information_schema.columns col
ON col.table_name = tbl.table_name
LEFT JOIN sys.extended_properties tableProp
ON tableProp.major_id = object_id(tbl.table_schema + '.' + tbl.table_name)
AND tableProp.minor_id = 0
AND tableProp.name = 'MS_Description'
LEFT JOIN (
SELECT sc.object_id, sc.column_id, sc.name, colProp.[value] AS ColumnDescription
FROM sys.columns sc
INNER JOIN sys.extended_properties colProp
ON colProp.major_id = sc.object_id
AND colProp.minor_id = sc.column_id
AND colProp.name = 'MS_Description'
) colDesc
ON colDesc.object_id = object_id(tbl.table_schema + '.' + tbl.table_name)
AND colDesc.name = col.COLUMN_NAME
WHERE tbl.table_type = 'base table'
--AND tableProp.[value] IS NOT NULL OR colDesc.ColumnDescription IS NOT null
$(this).parent().siblings(":first").text()
parent
gives you the <td>
around the link,
siblings
gives all the <td>
tags in that <tr>
,
:first
gives the first matched element in the set.
text()
gives the contents of the tag.
With Chrome and Safari you can add the CSS style -webkit-print-color-adjust: exact;
to the element to force print the background color and/or image
As @Felix Kling suggested use action='store_true'
:
>>> from argparse import ArgumentParser
>>> p = ArgumentParser()
>>> _ = p.add_argument('-f', '--foo', action='store_true')
>>> args = p.parse_args()
>>> args.foo
False
>>> args = p.parse_args(['-f'])
>>> args.foo
True
The raw info is in pg_index.
You can encapsulate your block of code with a try ... catch statement, and when you run your code, if the column doesn't exist it will throw an exception. You can then figure out what specific exception it throws and have it handle that specific exception in a different way if you so desire, such as returning "Column Not Found".
A method that I use is to load the table into R as a data.frame
, then use dbWriteTable
to push it to PostgreSQL. These two steps are shown below.
R's data.frame
objects are database-like, where named columns have explicit types, such as text or numbers. There are several ways to get a spreadsheet into R, such as XLConnect. However, a really simple method is to select the range of the Excel table (including the header), copy it (i.e. CTRL+C), then in R use this command to get it from the clipboard:
d <- read.table("clipboard", header=TRUE, sep="\t", quote="\"", na.strings="", as.is=TRUE)
If you have RStudio, you can easily view the d
object to make sure it is as expected.
Ensure you have RPostgreSQL installed from CRAN, then make a connection and send the data.frame
to the database:
library(RPostgreSQL)
conn <- dbConnect(PostgreSQL(), dbname="mydb")
dbWriteTable(conn, "some_table_name", d)
Now some_table_name
should appear in the database.
Some common clean-up steps can be done from pgAdmin or psql:
ALTER TABLE some_table_name RENAME "row.names" TO id;
ALTER TABLE some_table_name ALTER COLUMN id TYPE integer USING id::integer;
ALTER TABLE some_table_name ADD PRIMARY KEY (id);
an SQL that shows SQL commands, need to run to duplicate a database from one database to another. for each table there is create a table statement and an insert statement. it assumes both databases are on the same server:
select @fromdb:="crm";
select @todb:="crmen";
SET group_concat_max_len=100000000;
SELECT GROUP_CONCAT( concat("CREATE TABLE `",@todb,"`.`",table_name,"` LIKE `",@fromdb,"`.`",table_name,"`;\n",
"INSERT INTO `",@todb,"`.`",table_name,"` SELECT * FROM `",@fromdb,"`.`",table_name,"`;")
SEPARATOR '\n\n')
as sqlstatement
FROM information_schema.tables where table_schema=@fromdb and TABLE_TYPE='BASE TABLE';
.scroll {
width: 200px; height: 400px;
overflow: auto;
}
If you want string to be on the left and image on the right, this should be fine (Swift 5)
/// [ String ------------------ Image ] Style Custom Button
/// For use, just define 'Title Text' and 'Image' on ib / source with setting the class 'DistantTextImageButton'.
class DistantTextImageButton: UIButton {
override func layoutSubviews() {
super.layoutSubviews()
self.semanticContentAttribute = .forceRightToLeft
self.contentHorizontalAlignment = .left
guard let imageView = imageView,
let title = title(for: .normal),
let font = titleLabel?.font else { return }
imageEdgeInsets = UIEdgeInsets(top: 0, left: bounds.width - imageView.bounds.width - title.textSizeWithFont(font).width, bottom: 0, right: 0)
titleEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
}
extension String {
func textSizeWithFont(_ font: UIFont) -> CGSize {
return self.size(withAttributes: [.font: font])
}
}
If you are OK with converting the input button to a server side control by specifying runat="server"
, and you are using asp.net
, an option could be using the HtmlButton.OnServerClick property.
<input id="foo "runat="server" type="button" onserverclick="foo_OnClick" />
This should work and call foo_OnClick
in your server side code.
Also notice that based on Microsoft documentation linked above, you should also be able to use the HTML 4.0 tag.
(throws IOException)
Image image = null;
try {
URL url = new URL("http://www.yahoo.com/image_to_read.jpg");
image = ImageIO.read(url);
} catch (IOException e) {
}
See javax.imageio
package for more info. That's using the AWT image. Otherwise you could do:
URL url = new URL("http://www.yahoo.com/image_to_read.jpg");
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
And you may then want to save the image so do:
FileOutputStream fos = new FileOutputStream("C://borrowed_image.jpg");
fos.write(response);
fos.close();
thanks to everyone else for the clues.
I used this method
div.image-thumbnail
{
width: 85px;
height: 85px;
line-height: 85px;
display: inline-block;
text-align: center;
}
div.image-thumbnail img
{
vertical-align: middle;
}
Very late to the party, but posting in case this may help someone in the future. For my use case, the following function worked the best. Works to pull any data type out of dictionary
dict is the dictionary containing our value
list is a list of "steps" towards our value
def getnestedvalue(dict, list):
length = len(list)
try:
for depth, key in enumerate(list):
if depth == length - 1:
output = dict[key]
return output
dict = dict[key]
except (KeyError, TypeError):
return None
return None
If you are at the office and behind the company proxy, try to imports all company proxy cacert into jre\lib\security
because gradle uses jre's certificates.
Plus, config your gradle.properties. It should work
More details go to that thread: https://groups.google.com/forum/#!msg/adt-dev/kdP2iNgcQFM/BDY7H0os18oJ
I got tired of seeing this page with its by-now stale references to defunct Codehaus pages so I asked on the Maven Users mailing list and got some more up-to-date answers.
I would say that the best (and most authoritative) answer contained in my link above is the one contributed by Hervé BOUTEMY:
here is the core reference: http://maven.apache.org/ref/3-LATEST/maven-model-builder/
it does not explain everyting that can be found in POM or in settings, since there are so much info available but it points to POM and settings descriptors and explains everything that is not POM or settings
There is no difference in terms of functionality
The addwithvalue
method takes an object as the value. There is no type data type checking. Potentially, that could lead to error if data type does not match with SQL table. The add
method requires that you specify the Database type first. This helps to reduce such errors.
For more detail Please click here
The above answer is already satisfying the topic. Anyway, if you need all the data in memory - have a look at bcolz. Its compressing the data in memory. I have had really good experience with it. But its missing a lot of pandas features
Edit: I got compression rates at around 1/10 or orig size i think, of course depending of the kind of data. Important features missing were aggregates.
For me android:gravity="center"
did the trick in the parent layout element.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:orientation="vertical" >
<ImageView
android:id="@+id/fullImageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:contentDescription="@string/fullImageView"
android:layout_gravity="center" />
</LinearLayout>
I think that the best way i use git rebase -i
. I created a video to show the steps to split a commit: https://www.youtube.com/watch?v=3EzOz7e1ADI
The String
class exposes some methods to enable this, such as IndexOf
and LastIndexOf
, so that you may do this:
Dim myText = "abcde"
Dim dIndex = myText.IndexOf("d")
If (dIndex > -1) Then
End If
$(function() {
$('.mhz-news-img img').each(function() {
var maxWidth = 320; // Max width for the image
var maxHeight = 200; // Max height for the image
var maxratio=maxHeight/maxWidth;
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
var curentratio=height/width;
// Check if the current width is larger than the max
if(curentratio>maxratio)
{
ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height *ratio); // Scale height based on ratio
}
else
{
ratio = maxHeight / height; // get ratio for scaling image
$(this).css("height", maxHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
}
});
});
There are helper classes in bootstrap 3 with contextual colors please use these classes in html attributes.
<p class="text-muted">...</p>
<p class="text-primary">...</p>
<p class="text-success">...</p>
<p class="text-info">...</p>
<p class="text-warning">...</p>
<p class="text-danger">...</p>
Reference: http://getbootstrap.com/css/#type
For people who are not able to find the coverage view , follow these steps :
Go to Windows Menu bar > Show View > Other > Type coverage and open it.
Click on Coverage.
To clear highlightings, click on X or XX icon as per convenience.
One-liner.
i.fa.fa-chevron-right.collapse.in { transform: rotate(180deg); }
In this example it's being used to group collapsible table rows. The only thing you need to do is add the target class name (my-collapse-name) to your icon:
<tr data-toggle="collapse" data-target=".my-collapse-name">
<th><i class="fa fa-chevron-right my-collapse-name"></span></th>
<th>Master Row - Title</th>
</tr>
<tr class="collapse my-collapse-name">
<td></td>
<td>Detail Row - Content</td>
</tr>
You could accomplish the same with Bootstrap's native caret class by using <span class='caret my-collapse-name'></span>
and span.caret.collapse.in { transform: rotate(90deg); }
GROUP BY 1
I've never known GROUP BY to support using ordinals, only ORDER BY. Either way, only MySQL supports GROUP BY's not including all columns without aggregate functions performed on them. Ordinals aren't recommended practice either because if they're based on the order of the SELECT - if that changes, so does your ORDER BY (or GROUP BY if supported).
There's no need to run GROUP BY
on the contents when you're using UNION
- UNION ensures that duplicates are removed; UNION ALL
is faster because it doesn't - and in that case you would need the GROUP BY...
Your query only needs to be:
SELECT a.id,
a.time
FROM dbo.TABLE_A a
UNION
SELECT b.id,
b.time
FROM dbo.TABLE_B b
Its very easy to create procedure in Mysql. Here, in my example I am going to create a procedure which is responsible to fetch all data from student table according to supplied name.
DELIMITER //
CREATE PROCEDURE getStudentInfo(IN s_name VARCHAR(64))
BEGIN
SELECT * FROM student_database.student s where s.sname = s_name;
END//
DELIMITER;
In the above example ,database and table names are student_database and student respectively. Note: Instead of s_name, you can also pass @s_name as global variable.
How to call procedure? Well! its very easy, simply you can call procedure by hitting this command
$mysql> CAll getStudentInfo('pass_required_name');
You can go to Design mode and select "Fix" at the bottom of the warning. Then a pop up will appear (seems like it's going to register the new string) and voila, the error is fixed.
This will solve the problem:
const json_data = {"2013-01-21":1,"2013-01-22":7};
const arr = Object.keys(json_data).map((key) => [key, json_data[key]]);
console.log(arr);
Or using Object.entries() method:
console.log(Object.entries(json_data));
In both the cases, output will be:
/* output:
[['2013-01-21', 1], ['2013-01-22', 7]]
*/
Look at the documentation regarding the SELECT ... INTO OUTFILE syntax.
SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt'
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
FROM test_table;
Datetime is a datatype.
Timestamp is a method for row versioning. In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to rowversion. It basically means that every time a row is changed, this value is increased. This is done with a database counter which automatically increase for every inserted or updated row.
For more information:
http://www.sqlteam.com/article/timestamps-vs-datetime-data-types
SFTP Plug-in: http://www.jcraft.com/eclipse-sftp/ :)
Create a dynamic view and get result from it.......
CREATE PROCEDURE dbo.usp_userwise_columns_value
(
@userid BIGINT
)
AS
BEGIN
DECLARE @maincmd NVARCHAR(max);
DECLARE @columnlist NVARCHAR(max);
DECLARE @columnname VARCHAR(150);
DECLARE @nickname VARCHAR(50);
SET @maincmd = '';
SET @columnname = '';
SET @columnlist = '';
SET @nickname = '';
DECLARE CUR_COLUMNLIST CURSOR FAST_FORWARD
FOR
SELECT columnname , nickname
FROM dbo.v_userwise_columns
WHERE userid = @userid
OPEN CUR_COLUMNLIST
IF @@ERROR <> 0
BEGIN
ROLLBACK
RETURN
END
FETCH NEXT FROM CUR_COLUMNLIST
INTO @columnname, @nickname
WHILE @@FETCH_STATUS = 0
BEGIN
SET @columnlist = @columnlist + @columnname + ','
FETCH NEXT FROM CUR_COLUMNLIST
INTO @columnname, @nickname
END
CLOSE CUR_COLUMNLIST
DEALLOCATE CUR_COLUMNLIST
IF NOT EXISTS (SELECT * FROM sys.views WHERE name = 'v_userwise_columns_value')
BEGIN
SET @maincmd = 'CREATE VIEW dbo.v_userwise_columns_value AS SELECT sjoid, CONVERT(BIGINT, ' + CONVERT(VARCHAR(10), @userid) + ') as userid , '
+ CHAR(39) + @nickname + CHAR(39) + ' as nickname, '
+ @columnlist + ' compcode FROM dbo.SJOTran '
END
ELSE
BEGIN
SET @maincmd = 'ALTER VIEW dbo.v_userwise_columns_value AS SELECT sjoid, CONVERT(BIGINT, ' + CONVERT(VARCHAR(10), @userid) + ') as userid , '
+ CHAR(39) + @nickname + CHAR(39) + ' as nickname, '
+ @columnlist + ' compcode FROM dbo.SJOTran '
END
--PRINT @maincmd
EXECUTE sp_executesql @maincmd
END
-----------------------------------------------
SELECT * FROM dbo.v_userwise_columns_value
Possible repeated question from How to overcome the CORS issue in ReactJS
CORS works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. This must be configured in the server to allow cross domain.
You can temporary solve this issue by a chrome plugin called CORS.
This worked for me:
$(window).scroll(function() {
buffer = 40 // # of pixels from bottom of scroll to fire your function. Can be 0
if ($(".myDiv").prop('scrollHeight') - $(".myDiv").scrollTop() <= $(".myDiv").height() + buffer ) {
doThing();
}
});
Must use jQuery 1.6 or higher
Since people will be coming from Google, make sure you're in the right database.
Running SQL in the 'master' database will often return this error.
I have had the exact same problem with a solution, that System.Windows.Interactivity
was required for one of the project in Visual Studio 2019, and I tried to install Blend for Visual Studio SDK for .NET
from Visual Studio 2019 Individual components, but it did not exist in it.
The consequence of that, I was not able to build the project in my solution with repetitive of following similar error on different XAML parts of the project:
The tag 'Interaction.Behaviors' does not exist in XML namespace 'clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity'.
The above mentioned errors snapshot example
The solution, the way I solved it, is by installing Microsoft Expression Blend Software Development Kit (SDK) for .NET 4 from Microsoft.
Thanks to my colleague @felza, mentioned that System.Windows.Interactivity
requires this sdk, that is suppose to be located in this folder:
C:\Program Files (x86)\Microsoft SDKs\Expression\Blend\.NETFramework\v4.0
In my case it was not installed. I have had this folder C:\Program Files (x86)\Microsoft SDKs
with out Expression\Blend\.NETFramework\v4.0
folder inside it.
After installing it, all errors disappeared.
This is shorter, but shorter isn't necessarily better (and it won't catch integer values which are out of range, as pointed out in danatel's comment):
input.matches("^-?\\d+$");
Personally, since the implementation is squirrelled away in a helper method and correctness trumps length, I would just go with something like what you have (minus catching the base Exception
class rather than NumberFormatException
).
With the background-size property in those browsers which support this very new feature of CSS.
Does this work for you?
string1.indexOf(string2) >= 0
Edit: This may not be faster than a RegExp if the string2 contains repeated patterns. On some browsers, indexOf may be much slower than RegExp. See comments.
Edit 2: RegExp may be faster than indexOf when the strings are very long and/or contain repeated patterns. See comments and @Felix's answer.
Take a look on a free tool - Valentina Studio. Amazing product! IMO this is the best manager for SQLite for all platforms:
Also it works on Mac OS X, you can install Valentina Studio (FREE) directly from Mac App Store:
Just to answer this question in a little more detail, and as Pavel said, Batch Normalization is just another layer, so you can use it as such to create your desired network architecture.
The general use case is to use BN between the linear and non-linear layers in your network, because it normalizes the input to your activation function, so that you're centered in the linear section of the activation function (such as Sigmoid). There's a small discussion of it here
In your case above, this might look like:
# import BatchNormalization
from keras.layers.normalization import BatchNormalization
# instantiate model
model = Sequential()
# we can think of this chunk as the input layer
model.add(Dense(64, input_dim=14, init='uniform'))
model.add(BatchNormalization())
model.add(Activation('tanh'))
model.add(Dropout(0.5))
# we can think of this chunk as the hidden layer
model.add(Dense(64, init='uniform'))
model.add(BatchNormalization())
model.add(Activation('tanh'))
model.add(Dropout(0.5))
# we can think of this chunk as the output layer
model.add(Dense(2, init='uniform'))
model.add(BatchNormalization())
model.add(Activation('softmax'))
# setting up the optimization of our weights
sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='binary_crossentropy', optimizer=sgd)
# running the fitting
model.fit(X_train, y_train, nb_epoch=20, batch_size=16, show_accuracy=True, validation_split=0.2, verbose = 2)
Hope this clarifies things a bit more.
All upper code is not correct to the end.
This is because when searching zz*foo* or zz* you will not get correct results.
And if you search "abcd*" in "abcd" in TotalCommander will he find a abcd file so all upper code is wrong.
Here is the correct code.
public string WildcardToRegex(string pattern)
{
string result= Regex.Escape(pattern).
Replace(@"\*", ".+?").
Replace(@"\?", ".");
if (result.EndsWith(".+?"))
{
result = result.Remove(result.Length - 3, 3);
result += ".*";
}
return result;
}
Use stored procedures.
And even assuming you would want not to use stored procedures - there is at most 3 commands to be run, not 4. Second getting id is useless, as you can do "INSERT INTO ... RETURNING".
You (or Joomla) is likely including this file multiple times. Enclose your function in a conditional block:
if (!function_exists('parseDate')) {
// ... proceed to declare your function
}
This script will read lines from large file and write to new small files. Will duplicate the header of the first line (Header) to all child files
Dim strLine
lCounter = 1
fCounter = 1
cPosition = 1
MaxLine = 1000
splitAt = MaxLine
Dim fHeader
sFile = "inputFile.txt"
dFile = LEFT(sFile, (LEN(sFile)-4))& "_0" & fCounter & ".txt"
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile(sFile,1)
Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
do while not objFileToRead.AtEndOfStream
strLine = objFileToRead.ReadLine()
objFileToWrite.WriteLine(strLine)
If cPosition = 1 Then
fHeader = strLine
End If
If cPosition = splitAt Then
fCounter = fCounter + 1
splitAt = splitAt + MaxLine
objFileToWrite.Close
Set objFileToWrite = Nothing
If fCounter < 10 Then
dFile=LEFT(dFile, (LEN(dFile)-5))& fCounter & ".txt"
Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
objFileToWrite.WriteLine(fHeader)
ElseIf fCounter <100 Or fCounter = 100 Then
dFile=LEFT(dFile, (LEN(dFile)-6))& fCounter & ".txt"
Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
objFileToWrite.WriteLine(fHeader)
Else
dFile=LEFT(dFile, (LEN(dFile)-7)) & fCounter & ".txt"
Set objFileToWrite = CreateObject("Scripting.FileSystemObject").OpenTextFile(dFile,2,true)
objFileToWrite.WriteLine(fHeader)
End If
End If
lCounter=lCounter + 1
cPosition=cPosition + 1
Loop
objFileToWrite.Close
Set objFileToWrite = Nothing
objFileToRead.Close
Set objFileToRead = Nothing
response_json = ("{ \"response_json\":" + str(list_of_dict)+ "}").replace("\'","\"")
response_json = json.dumps(response_json)
response_json = json.loads(response_json)
MailAddress fromAddress = new MailAddress (fromMail,fromName);
MailAddress toAddress = new MailAddress(toMail,toName);
MailMessage message = new MailMessage(fromAddress,toAddress);
message.Subject = subject;
message.Body = body;
SmtpClient smtp = new SmtpClient()
{
Host = host, Port = port,
enabHost = "smtp.gmail.com",
Port = 25,
EnableSsl = true,
UseDefaultCredentials = true,
Credentials = new NetworkCredentials (fromMail, password)
};
smtp.send(message);
Query query = session.createQuery("from Employee");
Note: from Employee. here Employee is not your table name it's POJO name.
The answers did help, but I think a full implementation of this will help a lot of people.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace Dom
{
class Dom
{
public static string make_Sting_From_Dom(string reportname)
{
try
{
WebClient client = new WebClient();
client.Credentials = CredentialCache.DefaultCredentials;
// Retrieve resource as a stream
Stream data = client.OpenRead(new Uri(reportname.Trim()));
// Retrieve the text
StreamReader reader = new StreamReader(data);
string htmlContent = reader.ReadToEnd();
string mtch = "TILDE";
bool b = htmlContent.Contains(mtch);
if (b)
{
int index = htmlContent.IndexOf(mtch);
if (index >= 0)
Console.WriteLine("'{0} begins at character position {1}",
mtch, index + 1);
}
// Cleanup
data.Close();
reader.Close();
return htmlContent;
}
catch (Exception)
{
throw;
}
}
static void Main(string[] args)
{
make_Sting_From_Dom("https://www.w3.org/TR/PNG/iso_8859-1.txt");
}
}
}
XAMPP should have come with a "fake" sendmail program. In that case, you can use sendmail as well:
[mail function]
; For Win32 only.
; http://php.net/smtp
;SMTP = localhost
; http://php.net/smtp-port
;smtp_port = 25
; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = [email protected]
; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = "C:/xampp/sendmail/sendmail.exe -t -i"
Sendmail should have a sendmail.ini
with it; it should be configured as so:
# Example for a user configuration file
# Set default values for all following accounts.
defaults
logfile "C:\xampp\sendmail\sendmail.log"
# Mercury
#account Mercury
#host localhost
#from postmaster@localhost
#auth off
# A freemail service example
account ACCOUNTNAME_HERE
tls on
tls_certcheck off
host smtp.gmail.com
from EMAIL_HERE
auth on
user EMAIL_HERE
password PASSWORD_HERE
# Set a default account
account default : ACCOUNTNAME_HERE
Of course, replace ACCOUNTNAME_HERE with an arbitrary account name, replace EMAIL_HERE with a valid email (such as a Gmail or Hotmail), and replace PASSWORD_HERE with the password to your email. Now, you should be able to send mail. Remember to restart Apache (from the control panel or the batch files) to allow the changes to PHP to work.
I would use git stash save --patch
. I don't find the interactivity to be annoying because there are options during it to apply the desired operation to entire files.
some thing as follows ::
Add this After the body tag
This is a rough sketch, you will need to modify it according to your needs.
<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");
var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");
var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");
f.appendChild(i);
f.appendChild(s);
//and some more input elements here
//and dont forget to add a submit button
document.getElementsByTagName('body')[0].appendChild(f);
</script>
The accepted answer is helpful, but it isn't immediately obvious how to retrieve a filename from a path if you are NOT using passed in values. I was able to work this out from this thread, but in case others aren't so lucky, here is how it is done:
@echo off
setlocal enabledelayedexpansion enableextensions
set myPath=C:\Somewhere\Somewhere\SomeFile.txt
call :file_name_from_path result !myPath!
echo %result%
goto :eof
:file_name_from_path <resultVar> <pathVar>
(
set "%~1=%~nx2"
exit /b
)
:eof
endlocal
Now the :file_name_from_path
function can be used anywhere to retrieve the value, not just for passed in arguments. This can be extremely helpful if the arguments can be passed into the file in an indeterminate order or the path isn't passed into the file at all.
For formatting jsonfile gives spaces
option which you can pass as a parameter:
jsonfile.writeFile(file, obj, {spaces: 2}, function (err) {
console.error(err);
})
Or use jsonfile.spaces = 4
. Read details here.
I would not suggest writing to file each time in the loop, instead construct the JSON object in the loop and write to file outside the loop.
var jsonfile = require('jsonfile');
var obj={
'table':[]
};
for (i=0; i <11 ; i++){
obj.table.push({"id":i,"square":i*i});
}
jsonfile.writeFile('loop.json', obj, {spaces:2}, function(err){
console.log(err);
});
Use cd
in a subshell; the shorthand way to use this kind of subshell is parentheses.
(cd wherever; mycommand ...)
That said, if your command has an environment that it requires, it should really ensure that environment itself instead of putting the onus on anything that might want to use it (unless it's an internal command used in very specific circumstances in the context of a well defined larger system, such that any caller already needs to ensure the environment it requires). Usually this would be some kind of shell script wrapper.
Java 8 - LocalDateTime
What about this?
final LocalDateTime now = LocalDateTime.now();
final LocalDateTime minRange = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), 22, 30); //Today, 10:30pm
LocalDateTime maxRange = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), 6, 30); //Tomorrow, 6:30am
maxRange = maxRange.plusDays(1); //Ensures that you don't run into an exception if minRange is the last day in the month.
if (now.isAfter(minRange) && now.isBefore(maxRange)) {
//Action
}
The best way I have found is to use jQuery JSON
Use the @import
method:
@import url('https://fonts.googleapis.com/css?family=Open+Sans&display=swap');
Obviously, "Open Sans" (Open+Sans
) is the font that is imported. So replace it with yours. If the font's name has multiple words, URL-encode it by adding a +
sign between each word, as I did.
Make sure to place the @import
at the very top of your CSS, before any rules.
Google Fonts can automatically generate the @import
directive for you. Once you have chosen a font, click the (+)
icon next to it. In bottom-left corner, a container titled "1 Family Selected" will appear. Click it, and it will expand. Use the "Customize" tab to select options, and then switch back to "Embed" and click "@import" under "Embed Font". Copy the CSS between the <style>
tags into your stylesheet.
Example for SignalR 2.2.1 (May 2017)
Server
Install-Package Microsoft.AspNet.SignalR.SelfHost -Version 2.2.1
[assembly: OwinStartup(typeof(Program.Startup))]
namespace ConsoleApplication116_SignalRServer
{
class Program
{
static IDisposable SignalR;
static void Main(string[] args)
{
string url = "http://127.0.0.1:8088";
SignalR = WebApp.Start(url);
Console.ReadKey();
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
/* CAMEL CASE & JSON DATE FORMATTING
use SignalRContractResolver from
https://stackoverflow.com/questions/30005575/signalr-use-camel-case
var settings = new JsonSerializerSettings()
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc
};
settings.ContractResolver = new SignalRContractResolver();
var serializer = JsonSerializer.Create(settings);
GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);
*/
app.MapSignalR();
}
}
[HubName("MyHub")]
public class MyHub : Hub
{
public void Send(string name, string message)
{
Clients.All.addMessage(name, message);
}
}
}
}
Client
(almost the same as Mehrdad Bahrainy reply)
Install-Package Microsoft.AspNet.SignalR.Client -Version 2.2.1
namespace ConsoleApplication116_SignalRClient
{
class Program
{
private static void Main(string[] args)
{
var connection = new HubConnection("http://127.0.0.1:8088/");
var myHub = connection.CreateHubProxy("MyHub");
Console.WriteLine("Enter your name");
string name = Console.ReadLine();
connection.Start().ContinueWith(task => {
if (task.IsFaulted)
{
Console.WriteLine("There was an error opening the connection:{0}", task.Exception.GetBaseException());
}
else
{
Console.WriteLine("Connected");
myHub.On<string, string>("addMessage", (s1, s2) => {
Console.WriteLine(s1 + ": " + s2);
});
while (true)
{
Console.WriteLine("Please Enter Message");
string message = Console.ReadLine();
if (string.IsNullOrEmpty(message))
{
break;
}
myHub.Invoke<string>("Send", name, message).ContinueWith(task1 => {
if (task1.IsFaulted)
{
Console.WriteLine("There was an error calling send: {0}", task1.Exception.GetBaseException());
}
else
{
Console.WriteLine(task1.Result);
}
});
}
}
}).Wait();
Console.Read();
connection.Stop();
}
}
}
One way to do that is to set the cascade option on you "One" side of relationship:
class Employee {
//
@OneToMany(cascade = {CascadeType.PERSIST})
private Set<Vehicles> vehicles = new HashSet<Vehicles>();
//
}
by this, when you call
Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);
it will save the vehicles too.
Yes you can use .is(':visible')
in jquery. But while the code is running under the safari browser
.is(':visible')
is won't work.
So please use the below code
if( $(".example").offset().top > 0 )
The above line will work both IE as well as safari also.
You need to download this from Microsoft: http://www.microsoft.com/en-us/download/details.aspx?id=7435.
The tool is called "Microsoft URL Rewrite Module 2.0 for IIS 7" and is described as follows by Microsoft: "URL Rewrite Module 2.0 provides a rule-based rewriting mechanism for changing requested URL’s before they get processed by web server and for modifying response content before it gets served to HTTP clients"
I think this example explains clearly the differences between inheritance and composition.
In this exmple, the problem is solved using inheritance and composition. The author pays attention to the fact that ; in inheritance, a change in superclass might cause problems in derived class, that inherit it.
There you can also see the difference in representation when you use a UML for inheritance or composition.
You can not use input for it, you need to use textarea instead.
Use textarea with the wrap="soft"
code and optional the rest of the attributes like this:
<textarea name="text" rows="14" cols="10" wrap="soft"> </textarea>
Atributes: To limit the amount of text in it for example to "40" characters you can add the attribute maxlength="40"
like this: <textarea name="text" rows="14" cols="10" wrap="soft" maxlength="40"></textarea>
To hide the scroll the style for it. if you only use overflow:scroll;
or overflow:hidden;
or overflow:auto;
it will only take affect for one scroll bar. If you want different attributes for each scroll bar then use the attributes like this overflow:scroll; overflow-x:auto; overflow-y:hidden;
in the style area:
To make the textarea not resizable you can use the style with resize:none;
like this:
<textarea name="text" rows="14" cols="10" wrap="soft" maxlength="40" style="overflow:hidden; resize:none;></textarea>
That way you can have or example a textarea with 14 rows and 10 cols with word wrap and max character length of "40" characters that works exactly like a input text box does but with rows instead and without using input text.
NOTE: textarea works with rows unlike like input <input type="text" name="tbox" size="10"></input>
that is made to not work with rows at all.
You should have a look at the official ICU4J library. It provides a MessageFormat class similar to the one available with the JDK but this former supports named placeholders.
Unlike other solutions provided on this page. ICU4j is part of the ICU project that is maintained by IBM and regularly updated. In addition, it supports advanced use cases such as pluralization and much more.
Here is a code example:
MessageFormat messageFormat =
new MessageFormat("Publication written by {author}.");
Map<String, String> args = Map.of("author", "John Doe");
System.out.println(messageFormat.format(args));
We encountered a very similar situation.
Activity 1 (Opening) -> Activity 2 (Preview) -> Activity 3 (Detail)
Incorrect "on back press" Response
I have checked all answers posted above and none of them worked. Java syntax for transition between Activity 2 and Activity 3 was reviewed to be correct.
Fresh from coding on calling out a 3rd party app. by an Activity. We decided to investigate the configuration angle - eventually enabling us to identify the root cause of the problem.
Scope: Configuration of Activity 2 (caller).
Root Cause:
android:launchMode="singleInstance"
Solution:
android:launchMode="singleTask"
Apparently on this "on back press" issue singleInstance considers invoked Activities in one instance with the calling Activity, whereas singleTask will allow for invoked Activities having their own identity enough for the intended on back press to function to work as it should to.
I've found a secure and reliable way in my InnoSetup-based script to understand whether a particular application is 32-bit or 64-bit (in my case I needed to test Excel), by using a Win32 API function. This function is called GetBinaryType()
, it comes from `kernel32' (despite the name it comes in 32 and 64 bit flavor) and looks directly at the exe's header.
You can use mutate_if
(dplyr
):
For example, coerce integer
in factor
:
mydata=structure(list(a = 1:10, b = 1:10, c = c("a", "a", "b", "b",
"c", "c", "c", "c", "c", "c")), row.names = c(NA, -10L), class = c("tbl_df",
"tbl", "data.frame"))
# A tibble: 10 x 3
a b c
<int> <int> <chr>
1 1 1 a
2 2 2 a
3 3 3 b
4 4 4 b
5 5 5 c
6 6 6 c
7 7 7 c
8 8 8 c
9 9 9 c
10 10 10 c
Use the function:
library(dplyr)
mydata%>%
mutate_if(is.integer,as.factor)
# A tibble: 10 x 3
a b c
<fct> <fct> <chr>
1 1 1 a
2 2 2 a
3 3 3 b
4 4 4 b
5 5 5 c
6 6 6 c
7 7 7 c
8 8 8 c
9 9 9 c
10 10 10 c
Thanks for Sharing. After struggling for 1.5 days, noticed that Report Server was configured with wrong domain IP. It was configured with backup domain IP which is offline. I have identified this in the user group configuration where Domain name was not listed. Changed IP and reboot the Report server. Issue resolved.
Whevever you get a problem like this just go to the man page for the function in question and it will tell you what header you are missing, e.g.
$ man memset
MEMSET(3) BSD Library Functions Manual MEMSET(3)
NAME
memset -- fill a byte string with a byte value
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
#include <string.h>
void *
memset(void *b, int c, size_t len);
Note that for C++ it's generally preferable to use the proper equivalent C++ headers, <cstring>
/<cstdio>
/<cstdlib>
/etc, rather than C's <string.h>
/<stdio.h>
/<stdlib.h>
/etc.
I think you can use db.collection.distinct(fields,query)
You will be able to get the distinct values in your case for NetworkID.
It should be something like this :
Db.collection.distinct('NetworkID')
Wrapping works but when you just want a space, I like:
<div class="col-xs-12" style="height:50px;"></div>
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
It works for me.
parseInt()
-> Parses a number to specified redix.
Number()
-> Converts the specified value to its numeric equivalent or NaN if it fails to do so.
Hence for converting some non-numeric value to number we should always use Number() function.
eg.
Number("")//0
parseInt("")//NaN
Number("123")//123
parseInt("123")//123
Number("123ac") //NaN,as it is a non numeric string
parsInt("123ac") //123,it parse decimal number outof string
Number(true)//1
parseInt(true) //NaN
There are various corner case to parseInt()
functions as it does redix conversion, hence we should avoid using parseInt() function for coersion purposes.
Now, to check weather the provided value is Numeric or not,we should use nativeisNaN()
function
Date.prototype.dayOfYear= function(){
var j1= new Date(this);
j1.setMonth(0, 0);
return Math.round((this-j1)/8.64e7);
}
alert(new Date().dayOfYear())
The problem with catching the click event is that each subsequent click within the text will select it again, whereas the user was probably expecting to reposition the cursor.
What worked for me was declaring a variable, selectSearchTextOnClick, and setting it to true by default. The click handler checks that the variable's still true: if it is, it sets it to false and performs the select(). I then have a blur event handler which sets it back to true.
Results so far seem like the behavior I'd expect.
(Edit: I neglected to say that I'd tried catching the focus event as someone suggested,but that doesn't work: after the focus event fires, the click event can fire, immediately deselecting the text).
Here's a nice, tidy solution for you: (also see the live demo ->)
window.onload = function start() {
slide();
}
function slide() {
var currMarg = 0,
contStyle = document.getElementById('container').style;
setInterval(function() {
currMarg = currMarg == 1800 ? 0 : currMarg + 600;
contStyle.marginLeft = '-' + currMarg + 'px';
}, 3000);
}
Since you are trying to learn, allow me to explain how this works.
First we declare two variables: currMarg
and contStyle
. currMarg
is an integer that we will use to track/update what left margin the container should have. We declare it outside the actual update function (in a closure), so that it can be continuously updated/access without losing its value. contStyle
is simply a convenience variable that gives us access to the containers styles without having to locate the element on each interval.
Next, we will use setInterval
to establish a function which should be called every 3 seconds, until we tell it to stop (there's your infinite loop, without freezing the browser). It works exactly like setTimeout
, except it happens infinitely until cancelled, instead of just happening once.
We pass an anonymous function to setInterval
, which will do our work for us. The first line is:
currMarg = currMarg == 1800 ? 0 : currMarg + 600;
This is a ternary operator. It will assign currMarg
the value of 0
if currMarg
is equal to 1800
, otherwise it will increment currMarg
by 600
.
With the second line, we simply assign our chosen value to container
s marginLeft, and we're done!
Note: For the demo, I changed the negative values to positive, so the effect would be visible.
Short answer
The purpose of meshgrid
is to help remplace Python loops (slow interpreted code) by vectorized operations within C NumPy library.
Borrowed from this site.
x = np.arange(-4, 4, 0.25)
y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(x, y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
meshgrid
is used to create pairs of coordinates between -4 and +4 with .25 increments in each direction X and Y. Each pair is then used to find R, and Z from it. This way of preparing "a grid" of coordinates is frequently used in plotting 3D surfaces, or coloring 2D surfaces.
Details: Python for-loop vs NumPy vector operation
To take a more simple example, let's say we have two sequences of values,
a = [2,7,9,20]
b = [1,6,7,9] ?
and we want to perform an operation on each possible pair of values, one taken from the first list, one taken from the second list. We also want to store the result. For example, let's say we want to get the sum of the values for each possible pair.
Slow and laborious method
c = []
for i in range(len(b)):
row = []
for j in range(len(a)):
row.append (a[j] + b[i])
c.append (row)
print (c)
Result:
[[3, 8, 10, 21],
[8, 13, 15, 26],
[9, 14, 16, 27],
[11, 16, 18, 29]]
Python is interpreted, these loops are relatively slow to execute.
Fast and easy method
meshgrid
is intended to remove the loops from the code. It returns two arrays (i and j below) which can be combined to scan all the existing pairs like this:
i,j = np.meshgrid (a,b)
c = i + j
print (c)
Result:
[[ 3 8 10 21]
[ 8 13 15 26]
[ 9 14 16 27]
[11 16 18 29]]
Meshgrid under the hood
The two arrays prepared by meshgrid
are:
(array([[ 2, 7, 9, 20],
[ 2, 7, 9, 20],
[ 2, 7, 9, 20],
[ 2, 7, 9, 20]]),
array([[1, 1, 1, 1],
[6, 6, 6, 6],
[7, 7, 7, 7],
[9, 9, 9, 9]]))
These arrays are created by repeating the values provided. One contains the values in identical rows, the other contains the other values in identical columns. The number of rows and column is determined by the number of elements in the other sequence.
The two arrays created by meshgrid
are therefore shape compatible for a vector operation. Imagine x and y sequences in the code at the top of page having a different number of elements, X and Y resulting arrays will be shape compatible anyway, not requiring any broadcast.
Origin
numpy.meshgrid
comes from MATLAB, like many other NumPy functions. So you can also study the examples from MATLAB to see meshgrid
in use, the code for the 3D plotting looks the same in MATLAB.
Use my_map.count( key )
; it can only return 0 or 1, which is essentially the Boolean result you want.
Alternately my_map.find( key ) != my_map.end()
works too.
You should flatten using this code ( taken from http://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks ), the code is untested, but I'm pretty sure it works:
def flatten(x):
"""flatten(sequence) -> list
Returns a single, flat list which contains all elements retrieved
from the sequence and all recursively contained sub-sequences
(iterables).
Examples:
>>> [1, 2, [3,4], (5,6)]
[1, 2, [3, 4], (5, 6)]
>>> flatten([[[1,2,3], (42,None)], [4,5], [6], 7, MyVector(8,9,10)])
[1, 2, 3, 42, None, 4, 5, 6, 7, 8, 9, 10]"""
result = []
for el in x:
#if isinstance(el, (list, tuple)):
if hasattr(el, "__iter__") and not isinstance(el, basestring):
result.extend(flatten(el))
else:
result.append(el)
return result
After you had flattened the list, you perform the intersection in the usual way:
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
def intersect(a, b):
return list(set(a) & set(b))
print intersect(flatten(c1), flatten(c2))
I tried a bunch of the answers here, even the "best" answer. They all came up short of what I specifically was after. So besides the past 12 hours of sitting in regex code for multiple programs and reading and testing these answers this is what I came up with which works EXACTLY like I want.
find . -type f -name "*.*" | grep -o -E "\.[^\.]+$" | grep -o -E "[[:alpha:]]{2,16}" | awk '{print tolower($0)}' | sort -u
If you need a count of the file extensions then use the below code
find . -type f -name "*.*" | grep -o -E "\.[^\.]+$" | grep -o -E "[[:alpha:]]{2,16}" | awk '{print tolower($0)}' | sort | uniq -c | sort -rn
While these methods will take some time to complete and probably aren't the best ways to go about the problem, they work.
Update: Per @alpha_989 long file extensions will cause an issue. That's due to the original regex "[[:alpha:]]{3,6}". I have updated the answer to include the regex "[[:alpha:]]{2,16}". However anyone using this code should be aware that those numbers are the min and max of how long the extension is allowed for the final output. Anything outside that range will be split into multiple lines in the output.
Note: Original post did read "- Greps for file extensions between 3 and 6 characters (just adjust the numbers if they don't fit your need). This helps avoid cache files and system files (system file bit is to search jail)."
Idea: Could be used to find file extensions over a specific length via:
find . -type f -name "*.*" | grep -o -E "\.[^\.]+$" | grep -o -E "[[:alpha:]]{4,}" | awk '{print tolower($0)}' | sort -u
Where 4 is the file extensions length to include and then find also any extensions beyond that length.
Tilde folders
In the event pip uninstall numpy
and reinstallation of Numpy does not work. Review your site-packages folder for sub-folders beginning with a tilde ~
These folders relate to pip installations that got mangled and the installation was aborted part way through. The tilde folders were only ever meant to be tmp folders but ended up becoming permanent. In my case there was a file called ~mpy which was a mangled legacy Numpy folder. This led to compatibility issues and ImportErrors.
These mangled folders can safely be deleted, for further details see this answer
Go has objects. Objects can have constructors (although not automatic constructors). And finally, Go is an OOP language (data types have methods attached, but admittedly there are endless definitions of what OOP is.)
Nevertheless, the accepted best practice is to write zero or more constructors for your types.
As @dystroy posted his answer before me finishing this answer, let me just add an alternative version of his example constructor, which I would probably write instead as:
func NewThing(someParameter string) *Thing {
return &Thing{someParameter, 33} // <- 33: a very sensible default value
}
The reason I want to show you this version is that pretty often "inline" literals can be used instead of a "constructor" call.
a := NewThing("foo")
b := &Thing{"foo", 33}
Now *a == *b
.
Have you tried before and after rather than >= and <=? Also, is this a date or a timestamp?
Use this:
SELECT s.name AS Student, c.name AS Course
FROM student s
LEFT JOIN (bridge b CROSS JOIN course c)
ON (s.id = b.sid AND b.cid = c.id);
In order to access project from the homepage you need to create a Virtual Host first.
Most easiest way to do this is to use Wamp's Add a Virtual Host Utility.
Just follow these steps:
<?php
echo "<h1>Hello World</h1>";
?>
Now you can access the projects from the localhost's homepage. Just click the project link and you'll see 'Hello World' printed on your screen.
I have successfully used as shown below in Jenkinsfile:
steps {
script {
def reportPath = "${WORKSPACE}/target/report"
...
}
}
Try linux command chsh
.
The detailed command is chsh -s /bin/bash
.
It will prompt you to enter your password.
Your default login shell is /bin/bash
now. You must log out and log back in to see this change.
The following is quoted from man page:
The chsh command changes the user login shell. This determines the name of the users initial login command. A normal user may only change the login shell for her own account, the superuser may change the login shell for any account
This command will change the default login shell permanently.
Note: If your user account is remote such as on Kerberos authentication (e.g. Enterprise RHEL) then you will not be able to use chsh
.
You use something like
from flask import send_file
@app.route('/get_image')
def get_image():
if request.args.get('type') == '1':
filename = 'ok.gif'
else:
filename = 'error.gif'
return send_file(filename, mimetype='image/gif')
to send back ok.gif
or error.gif
, depending on the type query parameter. See the documentation for the send_file
function and the request
object for more information.
The steel is far from hot, but I combined @abatishchev's solution with the answer from this post and got to this result. Hope it's useful:
public static class GlobalVars
{
private const string GlobalKey = "AllMyVars";
static GlobalVars()
{
Hashtable table = HttpContext.Current.Application[GlobalKey] as Hashtable;
if (table == null)
{
table = new Hashtable();
HttpContext.Current.Application[GlobalKey] = table;
}
}
public static Hashtable Vars
{
get { return HttpContext.Current.Application[GlobalKey] as Hashtable; }
}
public static IEnumerable<SomeClass> SomeCollection
{
get { return GetVar("SomeCollection") as IEnumerable<SomeClass>; }
set { WriteVar("SomeCollection", value); }
}
internal static DateTime SomeDate
{
get { return (DateTime)GetVar("SomeDate"); }
set { WriteVar("SomeDate", value); }
}
private static object GetVar(string varName)
{
if (Vars.ContainsKey(varName))
{
return Vars[varName];
}
return null;
}
private static void WriteVar(string varName, object value)
{
if (value == null)
{
if (Vars.ContainsKey(varName))
{
Vars.Remove(varName);
}
return;
}
if (Vars[varName] == null)
{
Vars.Add(varName, value);
}
else
{
Vars[varName] = value;
}
}
}
If you're testing this out in postman / insomnia and are just trying to get it working, hint: the server auth code (code parameter) is only good once. Meaning if you stuff up any of the other parameters in the request and get back a 400, you'll need to use a new server auth code or you'll just get another 400.
use this, it realy works:
data.addColumn no of your key, you can add more columns or remove
<?php
$con=mysql_connect("localhost","USername","Password") or die("Failed to connect with database!!!!");
mysql_select_db("Database Name", $con);
// The Chart table contain two fields: Weekly_task and percentage
//this example will display a pie chart.if u need other charts such as Bar chart, u will need to change little bit to make work with bar chart and others charts
$sth = mysql_query("SELECT * FROM chart");
while($r = mysql_fetch_assoc($sth)) {
$arr2=array_keys($r);
$arr1=array_values($r);
}
for($i=0;$i<count($arr1);$i++)
{
$chart_array[$i]=array((string)$arr2[$i],intval($arr1[$i]));
}
echo "<pre>";
$data=json_encode($chart_array);
?>
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable();
data.addColumn("string", "YEAR");
data.addColumn("number", "NO of record");
data.addRows(<?php $data ?>);
]);
var options = {
title: 'My Weekly Plan',
is3D: 'true',
width: 800,
height: 600
};
// Instantiate and draw our chart, passing in some options.
//do not forget to check ur div ID
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
So I had this exact same issue and lost about 6 hours of my life searching, I had the
withCredentials: true
But the browser still didn't save the cookie until for some weird reason I had the idea to shuffle the configuration setting:
Axios.post(GlobalVariables.API_URL + 'api/login', {
email,
password,
honeyPot
}, {
withCredentials: true,
headers: {'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'
}});
Seems like you should always send the 'withCredentials' Key first.
Here is an even simpler solution using base graphics and alpha-blending (which does not work on all graphics devices):
set.seed(42)
p1 <- hist(rnorm(500,4)) # centered at 4
p2 <- hist(rnorm(500,6)) # centered at 6
plot( p1, col=rgb(0,0,1,1/4), xlim=c(0,10)) # first histogram
plot( p2, col=rgb(1,0,0,1/4), xlim=c(0,10), add=T) # second
The key is that the colours are semi-transparent.
Edit, more than two years later: As this just got an upvote, I figure I may as well add a visual of what the code produces as alpha-blending is so darn useful:
Unfortunately, this answer here by @EatOng is not correct. After reading his answer I added a dummy variable to every AJAX request I was firing (even if some of them already had some fields) just to be sure the error never appears.
But just now I came across the same damn error from PHP. I double-confirmed that I had sent some POST data (some other fields too along with the dummy variable). PHP version 5.6.25
, always_populate_raw_post_data
value is set to 0
.
Also, as I am sending a application/json
request, PHP is not populating it to $_POST
, rather I have to json_decode()
the raw POST request body, accessible by php://input
.
As the answer by @rr- cites,
0/off/whatever: BC behavior (populate if content-type is not registered or request method is other than POST).
Because the request method is for sure POST, I guess PHP didn't recognize/like my Content-Type: application/json
request (again, why??).
OPTION 1:
Edit the php.ini
file manually and set the culprit variable to -1
, as many of the answers here suggest.
OPTION 2:
This is a PHP 5.6 bug. Upgrade PHP.
OPTION 3:
As @user9541305 answered here, changing the Content-Type
of AJAX request to application/x-www-form-urlencoded
or multipart/form-data
will make PHP populate the $_POST
from the POSTed body (because PHP likes/recognizes those content-type
headers!?).
OPTION 4: LAST RESORT
Well, I did not want to change the Content-Type
of AJAX, it would cause a lot of trouble for debugging. (Chrome DevTools nicely views the POSTed variables of JSON requests.)
I am developing this thing for a client and cannot ask them to use latest PHP, nor to edit the php.ini file. As a last resort, I will just check if it is set to 0
and if so, edit the php.ini
file in my PHP script itself. Of course I will have to ask the user to restart apache. What a shame!
Here is a sample code:
<?php
if(ini_get('always_populate_raw_post_data') != '-1')
{
// Get the path to php.ini file
$iniFilePath = php_ini_loaded_file();
// Get the php.ini file content
$iniContent = file_get_contents($iniFilePath);
// Un-comment (if commented) always_populate_raw_post_data line, and set its value to -1
$iniContent = preg_replace('~^\s*;?\s*always_populate_raw_post_data\s*=\s*.*$~im', 'always_populate_raw_post_data = -1', $iniContent);
// Write the content back to the php.ini file
file_put_contents($iniFilePath, $iniContent);
// Exit the php script here
// Also, write some response here to notify the user and ask to restart Apache / WAMP / Whatever.
exit;
}
Model:
namespace MvcApplicationrazor.Models
{
public class CountryModel
{
public List<State> StateModel { get; set; }
public SelectList FilteredCity { get; set; }
}
public class State
{
public int Id { get; set; }
public string StateName { get; set; }
}
public class City
{
public int Id { get; set; }
public int StateId { get; set; }
public string CityName { get; set; }
}
}
Controller:
public ActionResult Index()
{
CountryModel objcountrymodel = new CountryModel();
objcountrymodel.StateModel = new List<State>();
objcountrymodel.StateModel = GetAllState();
return View(objcountrymodel);
}
//Action result for ajax call
[HttpPost]
public ActionResult GetCityByStateId(int stateid)
{
List<City> objcity = new List<City>();
objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
return Json(obgcity);
}
// Collection for state
public List<State> GetAllState()
{
List<State> objstate = new List<State>();
objstate.Add(new State { Id = 0, StateName = "Select State" });
objstate.Add(new State { Id = 1, StateName = "State 1" });
objstate.Add(new State { Id = 2, StateName = "State 2" });
objstate.Add(new State { Id = 3, StateName = "State 3" });
objstate.Add(new State { Id = 4, StateName = "State 4" });
return objstate;
}
//collection for city
public List<City> GetAllCity()
{
List<City> objcity = new List<City>();
objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
return objcity;
}
View:
@model MvcApplicationrazor.Models.CountryModel
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
function GetCity(_stateId) {
var procemessage = "<option value='0'> Please wait...</option>";
$("#ddlcity").html(procemessage).show();
var url = "/Test/GetCityByStateId/";
$.ajax({
url: url,
data: { stateid: _stateId },
cache: false,
type: "POST",
success: function (data) {
var markup = "<option value='0'>Select City</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#ddlcity").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
</script>
<h4>
MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
<br />
<br />
<select id="ddlcity" name="ddlcity" style="width: 200px">
</select>
<br /><br />
}
On MVC 5 is quite similar
@Html.ActionLink("LinkText", "ActionName", new { id = "id" })
You can pass a method as parameter with method(:function)
way. Below is a very simple example:
def double(a) return a * 2 end => nil def method_with_function_as_param( callback, number) callback.call(number) end => nil method_with_function_as_param( method(:double) , 10 ) => 20
Well, as the error says, you have an expression (((t[1])/length) * t[1]
) on the left side of the assignment, rather than a variable name. You have that expression, and then you tell Python to add string
to it (which is always ""
) and assign it to... where? ((t[1])/length) * t[1]
isn't a variable name, so you can't store the result into it.
Did you mean string += ((t[1])/length) * t[1]
? That would make more sense. Of course, you're still trying to add a number to a string, or multiply by a string... one of those t[1]
s should probably be a t[0]
.
Comparison of execution time of bubble sort and selection sort I have a program which compares the execution time of bubble sort and selection sort. To find out the time of execution of a block of code compute the time before and after the block by
clock_t start=clock();
…
clock_t end=clock();
CLOCKS_PER_SEC is constant in time.h library
Example code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int a[10000],i,j,min,temp;
for(i=0;i<10000;i++)
{
a[i]=rand()%10000;
}
//The bubble Sort
clock_t start,end;
start=clock();
for(i=0;i<10000;i++)
{
for(j=i+1;j<10000;j++)
{
if(a[i]>a[j])
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
end=clock();
double extime=(double) (end-start)/CLOCKS_PER_SEC;
printf("\n\tExecution time for the bubble sort is %f seconds\n ",extime);
for(i=0;i<10000;i++)
{
a[i]=rand()%10000;
}
clock_t start1,end1;
start1=clock();
// The Selection Sort
for(i=0;i<10000;i++)
{
min=i;
for(j=i+1;j<10000;j++)
{
if(a[min]>a[j])
{
min=j;
}
}
temp=a[min];
a[min]=a[i];
a[i]=temp;
}
end1=clock();
double extime1=(double) (end1-start1)/CLOCKS_PER_SEC;
printf("\n");
printf("\tExecution time for the selection sort is %f seconds\n\n", extime1);
if(extime1<extime)
printf("\tSelection sort is faster than Bubble sort by %f seconds\n\n", extime - extime1);
else if(extime1>extime)
printf("\tBubble sort is faster than Selection sort by %f seconds\n\n", extime1 - extime);
else
printf("\tBoth algorithms have the same execution time\n\n");
}
You can also try using multiprocessing.Process
with daemon=True
; the process.start()
method does not block and you can return a response/status immediately to the caller while your expensive function executes in the background.
I experienced similar problem while working with falcon framework and using daemon
process helped.
You'd need to do the following:
from multiprocessing import Process
@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
...
heavy_process = Process( # Create a daemonic process with heavy "my_func"
target=my_func,
daemon=True
)
heavy_process.start()
return Response(
mimetype='application/json',
status=200
)
# Define some heavy function
def my_func():
time.sleep(10)
print("Process finished")
You should get a response immediately and, after 10s you should see a printed message in the console.
NOTE: Keep in mind that daemonic
processes are not allowed to spawn any child processes.
You could try using HTML5s sessionStorage it lasts for the duration on the page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.
sessionStorage.setItem("username", "John");
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage
Browser Compatibility https://code.google.com/p/sessionstorage/ compatible with every A-grade browser, included iPhone or Android. http://www.nczonline.net/blog/2009/07/21/introduction-to-sessionstorage/
The ByteBuffer class is important because it forms a basis for the use of channels in Java. ByteBuffer class defines six categories of operations upon byte buffers, as stated in the Java 7 documentation:
Absolute and relative get and put methods that read and write single bytes;
Relative bulk get methods that transfer contiguous sequences of bytes from this buffer into an array;
Relative bulk put methods that transfer contiguous sequences of bytes from a byte array or some other byte buffer into this buffer;
Absolute and relative get and put methods that read and write values of other primitive types, translating them to and from sequences of bytes in a particular byte order;
Methods for creating view buffers, which allow a byte buffer to be viewed as a buffer containing values of some other primitive type; and
Methods for compacting, duplicating, and slicing a byte buffer.
Example code : Putting Bytes into a buffer.
// Create an empty ByteBuffer with a 10 byte capacity
ByteBuffer bbuf = ByteBuffer.allocate(10);
// Get the buffer's capacity
int capacity = bbuf.capacity(); // 10
// Use the absolute put(int, byte).
// This method does not affect the position.
bbuf.put(0, (byte)0xFF); // position=0
// Set the position
bbuf.position(5);
// Use the relative put(byte)
bbuf.put((byte)0xFF);
// Get the new position
int pos = bbuf.position(); // 6
// Get remaining byte count
int rem = bbuf.remaining(); // 4
// Set the limit
bbuf.limit(7); // remaining=1
// This convenience method sets the position to 0
bbuf.rewind(); // remaining=7
Yes with Virtual Host you can have as many parallel programs as you want:
Open
/etc/httpd/conf/httpd.conf
Listen 81
Listen 82
Listen 83
<VirtualHost *:81>
ServerAdmin [email protected]
DocumentRoot /var/www/site1/html
ServerName site1.com
ErrorLog logs/site1-error_log
CustomLog logs/site1-access_log common
ScriptAlias /cgi-bin/ "/var/www/site1/cgi-bin/"
</VirtualHost>
<VirtualHost *:82>
ServerAdmin [email protected]
DocumentRoot /var/www/site2/html
ServerName site2.com
ErrorLog logs/site2-error_log
CustomLog logs/site2-access_log common
ScriptAlias /cgi-bin/ "/var/www/site2/cgi-bin/"
</VirtualHost>
<VirtualHost *:83>
ServerAdmin [email protected]
DocumentRoot /var/www/site3/html
ServerName site3.com
ErrorLog logs/site3-error_log
CustomLog logs/site3-access_log common
ScriptAlias /cgi-bin/ "/var/www/site3/cgi-bin/"
</VirtualHost>
Restart apache
service httpd restart
You can now refer Site1 :
http://<ip-address>:81/
http://<ip-address>:81/cgi-bin/
Site2 :
http://<ip-address>:82/
http://<ip-address>:82/cgi-bin/
Site3 :
http://<ip-address>:83/
http://<ip-address>:83/cgi-bin/
If path is not hardcoded in any script then your websites should work seamlessly.
Using these:
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Linq;
You can use a series of LINQ methods to grab the most preferred IP address.
public static bool IsIPv4(IPAddress ipa) => ipa.AddressFamily == AddressFamily.InterNetwork;
public static IPAddress GetMainIPv4() => NetworkInterface.GetAllNetworkInterfaces()
.Select((ni)=>ni.GetIPProperties())
.Where((ip)=> ip.GatewayAddresses.Where((ga) => IsIPv4(ga.Address)).Count() > 0)
.FirstOrDefault()?.UnicastAddresses?
.Where((ua) => IsIPv4(ua.Address))?.FirstOrDefault()?.Address;
This simply finds the first Network Interface that has an IPv4 Default Gateway, and gets the first IPv4 address on that interface. Networking stacks are designed to have only one Default Gateway, and therefore the one with a Default Gateway, is the best one.
WARNING: If you have an abnormal setup where the main adapter has more than one IPv4 Address, this will grab only the first one. (The solution to grabbing the best one in that scenario involves grabbing the Gateway IP, and checking to see which Unicast IP is in the same subnet as the Gateway IP Address, which would kill our ability to create a pretty LINQ method based solution, as well as being a LOT more code)
On Mac OS X El Capitan I had to run these two commands to fix this error:
xcode-select --install
pip install lxml
Which ended up installing lxml-3.5.0
When you run the xcode-select command you may have to sign a EULA (so have an X-Term handy for the UI if you're doing this on a headless machine).
class Phone {
public Phone getMsg() {
System.out.println("phone...");
return new Phone();
}
}
class Samsung extends Phone{
@Override
public Samsung getMsg() {
System.out.println("samsung...");
return new Samsung();
}
public static void main(String[] args) {
Phone p=new Samsung();
p.getMsg();
}
}
if you put your full code here so i can help you. if your setting the listener in XML and calling the set background color on View so it will change the background color of the view means it ur Botton so put ur listener in ur activity and then change the color of your view
That really depends on if you expect to find the object, or not. If you follow the school of thought that exceptions should be used for indicating something, well, err, exceptional has occured then:
Otherwise, return null.
Chromedriver is a WebDriver. WebDriver is an open-source tool for automated testing of web apps across many browsers. It provides capabilities for navigating to web pages, user input, JavaScript execution, and more. When you run this driver, it will enable your scripts to access this and run commands on Google Chrome.
This can be done via scripts running in the local network (Only local connections are allowed.
) or via scripts running on outside networks (All remote connections are allowed.
). It is always safer to use the Local Connection option. By default your Chromedriver is accessible via port 9515
.
To answer the question, it is just an informational message. You don't have to worry about it.
Given below are both options.
$ chromedriver
Starting ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103@{#416}) on port 9515
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
This is by whitelisting all IPs.
$ chromedriver --whitelisted-ips=""
Starting ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103@{#416}) on port 9515
All remote connections are allowed. Use a whitelist instead!
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Select the Object -> Format -> Selection Pane -> Double click to change the name
You will have to use something like below
#menu ul{_x000D_
list-style: none;_x000D_
}_x000D_
#menu li{_x000D_
display: inline;_x000D_
}_x000D_
_x000D_
<div id="menu">_x000D_
<ul>_x000D_
<li>First menu item</li>_x000D_
<li>Second menu item</li>_x000D_
<li>Third menu item</li>_x000D_
</ul>_x000D_
</div>
_x000D_
When we are going to migrate JQuery from 1.x to 2x or 3.x in our old existing application , then we will use .done,.fail instead of success,error as JQuery up gradation is going to be deprecated these methods.For example when we make a call to server web methods then server returns promise objects to the calling methods(Ajax methods) and this promise objects contains .done,.fail..etc methods.Hence we will the same for success and failure response. Below is the example(it is for POST request same way we can construct for request type like GET...)
$.ajax({
type: "POST",
url: url,
data: '{"name" :"sheo"}',
contentType: "application/json; charset=utf-8",
async: false,
cache: false
}).done(function (Response) {
//do something when get response })
.fail(function (Response) {
//do something when any error occurs.
});
string x ="Hi ,World";
string y = x;
char[] whitespace = new char[]{ ' ',\t'};
string[] fooArray = y.Split(whitespace); // now you have an array of 3 strings
y = String.Join(" ", fooArray);
string[] target = { "Hi", "World", "VW_Slep" };
for (int i = 0; i < target.Length; i++)
{
string v = target[i];
string results = Array.Find(fooArray, element => element.StartsWith(v, StringComparison.Ordinal));
//
if (results != null)
{ MessageBox.Show(results); }
}
Creating a Dump File SQL.gz on the current server
$ sudo apt-get install pigz pv
$ pv | mysqldump --user=<yourdbuser> --password=<yourdbpassword> <currentexistingdbname> --single-transaction --routines --triggers --events --quick --opt -Q --flush-logs --allow-keywords --hex-blob --order-by-primary --skip-comments --skip-disable-keys --skip-add-locks --extended-insert --log-error=/var/log/mysql/<dbname>_backup.log | pigz > /path/to/folder/<dbname>_`date +\%Y\%m\%d_\%H\%M`.sql.gz
Optional: Command Arguments for connection
--host=127.0.0.1 / localhost / IP Address of the Dump Server
--port=3306
Importing the dumpfile created above to a different Server
$ sudo apt-get install pigz pv
$ zcat /path/to/folder/<dbname>_`date +\%Y\%m\%d_\%H\%M`.sql.gz | pv | mysql --user=<yourdbuser> --password=<yourdbpassword> --database=<yournewdatabasename> --compress --reconnect --unbuffered --net_buffer_length=1048576 --max_allowed_packet=1073741824 --connect_timeout=36000 --line-numbers --wait --init-command="SET GLOBAL net_buffer_length=1048576;SET GLOBAL max_allowed_packet=1073741824;SET FOREIGN_KEY_CHECKS=0;SET UNIQUE_CHECKS = 0;SET AUTOCOMMIT = 1;FLUSH NO_WRITE_TO_BINLOG QUERY CACHE, STATUS, SLOW LOGS, GENERAL LOGS, ERROR LOGS, ENGINE LOGS, BINARY LOGS, LOGS;"
Optional: Command Arguments for connection
--host=127.0.0.1 / localhost / IP Address of the Import Server
--port=3306
mysql: [Warning] Using a password on the command line interface can be insecure. 1.0GiB 00:06:51 [8.05MiB/s] [<=> ]
The optional software packages are helpful to import your database SQL file faster
for faster zipping of the output
var model = {"Id": "xx", "Name":"Ravi"};
$.ajax({ url: 'test/set',
type: "POST",
data: model,
success: function (res) {
if (res != null) {
alert("done.");
}
},
error: function (res) {
}
});
You can use the directive v-html to show it. like this:
<td v-html="desc"></td>
As the error notes, the problem is in the line:
if guess[i] == winning_numbers[i]
The error is that your list indices are out of range--that is, you are trying to refer to some index that doesn't even exist. Without debugging your code fully, I would check the line where you are adding guesses based on input:
for i in range(tickets):
bubble = input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split(" ")
guess.append(bubble)
print(bubble)
The size of how many guesses you are giving your user is based on
# Prompts the user to enter the number of tickets they wish to play.
tickets = int(input("How many lottery tickets do you want?\n"))
So if the number of tickets they want is less than 5, then your code here
for i in range(5):
if guess[i] == winning_numbers[i]:
match = match+1
return match
will throw an error because there simply aren't that many elements in the guess
list.
You can also execute the following code. It is tested and working.
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;
public class SFTPTest {
public static void main(String[] args) {
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession("username", "mywebsite.com", 22); //default port is 22
UserInfo ui = new MyUserInfo();
session.setUserInfo(ui);
session.setPassword("123456".getBytes());
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
System.out.println("Connected");
} catch (JSchException e) {
e.printStackTrace(System.out);
} catch (Exception e){
e.printStackTrace(System.out);
} finally{
session.disconnect();
System.out.println("Disconnected");
}
}
public static class MyUserInfo implements UserInfo, UIKeyboardInteractive {
@Override
public String getPassphrase() {
return null;
}
@Override
public String getPassword() {
return null;
}
@Override
public boolean promptPassphrase(String arg0) {
return false;
}
@Override
public boolean promptPassword(String arg0) {
return false;
}
@Override
public boolean promptYesNo(String arg0) {
return false;
}
@Override
public void showMessage(String arg0) {
}
@Override
public String[] promptKeyboardInteractive(String arg0, String arg1,
String arg2, String[] arg3, boolean[] arg4) {
return null;
}
}
}
Please substitute the appropriate values.
How about User-Defined Type Guards? https://www.typescriptlang.org/docs/handbook/advanced-types.html
interface Bird {
fly();
layEggs();
}
interface Fish {
swim();
layEggs();
}
function isFish(pet: Fish | Bird): pet is Fish { //magic happens here
return (<Fish>pet).swim !== undefined;
}
// Both calls to 'swim' and 'fly' are now okay.
if (isFish(pet)) {
pet.swim();
}
else {
pet.fly();
}
Another option you can always consider is Apache Commons. It provides a lot of options.
import org.apache.commons.lang3.builder.CompareToBuilder;
Ex:
public int compare(Person a, Person b){
return new CompareToBuilder()
.append(a.getName(), b.getName())
.append(a.getAddress(), b.getAddress())
.toComparison();
}
The solutions like cmd /c pause
cause a new command interpreter to start and run in the background. Although acceptable in some cases, this isn't really ideal.
The solutions using Read-Host
force the user to press Enter and are not really "any key".
This solution will give you a true "press any key to continue" interface and will not start a new interpreter, which will essentially mimic the original pause
command.
Write-Host "Press any key to continue..."
[void][System.Console]::ReadKey($true)
Try This Method
For Java :
EditText yourEditText = (EditText) findViewById(R.id.yourEditText);
yourEditText.setFilters(new InputFilter[] {
new InputFilter() {
@Override
public CharSequence filter(CharSequence cs, int start,
int end, Spanned spanned, int dStart, int dEnd) {
// TODO Auto-generated method stub
if(cs.equals("")){ // for backspace
return cs;
}
if(cs.toString().matches("[a-zA-Z ]+")){
return cs;
}
return "";
}
}});
For Kotlin :
val yourEditText = findViewById<View>(android.R.id.yourEditText) as EditText
val reges = Regex("^[0-9a-zA-Z ]+$")
//this will allow user to only write letter and white space
yourEditText.filters = arrayOf<InputFilter>(
object : InputFilter {
override fun filter(
cs: CharSequence, start: Int,
end: Int, spanned: Spanned?, dStart: Int, dEnd: Int,
): CharSequence? {
if (cs == "") { // for backspace
return cs
}
return if (cs.toString().matches(reges)) {
cs
} else ""
}
}
)
The answer provided by @DSM is simple and straightforward, but I thought I'd add my own input to this question. If you look at the code for pandas.value_counts, you'll see that there is a lot going on.
If you need to calculate the frequency of many series, this could take a while. A faster implementation would be to use numpy.unique with return_counts = True
Here is an example:
import pandas as pd
import numpy as np
my_series = pd.Series([1,2,2,3,3,3])
print(my_series.value_counts())
3 3
2 2
1 1
dtype: int64
Notice here that the item returned is a pandas.Series
In comparison, numpy.unique
returns a tuple with two items, the unique values and the counts.
vals, counts = np.unique(my_series, return_counts=True)
print(vals, counts)
[1 2 3] [1 2 3]
You can then combine these into a dictionary:
results = dict(zip(vals, counts))
print(results)
{1: 1, 2: 2, 3: 3}
And then into a pandas.Series
print(pd.Series(results))
1 1
2 2
3 3
dtype: int64
You can use quotemeta (\Q \E)
if your Perl is version 5.16 or later, but if below you can simply avoid using a regular expression at all.
For example, by using the index
command:
if (index($text_to_search, $search_string) > -1) {
print "wee";
}
Install qt using:
sudo apt install qt5-qmake
Open ~/.bashrc
file:
vim ~/.bashrc
Added the path below to the ~/.bashrc
file:
export PATH="/opt/Qt/5.15.1/gcc_64/bin/:$PATH"
Execute/load a ~/.bashrc
file in your current shell
source ~/.bashrc`
Try now qmake
by using the version command below:
qmake --version
Razor is a view engine for ASP.NET MVC, and also a template engine. Razor code and ASP.NET inline code (code mixed with markup) both get compiled first and get turned into a temporary assembly before being executed. Thus, just like C# and VB.NET both compile to IL which makes them interchangable, Razor and Inline code are both interchangable.
Therefore, it's more a matter of style and interest. I'm more comfortable with razor, rather than ASP.NET inline code, that is, I prefer Razor (cshtml) pages to .aspx pages.
Imagine that you want to get a Human
class, and render it. In cshtml files you write:
<div>Name is @Model.Name</div>
While in aspx files you write:
<div>Name is <%= Human.Name %></div>
As you can see, @
sign of razor makes mixing code and markup much easier.
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
I found a faster way of embedding:
Are you familiar with the DataSet
class?
The DataSet
can also load
XML documents and you may find it easier to iterate.
http://msdn.microsoft.com/en-us/library/system.data.dataset.readxml.aspx
DataSet dt = new DataSet();
dt.ReadXml(@"c:\test.xml");