Change debug port of your server configured in the Intelli J.
if non of the steps work from the above. my device still offline after connected through wifi. i did the following:
go to your device...
go to settings.
go to developer options.
Allow adb debugging in charge mode only.
repeat the steps as you always do . which is:
a. connet your usb on chargemode only. b. open command write: - adb tcpip 4455 - adb connect 192.168.1.11:4455 b. disconnect usb.
now everythings work for me .
I had the same problem in Safari and Chrome (the only ones I've tested) but I just did something that seems to work, at least I haven't been able to reproduce the problem since I added the solution. What I did was add a metatag to the header with a generated timstamp. Doesn't seem right but it's simple :)
<meta name="304workaround" content="2013-10-24 21:17:23">
Update P.S As far as I can tell, the problem disappears when I remove my node proxy (by proxy i mean both express.vhost and http-proxy module), which is weird...
1. //push the latest changes of current development branch if any
git push (current development branch)
2. //switch to master branch
git checkout master
3. //pull all the changes if any from (current development branch)
git pull origin (current development branch)
4. //Now merge development into master
git merge development
5. //push the master branch
git push origin master
Error
To https://github.com/rajputankit22/todos-posts.git
! [rejected] master -> master (fetch first)
error: failed to push some refs to 'https://github.com/rajputankit22/todos-posts.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
Then Use
5. //push the master branch forcefully
git push -f origin master
Next variation on Peter Lawrey's answer without initialization of a new string every loop turn
String concatList(List<String> sList, String separator)
{
Iterator<String> iter = sList.iterator();
StringBuilder sb = new StringBuilder();
while (iter.hasNext())
{
sb.append(iter.next()).append( iter.hasNext() ? separator : "");
}
return sb.toString();
}
The differences are
String class is overriding toString(), equals(), hashCode() of Object class, but StringBuffer only overrides toString().
String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1.equals(s2)); // output true
StringBuffer sb1 = new StringBuffer("abc");
StringBuffer sb2 = new StringBuffer("abc");
System.out.println(sb1.equals(sb2)); // output false
String class is both Serializable as well as Comparable, but StringBuffer is only Serializable.
Set<StringBuffer> set = new TreeSet<StringBuffer>();
set.add(sb1);
set.add(sb2);
System.out.println(set); // gives ClassCastException because there is no Comparison mechanism
We can create a String object with and without new operator, but StringBuffer object can only be created using new operator.
For anyone experiencing this issue working on a Django application and deploying to AWS, the method described in this tutorial worked for me: https://realpython.com/deploying-a-django-app-and-postgresql-to-aws-elastic-beanstalk/
Here is the author's explanation for when you get the following error:
Error: pg_config executable not found.
The problem is that we tried to install psycopy2 (the Postgres Python bindings), but we need the Postgres client drivers to be installed as well. Since they are not installed by default, we need to install them first.
eb will read custom .config files from a folder called “.ebextensions” at the root level of your project. These .config files allow you to install packages, run arbitrary commands and/or set environment variables. Files in the “.ebextensions” directory should conform to either JSON or YAML syntax and are executed in alphabetical order.
The first thing to do is install some packages so that our pip install command will complete successfully. To do this, let’s create a file called .ebextensions/01_packages.config:
packages:
yum:
git: []
postgresql93-devel: []
libjpeg-turbo-devel: []
EC2 instances run Amazon Linux, which is a Redhat flavor, so we can use yum to install the packages that we need. For now, we are just going to install three packages - git, the Postgres client, and libjpeg for Pillow.
Here is an example of concatenation operator:
architecture EXAMPLE of CONCATENATION is
signal Z_BUS : bit_vector (3 downto 0);
signal A_BIT, B_BIT, C_BIT, D_BIT : bit;
begin
Z_BUS <= A_BIT & B_BIT & C_BIT & D_BIT;
end EXAMPLE;
I found a solution.
background-size:100% auto;
Regarding existing answers, note that signal handling is platform dependent. Win32 for example handles far fewer signals than POSIX operating systems; see here. While SIGINT is declared in signals.h on Win32, see the note in the documentation that explains that it will not do what you might expect.
I changed the plugin folder name. Restart Notepad ++ It works now, a
In sql server, you can do
SELECT *
FROM table t
WHERE t.date > DATEADD(dd,90,now())
In case someone needs a CSS background with different color repeating horizontal stripes, here is how I managed to achieve this:
body {_x000D_
font-family: 'Lucida Grande', 'Helvetica Neue', Helvetica, Arial, sans-serif;_x000D_
font-size: 13px;_x000D_
}_x000D_
_x000D_
.css-stripes {_x000D_
margin: 0 auto;_x000D_
width: 200px;_x000D_
padding: 100px;_x000D_
text-align: center;_x000D_
/* For browsers that do not support gradients */_x000D_
background-color: #F691FF;_x000D_
/* Safari 5.1 to 6.0 */_x000D_
background: -webkit-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
/* Opera 11.1 to 12.0 */_x000D_
background: -o-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
/* Firefox 3.6 to 15 */_x000D_
background: -moz-repeating-linear-gradient(#F691FF, #EC72A8);_x000D_
/* Standard syntax */_x000D_
background-image: repeating-linear-gradient(to top, #F691FF, #EC72A8);_x000D_
background-size: 1px 2px;_x000D_
}
_x000D_
<div class="css-stripes">Hello World!</div>
_x000D_
For any char with ord($char) < 16 you get a HEX back which is only 1 long. You forgot to add 0 padding.
This should solve it:
<?php
function strToHex($string){
$hex = '';
for ($i=0; $i<strlen($string); $i++){
$ord = ord($string[$i]);
$hexCode = dechex($ord);
$hex .= substr('0'.$hexCode, -2);
}
return strToUpper($hex);
}
function hexToStr($hex){
$string='';
for ($i=0; $i < strlen($hex)-1; $i+=2){
$string .= chr(hexdec($hex[$i].$hex[$i+1]));
}
return $string;
}
// Tests
header('Content-Type: text/plain');
function test($expected, $actual, $success) {
if($expected !== $actual) {
echo "Expected: '$expected'\n";
echo "Actual: '$actual'\n";
echo "\n";
$success = false;
}
return $success;
}
$success = true;
$success = test('00', strToHex(hexToStr('00')), $success);
$success = test('FF', strToHex(hexToStr('FF')), $success);
$success = test('000102FF', strToHex(hexToStr('000102FF')), $success);
$success = test('???§P?§P ?§T?§?', hexToStr(strToHex('???§P?§P ?§T?§?')), $success);
echo $success ? "Success" : "\nFailed";
As cardern has said list will do the job.
Here is how you can use a named range.
Select your range and enter a new name:
Select your cell that you want a drop down to be in and goto data tab -> data validation.
Select 'List' from the 'Allow' Drop down menu.
Enter your named range like this:
Now you have a drop down linked to your range. If you insert new rows in your range everything will update automatically.
This works:
var form = $(this).closest('form');
form = form.serializeArray();
form = form.concat([
{name: "customer_id", value: window.username},
{name: "post_action", value: "Update Information"}
]);
$.post('/change-user-details', form, function(d) {
if (d.error) {
alert("There was a problem updating your user details")
}
});
LocalDate.parse( "2011-01-01" )
.format( DateTimeFormatter.ofPattern( "MM-dd-uuuu" ) )
The other Answers are now outdated. The troublesome old date-time classes such as java.util.Date
, java.util.Calendar
, and java.text.SimpleDateFormat
are now legacy, supplanted by the java.time classes.
The input string 2011-01-01
happens to comply with the ISO 8601 standard formats for date-time text. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate
The LocalDate
class represents a date-only value without time-of-day and without time zone.
LocalDate ld = LocalDate.parse( "2011-01-01" ) ;
Generate a String in the same format by calling toString
.
String output = ld.toString() ;
2011-01-01
DateTimeFormatter
To parse/generate other formats, use a DateTimeFormatter
.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM-dd-uuuu" ) ;
String output = ld.format( f ) ;
01-01-2011
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
I just emptied my session data then it worked again. Here is where you find the button:
I don't know about elegant, but it's certainly doable:
oldlist = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
# change into: list = [["A", "C"], ["B"], ["D", "E"]]
order=[]
dic=dict()
for value,key in oldlist:
try:
dic[key].append(value)
except KeyError:
order.append(key)
dic[key]=[value]
newlist=map(dic.get, order)
print newlist
This preserves the order of the first occurence of each key, as well as the order of items for each key. It requires the key to be hashable, but does not otherwise assign meaning to it.
I know this is extremely late to the party, but now, in year 2013, we have a few media types to cover error handling in a common distributed (RESTful) fashion. See "vnd.error", application/vnd.error+json (https://github.com/blongden/vnd.error) and "Problem Details for HTTP APIs", application/problem+json (https://tools.ietf.org/html/draft-nottingham-http-problem-05).
Don't forget to reboot your computer after installing node! That one got me.
I love how this is explained in the article Cool performance features of EclipseLink 2.5
Indexing Foreign Keys
The first feature is auto indexing of foreign keys. Most people incorrectly assume that databases index foreign keys by default. Well, they don't. Primary keys are auto indexed, but foreign keys are not. This means any query based on the foreign key will be doing full table scans. This is any OneToMany, ManyToMany or ElementCollection relationship, as well as many OneToOne relationships, and most queries on any relationship involving joins or object comparisons. This can be a major perform issue, and you should always index your foreign keys fields.
A standard Maven
settings.xml
file is as follows:
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
<localRepository/>
<interactiveMode/>
<usePluginRegistry/>
<offline/>
<proxies>
<proxy>
<active/>
<protocol/>
<username/>
<password/>
<port/>
<host/>
<nonProxyHosts/>
<id/>
</proxy>
</proxies>
<servers>
<server>
<username/>
<password/>
<privateKey/>
<passphrase/>
<filePermissions/>
<directoryPermissions/>
<configuration/>
<id/>
</server>
</servers>
<mirrors>
<mirror>
<mirrorOf/>
<name/>
<url/>
<layout/>
<mirrorOfLayouts/>
<id/>
</mirror>
</mirrors>
<profiles>
<profile>
<activation>
<activeByDefault/>
<jdk/>
<os>
<name/>
<family/>
<arch/>
<version/>
</os>
<property>
<name/>
<value/>
</property>
<file>
<missing/>
<exists/>
</file>
</activation>
<properties>
<key>value</key>
</properties>
<repositories>
<repository>
<releases>
<enabled/>
<updatePolicy/>
<checksumPolicy/>
</releases>
<snapshots>
<enabled/>
<updatePolicy/>
<checksumPolicy/>
</snapshots>
<id/>
<name/>
<url/>
<layout/>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<releases>
<enabled/>
<updatePolicy/>
<checksumPolicy/>
</releases>
<snapshots>
<enabled/>
<updatePolicy/>
<checksumPolicy/>
</snapshots>
<id/>
<name/>
<url/>
<layout/>
</pluginRepository>
</pluginRepositories>
<id/>
</profile>
</profiles>
<activeProfiles/>
<pluginGroups/>
</settings>
To access a proxy
, you can find detailed information on the official Maven
page here:
I hope it helps for someone.
In my case I used another solution.
As the project doesn't require CommonJS and it must have ES3 compatibility (modules not supported) all you need is just remove all export and import statements from your code, because your tsconfig doesn't contain
"module": "commonjs"
But use import and export statements in your referenced files
import { Utils } from "./utils"
export interface Actions {}
Final generated code will always have(at least for TypeScript 3.0) such lines
"use strict";
exports.__esModule = true;
var utils_1 = require("./utils");
....
utils_1.Utils.doSomething();
You can use, for example:
words = [word.replace('[br]','<br />') for word in words]
If something happens in any browser I'd be surprised. This is one of those outstanding form elements that browsers tend not to let you style that much, and that people usually try to replace with javascript so they can style/code something to look and act like a checkbox.
Actually, even that didn't work for me. When I executed "select dbms_metadata.get_ddl('TABLESPACE','TABLESPACE_NAME') from dual;" I again got only the first three lines, but this time each line was padded out to 15,000 characters. I was able to work around this with:
select substr(dbms_metadata.get_ddl('TABLESPACE','LM_THIN_DATA'),80) from dual;
select substr(dbms_metadata.get_ddl('TABLESPACE','LM_THIN_DATA'),160) from dual;
select substr(dbms_metadata.get_ddl('TABLESPACE','LM_THIN_DATA'),240) from dual;
It sure seemed like there ought to be an easier way, but I couldn't seem to find it.
For debugging when I start java add like mentioned:
-Djavax.net.debug=ssl
then you can see that the browser tried to use TLSv1 and Jetty 9.1.3 was talking TLSv1.2 so they were not communicating. That's Firefox. Chrome wanted SSLv3 so I added that also.
sslContextFactory.setIncludeProtocols( "TLSv1", "SSLv3" ); <-- Fix
sslContextFactory.setRenegotiationAllowed(true); <-- added don't know if helps anything.
I did not do most of the other stuff the orig poster did:
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
or this answer:
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory
.getDefaultAlgorithm());
or
.setEnabledCipherSuites
I created one self signed cert like this: (but I added .jks to filename) and read that in my jetty java code. http://www.eclipse.org/jetty/documentation/current/configuring-ssl.html
keytool -keystore keystore.jks -alias jetty -genkey -keyalg RSA
first & lastname *.mywebdomain.com
since android 4.4 file saving has been changed. there is
ContextCompat.getExternalFilesDirs(context, name);
it retuns an array.
when name is null
the first value is like /storage/emulated/0/Android/com.my.package/files
the second value is like /storage/extSdCard/Android/com.my.package/files
android 4.3 and less it retuns a single item array
parts of little messy code but it demonstrates how it works:
/** Create a File for saving an image or video
* @throws Exception */
private File getOutputMediaFile(int type) throws Exception{
// Check that the SDCard is mounted
File mediaStorageDir;
if(internalstorage.isChecked())
{
mediaStorageDir = new File(getFilesDir().getAbsolutePath() );
}
else
{
File[] dirs=ContextCompat.getExternalFilesDirs(this, null);
mediaStorageDir = new File(dirs[dirs.length>1?1:0].getAbsolutePath() );
}
// Create the storage directory(MyCameraVideo) if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
output.setText("Failed to create directory.");
Toast.makeText(this, "Failed to create directory.", Toast.LENGTH_LONG).show();
Log.d("myapp", "Failed to create directory");
return null;
}
}
// Create a media file name
// For unique file name appending current timeStamp with file name
java.util.Date date= new java.util.Date();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.ENGLISH) .format(date.getTime());
File mediaFile;
if(type == MEDIA_TYPE_VIDEO) {
// For unique video file name appending current timeStamp with file name
mediaFile = new File(mediaStorageDir.getPath() + File.separator + slpid + "_" + pwsid + "_" + timeStamp + ".mp4");
}
else if(type == MEDIA_TYPE_AUDIO) {
// For unique video file name appending current timeStamp with file name
mediaFile = new File(mediaStorageDir.getPath() + File.separator + slpid + "_" + pwsid + "_" + timeStamp + ".3gp");
} else {
return null;
}
return mediaFile;
}
/** Create a file Uri for saving an image or video
* @throws Exception */
private Uri getOutputMediaFileUri(int type) throws Exception{
return Uri.fromFile(getOutputMediaFile(type));
}
//usage:
try {
file=getOutputMediaFileUri(MEDIA_TYPE_AUDIO).getPath();
} catch (Exception e1) {
e1.printStackTrace();
return;
}
You can access elements of parent window from within an iframe by using window.parent
like this:
// using jquery
window.parent.$("#element_id");
Which is the same as:
// pure javascript
window.parent.document.getElementById("element_id");
And if you have more than one nested iframes and you want to access the topmost iframe, then you can use window.top
like this:
// using jquery
window.top.$("#element_id");
Which is the same as:
// pure javascript
window.top.document.getElementById("element_id");
This is a circle shape with icon inside:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ok_icon"/>
<item>
<shape
android:shape="oval">
<solid android:color="@color/transparent"/>
<stroke android:width="2dp" android:color="@color/button_grey"/>
</shape>
</item>
</layer-list>
You could make use of the Javascript DOM API. In particular, look at the createElement() method.
You could create a re-usable function that will create an image like so...
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
// This next line will just add it to the <body> tag
document.body.appendChild(img);
}
Then you could use it like this...
<button onclick=
"show_image('http://google.com/images/logo.gif',
276,
110,
'Google Logo');">Add Google Logo</button>
I was trying to figure this out myself recently, and I came up with a good solution that works perfectly in my browser (Chrome 51) and supports dynamic column widths. I should mention that after I independently derived my answer I also found a similar technique described elsewhere on the web...
The trick is to use two identical tables positioned on top of one another. The lower table is visible and the upper table is invisible expect for the header. The upper table also has pointer-events: none
set on the tbody so mouse interactions hit the underneath table. This way the lower table scrolls under the upper table's header.
For everything to layout and resize properly (when the user adjusts screen width for instance), both tables need to have the same scrollbar behavior. However, the upper table's scroll bar is ignored thanks to the pointer-events: none
and can be made invisible with:
<style>
.hiddenScrollbar::-webkit-scrollbar {
background-color: transparent;
}
</style>
Here is the complete code:
<html>_x000D_
_x000D_
<head>_x000D_
<style>_x000D_
td {_x000D_
border: 1px solid black; _x000D_
white-space: nowrap;_x000D_
}_x000D_
th {_x000D_
background-color: gray;_x000D_
border: 1px solid black;_x000D_
white-space: nowrap;_x000D_
}_x000D_
.hiddenScrollbar::-webkit-scrollbar {_x000D_
background-color: transparent;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
Table test. Use mouse wheel to scroll or scroll to the right to see vertical scroll bar. You can also remove the outermost div if you don't want a horizontal scroll bar._x000D_
<br/>_x000D_
<div style="display: inline-block; height: 10em; width: 15em; overflow-x: scroll; overflow-y: hidden">_x000D_
<div style="position: relative;">_x000D_
<div style="display: inline-block; position: absolute; left: 0px; top: 0px; height: 10em; overflow-y: scroll">_x000D_
<table style="border-collapse: collapse;">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Column 1</th>_x000D_
<th>Another Column</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>Data 1</td>_x000D_
<td>123409213750213</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data 2</td>_x000D_
<td>123409213750213</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data 3</td>_x000D_
<td>123409213750213</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data 4</td>_x000D_
<td>123409213750213</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data 5</td>_x000D_
<td>123409213750213</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data 6</td>_x000D_
<td>12340921375021342354235 very long...</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data 7</td>_x000D_
<td>123409213750213</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data 8</td>_x000D_
<td>123409213750213</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data 9</td>_x000D_
<td>123409213750213</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data 10</td>_x000D_
<td>123409213750213</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data 11</td>_x000D_
<td>123409213750213</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data 12</td>_x000D_
<td>123409213750213</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>_x000D_
<div class="hiddenScrollbar" style="display: inline-block; pointer-events: none; position: relative; left: 0px; top: 0px; height: 10em; overflow-y: scroll">_x000D_
<table style="border-collapse: collapse;">_x000D_
<thead style="pointer-events: auto">_x000D_
<tr>_x000D_
<th>Column 1</th>_x000D_
<th>Another Column</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody style="visibility: hidden">_x000D_
<tr>_x000D_
<tr>_x000D_
<td>Data 1</td>_x000D_
<td>123409213750213</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data 2</td>_x000D_
<td>123409213750213</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data 3</td>_x000D_
<td>123409213750213</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data 4</td>_x000D_
<td>123409213750213</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data 5</td>_x000D_
<td>123409213750213</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data 6</td>_x000D_
<td>12340921375021342354235 very long...</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data 7</td>_x000D_
<td>123409213750213</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data 8</td>_x000D_
<td>123409213750213</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data 9</td>_x000D_
<td>123409213750213</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data 10</td>_x000D_
<td>123409213750213</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data 11</td>_x000D_
<td>123409213750213</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Data 12</td>_x000D_
<td>123409213750213</td>_x000D_
</tr>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>_x000D_
</div>_x000D_
</div><br/>_x000D_
Stuff after table._x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Caveats: More work is required to prove this works in other browsers. Also I was rather liberal in mixing inline and stylesheet styles. However I believe the general concept is the best way of doing this since if the target browser supports it. The only functionality/display issues are that if you want a horizontal scroll bar, the vertical scroll bar can get scrolled out of view (as shown in the snippet). You can still scroll with the mouse wheel though. Additionally you can't have a transparent background on the header (otherwise the underneath table would show through). Finally you need a way to generate two identical tables. Personally I am using react.js and it is easy to do it with react, but php or other server-side generation or javascript will also work.
Below code is nice.. It was given by somebody else named aaronbd in this forum
<?php
$conn = new mysqli('localhost', 'username', 'password', 'database')
or die ('Cannot connect to db');
$result = $conn->query("select id, name from table");
echo "<html>";
echo "<body>";
echo "<select name='id'>";
while ($row = $result->fetch_assoc()) {
unset($id, $name);
$id = $row['id'];
$name = $row['name'];
echo '<option value="'.$id.'">'.$name.'</option>';
}
echo "</select>";
echo "</body>";
echo "</html>";
?>
$(window).bind("load", function() {
// write your code here
});
You can use assign
(doc) to change the value of perf.a1:
> assign(paste("perf.a", "1", sep=""),5)
> perf.a1
[1] 5
In my case, I was using a View that I´ve converted to partial view and I forgot to remove the template from "@section scripts". Removing the section block, solved my problem. This is because the sections aren´t rendered in partial views.
I suspect it's the same problem as when you use shortcuts in Windows... Try this:
import os;
os.system("\"C:\\Temp\\a b c\\Notepad.exe\" C:\\test.txt");
Taken From www.regular-expressions.info
Greediness: Greedy quantifiers first tries to repeat the token as many times as possible, and gradually gives up matches as the engine backtracks to find an overall match.
Laziness: Lazy quantifier first repeats the token as few times as required, and gradually expands the match as the engine backtracks through the regex to find an overall match.
I was facing same issue , In my case JQuery-ui.js version was 1.10.3, After referring jquery-ui-1.12.1.min.js close button started to visible.
A couple of wires are crossed here. The various autoplay
settings that you're working with only affect whether the SWF's root timeline starts out paused or not. So if your SWF had a timeline animation, or if it had an embedded video on the root timeline, then these settings would do what you're after.
However, the SWF you're working with almost certainly has only one frame on its timeline, so these settings won't affect playback at all. That one frame contains some flavor of video playback component, which contains ActionScript that controls how the video behaves. To get that player component to start of paused, you'll have to change the settings of the component itself.
Without knowing more about where the content came from it's hard to say more, but when one publishes from Flash, video player components normally include a parameter for whether to autoplay. If your SWF is being published by an application other than Flash (Captivate, I suppose, but I'm not up on that) then your best bet would be to check the settings for that app. Anyway it's not something you can control from the level of the HTML page. (Unless you were talking to the SWF from JavaScript, and for that to work the video component would have to be designed to allow it.)
You must check the String length. You assume that you can do substring(0,38)
as long as String is not null
, but you actually need the String to be of at least 38 characters length.
Here are two nice ways of doing that:
1.
import os
# Clear Windows command prompt.
if (os.name in ('ce', 'nt', 'dos')):
os.system('cls')
# Clear the Linux terminal.
elif ('posix' in os.name):
os.system('clear')
2.
import os
def clear():
if os.name == 'posix':
os.system('clear')
elif os.name in ('ce', 'nt', 'dos'):
os.system('cls')
clear()
I think you want to execute the javascript serverside and not in the browser after post-back, right?
That's not possible as far as I know
If you just want to get it execute after postback, you can do something like this:
this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "xx", "<script>test("+x+","+y+");</script>");
You can also run this script to find out the Apache process owner:
<?php echo exec('whoami'); ?>
And then change the owner of the destination directory to what you've got. Use the command:
chown user destination_dir
And then use the command
chmod 755 destination_dir
to change the destination directory permission.
Unicode string handling is already standardized in Python 3.
You only need to open file in utf-8
(32-bit Unicode to variable-byte-length utf-8 conversion is automatically performed from memory to file.)
out1 = "(???? ??? ??´ ??` ???` )"
fobj = open("t1.txt", "w", encoding="utf-8")
fobj.write(out1)
fobj.close()
concept = concept.encode('ascii', 'ignore')
concept = MySQLdb.escape_string(concept.decode('latin1').encode('utf8').rstrip())
I do this, I am not sure if that is a good approach but it works everytime !!
Just tried this solution, we don't have to even write int.
int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } };
Arrays.sort(twoDim, (a1,a2) -> a2[0] - a1[0]);
This thing will also work, it automatically detects the type of string.
I'd like to recommend two options worth considering. Both quite new and evolving.
ClangFormat-Xcode (free) - on each cmd+s file is reformatted to specific style and saved, easy to deploy within team
An Xcode plug-in to format your code using Clang's format tools, by @travisjeffery.
With clang-format you can use Clang to format your code to styles such as LLVM, Google, Chromium, Mozilla, WebKit, or your own configuration.
Objective-Clean (paid, didn't try it yet) - app raising build errors if predefined style rules are violated - possibly quite hard to use within the team, so I didn't try it out.
With very minimal setup, you can get Xcode to use our App to enforce your rules. If you are ever caught violating one of your rules, Xcode will throw a build error and take you right to the offending line.
Came across this issue two days back, spent whole complete two days, So I found that I need to give the access to IUSR user group at DCOMCNFG --> My Computer Properties --> Com Security --> Launch and Activation Permissions --> Edit defaults and give all rights to IUSR.
hope it will help someone....
I made a simple to use utility, hope you enjoy.
If the generated INSERT statements are being truncated, check the limit text length of the results on the Management Studio Options: Tools > Options
, Query Results > SQL Server > Results to Grid
, "Non XML data" value under "Maximum Characters Retrieved".
-- Make sure you're on the correct database
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION
DECLARE @Tables TABLE (
TableName varchar(50) NOT NULL,
Arguments varchar(1000) NULL
);
-- INSERT HERE THE TABLES AND CONDITIONS YOU WANT TO GENERATE THE INSERT STATEMENTS
INSERT INTO @Tables (TableName, Arguments) VALUES ('table1', 'WHERE field1 = 3101928464');
-- (ADD MORE LINES IF YOU LIKE) INSERT INTO @Tables (TableName, Arguments) VALUES ('table2', 'WHERE field2 IN (1, 3, 5)');
-- YOU DON'T NEED TO EDIT FROM NOW ON.
-- Generating the Script
DECLARE @TableName varchar(50),
@Arguments varchar(1000),
@ColumnName varchar(50),
@strSQL varchar(max),
@strSQL2 varchar(max),
@Lap int,
@Iden int,
@TypeOfData int;
DECLARE C1 CURSOR FOR
SELECT TableName, Arguments FROM @Tables
OPEN C1
FETCH NEXT FROM C1 INTO @TableName, @Arguments;
WHILE @@FETCH_STATUS = 0
BEGIN
-- If you want to delete the lines before inserting, uncomment the next line
-- PRINT 'DELETE FROM ' + @TableName + ' ' + @Arguments
SET @strSQL = 'INSERT INTO ' + @TableName + ' (';
-- List all the columns from the table (to the INSERT into columns...)
SET @Lap = 0;
DECLARE C2 CURSOR FOR
SELECT sc.name, sc.type FROM syscolumns sc INNER JOIN sysobjects so ON so.id = sc.id AND so.name = @TableName AND so.type = 'U' WHERE sc.colstat = 0 ORDER BY sc.colorder
OPEN C2
FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
WHILE @@FETCH_STATUS = 0
BEGIN
IF(@Lap>0)
BEGIN
SET @strSQL = @strSQL + ', ';
END
SET @strSQL = @strSQL + @ColumnName;
SET @Lap = @Lap + 1;
FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
END
CLOSE C2
DEALLOCATE C2
SET @strSQL = @strSQL + ')'
SET @strSQL2 = 'SELECT ''' + @strSQL + '
SELECT '' + ';
-- List all the columns from the table again (for the SELECT that will be the input to the INSERT INTO statement)
SET @Lap = 0;
DECLARE C2 CURSOR FOR
SELECT sc.name, sc.type FROM syscolumns sc INNER JOIN sysobjects so ON so.id = sc.id AND so.name = @TableName AND so.type = 'U' WHERE sc.colstat = 0 ORDER BY sc.colorder
OPEN C2
FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
WHILE @@FETCH_STATUS = 0
BEGIN
IF(@Lap>0)
BEGIN
SET @strSQL2 = @strSQL2 + ' + '', '' + ';
END
-- For each data type, convert the data properly
IF(@TypeOfData IN (55, 106, 56, 108, 63, 38, 109, 50, 48, 52)) -- Numbers
SET @strSQL2 = @strSQL2 + 'ISNULL(CONVERT(varchar(max), ' + @ColumnName + '), ''NULL'') + '' as ' + @ColumnName + '''';
ELSE IF(@TypeOfData IN (62)) -- Float Numbers
SET @strSQL2 = @strSQL2 + 'ISNULL(CONVERT(varchar(max), CONVERT(decimal(18,5), ' + @ColumnName + ')), ''NULL'') + '' as ' + @ColumnName + '''';
ELSE IF(@TypeOfData IN (61, 111)) -- Datetime
SET @strSQL2 = @strSQL2 + 'ISNULL( '''''''' + CONVERT(varchar(max),' + @ColumnName + ', 121) + '''''''', ''NULL'') + '' as ' + @ColumnName + '''';
ELSE IF(@TypeOfData IN (47, 39)) -- Texts
SET @strSQL2 = @strSQL2 + 'ISNULL('''''''' + RTRIM(LTRIM(' + @ColumnName + ')) + '''''''', ''NULL'') + '' as ' + @ColumnName + '''';
ELSE -- Unknown data types
SET @strSQL2 = @strSQL2 + 'ISNULL(CONVERT(varchar(max), ' + @ColumnName + '), ''NULL'') + '' as ' + @ColumnName + '(INCORRECT TYPE ' + CONVERT(varchar(10), @TypeOfData) + ')''';
SET @Lap = @Lap + 1;
FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
END
CLOSE C2
DEALLOCATE C2
SET @strSQL2 = @strSQL2 + ' as [-- ' + @TableName + ']
FROM ' + @TableName + ' WITH (NOLOCK) ' + @Arguments
SET @strSQL2 = @strSQL2 + ';
';
--PRINT @strSQL;
--PRINT @strSQL2;
EXEC(@strSQL2);
FETCH NEXT FROM C1 INTO @TableName, @Arguments;
END
CLOSE C1
DEALLOCATE C1
ROLLBACK
END TRY
BEGIN CATCH
ROLLBACK TRAN
SELECT 0 AS Situacao;
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage,
@strSQL As strSQL,
@strSQL2 as strSQL2;
END CATCH
// javascript using jQuery - can embed in the script tag
$(".video-link").click(function () {
var theModal = $(this).data("target");
videoSRC = $(this).attr("data-video");
videoSRCauto = videoSRC + "?modestbranding=1&rel=0&showinfo=0&html5=1&autoplay=1";
$(theModal + ' iframe').attr('src', videoSRCauto);
$(theModal + ' button.close').click(function () {
$(theModal + ' iframe').attr('src', videoSRC);
});
});
_x000D_
#video-section .modal-content {
min-width: 600px;
}
#video-section .modal-content iframe {
width: 560px;
height: 315px;
}
_x000D_
<!-- HTML with Bootstrap 4.5 and Fontawesome -->
<html>
<head>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.13.1/css/all.css"
integrity="sha384-xxzQGERXS00kBmZW/6qxqJPyxW3UR0BPsL4c8ILaIWXva5kFi7TxkIIaMiKtqV1Q" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
<section id="video-section" class="py-5 text-center text-white">
<div class="container h-100 d-flex justify-content-center">
<div class="row align-self-center">
<div class="col">
<div class="card bg-dark border-0 mb-2 text-white">
<div class="card-body">
<a href="#" class="btn btn-primary bg-dark stretched-link video-link" data-video="https://www.youtube.com/embed/HnwsG9a5riA" data-toggle="modal" data-target="#video-modal">
<i class="fas fa-play fa-3x"></i>
</a>
<h1 class="card-title">Play Video</h1>
</div>
</div>
</div>
</div>
</div>
<!-- Video Modal -->
<div class="modal fade" id="video-modal" tabindex="-1" role="dialog">
<div class="modal-dialog h-100 d-flex align-items-center">
<div class="modal-content">
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal">
<span>×</span>
</button>
<iframe frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
</section>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
</body>
</html>
_x000D_
[1]: https://codepen.io/richierich25/pen/yLOOYBL
Gil's answer holds promise (the library he linked to) --- but for the time being, it still doesn't work when scrolled down on the mobile device.
I solved the issue for myself using just a snippet of CSS at the end of my CSS files:
@media (max-width: 767px) {
#content .modal.fade.in {
top: 5%;
}
}
The #content
selector is simply an id that wraps my html so I can override Bootstrap's specificity (set to your own id wrapping your modal html).
The downside: It's not centered vertically on the mobile devices.
The upside: It's visible, and on smaller devices, a reasonably sized modal will take up much of the screen, so the "non-centering" won't be as apparent.
When you're at low screen sizes with Bootstrap's responsive CSS, for devices with smaller screens, it sets .modal.fade.in's 'top' to 'auto'. For some reason the mobile webkit browsers seem to have a hard time with figuring out the vertical placement with the "auto" assignment. So just switch it back to a fixed value and it works great.
Since the modal is already set to postition: absolute, the value is relative to the viewport's height, not the document height, so it works no matter how long the page is or where you're scrolled to.
You can do this with "just the regular expression" as you asked for in a comment:
(?<=sentence).*
(?<=sentence)
is a positive lookbehind assertion. This matches at a certain position in the string, namely at a position right after the text sentence
without making that text itself part of the match. Consequently, (?<=sentence).*
will match any text after sentence
.
This is quite a nice feature of regex. However, in Java this will only work for finite-length subexpressions, i. e. (?<=sentence|word|(foo){1,4})
is legal, but (?<=sentence\s*)
isn't.
They are successive, improved versions of the same product. Anyone noticed how the names of the last three and the next release are in alphabetical order (Galileo, Helios, Indigo, Juno)? This is probably how they will go in the future, in the same way that Ubuntu release codenames increase alphabetically (note Indigo is not a moon of Jupiter!).
functional requirements are the main things that the user expects from the software for example if the application is a banking application that application should be able to create a new account, update the account, delete an account, etc. functional requirements are detailed and are specified in the system design
Non-functional requirement are not straight forward the requirement of the system rather it is related to usability( in some way ) for example for a banking application a major non-functional requirement will be available the application should be available 24/7 with no downtime if possible.
Do you have a local user.name
or user.email
that's overriding the global one?
git config --list --global | grep user
user.name=YOUR NAME
user.email=YOUR@EMAIL
git config --list --local | grep user
user.name=YOUR NAME
user.email=
If so, remove them
git config --unset --local user.name
git config --unset --local user.email
The local settings are per-clone, so you'll have to unset the local user.name
and user.email
for each of the repos on your machine.
I successfully use the following method in one file,
But come up with exactly the same error again... Only the last line come up with error
Newpath = Mid(ThisWorkbook.FullName, 1, _
Len(ThisWorkbook.FullName) - Len(ThisWorkbook.Name)) & "\" & "ABC - " & Format(Date, "dd-mm-yyyy") & ".xlsm"
ThisWorkbook.SaveAs (Newpath)
You can use chsh to change a user's shell.
Run the following code, for instance, to change your shell to Zsh
chsh -s /bin/zsh
As described in the manpage, and by Lorin, if the shell is not known by the OS, you have to add it to its known list: /etc/shells
.
If your chart uses both fill
and color
aesthetics, you can remove the legend with:
+ guides(fill=FALSE, color=FALSE)
TCPDF is PHP class for generating pdf documents.Here we will learn TCPDF integration with CodeIgniter.we will use following step for TCPDF integration with CodeIgniter.
Step 1
To Download TCPDF Click Here.
Step 2
Unzip the above download inside application/libraries/tcpdf.
Step 3
Create a new file inside application/libraries/Pdf.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once dirname(__FILE__) . '/tcpdf/tcpdf.php';
class Pdf extends TCPDF
{ function __construct() { parent::__construct(); }
}
/*Author:Tutsway.com */
/* End of file Pdf.php */
/* Location: ./application/libraries/Pdf.php */
Step 4
Create Controller file inside application/controllers/pdfexample.php.
<?php
class pdfexample extends CI_Controller{
function __construct()
{ parent::__construct(); } function index() {
$this->load->library('Pdf');
$pdf = new Pdf('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetTitle('Pdf Example');
$pdf->SetHeaderMargin(30);
$pdf->SetTopMargin(20);
$pdf->setFooterMargin(20);
$pdf->SetAutoPageBreak(true);
$pdf->SetAuthor('Author');
$pdf->SetDisplayMode('real', 'default');
$pdf->Write(5, 'CodeIgniter TCPDF Integration');
$pdf->Output('pdfexample.pdf', 'I'); }
}
?>
It is working for me. I have taken reference from http://www.tutsway.com/codeignitertcpdf.php
Try curl -v http://localhost:8080/
instead of 127.0.0.1
I was just tinkering with danteuno's answer and found that while good-intentioned, sadly it's broken on several browsers that are not IE. This is because IE will be quite strict about what it accepts as the argument to the Date
constructor, but others will not. For example, Chrome 18 gives
> new Date("66")
Sat Jan 01 1966 00:00:00 GMT+0200 (GTB Standard Time)
This causes the code to take the "compare dates" path and it all goes downhill from there (e.g. new Date("11")
is greater than new Date("66")
and this is obviously the opposite of the desired effect).
Therefore after consideration I modified the code to give priority to the "numbers" path over the "dates" path and validate that the input is indeed numeric with the excellent method provided in Validate decimal numbers in JavaScript - IsNumeric().
In the end, the code becomes:
$.validator.addMethod(
"greaterThan",
function(value, element, params) {
var target = $(params).val();
var isValueNumeric = !isNaN(parseFloat(value)) && isFinite(value);
var isTargetNumeric = !isNaN(parseFloat(target)) && isFinite(target);
if (isValueNumeric && isTargetNumeric) {
return Number(value) > Number(target);
}
if (!/Invalid|NaN/.test(new Date(value))) {
return new Date(value) > new Date(target);
}
return false;
},
'Must be greater than {0}.');
Picasso sources | off site
(-)
Glide sources
(-)
Universal Image Loader sources
(-)
Tested by me on SGS2 (Android 4.1) (WiFi 8.43 Mbps)
Official versions for Java, not for Xamarin!
October 19 2015
I prefer to use Glide.
Read more here.
How to write cache to External Storage (SD Card) with Glide.
It's not related to Ken's case directly, but such an error also can occur if you copied .h file and forgot to change #ifndef
directive. In this case compiler will just skip definition of the class thinking that it's a duplication.
Theta(n): A function f(n)
belongs to Theta(g(n))
, if there exists positive constants c1
and c2
such that f(n)
can be sandwiched between c1(g(n))
and c2(g(n))
. i.e it gives both upper and as well as lower bound.
Theta(g(n)) = { f(n) : there exists positive constants c1,c2 and n1 such that 0<=c1(g(n))<=f(n)<=c2(g(n)) for all n>=n1 }
when we say f(n)=c2(g(n))
or f(n)=c1(g(n))
it represents asymptotically tight bound.
O(n): It gives only upper bound (may or may not be tight)
O(g(n)) = { f(n) : there exists positive constants c and n1 such that 0<=f(n)<=cg(n) for all n>=n1}
ex: The bound 2*(n^2) = O(n^2)
is asymptotically tight, whereas the bound 2*n = O(n^2)
is not asymptotically tight.
o(n): It gives only upper bound (never a tight bound)
the notable difference between O(n) & o(n) is f(n) is less than cg(n) for all n>=n1 but not equal as in O(n).
ex: 2*n = o(n^2)
, but 2*(n^2) != o(n^2)
Click on the Window tab in Eclipse, go to Preferences and when that window comes up, go to Java ? Installed JREs ? Execution Environment and choose JavaSE-1.5. You then have to go to Compiler and set the Compiler compliance level.
.each()
should work for you. http://api.jquery.com/jQuery.each/ or http://api.jquery.com/each/ or you could use .map
.
var newArray = $(array).map(function(i) {
return $('#event' + i, response).html();
});
Edit: I removed the adding of the prepended 0 since it is suggested to not use that.
If you must have it use
var newArray = $(array).map(function(i) {
var number = '' + i;
if (number.length == 1) {
number = '0' + number;
}
return $('#event' + number, response).html();
});
This problem happens when you install the JDK by _uncompressing_
it instead of _executing_
it.
By example:
unzip jdk-6u45-linux-x64.bin (wrong)
sh ./jdk-6u45-linux-x64.bin (right)
In the first scenario, the runtime libraries, as rt.jar, don't get automatically uncompresessed (thus, you can find the rt.pack files, etc. instead of the .jar ones).
Parallel.ForEach will optimize(may not even start new threads) and block until the loop is finished, and Task.Factory will explicitly create a new task instance for each item, and return before they are finished (asynchronous tasks). Parallel.Foreach is much more efficient.
I've used closures to do things like:
a = (function () {
var privatefunction = function () {
alert('hello');
}
return {
publicfunction : function () {
privatefunction();
}
}
})();
As you can see there, a
is now an object, with a method publicfunction
( a.publicfunction()
) which calls privatefunction
, which only exists inside the closure. You can not call privatefunction
directly (i.e. a.privatefunction()
), just publicfunction()
.
It's a minimal example, but maybe you can see uses to it? We used this to enforce public/private methods.
Simple way is generating code as bellow:
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
<style>_x000D_
table, td {_x000D_
border:1px solid black;_x000D_
}_x000D_
</style>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<p>Click on each tr element to alert its index position in the table:</p>_x000D_
<table>_x000D_
<tr onclick="myFunction(this)">_x000D_
<td>Click to show rowIndex</td>_x000D_
</tr>_x000D_
<tr onclick="myFunction(this)">_x000D_
<td>Click to show rowIndex</td>_x000D_
</tr>_x000D_
<tr onclick="myFunction(this)">_x000D_
<td>Click to show rowIndex</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
<script>_x000D_
function myFunction(x) {_x000D_
alert("Row index is: " + x.rowIndex);_x000D_
}_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
if you have an array
var subcategories=[{name:"test",desc:"test"}];
function hasCategory(nameStr) {
for(let i=0;i<subcategories.length;i++){
if(subcategories[i].name===nameStr){
return true;
}
}
return false;
}
if you have an object
var category={name:"asd",test:""};
if(category.hasOwnProperty('name')){//or category.name!==undefined
return true;
}else{
return false;
}
var test = $('#id').attr('value').match(/[^a-z0-9 ]+/);
Here you go!
Easy Workaround (no VBA required)
From here, edit the SQL directly by adding '?' wherever you want a parameter. Works the same way as before except you don't get nagged.
When you use spring then you can use
boolean isNullOrEmpty = org.springframework.util.ObjectUtils.isEmpty(obj);
where obj is any [map,collection,array,aything...]
otherwise: the code is:
public static boolean isEmpty(Object[] array) {
return (array == null || array.length == 0);
}
public static boolean isEmpty(Object obj) {
if (obj == null) {
return true;
}
if (obj.getClass().isArray()) {
return Array.getLength(obj) == 0;
}
if (obj instanceof CharSequence) {
return ((CharSequence) obj).length() == 0;
}
if (obj instanceof Collection) {
return ((Collection) obj).isEmpty();
}
if (obj instanceof Map) {
return ((Map) obj).isEmpty();
}
// else
return false;
}
for String best is:
boolean isNullOrEmpty = (str==null || str.trim().isEmpty());
If you like an ugly hacks which you should never do in real worlds systems; you could strip all :hover style rules from document.styleSheets.
Just go through all CSS styles with JavaScript and remove all rules, which contain ":hover" in their selector. I use this method when I need to remove :hover styles from bootstrap 2.
_.each(document.styleSheets, function (sheet) {
var rulesToLoose = [];
_.each(sheet.cssRules, function (rule, index) {
if (rule.selectorText && rule.selectorText.indexOf(':hover') > 0) {
rulesToLoose.push(index);
}
});
_.each(rulesToLoose.reverse(), function (index) {
if (sheet.deleteRule) {
sheet.deleteRule(index);
} else if (sheet.removeRule) {
sheet.removeRule(index);
}
});
});
I did use underscore for iterating arrays, but one could write those with pure js loop as well:
for (var i = 0; i < document.styleSheets.length; i++) {}
Since you mentioned ng-src
and it seems as though you want the page to finish rendering before loading your image, you may modify jaime's answer to run the native directive after the browser finishes rendering.
This blog post explains this pretty well; essentially, you insert the $timeout
wrapper for window.setTimeout
before the callback function wherein you make those modifications to the CSS.
For input and button:
$('button').prop('disabled', true);
For anchor:
$('a').attr('disabled', true);
Checked in firefox, chrome.
In javascript you have to use \. to match a dot.
Example
"blah.tests.zibri.org".match('test\\..*')
null
and
"blah.test.zibri.org".match('test\\..*')
["test.zibri.org", index: 5, input: "blah.test.zibri.org", groups: undefined]
The line starting ALREADYEXISTS
uses ’
as the closing quote, it should be using '
. The open quote on the next line (where the error is reported) is seen as the closing quote, and this mix up is causing the error.
To upper case: Ctrl+K, Ctrl+U
and to lower case: Ctrl+K, Ctrl+L.
Mnemonics:
K like the Keyboard
U like the Upper case
L like the Lower case
I am trying to write a class that is "both" a list
or a dict
. I want the programmer to be able to both "cast" this object to a list
(dropping the keys) or dict
(with the keys).
Looking at the way Python currently does the dict()
cast: It calls Mapping.update()
with the object that is passed. This is the code from the Python repo:
def update(self, other=(), /, **kwds):
''' D.update([E, ]**F) -> None. Update D from mapping/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k]
If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followed by: for k, v in F.items(): D[k] = v
'''
if isinstance(other, Mapping):
for key in other:
self[key] = other[key]
elif hasattr(other, "keys"):
for key in other.keys():
self[key] = other[key]
else:
for key, value in other:
self[key] = value
for key, value in kwds.items():
self[key] = value
The last subcase of the if statement, where it is iterating over other
is the one most people have in mind. However, as you can see, it is also possible to have a keys()
property. That, combined with a __getitem__()
should make it easy to have a subclass be properly casted to a dictionary:
class Wharrgarbl(object):
def __init__(self, a, b, c, sum, version='old'):
self.a = a
self.b = b
self.c = c
self.sum = 6
self.version = version
def __int__(self):
return self.sum + 9000
def __keys__(self):
return ["a", "b", "c"]
def __getitem__(self, key):
# have obj["a"] -> obj.a
return self.__getattribute__(key)
Then this will work:
>>> w = Wharrgarbl('one', 'two', 'three', 6)
>>> dict(w)
{'a': 'one', 'c': 'three', 'b': 'two'}
Its best practice to have TOP 1 1
always.
What if I use SELECT 1
-> If condition matches more than one record then your query will fetch all the columns records and returns 1.
What if I use SELECT TOP 1 1
-> If condition matches more than one record also, it will just fetch the existence of any row (with a self 1-valued column) and returns 1.
IF EXISTS (SELECT TOP 1 1 FROM tblGLUserAccess WHERE GLUserName ='xxxxxxxx')
BEGIN
SELECT 1
END
ELSE
BEGIN
SELECT 2
END
Below script will work well for both active and disconnected sessions as long as user has access to run logoff command remotely. All you have to do is change the servername from "YourServerName" on 4th line.
param (
$queryResults = $null,
[string]$UserName = $env:USERNAME,
[string]$ServerName = "YourServerName"
)
if (Test-Connection $ServerName -Count 1 -Quiet) {
Write-Host "`n`n`n$ServerName is online!" -BackgroundColor Green -ForegroundColor Black
Write-Host ("`nQuerying Server: `"$ServerName`" for disconnected sessions under UserName: `"" + $UserName.ToUpper() + "`"...") -BackgroundColor Gray -ForegroundColor Black
query user $UserName /server:$ServerName 2>&1 | foreach {
if ($_ -match "Active") {
Write-Host "Active Sessions"
$queryResults = ("`n$ServerName," + (($_.trim() -replace ' {2,}', ','))) | ConvertFrom-Csv -Delimiter "," -Header "ServerName","UserName","SessionName","SessionID","CurrentState","IdealTime","LogonTime"
$queryResults | ft
Write-Host "Starting logoff procedure..." -BackgroundColor Gray -ForegroundColor Black
$queryResults | foreach {
$Sessionl = $_.SessionID
$Serverl = $_.ServerName
Write-Host "Logging off"$_.username"from $serverl..." -ForegroundColor black -BackgroundColor Gray
sleep 2
logoff $Sessionl /server:$Serverl /v
}
}
elseif ($_ -match "Disc") {
Write-Host "Disconnected Sessions"
$queryResults = ("`n$ServerName," + (($_.trim() -replace ' {2,}', ','))) | ConvertFrom-Csv -Delimiter "," -Header "ServerName","UserName","SessionID","CurrentState","IdealTime","LogonTime"
$queryResults | ft
Write-Host "Starting logoff procedure..." -BackgroundColor Gray -ForegroundColor Black
$queryResults | foreach {
$Sessionl = $_.SessionID
$Serverl = $_.ServerName
Write-Host "Logging off"$_.username"from $serverl..."
sleep 2
logoff $Sessionl /server:$Serverl /v
}
}
elseif ($_ -match "The RPC server is unavailable") {
Write-Host "Unable to query the $ServerName, check for firewall settings on $ServerName!" -ForegroundColor White -BackgroundColor Red
}
elseif ($_ -match "No User exists for") {Write-Host "No user session exists"}
}
}
else {
Write-Host "`n`n`n$ServerName is Offline!" -BackgroundColor red -ForegroundColor white
Write-Host "Error: Unable to connect to $ServerName!" -BackgroundColor red -ForegroundColor white
Write-Host "Either the $ServerName is down or check for firewall settings on server $ServerName!" -BackgroundColor Yellow -ForegroundColor black
}
Read-Host "`n`nScript execution finished, press enter to exit!"
Some sample outputs. For active session:
if no sessions found: Check out this solution as well to query all AD servers for your username and logoff only disconnected sessions. The script will also tell you if there were error connecting or querying the server.
Powershell to find out disconnected RDP session and log off at the same time
Late to the party, but in case this happens with a WORDPRESS
installation :
#1273 - Unknown collation: 'utf8mb4_unicode_520_ci
In phpmyadmin, under export method
> Format-specific options
( custom export )
Set to : MYSQL40
If you will try to import now, you now might get another error message :
1064 - You have an error in your SQL syntax; .....
That is because The older TYPE
option that was synonymous with ENGINE
was removed in MySQL 5.5.
Open your .sql
file , search and replace all instances
from TYPE=
to ENGINE=
Now the import should go smoothly.
Try:
exec('drop table #tab') -- you can add condition 'if table exists'
exec('select * into #tab from tab')
there are a couple of ways of using a timer:
1) scheduled timer & using selector
NSTimer *t = [NSTimer scheduledTimerWithTimeInterval: 2.0
target: self
selector:@selector(onTick:)
userInfo: nil repeats:NO];
As a side note, instead of using a timer that doesn't repeat and calls the selector after a specified interval, you could use a simple statement like this:
[self performSelector:@selector(onTick:) withObject:nil afterDelay:2.0];
this will have the same effect as the sample code above; but if you want to call the selector every nth time, you use the timer with repeats:YES;
2) self-scheduled timer
NSDate *d = [NSDate dateWithTimeIntervalSinceNow: 60.0];
NSTimer *t = [[NSTimer alloc] initWithFireDate: d
interval: 1
target: self
selector:@selector(onTick:)
userInfo:nil repeats:YES];
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:t forMode: NSDefaultRunLoopMode];
[t release];
3) unscheduled timer & using invocation
NSMethodSignature *sgn = [self methodSignatureForSelector:@selector(onTick:)];
NSInvocation *inv = [NSInvocation invocationWithMethodSignature: sgn];
[inv setTarget: self];
[inv setSelector:@selector(onTick:)];
NSTimer *t = [NSTimer timerWithTimeInterval: 1.0
invocation:inv
repeats:YES];
and after that, you start the timer manually whenever you need like this:
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer: t forMode: NSDefaultRunLoopMode];
And as a note, onTick: method looks like this:
-(void)onTick:(NSTimer *)timer {
//do smth
}
This is working func for an objects comparison. In some cases you might have lot of fields to compare. Simply loop the array and call this function with a existing items and new item.
var objectsEqual = function (object1, object2) {
if(!object1 || !object2)
return false;
var result = true;
var arrayObj1 = _.keys(object1);
var currentKey = "";
for (var i = 0; i < arrayObj1.length; i++) {
currentKey = arrayObj1[i];
if (object1[currentKey] !== null && object2[currentKey] !== null)
if (!_.has(object2, currentKey) ||
!_.isEqual(object1[currentKey].toUpperCase(), object2[currentKey].toUpperCase()))
return false;
}
return result;
};
Go to your Arduino documents directory; inside you will find a directory named "Libraries". The imported library directory will be there. Just delete it and restart the Arduino app.
Your Arduino library folder should look like this (on Windows):
My Documents\Arduino\libraries\ArduinoParty\ArduinoParty.cpp
My Documents\Arduino\libraries\ArduinoParty\ArduinoParty.h
My Documents\Arduino\libraries\ArduinoParty\examples
....
or like this (on Mac and Linux):
Documents/Arduino/libraries/ArduinoParty/ArduinoParty.cpp
Documents/Arduino/libraries/ArduinoParty/ArduinoParty.h
Documents/Arduino/libraries/ArduinoParty/examples
The only issue with unused libraries is the trivial amount of disk space they use. They aren't loaded automatically so don't take up any application memory of the Arduino IDE.
Have a look at the System.Diagnostics
namespace. Lots of goodies in there!
System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();
This is really good to have a poke around in to learn whats going on under the hood.
I'd recommend that you have a look into logging solutions (Such as NLog, log4net or the Microsoft patterns and practices Enterprise Library) which may achieve your purposes and then some. Good luck mate!
Based on answers above you can use universal method to zoom map to fit all annotations and overlays at the same time.
-(MKMapRect)getZoomingRectOnMap:(MKMapView*)map toFitAllOverlays:(BOOL)overlays andAnnotations:(BOOL)annotations includeUserLocation:(BOOL)userLocation {
if (!map) {
return MKMapRectNull;
}
NSMutableArray* overlaysAndAnnotationsCoordinateArray = [[NSMutableArray alloc]init];
if (overlays) {
for (id <MKOverlay> overlay in map.overlays) {
MKMapPoint overlayPoint = MKMapPointForCoordinate(overlay.coordinate);
NSArray* coordinate = @[[NSNumber numberWithDouble:overlayPoint.x], [NSNumber numberWithDouble:overlayPoint.y]];
[overlaysAndAnnotationsCoordinateArray addObject:coordinate];
}
}
if (annotations) {
for (id <MKAnnotation> annotation in map.annotations) {
MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
NSArray* coordinate = @[[NSNumber numberWithDouble:annotationPoint.x], [NSNumber numberWithDouble:annotationPoint.y]];
[overlaysAndAnnotationsCoordinateArray addObject:coordinate];
}
}
MKMapRect zoomRect = MKMapRectNull;
if (userLocation) {
MKMapPoint annotationPoint = MKMapPointForCoordinate(map.userLocation.coordinate);
zoomRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1);
}
for (NSArray* coordinate in overlaysAndAnnotationsCoordinateArray) {
MKMapRect pointRect = MKMapRectMake([coordinate[0] doubleValue], [coordinate[1] doubleValue], 0.1, 0.1);
zoomRect = MKMapRectUnion(zoomRect, pointRect);
}
return zoomRect;
}
And then:
MKMapRect mapRect = [self getZoomingRectOnMap:mapView toFitAllOverlays:YES andAnnotations:YES includeUserLocation:NO];
[mapView setVisibleMapRect:mapRect edgePadding:UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0) animated:YES];
Without the main sentinel, the code would be executed even if the script were imported as a module.
PhpEdit has a built in debugger, but I usually end up using echo(); and print_r(); the old fashioned way!!
As @Brian Riley already said you should either remove 1 column in your select
select countrylanguage.language ,sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language
order by sum(country.population*countrylanguage.percentage) desc ;
or add it to your grouping
select countrylanguage.language, country.code, sum(country.population*countrylanguage.percentage/100)
from countrylanguage
join country on countrylanguage.countrycode = country.code
group by countrylanguage.language, country.code
order by sum(country.population*countrylanguage.percentage) desc ;
You can't do it with "anonymous" type parameters (ie, wildcards that use ?
), but you can do it with "named" type parameters. Simply declare the type parameter at method or class level.
import java.util.List;
interface A{}
interface B{}
public class Test<E extends B & A, T extends List<E>> {
T t;
}
If, rather than writing new code to trim a string, you're looking at existing code that calls "strip()" and wondering why it isn't working, you might want to check whether it attempts to include something like the prototypejs framework, and make sure it's actually getting loaded.
That framework adds a strip function to all String objects, but if e.g. you upgraded it and your web pages are still referring to the old .js file it'll of course not work.
you can't assign an event by string. Use that:
elemm.onclick = function(){ alert('blah'); };
http://en.wikipedia.org/wiki/Hexspeak
http://www.urbandictionary.com/define.php?term=dead%3Abeef
"Dead beef" is a very popular sentence in programming, because it is built only from letters a-f, which are used in hexadecimal notation. Colons in the beginning and in the middle of the sentence make this sentence a (theoretically) valid IPv6 address.
Browser does not care about autocomplete=off auto or even fills credentials to wrong text field?
I fixed it by setting the password field to read-only and activate it, when user clicks into it or uses tab-key to this field.
fix browser autofill in: readonly and set writeble on focus (at mouse click and tabbing through fields)
<input type="password" readonly
onfocus="$(this).removeAttr('readonly');"/>
Update: Mobile Safari sets cursor in the field, but does not show virtual keyboard. New Fix works like before but handles virtual keyboard:
<input id="email" readonly type="email" onfocus="if (this.hasAttribute('readonly')) {
this.removeAttribute('readonly');
// fix for mobile safari to show virtual keyboard
this.blur(); this.focus(); }" />
Live Demo https://jsfiddle.net/danielsuess/n0scguv6/
// UpdateEnd
By the way, more information on my observation:
Sometimes I notice this strange behavior on Chrome and Safari, when there are password fields in the same form. I guess, the browser looks for a password field to insert your saved credentials. Then it autofills username into the nearest textlike-input field , that appears prior the password field in DOM (just guessing due to observation). As the browser is the last instance and you can not control it, sometimes even autocomplete=off would not prevent to fill in credentials into wrong fields, but not user or nickname field.
To reload a section of the page, you could use jquerys load
with the current url and specify the fragment you need, which would be the same element that load
is called on, in this case #here
:
function updateDiv()
{
$( "#here" ).load(window.location.href + " #here" );
}
+ " #here"
This function can be called within an interval, or attached to a click event
To resolve 'ASP.NET 4.0 has not been registered. You need to manually configure your Web server for ASP.NET 4.0 in order for your site to run correctly' error when opening a solution we can:
1 Ensure the IIS feature is turned on with ASP.NET. Go to Control Panel\All Control Panel Items\Programs and Features then click 'Turn Windows Featrues on. Then in the IIS --> WWW servers --> App Dev Features ensure that ASP.NET is checked.
2 And run the following cmd line to install
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis -i
Hope this helps
If you are fine with modifying the original set (which you may want to do in some cases), you can use set.update()
:
S.update(T)
The return value is None
, but S
will be updated to be the union of the original S
and T
.
Because of the way the function is called (i.e. as a simple call to a function variable), this
is the global object (for which window
is an alias in browsers). Use the obj
parameter instead.
Also, creating a jQuery object and the using its attr()
method for obtaining an element ID is inefficient and unnecessary. Just use the element's id
property, which works in all browsers.
function showHideOther(obj){
var sel = obj.options[obj.selectedIndex].value;
var ID = obj.id;
if (sel == 'other') {
$(obj).html("<input type='text' name='" + ID + "' id='" + ID + "' />");
} else {
$(obj).css({'display' : 'none'});
}
}
I'm not able to comment (too little reputation? I'm pretty new) on Lukas' post.
On my PG setup to_number(NULL)
does not work, so my solution would be:
SELECT CASE WHEN column = NULL THEN NULL ELSE column :: Integer END
FROM table
Try:
import itertools as it
''.join(el[0] for el in it.takewhile(lambda t: t[0] == t[1], zip(string1, string2)))
It does the comparison from the beginning of both strings.
You don't have sufficient permissions to write to the root directory. See the leading slash on the filename?
Combining the Dictionary approach from Tim with the variant array from Jean_Francois below.
The array you want is in objDict.keys
Sub A_Unique_B()
Dim X
Dim objDict As Object
Dim lngRow As Long
Set objDict = CreateObject("Scripting.Dictionary")
X = Application.Transpose(Range([a1], Cells(Rows.Count, "A").End(xlUp)))
For lngRow = 1 To UBound(X, 1)
objDict(X(lngRow)) = 1
Next
Range("B1:B" & objDict.Count) = Application.Transpose(objDict.keys)
End Sub
Inspired by this and other questions on SO, I've created a minimal open source basic-http-client that embodies most of the techniques found here.
google-http-java-client is also a great open source resource.
SELECT CONVERT(NVARCHAR, LoginDate, 105)+' '+CONVERT(NVARCHAR, LoginDate, 108) AS LoginDate FROM YourTable
Output
-------------------
29-08-2013 13:55:48
I think using enumerate on the outer loop and using the index to slice the list on the inner loop is pretty Pythonic:
for index, this in enumerate(mylist):
for that in mylist[index+1:]:
compare(this, that)
Just a little expansion to Nathan's Linq Expression solution. Use multi generic param so that the property doesn't limited to string.
void GetString<TClass, TProperty>(string input, TClass outObj, Expression<Func<TClass, TProperty>> outExpr)
{
if (!string.IsNullOrEmpty(input))
{
var expr = (MemberExpression) outExpr.Body;
var prop = (PropertyInfo) expr.Member;
if (!prop.GetValue(outObj).Equals(input))
{
prop.SetValue(outObj, input, null);
}
}
}
Scikit-Learn is just telling you it doesn't recognise the argument "stratify", not that you're using it incorrectly. This is because the parameter was added in version 0.17 as indicated in the documentation you quoted.
So you just need to update Scikit-Learn.
If you want to do this, you need to save it in a variable first. So you don't need to use id to query this element every time.
var el = $("#page_navigation1");
$("#add").click(function(){
el.attr("id","page_navigation1");
});
$("#remove").click(function(){
el.removeAttr("id");
});
You can get the path via fp.name
. Example:
>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'
You might need os.path.basename
if you want only the file name:
>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'
File object docs (for Python 2) here.
I juste wrote a proxy in nodejs that take care of HTTPS with optional decoding of the message. This proxy also can add proxy-authentification header in order to go through a corporate proxy. You need to give as argument the url to find the proxy.pac file in order to configurate the usage of corporate proxy.
In addition to people who advices to host it on own server, I'd proposed to keep it on separate domain (e.g. static.website.com) to allow browsers to load it into separate from other content thread. This tip also works for all static stuff, say images and css.
the above guy was close but here is what you want:
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var r = 0, n = table.rows.length; r < n; r++) {
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
alert(table.rows[r].cells[c].firstChild.value);
}
}
}catch(e) {
alert(e);
}
You can see if it's really not set. Run the command set | grep TERM
.
If not, you can set it like that:
export TERM=xterm
Fastest way I found is via inner1d. Here's how it compares to other numpy methods:
import numpy as np
from numpy.core.umath_tests import inner1d
V = np.random.random_sample((10**6,3,)) # 1 million vectors
A = np.sqrt(np.einsum('...i,...i', V, V))
B = np.linalg.norm(V,axis=1)
C = np.sqrt((V ** 2).sum(-1))
D = np.sqrt((V*V).sum(axis=1))
E = np.sqrt(inner1d(V,V))
print [np.allclose(E,x) for x in [A,B,C,D]] # [True, True, True, True]
import cProfile
cProfile.run("np.sqrt(np.einsum('...i,...i', V, V))") # 3 function calls in 0.013 seconds
cProfile.run('np.linalg.norm(V,axis=1)') # 9 function calls in 0.029 seconds
cProfile.run('np.sqrt((V ** 2).sum(-1))') # 5 function calls in 0.028 seconds
cProfile.run('np.sqrt((V*V).sum(axis=1))') # 5 function calls in 0.027 seconds
cProfile.run('np.sqrt(inner1d(V,V))') # 2 function calls in 0.009 seconds
inner1d is ~3x faster than linalg.norm and a hair faster than einsum
On Debian/Ubuntu:
aptitude install python-numpy
On Windows, download the installer:
http://sourceforge.net/projects/numpy/files/NumPy/
On other systems, download the tar.gz and run the following:
$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install
jsonb
in Postgres 9.4+You can use the same query as below, just with jsonb_array_elements()
.
But rather use the jsonb
"contains" operator @>
in combination with a matching GIN index on the expression data->'objects'
:
CREATE INDEX reports_data_gin_idx ON reports
USING gin ((data->'objects') jsonb_path_ops);
SELECT * FROM reports WHERE data->'objects' @> '[{"src":"foo.png"}]';
Since the key objects
holds a JSON array, we need to match the structure in the search term and wrap the array element into square brackets, too. Drop the array brackets when searching a plain record.
More explanation and options:
json
in Postgres 9.3+Unnest the JSON array with the function json_array_elements()
in a lateral join in the FROM
clause and test for its elements:
SELECT data::text, obj
FROM reports r, json_array_elements(r.data#>'{objects}') obj
WHERE obj->>'src' = 'foo.png';
The CTE (WITH
query) just substitutes for a table reports
.
Or, equivalent for just a single level of nesting:
SELECT *
FROM reports r, json_array_elements(r.data->'objects') obj
WHERE obj->>'src' = 'foo.png';
->>
, ->
and #>
operators are explained in the manual.
Both queries use an implicit JOIN LATERAL
.
Closely related:
This is my code:
try {_x000D_
String folderPath = "../" + filePath.trim() + "/";_x000D_
logger.info("Path: " + folderPath);_x000D_
File folder = new File(folderPath);_x000D_
File[] listOfFiles = folder.listFiles();_x000D_
int length = listOfFiles.length;_x000D_
logger.info("So luong files: " + length);_x000D_
ArrayList<CdrFileBO> lstFile = new ArrayList< CdrFileBO>();_x000D_
_x000D_
if (listOfFiles != null && length > 0) {_x000D_
int count = 0;_x000D_
for (int i = 0; i < length; i++) {_x000D_
if (listOfFiles[i].isFile()) {_x000D_
lstFile.add(new CdrFileBO(listOfFiles[i]));_x000D_
}_x000D_
}_x000D_
Collections.sort(lstFile);_x000D_
for (CdrFileBO bo : lstFile) {_x000D_
//String newName = START_NAME + "_" + getSeq(SEQ_START) + "_" + DateSTR + ".s";_x000D_
String newName = START_NAME + DateSTR + getSeq(SEQ_START) + ".DAT";_x000D_
SEQ_START = SEQ_START + 1;_x000D_
bo.getFile().renameTo(new File(folderPath + newName));_x000D_
logger.info("newName: " + newName);_x000D_
logger.info("Next file: " + getSeq(SEQ_START));_x000D_
}_x000D_
_x000D_
}_x000D_
} catch (Exception ex) {_x000D_
logger.error(ex);_x000D_
ex.printStackTrace();_x000D_
}
_x000D_
If you are using an IDE like eclipse, you can use this easy way.
Right click on the project -> Team - Show history
In that right click on the revision id for your commit and select 'Set commit properties'
.
You can modify the message as you want from here.
localStorage
only supports strings. Use JSON.stringify()
and JSON.parse()
.
var names = [];
names[0] = prompt("New member name?");
localStorage.setItem("names", JSON.stringify(names));
//...
var storedNames = JSON.parse(localStorage.getItem("names"));
As in many other programming and scripting languages you can do so by adding !
in front of the condition
if (![string]::IsNullOrEmpty($version))
{
$request += "/" + $version
}
Same thing happend to me after upgrading distro.
Running sudo apt-get install php7.0-mysql
fixed it for me.
You append a newline to both the username and the password, i.e. the output would be something like
Sebastian
password
John
hfsjaijn
use fwrite($fh,$user." ".$password."\n");
instead to have them both on one line.
Or use fputcsv() to write the data and fgetcsv()
to fetch it. This way you would at least avoid encoding problems like e.g. with $username='Charles, III';
...i.e. setting aside all the things that are wrong about storing plain passwords in plain files and using _GET for this type of operation (use _POST instead) ;-)
I know this has been answered but here is how I implemented something similar:
Intent intent = getPackageManager().getLaunchIntentForPackage("com.package.name");
if (intent != null) {
// We found the activity now start the activity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else {
// Bring user to the market or let them choose an app?
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("market://details?id=" + "com.package.name"));
startActivity(intent);
}
Even better, here is the method:
public void startNewActivity(Context context, String packageName) {
Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
if (intent != null) {
// We found the activity now start the activity
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
} else {
// Bring user to the market or let them choose an app?
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("market://details?id=" + packageName));
context.startActivity(intent);
}
}
Removed duplicate code:
public void startNewActivity(Context context, String packageName) {
Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
if (intent == null) {
// Bring user to the market or let them choose an app?
intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("market://details?id=" + packageName));
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
Use either lodash's truncate
_.truncate('hi-diddly-ho there, neighborino');
// ? 'hi-diddly-ho there, neighbo…'
or underscore.string's truncate.
_('Hello world').truncate(5); => 'Hello...'
To remove everything before the first /
input = input.Substring(input.IndexOf("/"));
To remove everything after the first /
input = input.Substring(0, input.IndexOf("/") + 1);
To remove everything before the last /
input = input.Substring(input.LastIndexOf("/"));
To remove everything after the last /
input = input.Substring(0, input.LastIndexOf("/") + 1);
An even more simpler solution for removing characters after a specified char is to use the String.Remove() method as follows:
To remove everything after the first /
input = input.Remove(input.IndexOf("/") + 1);
To remove everything after the last /
input = input.Remove(input.LastIndexOf("/") + 1);
Use Loaded event:
private void cmb_Loaded(object sender, RoutedEventArgs e) {
if (cmb.Items.Count > 0) cmb.SelectedIndex = 0;
}
It works for me.
Maybe the author of that unnamed book has read that a > 0
runs faster than a >= 1
and thinks that is true universally.
But it is because a 0
is involved (because CMP
can, depending on the architecture, replaced e.g. with OR
) and not because of the <
.
My simple test also failed, following the advice of the other answers here--until I realized that the config file that I added to my desktop application was given the name "App1.config". I renamed it to "App.config" and everything immediately worked as it ought.
for stylesheets: url(asset_path('image.jpg'))
What helped me was a look at the source code of the two functions.
Map - wraps the result in an Optional.
public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Optional.ofNullable(mapper.apply(value)); //<--- wraps in an optional
}
}
flatMap - returns the 'raw' object
public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Objects.requireNonNull(mapper.apply(value)); //<--- returns 'raw' object
}
}
For coffeescript lovers
expect( => someMethodCall(arg1, arg2)).toThrow()
dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;
Here is how the default implementation (ASP.NET Framework or ASP.NET Core) works. It uses a Key Derivation Function with random salt to produce the hash. The salt is included as part of the output of the KDF. Thus, each time you "hash" the same password you will get different hashes. To verify the hash the output is split back to the salt and the rest, and the KDF is run again on the password with the specified salt. If the result matches to the rest of the initial output the hash is verified.
Hashing:
public static string HashPassword(string password)
{
byte[] salt;
byte[] buffer2;
if (password == null)
{
throw new ArgumentNullException("password");
}
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, 0x10, 0x3e8))
{
salt = bytes.Salt;
buffer2 = bytes.GetBytes(0x20);
}
byte[] dst = new byte[0x31];
Buffer.BlockCopy(salt, 0, dst, 1, 0x10);
Buffer.BlockCopy(buffer2, 0, dst, 0x11, 0x20);
return Convert.ToBase64String(dst);
}
Verifying:
public static bool VerifyHashedPassword(string hashedPassword, string password)
{
byte[] buffer4;
if (hashedPassword == null)
{
return false;
}
if (password == null)
{
throw new ArgumentNullException("password");
}
byte[] src = Convert.FromBase64String(hashedPassword);
if ((src.Length != 0x31) || (src[0] != 0))
{
return false;
}
byte[] dst = new byte[0x10];
Buffer.BlockCopy(src, 1, dst, 0, 0x10);
byte[] buffer3 = new byte[0x20];
Buffer.BlockCopy(src, 0x11, buffer3, 0, 0x20);
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, dst, 0x3e8))
{
buffer4 = bytes.GetBytes(0x20);
}
return ByteArraysEqual(buffer3, buffer4);
}
@Robino was suggesting to add some tests which make sense, so here is a simple benchmark between 3 possible ways (maybe the most used ones) to convert an iterator to a list:
list(my_iterator)
[*my_iterator]
[e for e in my_iterator]
I have been using simple_bechmark library
from simple_benchmark import BenchmarkBuilder
from heapq import nsmallest
b = BenchmarkBuilder()
@b.add_function()
def convert_by_type_constructor(size):
list(iter(range(size)))
@b.add_function()
def convert_by_list_comprehension(size):
[e for e in iter(range(size))]
@b.add_function()
def convert_by_unpacking(size):
[*iter(range(size))]
@b.add_arguments('Convert an iterator to a list')
def argument_provider():
for exp in range(2, 22):
size = 2**exp
yield size, size
r = b.run()
r.plot()
As you can see there is very hard to make a difference between conversion by the constructor and conversion by unpacking, conversion by list comprehension is the “slowest” approach.
I have been testing also across different Python versions (3.6, 3.7, 3.8, 3.9) by using the following simple script:
import argparse
import timeit
parser = argparse.ArgumentParser(
description='Test convert iterator to list')
parser.add_argument(
'--size', help='The number of elements from iterator')
args = parser.parse_args()
size = int(args.size)
repeat_number = 10000
# do not wait too much if the size is too big
if size > 10000:
repeat_number = 100
def test_convert_by_type_constructor():
list(iter(range(size)))
def test_convert_by_list_comprehension():
[e for e in iter(range(size))]
def test_convert_by_unpacking():
[*iter(range(size))]
def get_avg_time_in_ms(func):
avg_time = timeit.timeit(func, number=repeat_number) * 1000 / repeat_number
return round(avg_time, 6)
funcs = [test_convert_by_type_constructor,
test_convert_by_unpacking, test_convert_by_list_comprehension]
print(*map(get_avg_time_in_ms, funcs))
The script will be executed via a subprocess from a Jupyter Notebook (or a script), the size parameter will be passed through command-line arguments and the script results will be taken from standard output.
from subprocess import PIPE, run
import pandas
simple_data = {'constructor': [], 'unpacking': [], 'comprehension': [],
'size': [], 'python version': []}
size_test = 100, 1000, 10_000, 100_000, 1_000_000
for version in ['3.6', '3.7', '3.8', '3.9']:
print('test for python', version)
for size in size_test:
command = [f'python{version}', 'perf_test_convert_iterator.py', f'--size={size}']
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
constructor, unpacking, comprehension = result.stdout.split()
simple_data['constructor'].append(float(constructor))
simple_data['unpacking'].append(float(unpacking))
simple_data['comprehension'].append(float(comprehension))
simple_data['python version'].append(version)
simple_data['size'].append(size)
df_ = pandas.DataFrame(simple_data)
df_
You can get my full notebook from here.
In most of the cases, in my tests, unpacking shows to be faster, but the difference is so small that the results may change from a run to the other. Again, the comprehension approach is the slowest, in fact, the other 2 methods are up to ~ 60% faster.
On a linux server you can just use this commands to reconfigure Tomcat to listen on port 80:
sed -i 's|port="8080"|port="80"|g' /etc/tomcat?/server.xml
sed -i 's|#AUTHBIND=no|AUTHBIND=yes|g' /etc/default/tomcat?
service tomcat8 restart
I suspect you're confused here because it's fundamentally confusing. To make things worse, the whole ours/theirs stuff switches roles (becomes backwards) when you are doing a rebase.
Ultimately, during a git merge
, the "ours" branch refers to the branch you're merging into:
git checkout merge-into-ours
and the "theirs" branch refers to the (single) branch you're merging:
git merge from-theirs
and here "ours" and "theirs" makes some sense, as even though "theirs" is probably yours anyway, "theirs" is not the one you were on when you ran git merge
.
While using the actual branch name might be pretty cool, it falls apart in more complex cases. For instance, instead of the above, you might do:
git checkout ours
git merge 1234567
where you're merging by raw commit-ID. Worse, you can even do this:
git checkout 7777777 # detach HEAD
git merge 1234567 # do a test merge
in which case there are no branch names involved!
I think it's little help here, but in fact, in gitrevisions
syntax, you can refer to an individual path in the index by number, during a conflicted merge
git show :1:README
git show :2:README
git show :3:README
Stage #1 is the common ancestor of the files, stage #2 is the target-branch version, and stage #3 is the version you are merging from.
The reason the "ours" and "theirs" notions get swapped around during rebase
is that rebase works by doing a series of cherry-picks, into an anonymous branch (detached HEAD mode). The target branch is the anonymous branch, and the merge-from branch is your original (pre-rebase) branch: so "--ours" means the anonymous one rebase is building while "--theirs" means "our branch being rebased".
As for the gitattributes entry: it could have an effect: "ours" really means "use stage #2" internally. But as you note, it's not actually in place at the time, so it should not have an effect here ... well, not unless you copy it into the work tree before you start.
Also, by the way, this applies to all uses of ours and theirs, but some are on a whole file level (-s ours
for a merge strategy; git checkout --ours
during a merge conflict) and some are on a piece-by-piece basis (-X ours
or -X theirs
during a -s recursive
merge). Which probably does not help with any of the confusion.
I've never come up with a better name for these, though. And: see VonC's answer to another question, where git mergetool
introduces yet more names for these, calling them "local" and "remote"!
Use the \
character to escape a character that has special meaning inside a regular expression.
To automate it, you could use this:
function escapeRegExp(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}
Update: There is now a proposal to standardize this method, possibly in ES2016: https://github.com/benjamingr/RegExp.escape
Update: The abovementioned proposal was rejected, so keep implementing this yourself if you need it.
Here is example which can give you some hints to iterate through existing array and add items to new array. I use UnderscoreJS Module to use as my utility file.
You can download from (https://npmjs.org/package/underscore)
$ npm install underscore
Here is small snippet to demonstrate how you can do it.
var _ = require("underscore");
var calendars = [1, "String", {}, 1.1, true],
newArray = [];
_.each(calendars, function (item, index) {
newArray.push(item);
});
console.log(newArray);
I had a similar question, but was actually looking for a different answer; I'm looking to create a custom event. For example instead of always saying this:
$('#myInput').keydown(function(ev) {
if (ev.which == 13) {
ev.preventDefault();
// Do some stuff that handles the enter key
}
});
I want to abbreviate it to this:
$('#myInput').enterKey(function() {
// Do some stuff that handles the enter key
});
trigger and bind don't tell the whole story - this is a JQuery plugin. http://docs.jquery.com/Plugins/Authoring
The "enterKey" function gets attached as a property to jQuery.fn - this is the code required:
(function($){
$('body').on('keydown', 'input', function(ev) {
if (ev.which == 13) {
var enterEv = $.extend({}, ev, { type: 'enterKey' });
return $(ev.target).trigger(enterEv);
}
});
$.fn.enterKey = function(selector, data, fn) {
return this.on('enterKey', selector, data, fn);
};
})(jQuery);
http://jsfiddle.net/b9chris/CkvuJ/4/
A nicety of the above is you can handle keyboard input gracefully on link listeners like:
$('a.button').on('click enterKey', function(ev) {
ev.preventDefault();
...
});
Edits: Updated to properly pass the right this
context to the handler, and to return any return value back from the handler to jQuery (for example in case you were looking to cancel the event and bubbling). Updated to pass a proper jQuery event object to handlers, including key code and ability to cancel event.
Old jsfiddle: http://jsfiddle.net/b9chris/VwEb9/24/
In Python, the name of the class refers to the class instance. Consider:
class A: pass
class B: pass
class C: pass
lst = [A, B, C]
# instantiate second class
b_instance = lst[1]()
print b_instance
The answers above are good. Adding a case that I used. Just if you don't want to use numpy and keep it as list without changing the contents.
You can run a small loop and change the dimension from 1xN to Nx1.
tmp=[]
for b in bus:
tmp.append([b])
bus=tmp
It is maybe not efficient while in case of very large numbers. But it works for a small set of numbers. Thanks
You can do a side-by-side diff
using sdiff
as follows:
$ git difftool -y -x sdiff HEAD^ | less
where HEAD^
is an example that you should replace with whatever you want to diff against.
I found this solution here where there are a couple of other suggestions also. However, this one answer's the OP's question succinctly and clearly.
See the man git-difftool for an explanation of the arguments.
Taking the comments on board, you can create a handy git sdiff
command by writing the following executable script:
#!/bin/sh
git difftool -y -x "sdiff -w $(tput cols)" "${@}" | less
Save it as /usr/bin/git-sdiff
and chmod +x
it. Then you'll be able to do this:
$ git sdiff HEAD^
As suggested in comments you can use icdiff
to do what sdiff
does with colored output:
$ more /usr/bin/git-sdiff
#!/bin/sh
git difftool -y -x "icdiff --cols=$(tput cols)" "${@}" | less
The way you are doing it is indeed the recommended one (for Python 2.x).
The issue of whether the class is passed explicitly to super
is a matter of style rather than functionality. Passing the class to super
fits in with Python's philosophy of "explicit is better than implicit".
I don't recall the exact syntax, but you may set the table column to be case insensitive. But be careful because then you won't be able to match based on case anymore and if you WANT 'cool' to not match 'CoOl' it will no longer be possible.
See this solution: Bootstrap TouchCarousel. A drop-in perfection for Twitter Bootstrap's Carousel (v3) to enable gestures on touch devices. http://ixisio.github.io/bootstrap-touch-carousel/
In the context of data storage, serialization (or serialisation) is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer) or transmitted (for example, across a network connection link) and reconstructed later. [...]
The opposite operation, extracting a data structure from a series of bytes, is deserialization. From Wikipedia
In Python "serialization" does nothing else than just converting the given data structure (e.g. a dict
) into its valid JSON pendant (object).
True
will be converted to JSONs true
and the dictionary itself will then be encapsulated in quotes.True
/ False
, true
/ false
json
is the standard way to do serialization:Code example:
data = {
"president": {
"name": "Zaphod Beeblebrox",
"species": "Betelgeusian",
"male": True,
}
}
import json
json_data = json.dumps(data, indent=2) # serialize
restored_data = json.loads(json_data) # deserialize
# serialized json_data now looks like:
# {
# "president": {
# "name": "Zaphod Beeblebrox",
# "species": "Betelgeusian",
# "male": true
# }
# }
Source: realpython.com
sudo npm install typings --global
npm install lodash --save
typings install lodash --ambient --save
System.config({
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
},
map: {
lodash: 'node_modules/lodash/index.js'
}
});
import _ from 'lodash';
Taking it further you could even parse on the fly
e.g.
& "my.exe" | %{
if ($_ -match 'OK')
{ Write-Host $_ -f Green }
else if ($_ -match 'FAIL|ERROR')
{ Write-Host $_ -f Red }
else
{ Write-Host $_ }
}
You can also use the element.scrollIntoView()
options
el.scrollIntoView(
{
behavior: 'smooth',
block: 'start'
},
);
which most browsers support
You would have got this Exception while doing a GET
on http://localhost:8080/projectname/login
As Vinay has correctly stated you can definitely use
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String displayLogin(Model model) {
model.addAttribute("login", new Login());
return "login";
}
But I am going to provide some alternative syntax which I think you were trying with Spring 3.0.
You can also achieve the above functionality with
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String displayLogin(Login loginModel) {
return "login";
}
and it login.jsp
(assuming you are using InternalResourceViewResolver
) you can have
<form:form method="POST" action="login.htm" modelAttribute="login">
Notice : modelAttribute is login
and not loginModel
. It is as per the class name you provide in argument. But if you want to use loginModel
as modelAttribute is jsp you can do the following
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String displayLogin(@ModelAttribute("loginModel")Login loginModel) {
return "login";
}
and jsp would have
<form:form method="POST" action="login.htm" modelAttribute="loginModel">
I know there are just different ways for doing the same thing. But the most important point to note here -
Imp Note: When you add your model class in your methods argument (like public String displayLogin(Login loginModel)
) it is automatically created and added to your Model object (which is why you can directly access it in JSP without manually putting it in model). Then it will search your request if request has attributes that it can map with the new ModelObject create. If yes Spring will inject values from request parameters to your custom model object class (Login in this case).
You can test this by doing
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String displayLogin(Login loginModel, Model model) {
System.out.println(model.asMap().get("login").equals(loginModel));
return "login";
}
Note : Above creating of new custom model object may not hold true if you have given @SessionAttributes({"login"})
. In this case it will get from session and populate values.
In regards to testing if a module you are utilizing is secure or not there are several routes you can take. I will touch on the pros/cons of each so you can make a more informed decision.
Currently, there aren't any vulnerabilities for the module you are utilizing, however, this can often lead to a false sense of security as there very well could be a vulnerability currently exploiting the module/software package you are using and you wouldn't be alerted to a problem until the vendor applies a fix/patch.
To keep abreast of vulnerabilities you will need to follow mailing lists, forums, IRC & other hacking related discussions. PRO: You can often times you will become aware of potential problems within a library before a vendor has been alerted or has issued a fix/patch to remedy the potential avenue of attack on their software. CON: This can be very time consuming and resource intensive. If you do go this route a bot using RSS feeds, log parsing (IRC chat logs) and or a web scrapper using key phrases (in this case node-mysql-native) and notifications can help reduce time spent trolling these resources.
Create a fuzzer, use a fuzzer or other vulnerability framework such as metasploit, sqlMap etc. to help test for problems that the vendor may not have looked for. PRO: This can prove to be a sure fire method of ensuring to an acceptable level whether or not the module/software you are implementing is safe for public access. CON: This also becomes time consuming and costly. The other problem will stem from false positives as well as uneducated review of the results where a problem resides but is not noticed.
Really security, and application security in general can be very time consuming and resource intensive. One thing managers will always use is a formula to determine the cost effectiveness (manpower, resources, time, pay etc) of performing the above two options.
Anyways, I realize this is not a 'yes' or 'no' answer that may have been hoping for but I don't think anyone can give that to you until they perform an analysis of the software in question.
gets()
is dangerous because it is possible for the user to crash the program by typing too much into the prompt. It can't detect the end of available memory, so if you allocate an amount of memory too small for the purpose, it can cause a seg fault and crash. Sometimes it seems very unlikely that a user will type 1000 letters into a prompt meant for a person's name, but as programmers, we need to make our programs bulletproof. (it may also be a security risk if a user can crash a system program by sending too much data).
fgets()
allows you to specify how many characters are taken out of the standard input buffer, so they don't overrun the variable.
The algorithm:
Now, parentheses are balanced for two conditions:
This will be the best way, to set the timeout for each service (passing timeout as parameter)
public static Retrofit getClient(String baseUrl, int serviceTimeout) {
Retrofit retrofitselected = baseUrl.contains("http:") ? retrofit : retrofithttps;
if (retrofitselected == null || retrofitselected.equals(retrofithttps)) {
retrofitselected = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(getGson().create()))
.client(!BuildConfig.FLAVOR.equals("PRE") ? new OkHttpClient.Builder()
.addInterceptor(new ResponseInterceptor())
.connectTimeout(serviceTimeout, TimeUnit.MILLISECONDS)
.writeTimeout(serviceTimeout, TimeUnit.MILLISECONDS)
.readTimeout(serviceTimeout, TimeUnit.MILLISECONDS)
.build() : getUnsafeOkHttpClient(serviceTimeout))
.build();
}
return retrofitselected;
}
And dont miss this for OkHttpClient.
private static OkHttpClient getUnsafeOkHttpClient(int serviceTimeout) {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.sslSocketFactory(sslSocketFactory);
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
OkHttpClient okHttpClient = builder
.addInterceptor(new ResponseInterceptor())
.connectTimeout(serviceTimeout, TimeUnit.MILLISECONDS)
.writeTimeout(serviceTimeout, TimeUnit.MILLISECONDS)
.readTimeout(serviceTimeout, TimeUnit.MILLISECONDS)
.build();
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Hope this will help anyone.
Since PostgreSQL 9.1 there is the convenient FOREACH
:
DO
$do$
DECLARE
m varchar[];
arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
FOREACH m SLICE 1 IN ARRAY arr
LOOP
RAISE NOTICE 'another_func(%,%)',m[1], m[2];
END LOOP;
END
$do$
Solution for older versions:
DO
$do$
DECLARE
arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
LOOP
RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
END LOOP;
END
$do$
Also, there is no difference between varchar[]
and varchar[][]
for the PostgreSQL type system. I explain in more detail here.
The DO
statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql
is the default (so you can omit the declaration).
Yes we can change that but with some more attention
Now add this in your build.gradle in your project while make sure you have checked the build variant of your project like release or Debug
so here I have set my build variant as release
but you may select as Debug as well.
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig getSigningConfig()
applicationVariants.all { variant ->
variant.outputs.each { output ->
def date = new Date();
def formattedDate = date.format('yyyyMMddHHmmss')
output.outputFile = new File(output.outputFile.parent,
output.outputFile.name.replace("-release", "-" + formattedDate)
//for Debug use output.outputFile = new File(output.outputFile.parent,
// output.outputFile.name.replace("-debug", "-" + formattedDate)
)
}
}
}
}
You may Do it With different Approach Like this
defaultConfig {
applicationId "com.myapp.status"
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
setProperty("archivesBaseName", "COMU-$versionName")
}
Using Set property method in build.gradle and Don't forget to sync the gradle before running the projects Hope It will solve your problem :)
A New approach to handle this added recently by google update You may now rename your build according to flavor or Variant output //Below source is from developer android documentation For more details follow the above documentation link
Using the Variant API to manipulate variant outputs is broken with the new plugin. It still works for simple tasks, such as changing the APK name during build time, as shown below:
// If you use each() to iterate through the variant objects,
// you need to start using all(). That's because each() iterates
// through only the objects that already exist during configuration time—
// but those object don't exist at configuration time with the new model.
// However, all() adapts to the new model by picking up object as they are
// added during execution.
android.applicationVariants.all { variant ->
variant.outputs.all {
outputFileName = "${variant.name}-${variant.versionName}.apk"
}
}
Renaming .aab bundle This is nicely answered by David Medenjak
tasks.whenTaskAdded { task ->
if (task.name.startsWith("bundle")) {
def renameTaskName = "rename${task.name.capitalize()}Aab"
def flavor = task.name.substring("bundle".length()).uncapitalize()
tasks.create(renameTaskName, Copy) {
def path = "${buildDir}/outputs/bundle/${flavor}/"
from(path)
include "app.aab"
destinationDir file("${buildDir}/outputs/renamedBundle/")
rename "app.aab", "${flavor}.aab"
}
task.finalizedBy(renameTaskName)
}
//@credit to David Medenjak for this block of code
}
Is there need of above code
What I have observed in the latest version of the android studio 3.3.1
The rename of .aab bundle is done by the previous code there don't require any task rename at all.
Hope it will help you guys. :)
SecurityManager
has a protected method getClassContext
By creating a utility class which extends SecurityManager, you can access this.
public class CallingClass extends SecurityManager {
public static final CallingClass INSTANCE = new CallingClass();
public Class[] getCallingClasses() {
return getClassContext();
}
}
Use CallingClass.INSTANCE.getCallingClasses()
to retrieve the calling classes.
There is also a small library (disclaimer: mine) WhoCalled which exposes this information. It uses Reflection.getCallerClass when available, else falls back to SecurityManager.
_tmain is a macro that gets redefined depending on whether or not you compile with Unicode or ASCII. It is a Microsoft extension and isn't guaranteed to work on any other compilers.
The correct declaration is
int _tmain(int argc, _TCHAR *argv[])
If the macro UNICODE is defined, that expands to
int wmain(int argc, wchar_t *argv[])
Otherwise it expands to
int main(int argc, char *argv[])
Your definition goes for a bit of each, and (if you have UNICODE defined) will expand to
int wmain(int argc, char *argv[])
which is just plain wrong.
std::cout works with ASCII characters. You need std::wcout if you are using wide characters.
try something like this
#include <iostream>
#include <tchar.h>
#if defined(UNICODE)
#define _tcout std::wcout
#else
#define _tcout std::cout
#endif
int _tmain(int argc, _TCHAR *argv[])
{
_tcout << _T("There are ") << argc << _T(" arguments:") << std::endl;
// Loop through each argument and print its number and value
for (int i=0; i<argc; i++)
_tcout << i << _T(" ") << argv[i] << std::endl;
return 0;
}
Or you could just decide in advance whether to use wide or narrow characters. :-)
Updated 12 Nov 2013:
Changed the traditional "TCHAR" to "_TCHAR" which seems to be the latest fashion. Both work fine.
End Update
I think this is the easy way to open a URL using this function
webbrowser.open_new_tab(url)
Try this:
.row > .span3 {
display: inline-block !important;
vertical-align: middle !important;
}
Fiddle: http://jsfiddle.net/EexYE/
You may need to add Diego's float: none !important;
also if span3 is floating and it interferes.
Fiddle: http://jsfiddle.net/D8McR/
In response to Alberto: if you fix the height of the row div, then to continue the vertical center alignment you'll need to set the line-height of the row to be the same as the pixel height of the row (ie. both to 300px in your case). If you'll do that you will notice that the child elements inherit the line-height, which is a problem in this case, so you will then need to set your line height for the span3s to whatever it should actually be (1.5 is the example value in the fiddle, or 1.5 x the font-size, which we did not change when we changed the line-height).
If you see those characters you probably just didn’t specify the character encoding properly. Because those characters are the result when an UTF-8 multi-byte string is interpreted with a single-byte encoding like ISO 8859-1 or Windows-1252.
In this case ë
could be encoded with 0xC3 0xAB that represents the Unicode character ë
(U+00EB) in UTF-8.
this works fine for me
<Link to={`link`} target="_blank">View</Link>
Try to run
java -cp ScrumTimeCaptureMaintenence.jar Main
You can use cookies if the data is small enough and does not present a security concern. The same HttpContext.Current based approach should work.
Request and response HTTP headers can also be used to pass information between service calls.
You can scroll by using the property contentOffset
in UIScrollView
, e.g.,
CGPoint offset = scrollview.contentOffset;
offset.y -= KEYBOARD_HEIGHT + 5;
scrollview.contentOffset = offset;
There's also a method to do animated scrolling.
As for the reason why your second edit is not scrolling correctly, it could be because you seem to assume that a new keyboard will appear every time editing starts. You could try checking if you've already adjusted for the "keyboard" visible position (and likewise check for keyboard visibility at the moment before reverting it).
A better solution might be to listen for the keyboard notification, e.g.:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidShow:)
name:UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
The Date
object is used to work with dates and times.
Date objects are created with new Date()
var now = new Date();
now - Current date and time object.
function changeDate() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
var date = new Date();
sheet.getRange(5, 2).setValue(date);
}
You can combine both in the same date function call
date("d-m-Y H:i:s");
No need to uninstall old python versions.
Just install new version say python-3.3.2-macosx10.6.dmg and change the soft link of python to newly installed python3.3
Check the path of default python and python3.3 with following commands
"which python" and "which python3.3"
then delete existing soft link of python and point it to python3.3
The default location for the MySQL socket on Mac OS X is /var/mysql/mysql.sock
.
Have some logic to check the color or have some flag,
function abc() {
var currentColor = document.getElementById("test").style.color;
if(currentColor == 'red'){
document.getElementById("test").style.color="black";
}else{
document.getElementById("test").style.color="red";
}
}
class Animal:
HUGE = "Huge"
BIG = "Big"
class Horse:
def printSize(self):
print(Animal.HUGE)
I am fighting the soft keyboard on the Honeywell Dolphin 70e with Android 4.0.3. I don't need the keyboard because the input comes from the builtin barcode reader through the 'scanwedge', set to generate key events.
What I found was that the trick described in the earlier answers of:
input.blur();
input.focus();
works, but only once, right at page initialization. It puts the focus in the input element without showing the soft keyboard. It does NOT work later, e.g. after a TAB character in the suffix of the barcode causes the onblur or oninput event on the input element.
To read and process lots of barcodes, you may use a different postfix than TAB (9), e.g. 8, which is not interpreted by the browser. In the input.keydown
event, use e.keyCode == 8
to detect a complete barcode to be processed.
This way, you initialize the page with focus in the input element, with keyboard hidden, all barcodes go to the input element, and the focus never leaves that element. Of course, the page cannot have other input elements (like buttons), because then you will not be able to return to the barcode input element with the soft keyboard hidden.
Perhaps reloading the page after a button click may be able to hide the keyboard. So use ajax for fast processing of barcodes, and use a regular asp.net button with PostBack to process a button click and reload the page to return focus to the barcode input with the keyboard hidden.
There's no one answer. The standard defines minimum ranges. An int must be able to hold at least 65535. Most modern compilers however allow ints to be 32-bit values. Additionally, there's nothing preventing multiple types from having the same capacity (e.g. int and long).
That being said, the standard does say in your particular case:
0 ? +18446744073709551615
as the range for unsigned long long int.
Further reading: http://en.wikipedia.org/wiki/C_variable_types_and_declarations#Size
It is not guaranteed that the slicing returns a view or a copy. You can do
df['column'] = df['column'].fillna(value)
In class A
, set value for key:
let text = "hai"
UserDefaults.standard.setValue(text, forKey: "textValue")
In class B
, get the value for the text using the key which declared in class A
and assign it to respective variable which you need:
var valueOfText = UserDefaults.value(forKey: "textValue")
All STL container are externally represented as "sequences" with one iteration mechanism. Trees don't follow this idiom.
Use specific value:
[Display(Name = "Date")]
public DateTime EntryDate {get; set;} = DateTime.Now;//by C# v6
You might be interested in pyp. Citing my other answer:
"The Pyed Piper", or pyp, is a linux command line text manipulation tool similar to awk or sed, but which uses standard python string and list methods as well as custom functions evolved to generate fast results in an intense production environment.
The answer to the question specifically asked is no. But have you been looking at mocking frameworks? I use MOQ but there's millions of them out there and they allow you to implement/stub (partially or fully) interfaces in-line. Eg.
public void ThisWillWork()
{
var source = new DummySource[0];
var mock = new Mock<DummyInterface>();
mock.SetupProperty(m => m.A, source.Select(s => s.A));
mock.SetupProperty(m => m.B, source.Select(s => s.C + "_" + s.D));
DoSomethingWithDummyInterface(mock.Object);
}
Try this
boxValue = boxValue.replace(/[^0-9\.]/g,"");
This Regular Expression will allow only digits and dots in the value of text box.
Typescript recognizes the Date interface out of the box - just like you would with a number, string, or custom type. So Just use:
myDate : Date;
Try this : (http://jsfiddle.net/TpqVx/)
.left-div {
float: left;
width: 100px;
/*height: 20px;*/
margin-right: 8px;
background-color: linen;
}
.right-div {
margin-left: 108px;
background-color: lime;
}??
<div class="left-div">
</div>
<div class="right-div">
My requirements are <b>[A]</b> Content in the two divs should line up at the top, <b>[B]</b> Long text in right-div should not wrap underneath left-div, and <b>[C]</b> I do not want to specify a width of right-div. I don't want to set the width of right-div because this markup needs to work within different widths.
</div>
<div style='clear:both;'> </div>
Hints :
float:left
in your left-most div only.height
, but anyway...<div 'clear:both'> </div>
after your last div.-Confirm
is a switch in most PowerShell cmdlets that forces the cmdlet to ask for user confirmation. What you're actually looking for is the Read-Host
cmdlet:
$confirmation = Read-Host "Are you Sure You Want To Proceed:"
if ($confirmation -eq 'y') {
# proceed
}
or the PromptForChoice()
method of the host user interface:
$title = 'something'
$question = 'Are you sure you want to proceed?'
$choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription]
$choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes'))
$choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&No'))
$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -eq 0) {
Write-Host 'confirmed'
} else {
Write-Host 'cancelled'
}
Edit:
As M-pixel pointed out in the comments the code could be simplified further, because the choices can be passed as a simple string array.
$title = 'something'
$question = 'Are you sure you want to proceed?'
$choices = '&Yes', '&No'
$decision = $Host.UI.PromptForChoice($title, $question, $choices, 1)
if ($decision -eq 0) {
Write-Host 'confirmed'
} else {
Write-Host 'cancelled'
}
protected bool ValidateBirthday(String date)
{
DateTime Temp;
if (DateTime.TryParse(date, out Temp) == true &&
Temp.Hour == 0 &&
Temp.Minute == 0 &&
Temp.Second == 0 &&
Temp.Millisecond == 0 &&
Temp > DateTime.MinValue)
return true;
else
return false;
}
//suppose that input string is short date format.
e.g. "2013/7/5" returns true or
"2013/2/31" returns false.
http://forums.asp.net/t/1250332.aspx/1
//bool booleanValue = ValidateBirthday("12:55"); returns false
If you have main.s file.
you can generate object file by GCC
and also as
# gcc -c main.s
# as main.s -o main.o
check this link, it will help you learn some binutils of GCC http://www.thegeekstuff.com/2017/01/gnu-binutils-commands/
If you are like me, and starring at your angular/ionic typescript, which looks like..
getPdf(endpoint: string): Observable<Blob> {
let url = this.url + '/' + endpoint;
let token = this.msal.accessToken;
console.log(token);
return this.http.post<Blob>(url, {
headers: new HttpHeaders(
{
'Access-Control-Allow-Origin': 'https://localhost:5100',
'Access-Control-Allow-Methods': 'POST',
'Content-Type': 'application/pdf',
'Authorization': 'Bearer ' + token,
'Accept': '*/*',
}),
//responseType: ResponseContentType.Blob,
});
}
And while you are setting options but can't seem to figure why they aren't anywhere..
Well.. if you were like me and started this post
from a copy/paste of a get
, then...
Change to:
getPdf(endpoint: string): Observable<Blob> {
let url = this.url + '/' + endpoint;
let token = this.msal.accessToken;
console.log(token);
return this.http.post<Blob>(url, null, { // <----- notice the null *****
headers: new HttpHeaders(
{
'Authorization': 'Bearer ' + token,
'Accept': '*/*',
}),
//responseType: ResponseContentType.Blob,
});
}
Maven uses batch files to do its business. With any batch script, you must call another script using the call
command so it knows to return back to your script after the called script completes. Try prepending call
to all commands.
Another thing you could try is using the start
command which should work similarly.
The selected answer authored by Anurag is only partially correct. Due to some internals of jQuery's event handling, the proposed bindFirst function will not work if you have a mix of handlers with and without filters (ie: $(document).on("click", handler) vs $(document).on("click", "button", handler)).
The issue is that jQuery will place (and expect) that the first elements in the handler array will be these filtered handlers, so placing our event without a filter at the beginning breaks this logic and things start to fall apart. The updated bindFirst function should be as follows:
$.fn.bindFirst = function (name, fn) {
// bind as you normally would
// don't want to miss out on any jQuery magic
this.on(name, fn);
// Thanks to a comment by @Martin, adding support for
// namespaced events too.
this.each(function () {
var handlers = $._data(this, 'events')[name.split('.')[0]];
// take out the handler we just inserted from the end
var handler = handlers.pop();
// get the index of the first handler without a selector
var firstNonDelegate = handlers.first(function(h) { return !h.selector; });
var index = firstNonDelegate ? handlers.indexOf(firstNonDelegate)
: handlers.length; // Either all handlers are selectors or we have no handlers
// move it at the beginning
handlers.splice(index, 0, handler);
});
};
I landed here with the same issue, then figured it out on my own. This weird character was appearing with my HTML.
The issue is most likely your code editor. I use Espresso and sometimes run into issues like this.
To fix it, simply highlight the affected code, then go to the menu and click "convert to numeric entities". You'll see the numeric value of this character appear; simply delete it and it's gone forever.
just enhancing above solution.. so header it self resize its width in order to accommodate lengthy string like 12345
private void advancedDataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
var grid = sender as DataGridView;
var rowIdx = (e.RowIndex + 1).ToString();
var centerFormat = new StringFormat()
{
// right alignment might actually make more sense for numbers
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
//get the size of the string
Size textSize = TextRenderer.MeasureText(rowIdx, this.Font);
//if header width lower then string width then resize
if (grid.RowHeadersWidth < textSize.Width + 40)
{
grid.RowHeadersWidth = textSize.Width + 40;
}
var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
}
ES6: Instead of including many js files using <script>
in .html you can include only one main file e.g. script.js
using attribute type="module"
(support) and inside script.js
you can include other files:
<script type="module" src="script.js"></script>
And in script.js
file include another file like that:
import { hello } from './module.js';
...
// alert(hello());
In 'module.js' you must export function/class that you will import
export function hello() {
return "Hello World";
}
Working example here.
Since .NET4.5
if you want one-liner you can use System.Collections.Generic
ForEach.
source.ForEach(o => destination.Add(o));
or even shorter as
source.ForEach(destination.Add);
Performance-wise it's the same as for each loop (syntactic sugar).
Also don't try assigning it like
var x = source.ForEach(destination.Add)
cause ForEach
is void.
Edit: Copied from comments, Lipert's opinion on ForEach
To be a little more ECMAScript-5.1-precise than the other answers (some might say pedantic):
In JavaScript, variables (and properties) don't have types: values do. Further, there are only 6 types of values: Undefined, Null, Boolean, String, Number, and Object. (Technically, there are also 7 "specification types", but you can't store values of those types as properties of objects or values of variables--they are only used within the spec itself, to define how the language works. The values you can explicitly manipulate are of only the 6 types I listed.)
The spec uses the notation "Type(x)" when it wants to talk about "the type of x". This is only a notation used within the spec: it is not a feature of the language.
As other answers make clear, in practice you may well want to know more than the type of a value--particularly when the type is Object. Regardless, and for completeness, here is a simple JavaScript implementation of Type(x) as it is used in the spec:
function Type(x) {
if (x === null) {
return 'Null';
}
switch (typeof x) {
case 'undefined': return 'Undefined';
case 'boolean' : return 'Boolean';
case 'number' : return 'Number';
case 'string' : return 'String';
default : return 'Object';
}
}
DISCLAIMER: Please, @juanpa.arrivillaga, if you see this answer, feel free to write your own and I will remove this post.
@juanpa.arrivillaga had mentioned above:
Is there a file name enum.py in your working directory, by any chance?
This was the issue I encountered. I was not aware of the enum module on python at the time and had named my test file enum.py
.
Since the file name is the module name, there was a conflict. More info on modules here: https://docs.python.org/2/tutorial/modules.html
Slight modification to the answer by @pauloppenheim , as it will not properly handle parameter names which can be a part of other parameter names.
Eg: If you have "appenv" & "env" parameters, redeaing the value for "env" can pick-up "appenv" value.
Fix:
var urlParamVal = function (name) {
var result = RegExp("(&|\\?)" + name + "=(.+?)(&|$)").exec(location.search);
return result ? decodeURIComponent(result[2]) : "";
};