TL;DR Use Cmd/Ctrl+Shift+P
then Package Control: Install Package
, then Print to HTML
and install it. Use Alt+Shift+P
to print.
My favorite tool for printing from Sublime Text is Print to HTML package. You can "print" a selection or a whole file - via the web browser.
This opens your browser print dialog (Chrome for me) with the selected text neatly in the print dialog window and syntax highlighting intact. There you can choose a printer or export to PDF, and print.
Install the "Print to HTML" package using the package manager.
Ctrl + Shift + P
=> Gives a list of commands.install
"Package Control: Install Package
"print to
"Print to HTML
". Select that, and it is being installed.Alt+Shift+P
You may try with below query :
INSERT INTO errortable (dateupdated,table1id)
VALUES (to_date(to_char(sysdate,'dd/mon/yyyy hh24:mi:ss'), 'dd/mm/yyyy hh24:mi:ss' ),1083 );
To view the result of it:
SELECT to_char(hire_dateupdated, 'dd/mm/yyyy hh24:mi:ss')
FROM errortable
WHERE table1id = 1083;
I have a table which forget to add a primary key in the id row. Though is has auto_increment on the id. But one day, one stuff replay the mysql bin log on the database which insert some duplicate rows.
I remove the duplicate row by
select T1.* from table_name T1 inner join (select count(*) as c,id from table_name group by id) T2 on T1.id = T2.id where T2.c > 1 group by T1.id;
delete the duplicate rows by id
insert the row from the exported data.
Then add the primary key on id
If you'd prefer to do it in SQL, enter this query into the query window:
CREATE SCHEMA Test
Press CTRL + Enter to submit it, and you should see confirmation in the output pane underneath the query window. You'll have to right-click on an existing schema in the Object panel and click "Refresh All" to see it show up, though.
The source element as a jQuery object should be obtained via
var $el = $(event.target);
This gets you the source of the click, rather than the element that the click function was assigned too. Can be useful when the click event is on a parent object EG.a click event on a table row, and you need the cell that was clicked
$("tr").click(function(event){
var $td = $(event.target);
});
You are asking two separate questions here:
What's the maximum length of an HTTP GET request?
As already mentioned, HTTP itself doesn't impose any hard-coded limit on request length; but browsers have limits ranging on the 2 KB - 8 KB (255 bytes if we count very old browsers).
Is there a response error defined that the server can/should return if it receives a GET request exceeds this length?
That's the one nobody has answered.
HTTP 1.1 defines status code 414 Request-URI Too Long
for the cases where a server-defined limit is reached. You can see further details on RFC 2616.
For the case of client-defined limits, there isn't any sense on the server returning something, because the server won't receive the request at all.
For PHP 8:
sudo apt update
sudo apt-get install php8.0-soap
Can we guarantee it will not die?
As long there is no reference returned, it's perfectly fine to do so. words
will be moved to the variable receiving the result.
The local variable will go out of scope. after it was moved (or copied).
Two ways I know of:
export class SomeComponent implements OnInit
{
public localVar:any;
ngOnInit(){
this.http.get(Path).map(res => res.json()).subscribe(res => this.localVar = res);
}
}
This will assign your result into local variable once information is returned just like in a promise. Then you just do {{ localVar }}
Another Way is to get a observable as a localVariable.
export class SomeComponent
{
public localVar:any;
constructor()
{
this.localVar = this.http.get(path).map(res => res.json());
}
}
This way you're exposing a observable at which point you can do in your html is to use AsyncPipe {{ localVar | async }}
Please try it out and let me know if it works. Also, since angular 2 is pretty new, feel free to comment if something is wrong.
Hope it helps
GNU find
find /path -type f -name "*.py" -exec md5sum "{}" +;
GestureDetector.SimpleOnGestureListener has methods to help in these 3 cases;
GestureDetector gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
//for single click event.
@Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
return true;
}
//for detecting a press event. Code for drag can be added here.
@Override
public void onShowPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
ClipboardManager clipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = ClipData.newPlainText("..", "...");
clipboardManager.setPrimaryClip(clipData);
ConceptDragShadowBuilder dragShadowBuilder = new CustomDragShadowBuilder(child);
// drag child view.
child.startDrag(clipData, dragShadowBuilder, child, 0);
}
//for detecting longpress event
@Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
}
});
another version based on numpy
only
from numpy import dot
from numpy.linalg import norm
cos_sim = dot(a, b)/(norm(a)*norm(b))
Getting SOAP working usually does not require compiling PHP from source. I would recommend trying that only as a last option.
For good measure, check to see what your phpinfo says, if anything, about SOAP extensions:
$ php -i | grep -i soap
to ensure that it is the PHP extension that is missing.
Assuming you do not see anything about SOAP in the phpinfo, see what PHP SOAP packages might be available to you.
In Ubuntu/Debian you can search with:
$ apt-cache search php | grep -i soap
or in RHEL/Fedora you can search with:
$ yum search php | grep -i soap
There are usually two PHP SOAP packages available to you, usually php-soap
and php-nusoap
. php-soap
is typically what you get with configuring PHP with --enable-soap
.
In Ubuntu/Debian you can install with:
$ sudo apt-get install php-soap
Or in RHEL/Fedora you can install with:
$ sudo yum install php-soap
After the installation, you might need to place an ini file and restart Apache.
See ?merge
:
the name "row.names" or the number 0 specifies the row names.
Example:
R> de <- merge(d, e, by=0, all=TRUE) # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0 # replace NA values
R> de
Row.names a b c d e f g h i j k l m n o p q r s
1 1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2 2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 0 0 0 0 0 0 0 0 0
3 3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 21 22 23 24 25 26 27 28 29
t
1 20
2 0
3 30
I think this is the easiest way
<!-- Submit Button-->
<button
mat-raised-button
color="primary"
[disabled]="!f.valid"
>
Submit
</button>
As mentioned above it is not good idea to watch changes directly in store
But in some very rare cases it may be useful for someone, so i will leave this answer. For others cases, please see @gabriel-robert answer
You can do this through state.$watch
. Add this in your created
(or where u need this to be executed) method in component
this.$store.watch(
function (state) {
return state.my_state;
},
function () {
//do something on data change
},
{
deep: true //add this if u need to watch object properties change etc.
}
);
More details: https://vuex.vuejs.org/api/#watch
List<String> colors = new ArrayList<>(
Arrays.asList("RED", null, "BLUE", null, "GREEN"));
// using removeIf() + Objects.isNull()
colors.removeIf(Objects::isNull);
If I understand correctly, you need a regex statement that checks for at least 6 characters (letters & numbers)?
/[0-9a-zA-Z]{6,}/
Here are 2 ways(both are OS independent.)
Using Paths
: Since 1.7
Path p = Paths.get(<Absolute Path of Linux/Windows system>);
String fileName = p.getFileName().toString();
String directory = p.getParent().toString();
Using FilenameUtils
in Apache Commons IO :
String name1 = FilenameUtils.getName("/ab/cd/xyz.txt");
String name2 = FilenameUtils.getName("c:\\ab\\cd\\xyz.txt");
Select both Signature Version v1 and v2 will resolve the issue
v1 scheme
A JAR file can be signed by using the command line jarsigner tool or directly through the java.security API. Every file entry, including non-signature related files in the META-INF directory, will be signed if the JAR file is signed by the jarsigner tool. For every file entry signed in the signed JAR file, an individual manifest entry is created for it as long as it does not already exist in the manifest
V2 scheme
v1 signatures do not protect some parts of the APK, such as ZIP metadata. The APK verifier needs to process lots of untrusted (not yet verified) data structures and then discard data not covered by the signatures. This offers a sizeable attack surface. Moreover, the APK verifier must uncompress all compressed entries, consuming more time and memory. To address these issues, Android 7.0 introduced APK Signature Scheme v2
By default, Android Studio 2.2 and the Android Plugin for Gradle 2.2 sign your app using both APK Signature Scheme v2 and the traditional signing scheme, which uses JAR signing.
It is recommended to use APK Signature Scheme v2 but is not mandatory. please see the details
If updating cURL doesn't fix it, updating NSS should do the trick.
If you can get away with it, static const
has a lot of advantages. It obeys the normal scope principles, is visible in a debugger, and generally obeys the rules that variables obey.
However, at least in the original C standard, it isn't actually a constant. If you use #define var 5
, you can write int foo[var];
as a declaration, but you can't do that (except as a compiler extension" with static const int var = 5;
. This is not the case in C++, where the static const
version can be used anywhere the #define
version can, and I believe this is also the case with C99.
However, never name a #define
constant with a lowercase name. It will override any possible use of that name until the end of the translation unit. Macro constants should be in what is effectively their own namespace, which is traditionally all capital letters, perhaps with a prefix.
along with these two variants, there is also jade.renderFile
which generates html that need not be passed to the client.
usage-
var jade = require('jade');
exports.getJson = getJson;
function getJson(req, res) {
var html = jade.renderFile('views/test.jade', {some:'json'});
res.send({message: 'i sent json'});
}
getJson()
is available as a route in app.js.
Also make sure php is enabled by uncommenting the
LoadModule php5_module libexec/apache2/libphp5.so
line that comes right after
LoadModule rewrite_module libexec/apache2/mod_rewrite.so
Make sure both those lines in
/etc/apache2/httpd.conf
are uncommented.
No, you'll have to specify the authentication method to use (typically "Basic") and the authentication realm. See http://en.wikipedia.org/wiki/Basic_access_authentication for an example request and response.
You might also want to read RFC 2617 - HTTP Authentication: Basic and Digest Access Authentication.
Go to root folder
Right Click, click on Properties
Choose Tab Security
Click on Edit
Click on Add
Type 'EveryOne'
Click OK
Check Out Full Control
Click OK
The correct answer to this question has been changed by the publication of RFC 8314. As a result, port 465 and 587 are both valid ports for a mail submission agent (MSA). Port 465 requires negotiation of TLS/SSL at connection setup and port 587 uses STARTTLS if one chooses to negotiate TLS. The IANA registry was updated to allow legitimate use of port 465 for this purpose. For mail relay, only port 25 is used so STARTTLS is the only way to do TLS with mail relay. It's helpful to think of mail relay and mail submission as two very different services (with many behavior differences like requiring auth, different timeouts, different message modification rules, etc.) that happen to use a similar wire protocol.
When you define your function using this syntax:
def someFunc(*args):
for x in args
print x
You're telling it that you expect a variable number of arguments. If you want to pass in a List (Array from other languages) you'd do something like this:
def someFunc(myList = [], *args):
for x in myList:
print x
Then you can call it with this:
items = [1,2,3,4,5]
someFunc(items)
You need to define named arguments before variable arguments, and variable arguments before keyword arguments. You can also have this:
def someFunc(arg1, arg2, arg3, *args, **kwargs):
for x in args
print x
Which requires at least three arguments, and supports variable numbers of other arguments and keyword arguments.
Fastlane's sigh provides a fairly robust solution for resigning IPAs.
From their README:
Resign
If you generated your
ipa
file but want to apply a different code signing onto the ipa file, you can usesigh resign
:
fastlane sigh resign
sigh
will find the ipa file and the provisioning profile for you if they are located in the current folder.You can pass more information using the command line:
fastlane sigh resign ./path/app.ipa --signing_identity "iPhone Distribution: Felix Krause" -p "my.mobileprovision"
It will even handle provisioning profiles for nested applications (eg. if you have watchkit apps)
Git and DVCS in general is great for developers doing a lot of coding independently of each other because everyone has their own branch. If you need a change from someone else, though, she has to commit to her local repo and then she must push that changeset to you or you must pull it from her.
My own reasoning also makes me think DVCS makes things harder for QA and release management if you do things like centralized releases. Someone has to be responsible for doing that push/pull from everyone else's repository, resolving any conflicts that would have been resolved at initial commit time before, then doing the build, and then having all the other developers re-sync their repos.
All of this can be addressed with human processes, of course; DVCS just broke something that was fixed by centralized version control in order to provide some new conveniences.
You should escape the forward slash too, here is the correct JSON:
[{
"id": "services.html",
"img": "img/SolutionInnerbananer.jpg",
"html": "<h2class=\"fg-white\">AboutUs<\/h2><pclass=\"fg-white\">developing and supporting complex IT solutions.Touchingmillions of lives world wide by bringing in innovative technology <\/p>"
}]
I Hope this is Helpfull
Step 1: App.js is (main module) import the Login Module
import React, { Component } from 'react';
import './App.css';
import Login from './login/login';
class App extends Component {
render() {
return (
<Login />
);
}
}
export default App;
Step 2: Create Login Folder and create login.js file and customize your needs it automatically render to App.js Example Login.js
import React, { Component } from 'react';
import '../login/login.css';
class Login extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default Login;
I like jjvainio's answer. As Zan Lnyx says, it uses the local routing table to find the IP address of the ethernet interface that would be used for a connection to a specific external host. By using a connected UDP socket, you can get the information without actually sending any packets. The approach requires that you choose a specific external host. Most of the time, any well-known public IP should do the trick. I like Google's public DNS server address 8.8.8.8 for this purpose, but there may be times you'd want to choose a different external host IP. Here is some code that illustrates the full approach.
void GetPrimaryIp(char* buffer, size_t buflen)
{
assert(buflen >= 16);
int sock = socket(AF_INET, SOCK_DGRAM, 0);
assert(sock != -1);
const char* kGoogleDnsIp = "8.8.8.8";
uint16_t kDnsPort = 53;
struct sockaddr_in serv;
memset(&serv, 0, sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = inet_addr(kGoogleDnsIp);
serv.sin_port = htons(kDnsPort);
int err = connect(sock, (const sockaddr*) &serv, sizeof(serv));
assert(err != -1);
sockaddr_in name;
socklen_t namelen = sizeof(name);
err = getsockname(sock, (sockaddr*) &name, &namelen);
assert(err != -1);
const char* p = inet_ntop(AF_INET, &name.sin_addr, buffer, buflen);
assert(p);
close(sock);
}
Without a nicer solution, what I found to work is simply building my query string in the bean return:
public String submit() {
// Do something
return "/page2.xhtml?faces-redirect=true&id=" + id;
}
Not the most flexible of solutions, but seems to work how I want it to.
Also using this approach to clean up the process of building the query string: http://www.warski.org/blog/?p=185
You should use the os.Stat()
and os.IsNotExist()
functions as in the following example:
// Exists reports whether the named file or directory exists.
func Exists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
The example is extracted from here.
byte[] bytes = new byte[100];
Initializes all byte elements with default values, which for byte is 0. In fact, all elements of an array when constructed, are initialized with default values for the array element's type.
You can implement your OTF
font using @font-face like:
@font-face {
font-family: GraublauWeb;
src: url("path/GraublauWeb.otf") format("opentype");
}
@font-face {
font-family: GraublauWeb;
font-weight: bold;
src: url("path/GraublauWebBold.otf") format("opentype");
}
// Edit: OTF now works in most browsers, see comments
However if you want to support a wide variety of browsers i would recommend you to switch to WOFF
and TTF
font types. WOFF
type is implemented by every major desktop browser, while the TTF
type is a fallback for older Safari, Android and iOS browsers. If your font is a free font, you could convert your font using for example a transfonter.
@font-face {
font-family: GraublauWeb;
src: url("path/GraublauWebBold.woff") format("woff"), url("path/GraublauWebBold.ttf") format("truetype");
}
If you want to support nearly every browser that is still out there (not necessary anymore IMHO), you should add some more font-types like:
@font-face {
font-family: GraublauWeb;
src: url("webfont.eot"); /* IE9 Compat Modes */
src: url("webfont.eot?#iefix") format("embedded-opentype"), /* IE6-IE8 */
url("webfont.woff") format("woff"), /* Modern Browsers */
url("webfont.ttf") format("truetype"), /* Safari, Android, iOS */
url("webfont.svg#svgFontName") format("svg"); /* Legacy iOS */
}
You can read more about why all these types are implemented and their hacks here. To get a detailed view of which file-types are supported by which browsers, see:
hope this helps
How about using unique()
itself?
df <- data.frame(yad = c("BARBIE", "BARBIE", "BAKUGAN", "BAKUGAN"),
per = c("AYLIK", "AYLIK", "2 AYLIK", "2 AYLIK"),
hmm = 1:4)
df
# yad per hmm
# 1 BARBIE AYLIK 1
# 2 BARBIE AYLIK 2
# 3 BAKUGAN 2 AYLIK 3
# 4 BAKUGAN 2 AYLIK 4
unique(df[c("yad", "per")])
# yad per
# 1 BARBIE AYLIK
# 3 BAKUGAN 2 AYLIK
pd.Series.mode
is available!Use groupby
, GroupBy.agg
, and apply the pd.Series.mode
function to each group:
source.groupby(['Country','City'])['Short name'].agg(pd.Series.mode)
Country City
Russia Sankt-Petersburg Spb
USA New-York NY
Name: Short name, dtype: object
If this is needed as a DataFrame, use
source.groupby(['Country','City'])['Short name'].agg(pd.Series.mode).to_frame()
Short name
Country City
Russia Sankt-Petersburg Spb
USA New-York NY
The useful thing about Series.mode
is that it always returns a Series, making it very compatible with agg
and apply
, especially when reconstructing the groupby output. It is also faster.
# Accepted answer.
%timeit source.groupby(['Country','City']).agg(lambda x:x.value_counts().index[0])
# Proposed in this post.
%timeit source.groupby(['Country','City'])['Short name'].agg(pd.Series.mode)
5.56 ms ± 343 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
2.76 ms ± 387 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Series.mode
also does a good job when there are multiple modes:
source2 = source.append(
pd.Series({'Country': 'USA', 'City': 'New-York', 'Short name': 'New'}),
ignore_index=True)
# Now `source2` has two modes for the
# ("USA", "New-York") group, they are "NY" and "New".
source2
Country City Short name
0 USA New-York NY
1 USA New-York New
2 Russia Sankt-Petersburg Spb
3 USA New-York NY
4 USA New-York New
source2.groupby(['Country','City'])['Short name'].agg(pd.Series.mode)
Country City
Russia Sankt-Petersburg Spb
USA New-York [NY, New]
Name: Short name, dtype: object
Or, if you want a separate row for each mode, you can use GroupBy.apply
:
source2.groupby(['Country','City'])['Short name'].apply(pd.Series.mode)
Country City
Russia Sankt-Petersburg 0 Spb
USA New-York 0 NY
1 New
Name: Short name, dtype: object
If you don't care which mode is returned as long as it's either one of them, then you will need a lambda that calls mode
and extracts the first result.
source2.groupby(['Country','City'])['Short name'].agg(
lambda x: pd.Series.mode(x)[0])
Country City
Russia Sankt-Petersburg Spb
USA New-York NY
Name: Short name, dtype: object
You can also use statistics.mode
from python, but...
source.groupby(['Country','City'])['Short name'].apply(statistics.mode)
Country City
Russia Sankt-Petersburg Spb
USA New-York NY
Name: Short name, dtype: object
...it does not work well when having to deal with multiple modes; a StatisticsError
is raised. This is mentioned in the docs:
If data is empty, or if there is not exactly one most common value, StatisticsError is raised.
But you can see for yourself...
statistics.mode([1, 2])
# ---------------------------------------------------------------------------
# StatisticsError Traceback (most recent call last)
# ...
# StatisticsError: no unique mode; found 2 equally common values
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyClass
{
public static void main(String args[])
{
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
String dateInString = "Wed Mar 14 15:30:00 EET 2018";
SimpleDateFormat formatterOut = new SimpleDateFormat("dd MMM yyyy");
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatterOut.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
here is your Date object date and the output is :
Wed Mar 14 13:30:00 UTC 2018
14 Mar 2018
You can make an empty commit with git commit --allow-empty
, but that will not allow you to commit an empty folder structure as git does not know or care about folders as objects themselves -- just the files they contain.
I firstly made my own version and then found this topic.
Why does my version look simpler than others presented here? Am I doing something wrong? I didn't test it for speed.
inline char const* b64units = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
inline char* b64encode(void const* a, int64_t b) {
ASSERT(a != nullptr);
if (b > 0) {
uint8_t const* aa = static_cast<uint8_t const*>(a);
uint8_t v = 0;
int64_t bp = 0;
int64_t sb = 0;
int8_t off = 0;
int64_t nt = ((b + 2) / 3) * 4;
int64_t nd = (b * 8) / 6;
int64_t tl = ((b * 8) % 6) ? 1 : 0;
int64_t nf = nt - nd - tl;
int64_t ri = 0;
char* r = new char[nt + 1]();
for (int64_t i = 0; i < nd; i++) {
v = (aa[sb] << off) | (aa[sb + 1] >> (8 - off));
v >>= 2;
r[ri] = b64units[v];
ri += 1;
bp += 6;
sb = (bp / 8);
off = (bp % 8);
}
if (tl > 0) {
v = (aa[sb] << off);
v >>= 2;
r[ri] = b64units[v];
ri += 1;
}
for (int64_t i = 0; i < nf; i++) {
r[ri] = '=';
ri += 1;
}
return r;
} else return nullptr;
}
P.S.: My method works well. I tested it with Node.js:
let data = 'stackabuse.com';
let buff = new Buffer(data);
let base64data = buff.toString('base64');
Linked lists are preferable over arrays when:
you need constant-time insertions/deletions from the list (such as in real-time computing where time predictability is absolutely critical)
you don't know how many items will be in the list. With arrays, you may need to re-declare and copy memory if the array grows too big
you don't need random access to any elements
you want to be able to insert items in the middle of the list (such as a priority queue)
Arrays are preferable when:
you need indexed/random access to elements
you know the number of elements in the array ahead of time so that you can allocate the correct amount of memory for the array
you need speed when iterating through all the elements in sequence. You can use pointer math on the array to access each element, whereas you need to lookup the node based on the pointer for each element in linked list, which may result in page faults which may result in performance hits.
memory is a concern. Filled arrays take up less memory than linked lists. Each element in the array is just the data. Each linked list node requires the data as well as one (or more) pointers to the other elements in the linked list.
Array Lists (like those in .Net) give you the benefits of arrays, but dynamically allocate resources for you so that you don't need to worry too much about list size and you can delete items at any index without any effort or re-shuffling elements around. Performance-wise, arraylists are slower than raw arrays.
>>> txt = '7061756c'
>>> ''.join([chr(int(''.join(c), 16)) for c in zip(txt[0::2],txt[1::2])])
'paul'
i'm just having fun, but the important parts are:
>>> int('0a',16) # parse hex
10
>>> ''.join(['a', 'b']) # join characters
'ab'
>>> 'abcd'[0::2] # alternates
'ac'
>>> zip('abc', '123') # pair up
[('a', '1'), ('b', '2'), ('c', '3')]
>>> chr(32) # ascii to character
' '
will look at binascii now...
>>> print binascii.unhexlify('7061756c')
paul
cool (and i have no idea why other people want to make you jump through hoops before they'll help).
This is my version of a bash script. It takes database name as a parameter and converts all tables to another charset and collation (given by another parameters or default value defined in the script).
#!/bin/bash
# mycollate.sh <database> [<charset> <collation>]
# changes MySQL/MariaDB charset and collation for one database - all tables and
# all columns in all tables
DB="$1"
CHARSET="$2"
COLL="$3"
[ -n "$DB" ] || exit 1
[ -n "$CHARSET" ] || CHARSET="utf8mb4"
[ -n "$COLL" ] || COLL="utf8mb4_general_ci"
echo $DB
echo "ALTER DATABASE $DB CHARACTER SET $CHARSET COLLATE $COLL;" | mysql
echo "USE $DB; SHOW TABLES;" | mysql -s | (
while read TABLE; do
echo $DB.$TABLE
echo "ALTER TABLE $TABLE CONVERT TO CHARACTER SET $CHARSET COLLATE $COLL;" | mysql $DB
done
)
There is a lot of confusion on this topic because there are so many different ways to do it.
Here are the appropriate types used in the following screen shots:
private route: ActivatedRoute
private router: Router
1) Required Routing Parameters:
2) Route Optional Parameters:
3) Route Query Parameters:
4) You can use a service to pass data from one component to another without using route parameters at all.
For an example see: https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/
I have a plunker of this here: https://plnkr.co/edit/KT4JLmpcwGBM2xdZQeI9?p=preview
Use the ampersand just like you would from the shell.
#!/usr/bin/bash
function_to_fork() {
...
}
function_to_fork &
# ... execution continues in parent process ...
I had an issue with margin and padding with a Button
. I added Button inside a View
component and apply your properties to the View
.
<View style={{margin:10}}>
<Button
title="Decrypt Data"
color="orange"
accessibilityLabel="Tap to Decrypt Data"
onPress={() => {
Alert.alert('You tapped the Decrypt button!');
}}
/>
</View>
A similar error can occur, when you didn't give a valid client certificate and token that your server understands:
Error:
Http failure response for (unknown url): 0 Unknown Error
Example code:
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
class MyCls1 {
constructor(private http: HttpClient) {
}
public myFunc(): void {
let http: HttpClient;
http.get(
'https://www.example.com/mypage',
{
headers:
new HttpHeaders(
{
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'MyClientCert': '', // This is empty
'MyToken': '' // This is empty
}
)
}
).pipe( map(res => res), catchError(err => throwError(err)) );
}
}
Note that both MyClientCert
& MyToken
are empty strings, hence the error.
MyClientCert
& MyToken
can be any name that your server understands.
There's no reason I can come up with that it shouldn't be possible to do through an attribute. It might be in Microsoft's backlog. Who knows.
The best solution I have found is to use the defaultValueSql parameter in the code first migration.
CreateTable(
"dbo.SomeTable",
c => new
{
TheDateField = c.DateTime(defaultValueSql: "GETDATE()")
});
I don't like the often reference solution of setting it in the entity class constructor because if anything other than Entity Framework sticks a record in that table, the date field won't get a default value. And the idea of using a trigger to handle that case just seems wrong to me.
In IIS 8.5/ Windows 2012R2, Nothing mentioned here worked for me. I don't know what is meant by Removing WebDAV but that didn't solve the issue for me.
What helped me is the below steps;
Now everything is working.
RealProxy lets you create your own proxies for existing types.
This is super-advanced and I haven't seen anyone else use it -- which may mean that it's also really not that useful for most folks -- but it's one of those things that's good to know.
Basically, the .NET RealProxy class lets you create what is called a transparent proxy to another type. Transparent in this case means that it looks completely like the proxied target object to its client -- but it's really not: it's an instance of your class, which is derived from RealProxy.
This lets you apply powerful and comprehensive interception and "intermediation" services between the client and any methods or properties invoked on the real target object. Couple this power with the factory pattern (IoC etc), and you can hand back transparent proxies instead of real objects, allowing you to intercept all calls to the real objects and perform actions before and after each method invocation. In fact, I believe this is the very functionality .NET uses for remoting across app domain, process, and machine boundaries: .NET intercepts all access, sends serialized info to the remote object, receives the response, and returns it to your code.
Maybe an example will make it clear how this can be useful: I created a reference service stack for my last job as enterprise architect which specified the standard internal composition (the "stack") of any new WCF services across the division. The model mandated that the data access layer for (say) the Foo service implement IDAL<Foo>:
create a Foo, read a Foo, update a Foo, delete a Foo. Service developers used supplied common code (from me) that would locate and load the required DAL for a service:
IDAL<T> GetDAL<T>(); // retrieve data access layer for entity T
Data access strategies in that company had often been, well, performance-challenged. As an architect, I couldn't watch over every service developer to make sure that he/she wrote a performant data access layer. But what I could do within the GetDAL factory pattern was create a transparent proxy to the requested DAL (once the common service model code located the DLL and loaded it), and use high-performance timing APIs to profile all calls to any method of the DAL. Ranking laggards then is just a matter of sorting DAL call timings by descending total time. The advantage to this over development profiling (e.g. in the IDE) is that it can be done in the production environment as well, to ensure SLAs.
Here is an example of test code I wrote for the "entity profiler," which was common code to create a profiling proxy for any type with a single line:
[Test, Category("ProfileEntity")]
public void MyTest()
{
// this is the object that we want profiled.
// we would normally pass this around and call
// methods on this instance.
DALToBeProfiled dal = new DALToBeProfiled();
// To profile, instead we obtain our proxy
// and pass it around instead.
DALToBeProfiled dalProxy = (DALToBeProfiled)EntityProfiler.Instance(dal);
// or...
DALToBeProfiled dalProxy2 = EntityProfiler<DALToBeProfiled>.Instance(dal);
// Now use proxy wherever we would have used the original...
// All methods' timings are automatically recorded
// with a high-resolution timer
DoStuffToThisObject(dalProxy);
// Output profiling results
ProfileManager.Instance.ToConsole();
}
Again, this lets you intercept all methods and properties called by the client on the target object! In your RealProxy-derived class, you have to override Invoke:
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[SecurityPermission(SecurityAction.LinkDemand,
Flags = SecurityPermissionFlag.Infrastructure)] // per FxCop
public override IMessage Invoke(IMessage msg)
{
IMethodCallMessage msgMethodCall = msg as IMethodCallMessage;
Debug.Assert(msgMethodCall != null); // should not be null - research Invoke if this trips. KWB 2009.05.28
// The MethodCallMessageWrapper
// provides read/write access to the method
// call arguments.
MethodCallMessageWrapper mc =
new MethodCallMessageWrapper(msgMethodCall);
// This is the reflected method base of the called method.
MethodInfo mi = (MethodInfo)mc.MethodBase;
IMessage retval = null;
// Pass the call to the method and get our return value
string profileName = ProfileClassName + "." + mi.Name;
using (ProfileManager.Start(profileName))
{
IMessage myReturnMessage =
RemotingServices.ExecuteMessage(_target, msgMethodCall);
retval = myReturnMessage;
}
return retval;
}
Isn't it fascinating what .NET can do? The only restriction is that the target type must be derived from MarshalByRefObject. I hope this is helpful to someone.
Here is a list of all http-headers: http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
And here is a list of all apache-logformats: http://httpd.apache.org/docs/2.0/mod/mod_log_config.html#formats
As you did write correctly, the code for logging a specific header is %{foobar}i where foobar is the name of the header. So, the only solution is to create a specific format string. When you expect a non-standard header like x-my-nonstandard-header, then use %{x-my-nonstandard-header}i
. If your server is going to ignore this non-standard-header, why should you want to write it to your logfile? An unknown header has absolutely no effect to your system.
The shortest way is indeed just
String fileContents = new File('/path/to/file').text
but in this case you have no control on how the bytes in the file are interpreted as characters. AFAIK groovy tries to guess the encoding here by looking at the file content.
If you want a specific character encoding you can specify a charset name with
String fileContents = new File('/path/to/file').getText('UTF-8')
See API docs on File.getText(String)
for further reference.
If your subplots also have titles, you may need to adjust the main title size:
plt.suptitle("Main Title", size=16)
syntax is:
sheet.addMergedRegion(new CellRangeAddress(start-col,end-col,start-cell,end-cell));
Example:
sheet.addMergedRegion(new CellRangeAddress(4, 4, 0, 5));
Here the cell 0 to cell 5 will be merged of the 4th row.
Best answer doesn't work for me. I needed ssh://
from the beggining.
# does not work
git remote set-url origin [email protected]:10000/aaa/bbbb/ccc.git
# work
git remote set-url origin ssh://[email protected]:10000/aaa/bbbb/ccc.git
I follow all recommendations and all requirements. I install my self signed root CA on my iPhone. I make it trusted. I put certificate signed with this root CA on my local development server and I still get certificated error on safari iOS. Working on all other platforms.
You could try the following
select case when mydatetime IS NULL THEN '' else convert(varchar(20),@mydatetime,120) end as converted_date from sometable
-- Testing it out could do --
declare @mydatetime datetime
set @mydatetime = GETDATE() -- comment out for null value
--set @mydatetime = GETDATE()
select
case when @mydatetime IS NULL THEN ''
else convert(varchar(20),@mydatetime,120)
end as converted_date
Hope this helps!
Actually its very simple to access window object here is my basic component and i tested it its working
import { Component, OnInit,Inject } from '@angular/core';
import {DOCUMENT} from '@angular/platform-browser';
@Component({
selector: 'app-verticalbanners',
templateUrl: './verticalbanners.component.html',
styleUrls: ['./verticalbanners.component.css']
})
export class VerticalbannersComponent implements OnInit {
constructor(){ }
ngOnInit() {
console.log(window.innerHeight );
}
}
If adding your module folder to the PYTHONPATH didn't work, You can modify the sys.path list in your program where the Python interpreter searches for the modules to import, the python documentation says:
When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:
- the directory containing the input script (or the current directory).
- PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
- the installation-dependent default.
After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended.
Knowing this, you can do the following in your program:
import sys
# Add the ptdraft folder path to the sys.path list
sys.path.append('/path/to/ptdraft/')
# Now you can import your module
from ptdraft import nib
# Or just
import ptdraft
The existing answers are all good stuff, but I wanted to share one more little gem that has been valuable in debugging tricky precision issues in a GLSL shader. With very large int numbers represented as a floating point, one needs to take care to use floor(n) and floor(n + 0.5) properly to implement round() to an exact int. It is then possible to render a float value that is an exact int by the following logic to pack the byte components into R, G, and B output values.
// Break components out of 24 bit float with rounded int value
// scaledWOB = (offset >> 8) & 0xFFFF
float scaledWOB = floor(offset / 256.0);
// c2 = (scaledWOB >> 8) & 0xFF
float c2 = floor(scaledWOB / 256.0);
// c0 = offset - (scaledWOB << 8)
float c0 = offset - floor(scaledWOB * 256.0);
// c1 = scaledWOB - (c2 << 8)
float c1 = scaledWOB - floor(c2 * 256.0);
// Normalize to byte range
vec4 pix;
pix.r = c0 / 255.0;
pix.g = c1 / 255.0;
pix.b = c2 / 255.0;
pix.a = 1.0;
gl_FragColor = pix;
To add to the above answers, there's a good article: Useful JVM Flags – Part 8 (GC Logging) by Patrick Peschlow.
A brief excerpt:
The flag -XX:+PrintGC
(or the alias -verbose:gc
) activates the “simple” GC logging mode
By default the GC log is written to stdout. With -Xloggc:<file>
we may instead specify an output file. Note that this flag implicitly sets -XX:+PrintGC
and -XX:+PrintGCTimeStamps
as well.
If we use -XX:+PrintGCDetails
instead of -XX:+PrintGC
, we activate the “detailed” GC logging mode which differs depending on the GC algorithm used.
With -XX:+PrintGCTimeStamps
a timestamp reflecting the real time passed in seconds since JVM start is added to every line.
If we specify -XX:+PrintGCDateStamps
each line starts with the absolute date and time.
It's a LOT easier just to do it from within Excel.!! Open Excel Data>Import/Export Data>Import Data Next to file name click "New Source" Button On Welcome to the Data Connection Wizard, choose Microsoft SQL Server. Click Next. Enter Server Name and Credentials. From the drop down, choose whichever database holds the table you need. Select your table then Next..... Enter a Description if you'd like and click Finish. When your done and back in Excel, just click "OK" Easy.
I suggest this discriminative question:
Is the open-source tool necessary in your process of making money?
Oracle would be
SELECT NVL(MAX(X), 0) AS MaxX
FROM tbl
WHERE XID = 1;
Try putting the call to axis
after all plotting commands.
In my case, I had a similar issue after full installation of Debian 10.
Commandline:
php -v
show I am using php7.4
but print phpinfo()
gives me php7.3
Solution: Disable php7.3 Enable php7.4
$ a2dismod php7.3
$ a2enmod php7.4
$ update-alternatives --set php /usr/bin/php7.4
$ update-alternatives --set phar /usr/bin/phar7.4
$ update-alternatives --set phar.phar /usr/bin/phar.phar7.4
$ update-alternatives --set phpize /usr/bin/phpize7.4
$ update-alternatives --set php-config /usr/bin/php-config7.4
Use different format or pattern to get the information from the date
var myDate = new Date("2015-06-17 14:24:36");_x000D_
console.log(moment(myDate).format("YYYY-MM-DD HH:mm:ss"));_x000D_
console.log("Date: "+moment(myDate).format("YYYY-MM-DD"));_x000D_
console.log("Year: "+moment(myDate).format("YYYY"));_x000D_
console.log("Month: "+moment(myDate).format("MM"));_x000D_
console.log("Month: "+moment(myDate).format("MMMM"));_x000D_
console.log("Day: "+moment(myDate).format("DD"));_x000D_
console.log("Day: "+moment(myDate).format("dddd"));_x000D_
console.log("Time: "+moment(myDate).format("HH:mm")); // Time in24 hour format_x000D_
console.log("Time: "+moment(myDate).format("hh:mm A"));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
For more info: https://momentjs.com/docs/#/parsing/string-format/
To add to @migontech's answer and also his address his comment that you could "probably make it more generic", here's a way to do it. The below will allow you to search by any property:
.filter('getByProperty', function() {
return function(propertyName, propertyValue, collection) {
var i=0, len=collection.length;
for (; i<len; i++) {
if (collection[i][propertyName] == +propertyValue) {
return collection[i];
}
}
return null;
}
});
The call to filter would then become:
var found = $filter('getByProperty')('id', fish_id, $scope.fish);
Note, I removed the unary(+) operator to allow for string-based matches...
If you prefer to use pure Node.js then you might extract POST data like it is shown below:
// Dependencies_x000D_
const StringDecoder = require('string_decoder').StringDecoder;_x000D_
const http = require('http');_x000D_
_x000D_
// Instantiate the HTTP server._x000D_
const httpServer = http.createServer((request, response) => {_x000D_
// Get the payload, if any._x000D_
const decoder = new StringDecoder('utf-8');_x000D_
let payload = '';_x000D_
_x000D_
request.on('data', (data) => {_x000D_
payload += decoder.write(data);_x000D_
});_x000D_
_x000D_
request.on('end', () => {_x000D_
payload += decoder.end();_x000D_
_x000D_
// Parse payload to object._x000D_
payload = JSON.parse(payload);_x000D_
_x000D_
// Do smoething with the payload...._x000D_
});_x000D_
};_x000D_
_x000D_
// Start the HTTP server._x000D_
const port = 3000;_x000D_
httpServer.listen(port, () => {_x000D_
console.log(`The server is listening on port ${port}`);_x000D_
});
_x000D_
You need to set android:exported="true"
in your AndroidManifest.xml
file where you declare this Activity
:
<activity
android:name="com.example.lib.MainActivity"
android:label="LibMain"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" >
</action>
</intent-filter>
</activity>
Class org.apache.commons.lang3.CharEncoding.UTF_8
is deprecated after Java 7 introduced java.nio.charset.StandardCharsets
git log origin/master..master
or, more generally:
git log <since>..<until>
You can use this with grep to check for a specific, known commit:
git log <since>..<until> | grep <commit-hash>
Or you can also use git-rev-list to search for a specific commit:
git rev-list origin/master | grep <commit-hash>
It's all about programmer convenience. I can imagine writing quick and dirty programs with this object.
I don't think there is another way other than assigning value to that particular index of that array.
The best way is to use mpack!
mpack -s "Subject" -d "./body.txt" "././image.png" mailadress
mpack - subject - body - attachment - mailadress
I was getting this error on Vue 3. It was because defineComponent
must be imported like this:
<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
name: "HelloWorld",
props: {
msg: String,
},
created() {
this.testF();
},
methods: {
testF() {
console.log("testF");
},
},
});
</script>
Just to include new Python f String compatible functionality:
var_a = 10
f"""This is my quoted variable: "{var_a}". """
UPDATED:
TO NOT HAVE ANY
b
and quotes at first and endHow to convert
bytes
as seen to strings, even in weird situations.
As your code may have unrecognizable characters to 'utf-8'
encoding,
it's better to use just str without any additional parameters:
some_bad_bytes = b'\x02-\xdfI#)'
text = str( some_bad_bytes )[2:-1]
print(text)
Output: \x02-\xdfI
if you add 'utf-8'
parameter, to these specific bytes, you should receive error.
As PYTHON 3 standard says, text
would be in utf-8 now with no concern.
So that you don't mess up other permissions already on the file, use the flag +
, such as via
sudo chmod -R o+rw /var/www
If you copy any files across to a solution, make sure the files are not in Read Only mode. Right click on file and uncheck the attribute option solved my problem.
I like Çagatay's solution, but I the popups were not hiding on mouseout. I added this extra functionality with this:
// hides the popup
$('*[data-poload]').bind('mouseout',function(){
var e=$(this);
e.popover('hide');
});
There is nothing "dirty" about using try-except clause. This is the pythonic way. ValueError
will be raised by the .index
method only, because it's the only code you have there!
To answer the comment:
In Python, easier to ask forgiveness than to get permission philosophy is well established, and no index
will not raise this type of error for any other issues. Not that I can think of any.
git rev-parse --show-toplevel
could be enough if executed within a git repo.
From git rev-parse
man page:
--show-toplevel
Show the absolute path of the top-level directory.
For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":
git rev-parse --git-dir
That would give the path of the .git
directory.
The OP mentions:
git rev-parse --show-prefix
which returns the local path under the git repo root. (empty if you are at the git repo root)
Note: for simply checking if one is in a git repo, I find the following command quite expressive:
git rev-parse --is-inside-work-tree
And yes, if you need to check if you are in a .git
git-dir folder:
git rev-parse --is-inside-git-dir
MacOS High Sierra is very crazy to update openssl command suddenly.
Possible in last month:
$ openssl pkcs12 -in cert.p12 -out cert.pem -nodes -clcerts
MAC verified OK
But now:
$ openssl pkcs12 -in cert.p12 -out cert.pem -nodes -clcerts -password pass:
MAC verified OK
you can only focus required textbox an insert the text there. there is no way to find out where focus is AFAIK (maybe interating over all DOM nodes?).
check this stackoverflow - it has a solution for you: How do I find out which DOM element has the focus?
Pass the string and replace space with line break, it gives you desired result.
select replace('shailendra kumar',' ',chr(10)) from dual;
Adding Git to Windows 7/8/8.1 Path
Note: You must have msysgit installed on your machine. Also, the path to my Git installation is "C:\Program Files (x86)\Git". Yours might be different. Please check where yours is before continuing.
Open the Windows Environment Variables/Path Window.
Add the pwd to Git's binary and cmd at the end of the string like this:
;%PROGRAMFILES(x86)%\Git\bin;%PROGRAMFILES(x86)%\Git\cmd
Now test it out in PowerShell. Type git
and see if it recognizes the command.
Source: Adding Git to Windows 7 Path
You can try
#include <iostream>
#include <conio.h>
int main() {
//some codes
getch();
return 0;
}
Just add this method to the base class
public abstract class clsAbstractTable {
public abstract String getTAG();
public abstract void init();
}
Now every class that extends the base class (and does not want to be abstract) should provide a TAG
You could also go with BalusC's answer
You could take your entire server-side model and turn it into a Javascript object by doing the following:
var model = @Html.Raw(Json.Encode(Model));
In your case if you just want the FloorPlanSettings object, simply pass the Encode
method that property:
var floorplanSettings = @Html.Raw(Json.Encode(Model.FloorPlanSettings));
Adding to the answers above -
To use in a script, use the following :-
result=`ps aux | grep -i "myscript.sh" | grep -v "grep" | wc -l`
if [ $result -ge 1 ]
then
echo "script is running"
else
echo "script is not running"
fi
I have used NuSOAP in the past. I liked it because it is just a set of PHP files that you can include. There is nothing to install on the web server and no config options to change. It has WSDL support as well which is a bonus.
The other two answers are correct. When you include spaces in your CSS selectors you're targeting child elements so:
.form-group .required {
styles
}
Is targeting an element with the class of "required" that is inside an element with the class of "form-group".
Without the space it's targeting an element that has both classes. 'required' and 'form-group'
I think I have a simpler solution here. Just look for a directory whose name corresponds to the PID you are looking for, under the pseudo-filesystem accessible under the /proc
path. So if you have a program running, whose ID is 1199, cd
into it:
$ cd /proc/1199
Then look for the fd
directory underneath
$ cd fd
This fd
directory hold the file-descriptors objects that your program is using (0: stdin, 1: stdout, 2: stderr) and just tail -f
the one you need - in this case, stdout):
$ tail -f 1
You are to use something like this:
start /d C:\Windows\System32\calc.exe
start /d "C:\Program Files\Mozilla
Firefox" firefox.exe start /d
"C:\Program Files\Microsoft
Office\Office12" EXCEL.EXE
Also I advice you to use special batch files editor - Dr.Batcher
This can be done using the read() method :
text_as_string = open('Your_Text_File.txt', 'r').read()
Or as the default mode itself is 'r' (read) so simply use,
text_as_string = open('Your_Text_File.txt').read()
For anything with requests to URLs you might want to check out requests. For JSON in particular:
>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
Modern browsers implement something known as back-forward cache (BFCache). When you hit back/forward button the actual page is not reloaded (and the scripts are never re-run).
If you have to do something in case of user hitting back/forward keys - listen for BFCache pageshow
and pagehide
events:
window.addEventListener("pageshow", () => {
// update hidden input field
});
Peer to SamGoody and Lego Stormtroopr comments.
If you are looking for a PHP algorithm to rank search results based on proximity/relevance of multiple words here comes a quick and easy way of generating search results with PHP only:
Issues with the other boolean search methods such as strpos()
, preg_match()
, strstr()
or stristr()
PHP method based on Vector Space Model and tf-idf (term frequency–inverse document frequency):
It sounds difficult but is surprisingly easy.
If we want to search for multiple words in a string the core problem is how we assign a weight to each one of them?
If we could weight the terms in a string based on how representative they are of the string as a whole, we could order our results by the ones that best match the query.
This is the idea of the vector space model, not far from how SQL full-text search works:
function get_corpus_index($corpus = array(), $separator=' ') {
$dictionary = array();
$doc_count = array();
foreach($corpus as $doc_id => $doc) {
$terms = explode($separator, $doc);
$doc_count[$doc_id] = count($terms);
// tf–idf, short for term frequency–inverse document frequency,
// according to wikipedia is a numerical statistic that is intended to reflect
// how important a word is to a document in a corpus
foreach($terms as $term) {
if(!isset($dictionary[$term])) {
$dictionary[$term] = array('document_frequency' => 0, 'postings' => array());
}
if(!isset($dictionary[$term]['postings'][$doc_id])) {
$dictionary[$term]['document_frequency']++;
$dictionary[$term]['postings'][$doc_id] = array('term_frequency' => 0);
}
$dictionary[$term]['postings'][$doc_id]['term_frequency']++;
}
//from http://phpir.com/simple-search-the-vector-space-model/
}
return array('doc_count' => $doc_count, 'dictionary' => $dictionary);
}
function get_similar_documents($query='', $corpus=array(), $separator=' '){
$similar_documents=array();
if($query!=''&&!empty($corpus)){
$words=explode($separator,$query);
$corpus=get_corpus_index($corpus, $separator);
$doc_count=count($corpus['doc_count']);
foreach($words as $word) {
if(isset($corpus['dictionary'][$word])){
$entry = $corpus['dictionary'][$word];
foreach($entry['postings'] as $doc_id => $posting) {
//get term frequency–inverse document frequency
$score=$posting['term_frequency'] * log($doc_count + 1 / $entry['document_frequency'] + 1, 2);
if(isset($similar_documents[$doc_id])){
$similar_documents[$doc_id]+=$score;
}
else{
$similar_documents[$doc_id]=$score;
}
}
}
}
// length normalise
foreach($similar_documents as $doc_id => $score) {
$similar_documents[$doc_id] = $score/$corpus['doc_count'][$doc_id];
}
// sort from high to low
arsort($similar_documents);
}
return $similar_documents;
}
CASE 1
$query = 'are';
$corpus = array(
1 => 'How are you?',
);
$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
print_r($match_results);
echo '</pre>';
RESULT
Array
(
[1] => 0.52832083357372
)
CASE 2
$query = 'are';
$corpus = array(
1 => 'how are you today?',
2 => 'how do you do',
3 => 'here you are! how are you? Are we done yet?'
);
$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
print_r($match_results);
echo '</pre>';
RESULTS
Array
(
[1] => 0.54248125036058
[3] => 0.21699250014423
)
CASE 3
$query = 'we are done';
$corpus = array(
1 => 'how are you today?',
2 => 'how do you do',
3 => 'here you are! how are you? Are we done yet?'
);
$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
print_r($match_results);
echo '</pre>';
RESULTS
Array
(
[3] => 0.6813781191217
[1] => 0.54248125036058
)
There are plenty of improvements to be made
but the model provides a way of getting good results from natural queries,
which don't have boolean operators such as strpos()
, preg_match()
, strstr()
or stristr()
.
NOTA BENE
Optionally eliminating redundancy prior to search the words
thereby reducing index size and resulting in less storage requirement
less disk I/O
faster indexing and a consequently faster search.
1. Normalisation
2. Stopword elimination
3. Dictionary substitution
Replace words with others which have an identical or similar meaning. (ex:replace instances of 'hungrily' and 'hungry' with 'hunger')
Further algorithmic measures (snowball) may be performed to further reduce words to their essential meaning.
The replacement of colour names with their hexadecimal equivalents
The reduction of numeric values by reducing precision are other ways of normalising the text.
RESOURCES
# Switch rewrite engine off in case this was installed under HostPay.
RewriteEngine Off
SetEnv DEFAULT_PHP_VERSION 7
DirectoryIndex index.cgi index.php
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
# RewriteCond %{HTTP_HOST} ^compasscommunity.co.uk\.com$ [NC]
# RewriteRule ^(.*)$ https://www.compasscommunity.co.uk/$1 [L,R=301]
in mvc 5
@Html.EditorFor(x => x.Address,
new {htmlAttributes = new {@class = "form-control",
@placeholder = "Complete Address", @cols = 10, @rows = 10 } })
NITZ is a form of NTP and is sent to the mobile device over Layer 3 or NAS layers. Commonly this message is seen as GMM Info and contains the following informaiton:
Certain carriers dont support this and some support it and have it setup incorrectly.
LAYER 3 SIGNALING MESSAGE
Time: 9:38:49.800
GMM INFORMATION 3GPP TS 24.008 ver 12.12.0 Rel 12 (9.4.19)
M Protocol Discriminator (hex data: 8)
(0x8) Mobility Management message for GPRS services
M Skip Indicator (hex data: 0) Value: 0 M Message Type (hex data: 21) Message number: 33
O Network time zone (hex data: 4680) Time Zone value: GMT+2:00 O Universal time and time zone (hex data: 47716070 70831580) Year: 17 Month: 06 Day: 07 Hour: 07 Minute :38 Second: 51 Time zone value: GMT+2:00 O Network Daylight Saving Time (hex data: 490100) Daylight Saving Time value: No adjustment
Layer 3 data: 08 21 46 80 47 71 60 70 70 83 15 80 49 01 00
input -webkit-appearance: none;
alone does not work.
Try adding -webkit-border-radius:0px;
in addition.
http://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells
CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(
createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
This would work just fine, set the height to desired pixel
#inner-right{
height: 100px;
overflow:auto;
}
In MySQL TRUE
and FALSE
are synonyms for TINYINT(1)
.
So therefore its basically the same thing, but MySQL is converting to 0/1 - so just use a TINYINT
if that's easier for you
P.S.
The performance is likely to be so minuscule (if at all), that if you need to ask on StackOverflow, then it won't affect your database :)
you need nested foreach loops
foreach($samplearr as $key => $item){
echo $key;
foreach($item as $detail){
echo $detail['value1'] . " " . $detail['value2']
}
}
What browser are you testing in?
What DOCType have you set?
How exactly are you declaring your CSS?
Are you sure you haven't missed a ;
before/after the overflow-y: scroll
?
I've just tested the following in IE7 and Firefox and it works fine
<!-- Scroll bar present but disabled when less content -->_x000D_
<div style="width: 200px; height: 100px; overflow-y: scroll;">_x000D_
test_x000D_
</div>_x000D_
_x000D_
<!-- Scroll bar present and enabled when more contents --> _x000D_
<div style="width: 200px; height: 100px; overflow-y: scroll;">_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
</div>
_x000D_
curl -D- -X GET -H "Authorization: Basic ZnJlZDpmcmVk" -H "Content-Type: application/json" http://localhost:7990/rest/api/1.0/projects
--note
base46 encode =ZnJlZDpmcmVk
If you want a cryptographically strong random number generator (also thread safe) without using a third party API, you can use SecureRandom
.
Java 6 & 7:
SecureRandom random = new SecureRandom();
byte[] bytes = new byte[20];
random.nextBytes(bytes);
Java 8 (even more secure):
byte[] bytes = new byte[20];
SecureRandom.getInstanceStrong().nextBytes(bytes);
Swift 4.0.3
import UIKit
extension String {
func fromBase64() -> String? {
guard let data = Data(base64Encoded: self, options: Data.Base64DecodingOptions(rawValue: 0)) else {
return nil
}
return String(data: data as Data, encoding: String.Encoding.utf8)
}
func toBase64() -> String? {
guard let data = self.data(using: String.Encoding.utf8) else {
return nil
}
return data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))
}
}
Sometimes Jeb's and Jens's answers don't work and return null. In this case I use follow solution. Head of file usually contains type signature. I read it and compare with known in list of signatures.
/**
*
* @param is InputStream on start of file. Otherwise signature can not be defined.
* @return int id of signature or -1, if unknown signature was found. See SIGNATURE_ID_(type) constants to
* identify signature by its id.
* @throws IOException in cases of read errors.
*/
public static int getSignatureIdFromHeader(InputStream is) throws IOException {
// read signature from head of source and compare with known signatures
int signatureId = -1;
int sigCount = SIGNATURES.length;
int[] byteArray = new int[MAX_SIGNATURE_LENGTH];
StringBuilder builder = new StringBuilder();
for (int i = 0; i < MAX_SIGNATURE_LENGTH; i++) {
byteArray[i] = is.read();
builder.append(Integer.toHexString(byteArray[i]));
}
if (DEBUG) {
Log.d(TAG, "head bytes=" + builder.toString());
}
for (int i = 0; i < MAX_SIGNATURE_LENGTH; i++) {
// check each bytes with known signatures
int bytes = byteArray[i];
int lastSigId = -1;
int coincidences = 0;
for (int j = 0; j < sigCount; j++) {
int[] sig = SIGNATURES[j];
if (DEBUG) {
Log.d(TAG, "compare" + i + ": " + Integer.toHexString(bytes) + " with " + sig[i]);
}
if (bytes == sig[i]) {
lastSigId = j;
coincidences++;
}
}
// signature is unknown
if (coincidences == 0) {
break;
}
// if first bytes of signature is known we check signature for full coincidence
if (coincidences == 1) {
int[] sig = SIGNATURES[lastSigId];
int sigLength = sig.length;
boolean isSigKnown = true;
for (; i < MAX_SIGNATURE_LENGTH && i < sigLength; i++) {
bytes = byteArray[i];
if (bytes != sig[i]) {
isSigKnown = false;
break;
}
}
if (isSigKnown) {
signatureId = lastSigId;
}
break;
}
}
return signatureId;
}
signatureId
is an index of signature in array of signatures. For example,
private static final int[] SIGNATURE_PNG = hexStringToIntArray("89504E470D0A1A0A");
private static final int[] SIGNATURE_JPEG = hexStringToIntArray("FFD8FF");
private static final int[] SIGNATURE_GIF = hexStringToIntArray("474946");
public static final int SIGNATURE_ID_JPEG = 0;
public static final int SIGNATURE_ID_PNG = 1;
public static final int SIGNATURE_ID_GIF = 2;
private static final int[][] SIGNATURES = new int[3][];
static {
SIGNATURES[SIGNATURE_ID_JPEG] = SIGNATURE_JPEG;
SIGNATURES[SIGNATURE_ID_PNG] = SIGNATURE_PNG;
SIGNATURES[SIGNATURE_ID_GIF] = SIGNATURE_GIF;
}
Now I have file type even if URI of file haven't. Next I get mime type by file type. If you don't know which mime type to get, you can find proper in this table.
It works for a lot of file types. But for video it doesn't work, because you need to known video codec to get a mime type. To get video's mime type I use MediaMetadataRetriever.
When you change attribute value like mentioned above the change
event is not triggered so if needed for some reasons you can trigger it like so
$('input[name=video_radio][value="' + r.data.video_radio + '"]')
.prop('checked', true)
.trigger('change');
DELETE FROM blob
WHERE fileid NOT IN
(SELECT id
FROM files
WHERE id is NOT NULL/*This line is unlikely to be needed
but using NOT IN...*/
)
Array.Equals() appears to only test for the same instance.
There doesn't appear to be a method that compares the values but it would be very easy to write.
Just compare the lengths, if not equal, return false. Otherwise, loop through each value in the array and determine if they match.
Here is a solution using observables.
waitForElementToAppear(elementId) {
return Observable.create(function(observer) {
var el_ref;
var f = () => {
el_ref = document.getElementById(elementId);
if (el_ref) {
observer.next(el_ref);
observer.complete();
return;
}
window.requestAnimationFrame(f);
};
f();
});
}
Now you can write
waitForElementToAppear(elementId).subscribe(el_ref => doSomethingWith(el_ref);
This is another option, using jQuery and getting only tbody
rows (with the data) and desconsidering thead/tfoot
.
$("#tableId > tbody > tr").length
console.log($("#myTableId > tbody > tr").length);
_x000D_
.demo {
width:100%;
height:100%;
border:1px solid #C0C0C0;
border-collapse:collapse;
border-spacing:2px;
padding:5px;
}
.demo caption {
caption-side:top;
text-align:center;
}
.demo th {
border:1px solid #C0C0C0;
padding:5px;
background:#F0F0F0;
}
.demo td {
border:1px solid #C0C0C0;
text-align:left;
padding:5px;
background:#FFFFFF;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTableId" class="demo">
<caption>Table 1</caption>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
<th>Header 4</th>
</tr>
</thead>
<tbody>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan=4 style="background:#F0F0F0"> </td>
</tr>
</tfoot>
</table>
_x000D_
Set CMAKE_C_COMPILER
to your new path.
This warning is displayed because a new extension has appeared. It suppouse that you still can use the old one but in some cases it´s impossible.
I show you how I do the connection with database. You need just change the values of the variables.
My connection file: connection.php
<?php
$host='IP or Server Name (usually "localhost") ';
$user='Database user';
$password='Database password';
$db='Database name';
//PHP 5.4 o earlier (DEPRECATED)
$con = mysql_connect($host,$user,$password) or exit("Connection Error");
$connection = mysql_select_db($db, $con);
//PHP 5.5 (New method)
$connection = mysqli_connect($host,$user,$password,$db);
?>
The extension changes too when performing a query.
Query File: "example.php"
<?php
//First I call for the connection
require("connection.php");
// ... Here code if you need do something ...
$query = "Here the query you are going to perform";
//QUERY PHP 5.4 o earlier (DEPRECATED)
$result = mysql_query ($query) or exit("The query could not be performed");
//QUERY PHP 5.5 (NEW EXTENSION)
$result = mysqli_query ($query) or exit("The query could not be performed");
?>
This way is using MySQL Improved Extension, but you can use PDO (PHP Data Objects).
First method can be used only with MySQL databases, but PDO can manage different types of databases.
I'm going to put an example but it´s necessary to say that I only use the first one, so please correct me if there is any error.
My PDO connection file: "PDOconnection.php"
<?php
$hostDb='mysql:host= "Here IP or Server Name";dbname="Database name" ';
$user='Database user';
$password='Database password';
$connection = new PDO($hostDb, $user, $password);
?>
Query File (PDO): "example.php"
<?php
$query = "Here the query you are going to perform";
$result=$connection->$query;
?>
To finish just say that of course you can hide the warning but it´s not a good idea because can help you in future save time if an error happens (all of us knows the theory but if you work a lot of hours sometimes... brain is not there ^^ ).
This should do it
old_string = "this is going to have a full stop. some written sstuff!"
k = old_string.rfind(".")
new_string = old_string[:k] + ". - " + old_string[k+1:]
The problem is that HTML doesn't recognize the escape character. You could work around that by using the single quotes for the HTML attribute and the double quotes for the onclick.
<a href="#" onclick='DoEdit("Preliminary Assessment \"Mini\""); return false;'>edit</a>
IMHO it is better to use the regular notation (<br />
) instead of the forgiving notation (<br>
) for the following reasons:
In your HTML there is probably some SVG and SVG only support the regular notation (e.g. <rect />
).
It is not a case that frameworks like React and NativeScript use an XML notation.
Your markup code will be easier to parse.
The regular notation is easier to read and understand, even late at night.
Both <br>
and <br />
are valid HTML tags.
If you use a full-fledged text editor configure it to use the regular notation (which is called XHTML by Emmet).
For instance, in Visual Studio Code you just have to add the following line to your settings:
"emmet.syntaxProfiles": {"html": "xhtml"}
another bit of code here:
refer: https://github.com/stvnthomas/CodeIgniter-Multi-Upload
(This answer might seem needlessly complicated, but it’s easily extensible and robust regarding whitespace and special characters, as far as I know.)
You can feed data right through the standard input of the ssh
command and read
that from the remote location.
In the following example,
ssh
a null-terminated line giving the name and value of the variable.shh
command itself, we loop through these lines to initialise the required variables.# Initialize examples of variables.
# The first one even contains whitespace and a newline.
readonly FOO=$'apjlljs ailsi \n ajlls\t éjij'
readonly BAR=ygnàgyààynygbjrbjrb
# Make a list of what you want to pass through SSH.
# (The “unset” is just in case someone exported
# an associative array with this name.)
unset -v VAR_NAMES
readonly VAR_NAMES=(
FOO
BAR
)
for name in "${VAR_NAMES[@]}"
do
printf '%s %s\0' "$name" "${!name}"
done | ssh [email protected] '
while read -rd '"''"' name value
do
export "$name"="$value"
done
# Check
printf "FOO = [%q]; BAR = [%q]\n" "$FOO" "$BAR"
'
Output:
FOO = [$'apjlljs ailsi \n ajlls\t éjij']; BAR = [ygnàgyààynygbjrbjrb]
If you don’t need to export
those, you should be able to use declare
instead of export
.
A really simplified version (if you don’t need the extensibility, have a single variable to process, etc.) would look like:
$ ssh [email protected] 'read foo' <<< "$foo"
You can combine multiple selectors and this is so cool knowing that you can select every attribute and attribute based on their value like href
based on their values with CSS only..
Attributes selectors allows you play around some extra with id
and class
attributes
Here is an awesome read on Attribute Selectors
a[href="http://aamirshahzad.net"][title="Aamir"] {_x000D_
color: green;_x000D_
text-decoration: none;_x000D_
}_x000D_
_x000D_
a[id*="google"] {_x000D_
color: red;_x000D_
}_x000D_
_x000D_
a[class*="stack"] {_x000D_
color: yellow;_x000D_
}
_x000D_
<a href="http://aamirshahzad.net" title="Aamir">Aamir</a>_x000D_
<br>_x000D_
<a href="http://google.com" id="google-link" title="Google">Google</a>_x000D_
<br>_x000D_
<a href="http://stackoverflow.com" class="stack-link" title="stack">stack</a>
_x000D_
Browser support:
IE6+, Chrome, Firefox & Safari
You can check detail here.
alter table User
add constraint userProperties
foreign key (properties)
references Properties(ID)
I think
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div>Testing</div>
<div id="result" style="margin:1em 4em; background:rgb(200,200,255); height:500px"></div>
<div style="background:rgb(200,255,200); height:3000px; width:5000px;"></div>
<script>
(function(){
var link=$("#result");
var top = link.offset().top; // position from $(document).offset().top
var bottom = top + link.height(); // position from $(document).offset().top
var left = link.offset().left; // position from $(document).offset().left
var right = left + link.width(); // position from $(document).offset().left
var bottomFromBottom = $(document).height() - bottom;
// distance from document's bottom
var rightFromRight = $(document).width() - right;
// distance from document's right
var str="";
str+="top: "+top+"<br>";
str+="bottom: "+bottom+"<br>";
str+="left: "+left+"<br>";
str+="right: "+right+"<br>";
str+="bottomFromBottom: "+bottomFromBottom+"<br>";
str+="rightFromRight: "+rightFromRight+"<br>";
link.html(str);
})();
</script>
The result are
top: 44
bottom: 544
left: 72
right: 1277
bottomFromBottom: 3068
rightFromRight: 3731
in chrome browser of mine.
When the document is scrollable, $(window).height()
returns height of browser viewport, not the width of document of which some parts are hiden in scroll. See http://api.jquery.com/height/ .
Use LINQ if you can.
label1.Text = dataGridView1.Rows.Cast<DataGridViewRow>()
.AsEnumerable()
.Sum(x => int.Parse(x.Cells[1].Value.ToString()))
.ToString();
tried everything else but a reboot, what worked for me is rm -fr .git/REBASE_HEAD
your form is missing the method...
<form name="registrationform" action="register.php" method="post"> //here
anywyas to check the posted data u can use isset()..
Determine if a variable is set and is not NULL
if(!isset($firstname) || trim($firstname) == '')
{
echo "You did not fill out the required fields.";
}
It seem like your Resort
method doesn't declare a compareTo
method. This method typically belongs to the Comparable
interface. Make sure your class implements it.
Additionally, the compareTo
method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String
argument, but rather a Resort
.
Alternatively, you can compare the names of the resorts. For example
if (resortList[mid].getResortName().compareTo(resortName)>0)
This worked for me:
curl -H "Content-Type: application/json" -X POST -d @./my_json_body.txt http://192.168.1.1/json
You can use "Empty Img Element".
Empty Img Element - document.createElement("img")
[HTML Code]
<div id="hello" draggable="true">Drag!!!</div>
[JavaScript Code]
var block = document.querySelector('#hello');
block.addEventListener('dragstart', function(e){
var img = document.createElement("img");
e.dataTransfer.setDragImage(img, 0, 0);
})
I think what you are looking for is:
startDate.setDate(startDate.getDate() + 1);
Also, you can have a look at Moment.js
A javascript date library for parsing, validating, manipulating, and formatting dates.
You can make easily custom textview class :-
So what you need to do first, make Custom textview
class which extended with AppCompatTextView
.
public class CustomTextView extends AppCompatTextView {
private int mFont = FontUtils.FONTS_NORMAL;
boolean fontApplied;
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, context);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, context);
}
public CustomTextView(Context context) {
super(context);
init(null, context);
}
protected void init(AttributeSet attrs, Context cxt) {
if (!fontApplied) {
if (attrs != null) {
mFont = attrs.getAttributeIntValue(
"http://schemas.android.com/apk/res-auto", "Lato-Regular.ttf",
-1);
}
Typeface typeface = getTypeface();
int typefaceStyle = Typeface.NORMAL;
if (typeface != null) {
typefaceStyle = typeface.getStyle();
}
if (mFont > FontUtils.FONTS) {
typefaceStyle = mFont;
}
FontUtils.applyFont(this, typefaceStyle);
fontApplied = true;
}
}
}
Now , every time Custom text view call and we will get int value from attribute int fontValue = attrs.getAttributeIntValue("http://schemas.android.com/apk/res-auto","Lato-Regular.ttf",-1)
.
Or
We can also get getTypeface() from view which we set in our xml (android:textStyle="bold|normal|italic"
). So do what ever you want to do.
Now, we make FontUtils
for set any .ttf font into our view.
public class FontUtils {
public static final int FONTS = 1;
public static final int FONTS_NORMAL = 2;
public static final int FONTS_BOLD = 3;
public static final int FONTS_BOLD1 = 4;
private static Map<String, Typeface> TYPEFACE = new HashMap<String, Typeface>();
static Typeface getFonts(Context context, String name) {
Typeface typeface = TYPEFACE.get(name);
if (typeface == null) {
typeface = Typeface.createFromAsset(context.getAssets(), name);
TYPEFACE.put(name, typeface);
}
return typeface;
}
public static void applyFont(TextView tv, int typefaceStyle) {
Context cxt = tv.getContext();
Typeface typeface;
if(typefaceStyle == Typeface.BOLD_ITALIC) {
typeface = FontUtils.getFonts(cxt, "FaktPro-Normal.ttf");
}else if (typefaceStyle == Typeface.BOLD || typefaceStyle == SD_FONTS_BOLD|| typefaceStyle == FONTS_BOLD1) {
typeface = FontUtils.getFonts(cxt, "FaktPro-SemiBold.ttf");
} else if (typefaceStyle == Typeface.ITALIC) {
typeface = FontUtils.getFonts(cxt, "FaktPro-Thin.ttf");
} else {
typeface = FontUtils.getFonts(cxt, "FaktPro-Normal.ttf");
}
if (typeface != null) {
tv.setTypeface(typeface);
}
}
}
I am not very good in grep. But your problem can be solved using AWK command. Just see
awk '/select/,/from/' *.sql
The above code will result from first occurence of select
till first sequence of from
. Now you need to verify whether returned statements are having customername
or not. For this you can pipe the result. And can use awk or grep again.
as suggested here solving the famous LazyInitializationException is one of the following methods:
(1) Use Hibernate.initialize
Hibernate.initialize(topics.getComments());
(2) Use JOIN FETCH
You can use the JOIN FETCH syntax in your JPQL to explicitly fetch the child collection out. This is somehow like EAGER fetching.
(3) Use OpenSessionInViewFilter
LazyInitializationException often occurs in the view layer. If you use Spring framework, you can use OpenSessionInViewFilter. However, I do not suggest you to do so. It may leads to a performance issue if not used correctly.
In C++ you can access fields or methods, using different operators, depending on it's type:
Note that :: should be used with a class name rather than a class instance, since static fields or methods are common to all instances of a class.
class AClass{
public:
static int static_field;
int instance_field;
static void static_method();
void method();
};
then you access this way:
AClass instance;
AClass *pointer = new AClass();
instance.instance_field; //access instance_field through a reference to AClass
instance.method();
pointer->instance_field; //access instance_field through a pointer to AClass
pointer->method();
AClass::static_field;
AClass::static_method();
I found some useful information in a forum page, quoted below.
From this, mainly the sentences in bold formatting, my answer is:
Make a bash (shell) script version of your .bat file (like other
answers, with \
changed to /
in file paths). For example:
# File "example.command":
#!/bin/bash
java -cp ".;./supportlibraries/Framework_Core.jar; ...etc.
Then rename it to have the Mac OS file extension .command
.
That should make the script run using the Terminal app.
If the app user is going to use a bash script version of the file on Linux
or run it from the command line, they need to add executable rights
(change mode bits) using this command, in the folder that has the file:
chmod +rx [filename].sh
#or:# chmod +rx [filename].command
The forum page question:
Good day, [...] I wondering if there are some "simple" rules to write an equivalent
of the Windows (DOS) bat file. I would like just to click on a file and let it run.
Info from some answers after the question:
Write a shell script, and give it the extension ".command". For example:
#!/bin/bash printf "Hello World\n"
- Mar 23, 2010, Tony T1.
The DOS .BAT file was an attempt to bring to MS-DOS something like the idea of the UNIX script.
In general, UNIX permits you to make a text file with commands in it and run it by simply flagging
the text file as executable (rather than give it a specific suffix). This is how OS X does it.However, OS X adds the feature that if you give the file the suffix
.command
, Finder
will run Terminal.app to execute it (similar to how BAT files work in Windows).Unlike MS-DOS, however, UNIX (and OS X) permits you to specify what interpreter is used
for the script. An interpreter is a program that reads in text from a file and does something
with it. [...] In UNIX, you can specify which interpreter to use by making the first line in the
text file one that begins with "#!" followed by the path to the interpreter. For example [...]#!/bin/sh echo Hello World
- Mar 23, 2010, J D McIninch.
Also, info from an accepted answer for Equivalent of double-clickable .sh and .bat on Mac?:
On mac, there is a specific extension for executing shell
scripts by double clicking them: this is.command
.
For the 24-hour time, you need to use HH24
instead of HH
.
For the 12-hour time, the AM/PM indicator is written as A.M.
(if you want periods in the result) or AM
(if you don't). For example:
SELECT invoice_date,
TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
FROM invoices
;
For more information on the format models you can use with TO_CHAR
on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.
Yes, you are synchronizing correctly. I will explain this in more detail. You must synchronize two or more method calls on the synchronizedMap object only in a case you have to rely on results of previous method call(s) in the subsequent method call in the sequence of method calls on the synchronizedMap object. Let’s take a look at this code:
synchronized (synchronizedMap) {
if (synchronizedMap.containsKey(key)) {
synchronizedMap.get(key).add(value);
}
else {
List<String> valuesList = new ArrayList<String>();
valuesList.add(value);
synchronizedMap.put(key, valuesList);
}
}
In this code
synchronizedMap.get(key).add(value);
and
synchronizedMap.put(key, valuesList);
method calls are relied on the result of the previous
synchronizedMap.containsKey(key)
method call.
If the sequence of method calls were not synchronized the result might be wrong.
For example thread 1
is executing the method addToMap()
and thread 2
is executing the method doWork()
The sequence of method calls on the synchronizedMap
object might be as follows:
Thread 1
has executed the method
synchronizedMap.containsKey(key)
and the result is "true
".
After that operating system has switched execution control to thread 2
and it has executed
synchronizedMap.remove(key)
After that execution control has been switched back to the thread 1
and it has executed for example
synchronizedMap.get(key).add(value);
believing the synchronizedMap
object contains the key
and NullPointerException
will be thrown because synchronizedMap.get(key)
will return null
.
If the sequence of method calls on the synchronizedMap
object is not dependent on the results of each other then you don't need to synchronize the sequence.
For example you don't need to synchronize this sequence:
synchronizedMap.put(key1, valuesList1);
synchronizedMap.put(key2, valuesList2);
Here
synchronizedMap.put(key2, valuesList2);
method call does not rely on the results of the previous
synchronizedMap.put(key1, valuesList1);
method call (it does not care if some thread has interfered in between the two method calls and for example has removed the key1
).
You can duplicate a table without data by running:
CREATE TABLE x LIKE y;
(See the MySQL CREATE TABLE Docs)
You could write a script that takes the output from SHOW TABLES
from one database and copies the schema to another. You should be able to reference schema+table names like:
CREATE TABLE x LIKE other_db.y;
As far as the data goes, you can also do it in MySQL, but it's not necessarily fast. After you've created the references, you can run the following to copy the data:
INSERT INTO x SELECT * FROM other_db.y;
If you're using MyISAM, you're better off to copy the table files; it'll be much faster. You should be able to do the same if you're using INNODB with per table table spaces.
If you do end up doing an INSERT INTO SELECT
, be sure to temporarily turn off indexes with ALTER TABLE x DISABLE KEYS
!
EDIT Maatkit also has some scripts that may be helpful for syncing data. It may not be faster, but you could probably run their syncing scripts on live data without much locking.
You can also use the built-in sp_who2
stored procedure to get current blocked and blocking processes on a SQL Server instance. Typically you'd run this alongside a SQL Profiler instance to find a blocking process and look at the most recent command that spid issued in profiler.
There are two ways to go about this. You can either use the IDE to generate a WSDL, or you can do it via the command line.
1. To create it via the IDE:
In the solution explorer pane, right click on the project that you would like to add the Service to:
Then, you can enter the path to your service WSDL and hit go:
2. To create it via the command line:
Open a VS 2010 Command Prompt (Programs -> Visual Studio 2010 -> Visual Studio Tools)
Then execute:
WSDL /verbose C:\path\to\wsdl
WSDL.exe will then output a .cs file for your consumption.
If you have other dependencies that you received with the file, such as xsd's, add those to the argument list:
WSDL /verbose C:\path\to\wsdl C:\path\to\some\xsd C:\path\to\some\xsd
If you need VB output, use /language:VB
in addition to the /verbose
.
The jquery form plugin offers an easy way to iterate over your form elements and put them in a query string. It might also be useful for whatever else you need to do with these values.
var queryString = $('#myFormId').formSerialize();
From http://malsup.com/jquery/form
Or using straight jquery:
var queryString = $('#myFormId').serialize();
No - the object approach is JavaScript's answer to this. There is no problem with this provided your function expects an object rather than separate params.
In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:
CSS solution:
HTML4's scrolling="no"
is kind of an alias of the CSS's overflow: hidden
, to do so it is important to set size attributes width/height:
iframe.noScrolling{
width: 250px; /*or any other size*/
height: 300px; /*or any other size*/
overflow: hidden;
}
Add this class to your iframe and you're done:
<iframe src="http://www.example.com/" class="noScrolling"></iframe>
! IMPORTANT NOTE ! : overflow: hidden
for <iframe>
is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no"
and overflow:hidden
at the same time :)
UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors
I have been testing this out for my project.
Went through this $h!†
again after updating to Catalina, which requires an XCode
update.
And to clarify, while this post is about VS Code
, this issue, is system wide. Your git
install is affected/hosed. You can try to run git
in your terminal/bash/zsh or whatever it is now and it just won't.
Same fix, just update XCode
, start it up and agree to license. That's it.
Old post, but just hit this on MAC/OSX
so hope this helps someone.
VS Code
for some time and have no issues with Git
XCode
(for whatever reason - OS update, etc)XCode
, VS Code
suddenly "can't find Git and asks you to either install or set the Path in settings"Run XCode
(for the first time, after installing) and agree to license. That's it.
How I stumbled upon this "fix":
After going through numerous tips about checking git
, e.g. which git
and git --version
, the latter actually offered clues with this Terminal message:
Agreeing to the Xcode/iOS license requires admin privileges, please run “sudo xcodebuild -license” and then retry this command.
As to why XCode
would even wrap it's hands on git
, WAT
Happy holidays and happy coding :)
box-sizing: border-box;
width: 100%;
padding: 5px;
box-sizing: border box; makes it so that padding, margin and border are included in the width calculations.
You can do it as following:
class ProjectInfo
{
public string Name {get; set; }
public long Id {get; set; }
ProjectInfo(string n, long id)
{
name = n; Id = id;
}
}
public List<ProjectInfo> GetProjectForCombo()
{
using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
{
var query = from pro in db.Projects
select new ProjectInfo(pro.ProjectName,pro.ProjectId);
return query.ToList<ProjectInfo>();
}
}
var opt = new Option(name, id);
$("#selectboxName").append(opt);
opt.setAttribute("selected","selected");
i like this version:
import java.awt.Dimension;
import java.awt.GraphicsConfiguration;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class Test
{
public static void main(String [] args)
{
final JFrame frame = new JFrame();
final GraphicsConfiguration config = frame.getGraphicsConfiguration();
final int left = Toolkit.getDefaultToolkit().getScreenInsets(config).left;
final int right = Toolkit.getDefaultToolkit().getScreenInsets(config).right;
final int top = Toolkit.getDefaultToolkit().getScreenInsets(config).top;
final int bottom = Toolkit.getDefaultToolkit().getScreenInsets(config).bottom;
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
final int width = screenSize.width - left - right;
final int height = screenSize.height - top - bottom;
frame.setResizable(false);
frame.setSize(width,height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
update this part in metro blacklist
var sharedBlacklist = [
/node_modules[\/\\]react[\/\\]dist[\/\\].*/,
/website\/node_modules\/.*/,
/heapCapture\/bundle\.js/,
/.*\/__tests__\/.*/
];
https://nodejs.org/en/download/releases/ [Download the specified version]
1) answer of first question : according to Picasso Doc for With() method
The global default Picasso instance returned from with() is automatically initialized with defaults that are suitable to most implementations.
- LRU memory cache of 15% the available application RAM
- Disk cache of 2% storage space up to 50MB but no less than 5MB.
But Disk Cache
operation for global Default Picasso is only available on API 14+
2) answer of second Question : Picasso
use the HTTP
client request to Disk Cache
operation So you can make your own http request header
has property Cache-Control
with max-age
And create your own Static Picasso Instance instead of default Picasso By using
1] HttpResponseCache (Note: Works only for API 13+ )
2] OkHttpClient (Works for all APIs)
Example for using OkHttpClient
to create your own Static Picasso class:
First create a new class to get your own singleton picasso
object
import android.content.Context;
import com.squareup.picasso.Downloader;
import com.squareup.picasso.OkHttpDownloader;
import com.squareup.picasso.Picasso;
public class PicassoCache {
/**
* Static Picasso Instance
*/
private static Picasso picassoInstance = null;
/**
* PicassoCache Constructor
*
* @param context application Context
*/
private PicassoCache (Context context) {
Downloader downloader = new OkHttpDownloader(context, Integer.MAX_VALUE);
Picasso.Builder builder = new Picasso.Builder(context);
builder.downloader(downloader);
picassoInstance = builder.build();
}
/**
* Get Singleton Picasso Instance
*
* @param context application Context
* @return Picasso instance
*/
public static Picasso getPicassoInstance (Context context) {
if (picassoInstance == null) {
new PicassoCache(context);
return picassoInstance;
}
return picassoInstance;
}
}
use your own singleton picasso
object Instead of Picasso.With()
PicassoCache.getPicassoInstance(getContext()).load(imagePath).into(imageView)
3) answer for third question : you do not need any disk permissions for disk Cache operations
References: Github issue about disk cache, two Questions has been answered by @jake-wharton -> Question1 and Question2
with BytesIO() as output:
from PIL import Image
with Image.open(filename) as img:
img.convert('RGB').save(output, 'BMP')
data = output.getvalue()[14:]
I just use this for add a image to clipboard in windows.
This function creates confusion matrices for any number of classes.
def create_conf_matrix(expected, predicted, n_classes):
m = [[0] * n_classes for i in range(n_classes)]
for pred, exp in zip(predicted, expected):
m[pred][exp] += 1
return m
def calc_accuracy(conf_matrix):
t = sum(sum(l) for l in conf_matrix)
return sum(conf_matrix[i][i] for i in range(len(conf_matrix))) / t
In contrast to your function above, you have to extract the predicted classes before calling the function, based on your classification results, i.e. sth. like
[1 if p < .5 else 2 for p in classifications]
one of the approach if you want to get all user_id that satisfies all conditions is:
SELECT DISTINCT user_id FROM table WHERE ancestry IN ('England', '...', '...') GROUP BY user_id HAVING count(*) = <number of conditions that has to be satisfied>
etc. If you need to take all user_ids that satisfies at least one condition, then you can do
SELECT DISTINCT user_id from table where ancestry IN ('England', 'France', ... , '...')
I am not aware if there is something similar to IN but that joins conditions with AND instead of OR
On your existing button code, simply insert this line before the procedure:
If MsgBox("This will erase everything! Are you sure?", vbYesNo) = vbNo Then Exit Sub
This will force it to quit if the user presses no.
I use Windows 10 machine working with PHP 8 and Lavarel 8 and I got the same error, I used the following command :-
composer update --ignore-platform-reqs
to update all the packages regardless of the version conflicts.
I think you need this ..
Dim n as Integer
For n = 5 to 17
msgbox cells(n,3) '--> sched waste
msgbox cells(n,4) '--> type of treatm
msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
msgbox cells(n,6) '--> email col
Next
I prefer this syntax as it allows to set configuration parameters for the shell:
---
- name: an example
shell:
cmd: |
docker build -t current_dir .
echo "Hello World"
date
chdir: /home/vagrant/
from php.net
Warning
The superglobals $_GET
and $_REQUEST
are already decoded. Using urldecode()
on an element in $_GET
or $_REQUEST
could have unexpected and dangerous results.
link: http://php.net/manual/en/function.urldecode.php
be careful.
Stack corruptions ususally caused by buffer overflows. You can defend against them by programming defensively.
Whenever you access an array, put an assert before it to ensure the access is not out of bounds. For example:
assert(i + 1 < N);
assert(i < N);
a[i + 1] = a[i];
This makes you think about array bounds and also makes you think about adding tests to trigger them if possible. If some of these asserts can fail during normal use turn them into a regular if
.
$searchfor = $_GET['keyword'];
$file = 'users.txt';
$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*\$/m";
if (preg_match_all($pattern, $contents, $matches)) {
echo "Found matches:<br />";
echo implode("<br />", $matches[0]);
} else {
echo "No matches found";
fclose ($file);
}
eg:
from: /xxx/a/b/c/d/e/1.html
to: user@remote:/pre_existing/dir/b/c/d/e/1.html
rsync:
cd /xxx/a/ && rsync -auvR b/c/d/e/ user@remote:/pre_existing/dir/
In this moment with the last version of the C# driver (2.3.0) the only way I found to get the database name specified in connection string is this:
var connectionString = @"mongodb://usr:[email protected],srv2.acme.net,srv3.acme.net/dbName?replicaSet=rset";
var mongoUrl = new MongoUrl(connectionString);
var dbname = mongoUrl.DatabaseName;
var db = new MongoClient(mongoUrl).GetDatabase(dbname);
db.GetCollection<MyType>("myCollectionName");
<noscript>
isn't even necessary, and not to mention not supported in XHTML.
Working Example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html>
<head>
<title>My website</title>
<style>
#site {
display: none;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js "></script>
<script>
$(document).ready(function() {
$("#noJS").hide();
$("#site").show();
});
</script>
</head>
<body>
<div id="noJS">Please enable JavaScript...</div>
<div id="site">JavaScript dependent content here...</div>
</body>
</html>
In this example, if JavaScript is enabled, then you see the site. If not, then you see the "Please enable JavaScript" message. The best way to test if JavaScript is enabled, is to simply try and use JavaScript! If it works, it's enabled, if not, then it's not...
If you use git LFS, git count-objects does not count your binaries, but only the pointers to them.
If your LFS files are managed by Artifactorys, you should use the REST API:
===
is not necessary. You know both values are strings so you dont need to compare types.
function do_check()_x000D_
{_x000D_
var str1 = $("#textbox1").val();_x000D_
var str2 = $("#textbox2").val();_x000D_
_x000D_
if (str1 == str2)_x000D_
{_x000D_
$(":text").removeClass("incorrect");_x000D_
alert("equal");_x000D_
}_x000D_
else_x000D_
{_x000D_
$(":text").addClass("incorrect");_x000D_
alert("not equal");_x000D_
}_x000D_
}
_x000D_
.incorrect_x000D_
{_x000D_
background: #ff8888;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<input id="textbox1" type="text">_x000D_
<input id="textbox2" type="text">_x000D_
_x000D_
<button onclick="do_check()">check</button>
_x000D_
Not only is there a way to do this, there is more than one way to do this (which I concede is not very Pythonic, but then SQL*Developer is written in Java ).
I have a procedure with this signature: get_maxsal_by_dept( dno number, maxsal out number)
.
I highlight it in the SQL*Developer Object Navigator, invoke the right-click menu and chose Run. (I could use ctrl+F11.) This spawns a pop-up window with a test harness. (Note: If the stored procedure lives in a package, you'll need to right-click the package, not the icon below the package containing the procedure's name; you will then select the sproc from the package's "Target" list when the test harness appears.) In this example, the test harness will display the following:
DECLARE
DNO NUMBER;
MAXSAL NUMBER;
BEGIN
DNO := NULL;
GET_MAXSAL_BY_DEPT(
DNO => DNO,
MAXSAL => MAXSAL
);
DBMS_OUTPUT.PUT_LINE('MAXSAL = ' || MAXSAL);
END;
I set the variable DNO to 50 and press okay. In the Running - Log pane (bottom right-hand corner unless you've closed/moved/hidden it) I can see the following output:
Connecting to the database apc.
MAXSAL = 4500
Process exited.
Disconnecting from the database apc.
To be fair the runner is less friendly for functions which return a Ref Cursor, like this one: get_emps_by_dept (dno number) return sys_refcursor
.
DECLARE
DNO NUMBER;
v_Return sys_refcursor;
BEGIN
DNO := 50;
v_Return := GET_EMPS_BY_DEPT(
DNO => DNO
);
-- Modify the code to output the variable
-- DBMS_OUTPUT.PUT_LINE('v_Return = ' || v_Return);
END;
However, at least it offers the chance to save any changes to file, so we can retain our investment in tweaking the harness...
DECLARE
DNO NUMBER;
v_Return sys_refcursor;
v_rec emp%rowtype;
BEGIN
DNO := 50;
v_Return := GET_EMPS_BY_DEPT(
DNO => DNO
);
loop
fetch v_Return into v_rec;
exit when v_Return%notfound;
DBMS_OUTPUT.PUT_LINE('name = ' || v_rec.ename);
end loop;
END;
The output from the same location:
Connecting to the database apc.
name = TRICHLER
name = VERREYNNE
name = FEUERSTEIN
name = PODER
Process exited.
Disconnecting from the database apc.
Alternatively we can use the old SQLPLus commands in the SQLDeveloper worksheet:
var rc refcursor
exec :rc := get_emps_by_dept(30)
print rc
In that case the output appears in Script Output pane (default location is the tab to the right of the Results tab).
The very earliest versions of the IDE did not support much in the way of SQL*Plus. However, all of the above commands have been supported since 1.2.1. Refer to the matrix in the online documentation for more info.
"When I type just
var rc refcursor;
and select it and run it, I get this error (GUI):"
There is a feature - or a bug - in the way the worksheet interprets SQLPlus commands. It presumes SQLPlus commands are part of a script. So, if we enter a line of SQL*Plus, say var rc refcursor
and click Execute Statement
(or F9 ) the worksheet hurls ORA-900 because that is not an executable statement i.e. it's not SQL . What we need to do is click Run Script
(or F5 ), even for a single line of SQL*Plus.
"I am so close ... please help."
You program is a procedure with a signature of five mandatory parameters. You are getting an error because you are calling it as a function, and with just the one parameter:
exec :rc := get_account(1)
What you need is something like the following. I have used the named notation for clarity.
var ret1 number
var tran_cnt number
var msg_cnt number
var rc refcursor
exec :tran_cnt := 0
exec :msg_cnt := 123
exec get_account (Vret_val => :ret1,
Vtran_count => :tran_cnt,
Vmessage_count => :msg_cnt,
Vaccount_id => 1,
rc1 => :rc )
print tran_count
print rc
That is, you need a variable for each OUT or IN OUT parameter. IN parameters can be passed as literals. The first two EXEC statements assign values to a couple of the IN OUT parameters. The third EXEC calls the procedure. Procedures don't return a value (unlike functions) so we don't use an assignment syntax. Lastly this script displays the value of a couple of the variables mapped to OUT parameters.
This is a solution where you have many fields in your table and don't want to get a finger cramp from typing all the fields, just type the ones needed :)
How to copy some rows into the same table, with some fields having different values:
Your code:
CREATE table temporary_table AS SELECT * FROM original_table WHERE Event_ID="155";
UPDATE temporary_table SET Event_ID="120";
UPDATE temporary_table SET ID=NULL
INSERT INTO original_table SELECT * FROM temporary_table;
DROP TABLE temporary_table
General scenario code:
CREATE table temporary_table AS SELECT * FROM original_table WHERE <conditions>;
UPDATE temporary_table SET <fieldx>=<valuex>, <fieldy>=<valuey>, ...;
UPDATE temporary_table SET <auto_inc_field>=NULL;
INSERT INTO original_table SELECT * FROM temporary_table;
DROP TABLE temporary_table
Simplified/condensed code:
CREATE TEMPORARY TABLE temporary_table AS SELECT * FROM original_table WHERE <conditions>;
UPDATE temporary_table SET <auto_inc_field>=NULL, <fieldx>=<valuex>, <fieldy>=<valuey>, ...;
INSERT INTO original_table SELECT * FROM temporary_table;
As creation of the temporary table uses the TEMPORARY
keyword it will be dropped automatically when the session finishes (as @ar34z suggested).
You can add them in your htaccess file or vhost configuration.
See here : http://httpd.apache.org/docs/2.2/mod/mod_expires.html
But unless you own those domains .. they are our of your control.
import { FormControl, FormGroup, AbstractControl, FormBuilder, Validators } from '@angular/forms';_x000D_
_x000D_
_x000D_
this.userInfoForm = new FormGroup({_x000D_
userInfoUserName: new FormControl({ value: '' }, Validators.compose([Validators.required])),_x000D_
userInfoName: new FormControl({ value: '' }, Validators.compose([Validators.required])),_x000D_
userInfoSurName: new FormControl({ value: '' }, Validators.compose([Validators.required]))_x000D_
});
_x000D_
<form [formGroup]="userInfoForm" class="form-horizontal">_x000D_
<div class="form-group">_x000D_
<label class="control-label"><i>*</i> User Name</label>_x000D_
<input type="text" formControlName="userInfoUserName" class="form-control" [(ngModel)]="userInfo.userName">_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label class="control-label"><i>*</i> Name</label>_x000D_
<input type="text" formControlName="userInfoName" class="form-control" [(ngModel)]="userInfo.name">_x000D_
</div>_x000D_
<div class="form-group">_x000D_
<label class="control-label"><i>*</i> Surname</label>_x000D_
<input type="text" formControlName="userInfoSurName" class="form-control" [(ngModel)]="userInfo.surName">_x000D_
</div>_x000D_
</form>
_x000D_
Aside from the one being ANSI and speed etc., there is a very important difference that always matters to me; more than ANSI and speed. The number of bugs I have fixed due to this important overlook is large. I look for this during code reviews all the time.
-- Arrange
create table Employee (EmployeeId int);
insert into dbo.Employee values (1);
insert into dbo.Employee values (2);
insert into dbo.Employee values (3);
-- Act
declare @employeeId int;
select @employeeId = e.EmployeeId from dbo.Employee e;
-- Assert
-- This will print 3, the last EmployeeId from the query (an arbitrary value)
-- Almost always, this is not what the developer was intending.
print @employeeId;
Almost always, that is not what the developer is intending. In the above, the query is straight forward but I have seen queries that are quite complex and figuring out whether it will return a single value or not, is not trivial. The query is often more complex than this and by chance it has been returning single value. During developer testing all is fine. But this is like a ticking bomb and will cause issues when the query returns multiple results. Why? Because it will simply assign the last value to the variable.
Now let's try the same thing with SET
:
-- Act
set @employeeId = (select e.EmployeeId from dbo.Employee e);
You will receive an error:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
That is amazing and very important because why would you want to assign some trivial "last item in result" to the @employeeId
. With select
you will never get any error and you will spend minutes, hours debugging.
Perhaps, you are looking for a single Id and SET
will force you to fix your query. Thus you may do something like:
-- Act
-- Notice the where clause
set @employeeId = (select e.EmployeeId from dbo.Employee e where e.EmployeeId = 1);
print @employeeId;
Cleanup
drop table Employee;
In conclusion, use:
SET
: When you want to assign a single value to a variable and your variable is for a single value.SELECT
: When you want to assign multiple values to a variable. The variable may be a table, temp table or table variable etc. The valid syntax with named fields:
var array = [];
@foreach (var item in model.List)
{
@:array.push({
"Project": "@item.Project",
"ProjectOrgUnit": "@item.ProjectOrgUnit"
});
}
Here comes a solution with XSLT
:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="//element3">
<xsl:value-of select="element4/text()" />.<xsl:value-of select="element5/text()" />
</xsl:template>
</xsl:stylesheet>
The issue is not actually with the import statement, it's with anything being before the for loop. Or more specifically, anything appearing before an inlined block.
For example, these all work:
python -c "import sys; print 'rob'"
python -c "import sys; sys.stdout.write('rob\n')"
If import being a statement were an issue, this would work, but it doesn't:
python -c "__import__('sys'); for r in range(10): print 'rob'"
For your very basic example, you could rewrite it as this:
python -c "import sys; map(lambda x: sys.stdout.write('rob%d\n' % x), range(10))"
However, lambdas can only execute expressions, not statements or multiple statements, so you may still be unable to do the thing you want to do. However, between generator expressions, list comprehension, lambdas, sys.stdout.write, the "map" builtin, and some creative string interpolation, you can do some powerful one-liners.
The question is, how far do you want to go, and at what point is it not better to write a small .py
file which your makefile executes instead?
Our HTML:
<div id="addnew">
<input type="text" id="id">
<input type="text" id="content">
<input type="button" value="Add" id="submit">
</div>
<div id="check">
<input type="text" id="input">
<input type="button" value="Search" id="search">
</div>
JS (writing to the txt file):
function writeToFile(d1, d2){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 8, false, 0);
fh.WriteLine(d1 + ',' + d2);
fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
var id = document.getElementById("id").value;
var content = document.getElementById("content").value;
writeToFile(id, content);
}
checking a particular row:
function readFile(){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 1, false, 0);
var lines = "";
while (!fh.AtEndOfStream) {
lines += fh.ReadLine() + "\r";
}
fh.Close();
return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
var input = document.getElementById("input").value;
if (input != "") {
var text = readFile();
var lines = text.split("\r");
lines.pop();
var result;
for (var i = 0; i < lines.length; i++) {
if (lines[i].match(new RegExp(input))) {
result = "Found: " + lines[i].split(",")[1];
}
}
if (result) { alert(result); }
else { alert(input + " not found!"); }
}
}
Put these inside a .hta
file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.
There is already the nl2br()
function that inserts <br>
tags before new line characters:
Example (codepad):
<?php
// Won't work
$desc = 'Line one\nline two';
// Should work
$desc2 = "Line one\nline two";
echo nl2br($desc);
echo '<br/>';
echo nl2br($desc2);
?>
But if it is still not working make sure the text $desciption
is double-quoted.
That's because single quotes do not 'expand' escape sequences such as \n
comparing to double quoted strings. Quote from PHP documentation:
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
Adding the following line in the head tag fixed my issue.
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
The identifing relaionship means the child entity is totally depend on the existance of the parent entity. Example account table person table and personaccount.The person account table is identified by the existance of account and person table only.
The non identifing relationship means the child table does not identified by the existance of the parent table example there is table as accounttype and account.accounttype table is not identified with the existance of account table.
Secure_path is your friend, but if you want to exempt yourself from secure_path just do
sudo visudo
And append
Defaults exempt_group=your_goup
If you want to exempt a bunch of users create a group, add all the users to it, and use that as your exempt_group. man 5 sudoers for more.
For #4, the closest thing to starting java with a jar file for your app is a new feature in Python 2.6, executable zip files and directories.
python myapp.zip
Where myapp.zip is a zip containing a __main__.py
file which is executed as the script file to be executed. Your package dependencies can also be included in the file:
__main__.py
mypackage/__init__.py
mypackage/someliblibfile.py
You can also execute an egg, but the incantation is not as nice:
# Bourn Shell and derivatives (Linux/OSX/Unix)
PYTHONPATH=myapp.egg python -m myapp
rem Windows
set PYTHONPATH=myapp.egg
python -m myapp
This puts the myapp.egg on the Python path and uses the -m argument to run a module. Your myapp.egg will likely look something like:
myapp/__init__.py
myapp/somelibfile.py
And python will run __init__.py
(you should check that __file__=='__main__'
in your app for command line use).
Egg files are just zip files so you might be able to add __main__.py
to your egg with a zip tool and make it executable in python 2.6 and run it like python myapp.egg
instead of the above incantation where the PYTHONPATH environment variable is set.
More information on executable zip files including how to make them directly executable with a shebang can be found on Michael Foord's blog post on the subject.
My solution is to add the ID field as the LAST field in the table, thus bulk insert ignores it and it gets automatic values. Clean and simple ...
For instance, if inserting into a temp table:
CREATE TABLE #TempTable
(field1 varchar(max), field2 varchar(max), ...
ROW_ID int IDENTITY(1,1) NOT NULL)
Note that the ROW_ID
field MUST always be specified as LAST field!
Actually I got something like that on IE recently and it was related to JavaScript syntax "errors". I say error in quotes because it was fine everywhere but on IE. This was under IE6. The problem was related to JSON object creation and an extra comma, such as
{ one:1, two:2, three:3, }
IE6 really doesn't like that comma after 3. You might look for something like that, touchy little syntax formality issues.
Yeah, I thought the multi-million line number in my 25 line JavaScript was interesting too.
Good luck.
You can simply use datetime diff and format for calculating difference.
<?php
$datetime1 = new DateTime('2009-10-11 12:12:00');
$datetime2 = new DateTime('2009-10-13 10:12:00');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%Y-%m-%d %H:%i:%s');
?>
For more information OF DATETIME format, refer: here
You can change the interval format in the way,you want.
Here is the working example
P.S. These features( diff() and format()) work with >=PHP 5.3.0 only
Some basics:
RTSP server can be used for dead source as well as for live source. RTSP protocols provides you commands (Like your VCR Remote), and functionality depends upon your implementation.
RTP is real time protocol used for transporting audio and video in real time. Transport used can be unicast, multicast or broadcast, depending upon transport address and port. Besides transporting RTP does lots of things for you like packetization, reordering, jitter control, QoS, support for Lip sync.....
In your case if you want broadcasting streaming server then you need both RTSP (for control) as well as RTP (broadcasting audio and video)
To start with you can go through sample code provided by live555
Your model is @Messages
, change it to @message
.
To change it like you should use migration:
def change rename_table :old_table_name, :new_table_name end
Of course do not create that file by hand but use rails generator:
rails g migration ChangeMessagesToMessage
That will generate new file with proper timestamp in name in 'db
dir. Then run:
rake db:migrate
And your app should be fine since then.
Use LEFT JOIN
SELECT a.*
FROM table1 a
LEFT JOIN table2 b
on a.ID = b.ID
WHERE b.id IS NULL
After making the id
unique across the document
,You have to use event delegation
$("#container").on("click", "buttonid", function () {
alert("Hi");
});
I faced with the same issue. I just added credentials config:
aws_access_key_id = your_aws_access_key_id
aws_secret_access_key = your_aws_secret_access_key
into "~/.aws/credentials" + restart terminal for default profile.
In the case of multi profiles --profile arg needs to be added:
aws s3 sync ./localDir s3://bucketName --profile=${PROFILE_NAME}
where PROFILE_NAME:
.bash_profile ( or .bashrc) -> export PROFILE_NAME="yourProfileName"
More info about how to config credentials and multi profiles can be found here