If you don't care about any child elements, e.g. optgroup
, you can use empty()
...
$('select').empty();
Otherwise, if you only want option
elements removed, use remove()
.
$('select option').remove();
import ReactDOM from 'react-dom' ;
class SomeComponent {
constructor(props) {
// First, add this to your constructor
this.handleClickOutside = this.handleClickOutside.bind(this);
}
componentWillMount() {
document.addEventListener('mousedown', this.handleClickOutside, false);
}
// Unbind event on unmount to prevent leaks
componentWillUnmount() {
window.removeEventListener('mousedown', this.handleClickOutside, false);
}
handleClickOutside(event) {
if(!ReactDOM.findDOMNode(this).contains(event.path[0])){
console.log("OUTSIDE");
}
}
}
If you want to do it via setAttribute
you would change the style
attribute like so:
element.setAttribute('style','transform:rotate(90deg); -webkit-transform: rotate(90deg)') //etc
This would be helpful if you want to reset all other inline style and only set your needed style properties' values again, BUT in most cases you may not want that. That's why everybody advised to use this:
element.style.transform = 'rotate(90deg)';
element.style.webkitTransform = 'rotate(90deg)';
The above is equivalent to
element.style['transform'] = 'rotate(90deg)';
element.style['-webkit-transform'] = 'rotate(90deg)';
Html file (/index.html)
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<link rel="stylesheet" media="screen" href="assets/css/style.css" />
</head>
<body>
<h1>Background Image</h1>
</body>
</html>
Css file (/assets/css/style.css)
body{
background:url(../img/bg.jpg);
}
-n
returns line number.
-i
is for ignore-case. Only to be used if case matching is not necessary
$ grep -in null myfile.txt
2:example two null,
4:example four null,
Combine with awk
to print out the line number after the match:
$ grep -in null myfile.txt | awk -F: '{print $2" - Line number : "$1}'
example two null, - Line number : 2
example four null, - Line number : 4
Use command substitution to print out the total null count:
$ echo "Total null count :" $(grep -ic null myfile.txt)
Total null count : 2
Not optimal, but simple way to count occurrences:
String s = "...";
int counter = s.split("\\$", -1).length - 1;
Note:
To avoid linter errors, I use it like this:
render() {
const props = {
dangerouslySetInnerHTML: { __html: '<br/>' },
};
return (
<div {...props}></div>
);
}
Check if a MySQL connection is open
ConnectionState state = connection.State;
if (state == ConnectionState.Open)
{
return true;
}
else
{
connection.Open();
return true;
}
gvim version: 8.2
location of .gvimrc: %userprofile%/.gvimrc
" .gvimrc
colorscheme darkblue
Which color is allows me to choose?
Find your install directory and go to the directory of colors
.
in my case is:
%PROGRAMFILES(X86)%\Vim\vim82\colors
blue.vim
darkblue.vim
slate.vim
...
README.txt
You might be better served by using a JavaScript framework, that has functions to return such information (and so much more!) in a browser-independant fashion. Here are a few:
With these frameworks, you could do something like:
$('id-of-img').top
to get the y-pixel coordinate of the image.
Try this
ImageView img
Bitmap bmp;
int width=100;
int height=100;
img=(ImageView)findViewById(R.id.imgView);
bmp=BitmapFactory.decodeResource(getResources(),R.drawable.image);//image is your image
bmp=Bitmap.createScaledBitmap(bmp, width,height, true);
img.setImageBitmap(bmp);
Or If you want to load complete image size in memory then you can use
<ImageView
android:id="@+id/img"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/image"
android:scaleType="fitXY"/>
If notepad is already started, you should write:
// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);
//...
Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
}
GetProcessesByName
returns an array of processes, so you should get the first one (or find the one you want).
If you want to start notepad
and send the key, you should write:
Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");
The only situation in which the code may not work is when notepad
is started as Administrator and your application is not.
Well, this solution will help you select only current month, current week and only today
SELECT * FROM games WHERE games.published_gm = 1 AND YEAR(addedon_gm) = YEAR(NOW()) AND MONTH(addedon_gm) = MONTH(NOW()) AND DAY(addedon_gm) = DAY(NOW()) ORDER BY addedon_gm DESC;
For Weekly added posts:
WEEKOFYEAR(addedon_gm) = WEEKOFYEAR(NOW())
For Monthly added posts:
MONTH(addedon_gm) = MONTH(NOW())
For Yearly added posts:
YEAR(addedon_gm) = YEAR(NOW())
you'll get the accurate results where show only the games added today, otherwise you may display: "No New Games Found For Today". Using ShowIF recordset is empty transaction.
Here you go:
http://jsfiddle.net/damsarabi/gwAdA/
You cannot use width: 100px, because the display is table-cell. You can however use Max-width: 100px. then your box will never get bigger than 100px. but you need to add overflow:hidden to make sure the contect don't bleed to other cells. you can also add white-space: nowrap if you wish to keep the height from increasing.
With the release of iOS 7.0.4, the iOS7 fix broke in my current project, as 7.0.4 works w/o the fix. So added a minor control to just run it if running minor release 3 or less.
NSArray *vComp = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
if ([[vComp objectAtIndex:0] intValue] == 7 && [[vComp objectAtIndex:1] intValue] == 0 && [[vComp objectAtIndex:2] intValue] <= 3 ) {
CGRect oldBounds = [self.view bounds];
CGRect newViewBounds = CGRectMake( 0, -10, oldBounds.size.width, oldBounds.size.height-20 );
CGRect newWebViewBounds = CGRectMake( 0, -20, oldBounds.size.width, oldBounds.size.height-40 );
[self.view setBounds:newViewBounds];
[self.webView setBounds:newWebViewBounds];
}
Here's a bit of code I've got added to FlappySwift that works:
import SpriteKit
import AVFoundation
class GameScene: SKScene {
// Grab the path, make sure to add it to your project!
var coinSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "coin", ofType: "wav")!)
var audioPlayer = AVAudioPlayer()
// Initial setup
override func didMoveToView(view: SKView) {
audioPlayer = AVAudioPlayer(contentsOfURL: coinSound, error: nil)
audioPlayer.prepareToPlay()
}
// Trigger the sound effect when the player grabs the coin
func didBeginContact(contact: SKPhysicsContact!) {
audioPlayer.play()
}
}
There're several NuGet packages which can help with formatting. In some cases the capabilities of string.Format
are enough, but you may want to auto-size columns based on content, at least.
ConsoleTableExt is a simple library which allows formatting tables, including tables without grid lines. (A more popular package ConsoleTables doesn't seem to support borderless tables.) Here's an example of formatting a list of objects with columns sized based on their content:
ConsoleTableBuilder
.From(orders
.Select(o => new object[] {
o.CustomerName,
o.Sales,
o.Fee,
o.Value70,
o.Value30
})
.ToList())
.WithColumn(
"Customer",
"Sales",
"Fee",
"70% value",
"30% value")
.WithFormat(ConsoleTableBuilderFormat.Minimal)
.WithOptions(new ConsoleTableBuilderOption { DividerString = "" })
.ExportAndWriteLine();
If you need more features than that, any console formatting can be achieved with CsConsoleFormat.† For example, here's formatting of a list of objects as a grid with fixed column width of 10, like in the other answers using string.Format
:
ConsoleRenderer.RenderDocument(
new Document { Color = ConsoleColor.Gray }
.AddChildren(
new Grid { Stroke = LineThickness.None }
.AddColumns(10, 10, 10, 10, 10)
.AddChildren(
new Div("Customer"),
new Div("Sales"),
new Div("Fee"),
new Div("70% value"),
new Div("30% value"),
orders.Select(o => new object[] {
new Div().AddChildren(o.CustomerName),
new Div().AddChildren(o.Sales),
new Div().AddChildren(o.Fee),
new Div().AddChildren(o.Value70),
new Div().AddChildren(o.Value30)
})
)
));
It may look more complicated than pure string.Format
, but now it can be customized. For example:
If you want to auto-size columns based on content, replace AddColumns(10, 10, 10, 10, 10)
with AddColumns(-1, -1, -1, -1, -1)
(-1
is a shortcut to GridLength.Auto
, you have more sizing options, including percentage of console window's width).
If you want to align number columns to the right, add { Align = Right }
to a cell's initializer.
If you want to color a column, add { Color = Yellow }
to a cell's initializer.
You can change border styles and more.
† CsConsoleFormat was developed by me.
ORACLE DATABASE example:
select *
from table1 t1, table2 t2
WHERE t1.a like ('%' || t2.b || '%')
Some pages may require more than login/pass. There may even be hidden fields. The most reliable way is to use inspect tool and look at the network tab while logging in, to see what data is being passed on.
According to TLDP's Bash Guide for Beginners: Chapter 2. Writing and debugging scripts:
2.3.1. Debugging on the entire script
$ bash -x script1.sh
...
There is now a full-fledged debugger for Bash, available at SourceForge. These debugging features are available in most modern versions of Bash, starting from 3.x.
2.3.2. Debugging on part(s) of the script
set -x # Activate debugging from here w set +x # Stop debugging from here
...
Table 2-1. Overview of set debugging options
Short | Long notation | Result
-------+---------------+--------------------------------------------------------------
set -f | set -o noglob | Disable file name generation using metacharacters (globbing).
set -v | set -o verbose| Prints shell input lines as they are read.
set -x | set -o xtrace | Print command traces before executing command.
...
Alternatively, these modes can be specified in the script itself, by adding the desired options to the first line shell declaration. Options can be combined, as is usually the case with UNIX commands:
#!/bin/bash -xv
The above solution will modify the inf
s that are not in the target columns. To remedy that,
lst = [np.inf, -np.inf]
to_replace = {v: lst for v in ['col1', 'col2']}
df.replace(to_replace, np.nan)
Udacity's Blog has the Best LaTeX Primer I've seen: It clearly shows how to use LaTeX commands in easy to read, and easy to remember manner !! Highly recommended.
This Link has Excellent Examples showing both the code, and the rendered result !
You can use this site to quickly learn how to write LaTeX by example.
And, here is a quick Reference for LaTeX commands/symbols.
inline, wrap in: $
The equation used depends on whether the the value of
$V?max??$ is R, G, or B.
block, wrap in: $$
$$H? ?????0 ?+? \frac{??30(G-B)??}{Vmax-Vmin} ??, if V?max?? = R$$
block, wrap in: \begin{equation}
and \end{equation}
\begin{equation}
H? ???60 ?+? \frac{??30(B-R)??}{Vmax-Vmin} ??, if V?max?? = G
\end{equation}
block, wrap in: \begin{align}
and \end{align}
\begin{align}
H?120 ?+? \frac{??30(R-G)??}{Vmax-Vmin} ??, if V?max?? = B
\end{align}
LaTex Cell: %%latex
magic command turns the entire cell into a LaTeX Cell
%%latex
\begin{align}
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}
Math object to pass in a raw LaTeX string:
from IPython.display import Math
Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx')
Latex class. Note: you have to include the delimiters yourself. This allows you to use other LaTeX modes such as eqnarray
:
from IPython.display import Latex
Latex(r"""\begin{eqnarray}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{eqnarray}""")
(sorry, no example here, just the docs)
Raw cells Raw cells provide a place in which you can write output directly. Raw cells are not evaluated by the notebook. When passed through
nbconvert
, raw cells arrive in the destination format unmodified. For example, this allows you to type full LaTeX into a raw cell, which will only be rendered by LaTeX after conversion bynbconvert
.
For Markdown Cells, as quoted from Jupyter Notebook docs:
Within Markdown cells, you can also include mathematics in a straightforward way, using standard LaTeX notation: $...$ for inline mathematics and $$...$$ for displayed mathematics. When the Markdown cell is executed, the LaTeX portions are automatically rendered in the HTML output as equations with high quality typography. This is made possible by MathJax, which supports a large subset of LaTeX functionality
Standard mathematics environments defined by LaTeX and AMS-LaTeX (the amsmath package) also work, such as \begin{equation}...\end{equation}, and \begin{align}...\end{align}. New LaTeX macros may be defined using standard methods, such as \newcommand, by placing them anywhere between math delimiters in a Markdown cell. These definitions are then available throughout the rest of the IPython session.
Use these lines in the code, because the textEntryView is the parent of username edittext and password edittext.
final EditText input1 = (EditText) textEntryView .findViewById(R.id.username);
final EditText input2 = (EditText) textEntryView .findViewById(R.id.password);
After Ctrl+End, you can do the Ctrl+A to select all in the buffer and then paste into Excel. Excel even put each Oracle column into its own column instead of squishing the whole row into one column. Nice..
or do it with Route Attribute:
public class InventoryController : Controller
{
[Route("whatever/{firstItem}")]
public ActionResult ViewStockNext(int firstItem)
{
int yourNewVariable = firstItem;
// ...
}
}
Hide|Show events for keyboard can be listened through simple hack in OnGlobalLayoutListener :
final View activityRootView = findViewById(R.id.top_root);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
if (heightDiff > 100) {
// keyboard is up
} else {
// keyboard is down
}
}
});
Here activityRootView is your Activity's root view.
You can turn on your PHP errors with error_reporting
:
error_reporting(E_ALL);
ini_set('display_errors', 'on');
Edit: It's possible that even after putting this, errors still don't show up. This can be caused if there is a fatal error in the script. From PHP Runtime Configuration:
Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.
You should set display_errors = 1
in your php.ini
file and restart the server.
You need to use the .format()
function.
MM
- Month number
MMM
- Month word
var date = moment("2014-02-27T10:00:00").format('DD-MM-YYYY');
var dateMonthAsWord = moment("2014-02-27T10:00:00").format('DD-MMM-YYYY');
I'd rather recommend you to use Volley to make GET, PUT, POST... requests.
First, add dependency in your gradle file.
compile 'com.he5ed.lib:volley:android-cts-5.1_r4'
Now, use this code snippet to make requests.
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest postRequest = new StringRequest( com.android.volley.Request.Method.POST, mURL,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
//add your parameters here as key-value pairs
params.put("username", username);
params.put("password", password);
return params;
}
};
queue.add(postRequest);
In SQLDeveloper browse Tools --> Preferences
, as shown in below image.
In the Preferences options expand Database --> select Advanced --> under "Tnsnames Directory" --> Browse the directory
where tnsnames.ora present.
Then click on Ok.
as shown in below diagram.
You have Done!
Now you can connect via the TNSnames options.
If score
is a number, then
print("Total score for %s is %d" % (name, score))
If score is a string, then
print("Total score for %s is %s" % (name, score))
If score is a number, then it's %d
, if it's a string, then it's %s
, if score is a float, then it's %f
Unity 5.6.1 / 2017.1 fixes the Android SDK Tools 25.3.1+ compatibility issue. This is noted in Unity bug tracker under issue 888859 and their 5.6.1 release notes.
Please use below code
package com.myjava.string;
import java.util.StringTokenizer;
public class MyStrRemoveMultSpaces {
public static void main(String a[]){
String str = "String With Multiple Spaces";
StringTokenizer st = new StringTokenizer(str, " ");
StringBuffer sb = new StringBuffer();
while(st.hasMoreElements()){
sb.append(st.nextElement()).append(" ");
}
System.out.println(sb.toString().trim());
}
}
Although JS implementations might keep track of such a value internally, there's no standard way to get it.
In the past, Mozilla's Javascript variant exposed the non-standard __count__
, but it has been removed with version 1.8.5.
For cross-browser scripting you're stuck with explicitly iterating over the properties and checking hasOwnProperty()
:
function countProperties(obj) {
var count = 0;
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
++count;
}
return count;
}
In case of ECMAScript 5 capable implementations, this can also be written as (Kudos to Avi Flax)
function countProperties(obj) {
return Object.keys(obj).length;
}
Keep in mind that you'll also miss properties which aren't enumerable (eg an array's length
).
If you're using a framework like jQuery, Prototype, Mootools, $whatever-the-newest-hype, check if they come with their own collections API, which might be a better solution to your problem than using native JS objects.
another problem I had was I placed an inline comment.
tmp/* # ignore my tmp folder (this doesn't work)
this works
# ignore my tmp folder
tmp/
You can test it by using this snipped code:
private static void Main(string[] args)
{
int threadCount = 0;
try
{
for (int i = 0; i < int.MaxValue; i ++)
{
new Thread(() => Thread.Sleep(Timeout.Infinite)).Start();
threadCount ++;
}
}
catch
{
Console.WriteLine(threadCount);
Console.ReadKey(true);
}
}
Beware of 32-bit and 64-bit mode of application.
it's from this site - http://sqlzoo.net/3.htm 2 possible solutions:
with TOP 1 a ORDER BY ... DESC:
SELECT yr, COUNT(title)
FROM actor
JOIN casting ON actor.id=actorid
JOIN movie ON movie.id=movieid
WHERE name = 'John Travolta'
GROUP BY yr
HAVING count(title)=(SELECT TOP 1 COUNT(title)
FROM casting
JOIN movie ON movieid=movie.id
JOIN actor ON actor.id=actorid
WHERE name='John Travolta'
GROUP BY yr
ORDER BY count(title) desc)
with MAX:
SELECT yr, COUNT(title)
FROM actor
JOIN casting ON actor.id=actorid
JOIN movie ON movie.id=movieid
WHERE name = 'John Travolta'
GROUP BY yr
HAVING
count(title)=
(SELECT MAX(A.CNT)
FROM (SELECT COUNT(title) AS CNT FROM actor
JOIN casting ON actor.id=actorid
JOIN movie ON movie.id=movieid
WHERE name = 'John Travolta'
GROUP BY (yr)) AS A)
I would recommend you having a look at the basics of conditioning in bash.
The symbol "[" is a command and must have a whitespace prior to it. If you don't give whitespace after your elif, the system interprets elif[ as a a particular command which is definitely not what you'd want at this time.
Usage:
elif(A COMPULSORY WHITESPACE WITHOUT PARENTHESIS)[(A WHITE SPACE WITHOUT PARENTHESIS)conditions(A WHITESPACE WITHOUT PARENTHESIS)]
In short, edit your code segment to:
elif [ "$seconds" -gt 0 ]
You'd be fine with no compilation errors. Your final code segment should look like this:
#!/bin/sh
if [ "$seconds" -eq 0 ];then
$timezone_string="Z"
elif [ "$seconds" -gt 0 ]
then
$timezone_string=`printf "%02d:%02d" $seconds/3600 ($seconds/60)%60`
else
echo "Unknown parameter"
fi
Your regex should work 'as-is'. Assuming that it is doing what you want it to.
wordA(\s*)wordB(?! wordc)
This means match wordA
followed by 0 or more spaces followed by wordB
, but do not match if followed by wordc
. Note the single space between ?!
and wordc
which means that wordA wordB wordc
will not match, but wordA wordB wordc
will.
Here are some example matches and the associated replacement output:
Note that all matches are replaced no matter how many spaces. There are a couple of other points: -
(?! wordc)
is a negative lookahead, so you wont match lines wordA wordB wordc
which is assume is intended (and is why the last line is not matched). Currently you are relying on the space after ?!
to match the whitespace. You may want to be more precise and use (?!\swordc)
. If you want to match against more than one space before wordc you can use (?!\s*wordc)
for 0 or more spaces or (?!\s*+wordc)
for 1 or more spaces depending on what your intention is.
Of course, if you do want to match lines with wordc after wordB then you shouldn't use a negative lookahead.
*
will match 0 or more spaces so it will match wordAwordB. You may want to consider +
if you want at least one space.
(\s*)
- the brackets indicate a capturing group. Are you capturing the whitespace to a group for a reason? If not you could just remove the brackets, i.e. just use \s
.
Update based on comment
Hello the problem is not the expression but the HTML out put that are not considered as whitespace. it's a Joomla website.
Preserving your original regex you can use:
wordA((?:\s| )*)wordB(?!(?:\s| )wordc)
The only difference is that not the regex matches whitespace OR
. I replaced wordc
with \swordc
since that is more explicit. Note as I have already pointed out that the negative lookahead ?!
will not match when wordB is followed by a single whitespace and wordc. If you want to match multiple whitespaces then see my comments above. I also preserved the capture group around the whitespace, if you don't want this then remove the brackets as already described above.
Example matches:
Yes, it's "not equal".
Use shell=True
if you're passing a string to subprocess.call
.
From docs:
If passing a single string, either
shell
must beTrue
or else the string must simply name the program to be executed without specifying any arguments.
subprocess.call(crop, shell=True)
or:
import shlex
subprocess.call(shlex.split(crop))
A, = np.array(M.T)
depends what you mean by elegance i suppose but thats what i would do
You can encapsulate the list trivially:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
[XmlRoot("user_list")]
public class UserList
{
public UserList() {Items = new List<User>();}
[XmlElement("user")]
public List<User> Items {get;set;}
}
public class User
{
[XmlElement("id")]
public Int32 Id { get; set; }
[XmlElement("name")]
public String Name { get; set; }
}
static class Program
{
static void Main()
{
XmlSerializer ser= new XmlSerializer(typeof(UserList));
UserList list = new UserList();
list.Items.Add(new User { Id = 1, Name = "abc"});
list.Items.Add(new User { Id = 2, Name = "def"});
list.Items.Add(new User { Id = 3, Name = "ghi"});
ser.Serialize(Console.Out, list);
}
}
You can specialize your templates based on what's passed into their parameters like this:
template <> void foo<animal> {
}
Note that this creates an entirely new function based on the type that's passed as T
. This is usually preferable as it reduces clutter and is essentially the reason we have templates in the first place.
The answer that has 50 votes doesn't check for date in only checks for months. That answer is not correct. The code below works.
var dateFrom = "01/08/2017";
var dateTo = "01/10/2017";
var dateCheck = "05/09/2017";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
var from = new Date(d1); // -1 because months are from 0 to 11
var to = new Date(d2);
var check = new Date(c);
alert(check > from && check < to);
This is the code posted in another answer and I have changed the dates and that's how I noticed it doesn't work
var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "07/07/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); // -1 because months are from 0 to 11
var to = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var check = new Date(c[2], parseInt(c[1])-1, c[0]);
alert(check > from && check < to);
I added it for all fieldsets with
fieldset {
border: 1px solid lightgray;
}
I didnt work if I set it separately using for example
border-color : red
. Then a black line was drawn next to the red line.
You can set the System properties as VM arguments.
If your project is a maven project then you can execute following command while running the test class:
mvn test -Dapp.url="https://stackoverflow.com"
Test class:
public class AppTest {
@Test
public void testUrl() {
System.out.println(System.getProperty("app.url"));
}
}
If you want to run individual test class or method in eclipse then :
1) Go to Run -> Run Configuration
2) On left side select your Test class under the Junit section.
3) do the following :
This is a much more fool proof method.
VirtualPathUtility.ToAbsolute("~/");
Add this to your code
@Autowired
private ApplicationContext _applicationContext;
//Add below line in your calling method
MyClass class = (MyClass) _applicationContext.getBean("myClass");
// Or you can simply use this, put the below code in your controller data member declaration part.
@Autowired
private MyClass myClass;
This will simply inject myClass into your application
Topshelf is an OSS project which was started after this question was answered and it makes Windows service much, MUCH easier.I highly recommend looking into it.
How to configure and troubleshoot <p:fileUpload>
depends on PrimeFaces and JSF version.
The below requirements apply to all PrimeFaces versions:
The enctype
attribute of the <h:form>
needs to be set to multipart/form-data
. When this is absent, the ajax upload may just work, but the general browser behavior is unspecified and dependent on form composition and webbrowser make/version. Just always specify it to be on the safe side.
When using mode="advanced"
(i.e. ajax upload, this is the default), then make sure that you've a <h:head>
in the (master) template. This will ensure that the necessary JavaScript files are properly included. This is not required for mode="simple"
(non-ajax upload), but this would break look'n'feel and functionality of all other PrimeFaces components, so you don't want to miss that anyway.
When using mode="simple"
(i.e. non-ajax upload), then ajax must be disabled on any PrimeFaces command buttons/links by ajax="false"
, and you must use <p:fileUpload value>
with <p:commandButton action>
instead of <p:fileUpload listener>
.
So, if you want (auto) file upload with ajax support (mind the <h:head>
!):
<h:form enctype="multipart/form-data">
<p:fileUpload listener="#{bean.upload}" auto="true" /> // For PrimeFaces version older than 8.x this should be fileUploadListener instead of listener.
</h:form>
public void upload(FileUploadEvent event) {
UploadedFile uploadedFile = event.getFile();
String fileName = uploadedFile.getFileName();
String contentType = uploadedFile.getContentType();
byte[] contents = uploadedFile.getContents(); // Or getInputStream()
// ... Save it, now!
}
Or if you want non-ajax file upload:
<h:form enctype="multipart/form-data">
<p:fileUpload mode="simple" value="#{bean.uploadedFile}" />
<p:commandButton value="Upload" action="#{bean.upload}" ajax="false" />
</h:form>
private transient UploadedFile uploadedFile; // +getter+setter
public void upload() {
String fileName = uploadedFile.getFileName();
String contentType = uploadedFile.getContentType();
byte[] contents = uploadedFile.getContents(); // Or getInputStream()
// ... Save it, now!
}
Do note that ajax-related attributes such as auto
, allowTypes
, update
, onstart
, oncomplete
, etc are ignored in mode="simple"
. So it's needless to specify them in such case.
Also note that you should read the file contents immediately inside the abovementioned methods and not in a different bean method invoked by a later HTTP request. This is because the uploaded file contents is request scoped and thus unavailable in a later/different HTTP request. Any attempt to read it in a later request will most likely end up with java.io.FileNotFoundException
on the temporary file.
Configuration is identical to the 5.x version info below, but if your listener is not called, check if the method attribute is called listener
and not (like with pre 8.x versions) fileUploadListener
.
This does not require any additional configuration if you're using JSF 2.2 and your faces-config.xml
is also declared conform JSF 2.2 version. You do not need the PrimeFaces file upload filter at all and you also do not need the primefaces.UPLOADER
context parameter in web.xml
. In case it's unclear to you how to properly install and configure JSF depending on the target server used, head to How to properly install and configure JSF libraries via Maven? and "Installing JSF" section of our JSF wiki page.
If you're however not using JSF 2.2 yet and you can't upgrade it (should be effortless when already on a Servlet 3.0 compatible container), then you need to manually register the below PrimeFaces file upload filter in web.xml
(it will parse the multi part request and fill the regular request parameter map so that FacesServlet
can continue working as usual):
<filter>
<filter-name>primeFacesFileUploadFilter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>primeFacesFileUploadFilter</filter-name>
<servlet-name>facesServlet</servlet-name>
</filter-mapping>
The <servlet-name>
value of facesServlet
must match exactly the value in the <servlet>
entry of the javax.faces.webapp.FacesServlet
in the same web.xml
. So if it's e.g. Faces Servlet
, then you need to edit it accordingly to match.
The same story as PrimeFaces 5.x applies on 4.x as well.
There's only a potential problem in getting the uploaded file content by UploadedFile#getContents()
. This will return null
when native API is used instead of Apache Commons FileUpload. You need to use UploadedFile#getInputStream()
instead. See also How to insert uploaded image from p:fileUpload as BLOB in MySQL?
Another potential problem with native API will manifest is when the upload component is present in a form on which a different "regular" ajax request is fired which does not process the upload component. See also File upload doesn't work with AJAX in PrimeFaces 4.0/JSF 2.2.x - javax.servlet.ServletException: The request content-type is not a multipart/form-data.
Both problems can also be solved by switching to Apache Commons FileUpload. See PrimeFaces 3.x section for detail.
This version does not support JSF 2.2 / Servlet 3.0 native file upload. You need to manually install Apache Commons FileUpload and explicitly register the file upload filter in web.xml
.
You need the following libraries:
Those must be present in the webapp's runtime classpath. When using Maven, make sure they are at least runtime scoped (default scope of compile is also good). When manually carrying around JARs, make sure they end up in /WEB-INF/lib
folder.
The file upload filter registration detail can be found in PrimeFaces 5.x section here above. In case you're using PrimeFaces 4+ and you'd like to explicitly use Apache Commons FileUpload instead of JSF 2.2 / Servlet 3.0 native file upload, then you need next to the mentioned libraries and filter also the below context param in web.xml
:
<context-param>
<param-name>primefaces.UPLOADER</param-name>
<param-value>commons</param-value><!-- Allowed values: auto, native and commons. -->
</context-param>
In case it still doesn't work, here are another possible causes unrelated to PrimeFaces configuration:
Only if you're using the PrimeFaces file upload filter: There's another Filter
in your webapp which runs before the PrimeFaces file upload filter and has already consumed the request body by e.g. calling getParameter()
, getParameterMap()
, getReader()
, etcetera. A request body can be parsed only once. When you call one of those methods before the file upload filter does its job, then the file upload filter will get an empty request body.
To fix this, you'd need to put the <filter-mapping>
of the file upload filter before the other filter in web.xml
. If the request is not a multipart/form-data
request, then the file upload filter will just continue as if nothing happened. If you use filters that are automagically added because they use annotations (e.g. PrettyFaces), you might need to add explicit ordering via web.xml. See How to define servlet filter order of execution using annotations in WAR
Only if you're using the PrimeFaces file upload filter: There's another Filter
in your webapp which runs before the PrimeFaces file upload filter and has performed a RequestDispatcher#forward()
call. Usually, URL rewrite filters such as PrettyFaces do this. This triggers the FORWARD
dispatcher, but filters listen by default on REQUEST
dispatcher only.
To fix this, you'd need to either put the PrimeFaces file upload filter before the forwarding filter, or to reconfigure the PrimeFaces file upload filter to listen on FORWARD
dispatcher too:
<filter-mapping>
<filter-name>primeFacesFileUploadFilter</filter-name>
<servlet-name>facesServlet</servlet-name>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
There's a nested <h:form>
. This is illegal in HTML and the browser behavior is unspecified. More than often, the browser won't send the expected data on submit. Make sure that you are not nesting <h:form>
. This is completely regardless of the form's enctype
. Just do not nest forms at all.
If you're still having problems, well, debug the HTTP traffic. Open the webbrowser's developer toolset (press F12 in Chrome/Firebug23+/IE9+) and check the Net/Network section. If the HTTP part looks fine, then debug the JSF code. Put a breakpoint on FileUploadRenderer#decode()
and advance from there.
After you finally got it to work, your next question shall probably be like "How/where do I save the uploaded file?". Well, continue here: How to save uploaded file in JSF.
Just add this to config
<system.net>
<defaultProxy useDefaultCredentials="true" >
</defaultProxy>
</system.net>
These answers, including the selected answer, are good for introducing promises conceptually, but lacking in specifics of what exactly the differences are in the terminology that arises when using libraries implementing them (and there are important differences).
Since it is still an evolving spec, the answer currently comes from attempting to survey both references (like wikipedia) and implementations (like jQuery):
Deferred: Never described in popular references,
1
2
3
4
but commonly used by implementations as the arbiter of promise resolution (implementing resolve
and reject
).
5
6
7
Sometimes deferreds are also promises (implementing then
),
5
6
other times it's seen as more pure to have the Deferred only
capable of resolution, and forcing the user to access the promise for
using then
.
7
Promise: The most all-encompasing word for the strategy under discussion.
A proxy object storing the result of a target function whose
synchronicity we would like to abstract, plus exposing a then
function
accepting another target function and returning a new promise.
2
Example from CommonJS:
> asyncComputeTheAnswerToEverything()
.then(addTwo)
.then(printResult);
44
Always described in popular references, although never specified as to whose responsibility resolution falls to. 1 2 3 4
Always present in popular implementations, and never given resolution abilites. 5 6 7
Future: a seemingly deprecated term found in some popular references 1 and at least one popular implementation, 8 but seemingly being phased out of discussion in preference for the term 'promise' 3 and not always mentioned in popular introductions to the topic. 9
However, at least one library uses the term generically for abstracting
synchronicity and error handling, while not providing then
functionality.
10
It's unclear if avoiding the term 'promise' was intentional, but probably a
good choice since promises are built around 'thenables.'
2
Difference between Promises/A and Promises/A+
(TL;DR, Promises/A+ mostly resolves ambiguities in Promises/A)
You can go with the literal control of ASP.net or you can use panels or the purpose.
Here's some code that I ended up writing, based upon @Andrei's answer but without the elegancy/simplicity. The advantage is that it allows a more complex recursive merge and also differs between elements that should be connected with rbind
and those that are just connected with c
:
# Decided to move this outside the mapply, not sure this is
# that important for speed but I imagine redefining the function
# might be somewhat time-consuming
mergeLists_internal <- function(o_element, n_element){
if (is.list(n_element)){
# Fill in non-existant element with NA elements
if (length(n_element) != length(o_element)){
n_unique <- names(n_element)[! names(n_element) %in% names(o_element)]
if (length(n_unique) > 0){
for (n in n_unique){
if (is.matrix(n_element[[n]])){
o_element[[n]] <- matrix(NA,
nrow=nrow(n_element[[n]]),
ncol=ncol(n_element[[n]]))
}else{
o_element[[n]] <- rep(NA,
times=length(n_element[[n]]))
}
}
}
o_unique <- names(o_element)[! names(o_element) %in% names(n_element)]
if (length(o_unique) > 0){
for (n in o_unique){
if (is.matrix(n_element[[n]])){
n_element[[n]] <- matrix(NA,
nrow=nrow(o_element[[n]]),
ncol=ncol(o_element[[n]]))
}else{
n_element[[n]] <- rep(NA,
times=length(o_element[[n]]))
}
}
}
}
# Now merge the two lists
return(mergeLists(o_element,
n_element))
}
if(length(n_element)>1){
new_cols <- ifelse(is.matrix(n_element), ncol(n_element), length(n_element))
old_cols <- ifelse(is.matrix(o_element), ncol(o_element), length(o_element))
if (new_cols != old_cols)
stop("Your length doesn't match on the elements,",
" new element (", new_cols , ") !=",
" old element (", old_cols , ")")
}
return(rbind(o_element,
n_element,
deparse.level=0))
return(c(o_element,
n_element))
}
mergeLists <- function(old, new){
if (is.null(old))
return (new)
m <- mapply(mergeLists_internal, old, new, SIMPLIFY=FALSE)
return(m)
}
Here's my example:
v1 <- list("a"=c(1,2), b="test 1", sublist=list(one=20:21, two=21:22))
v2 <- list("a"=c(3,4), b="test 2", sublist=list(one=10:11, two=11:12, three=1:2))
mergeLists(v1, v2)
This results in:
$a
[,1] [,2]
[1,] 1 2
[2,] 3 4
$b
[1] "test 1" "test 2"
$sublist
$sublist$one
[,1] [,2]
[1,] 20 21
[2,] 10 11
$sublist$two
[,1] [,2]
[1,] 21 22
[2,] 11 12
$sublist$three
[,1] [,2]
[1,] NA NA
[2,] 1 2
Yeah, I know - perhaps not the most logical merge but I have a complex parallel loop that I had to generate a more customized .combine
function for, and therefore I wrote this monster :-)
Like for instance Bootstrap 4 Alpha has this Menu Event. Why not use?
// PREVENT INSIDE MEGA DROPDOWN
$('.dropdown-menu').on("click.bs.dropdown", function (e) {
e.stopPropagation();
e.preventDefault();
});
A possible alternative approach in Excel 2010 or later versions:
AGGREGATE(6,6,A1,B1)
In AGGREGATE
function the first 6
indicates PRODUCT
operation and the second 6
denotes "ignore errors"
[untested]
As long as this question remains unsanswered the OP's problem and Java has evolved over the years, I have decided to put my own one.
Let's change for sake of clarity the input String array to have 5 unique items.
String[] elements = {"a", "b", "c", "d", "e"};
You want to access two siblings in the list with each iteration incremented by one index.
for (int i=0; i<elements.length-1; i++) { // note the condition
String left = elements[i];
String right = elements[i+1];
System.out.println(left + " " + right); // prints 4 lines
}
Printing the pairs of left and right in four iterations result in the lines a b
, b c
, c d
, d e
in your console.
What can happen if the input string array has less than 2 elements? Nothing prints our as long as this for-loop extracts always two sibling nodes. With less than 2 elements the program doesn't enter to the loop itself.
As far as your snippet says you want to not discard the extracted values but add them an another variable, assuming outside the scope of the for-loop, you want to store them in either a list or an array. Let's say you want to concatenate the siblings with the +
character.
List<String> list = new ArrayList<>();
String[] array = new String[elements.length-1]; // note the defined size
for (int i=0; i<elements.length-1; i++) {
String left = elements[i];
String right = elements[i+1];
list.add(left + "+" + right); // adds to the list
array[i] = left + "+" + right; // adds to the array
}
Printing the contents both of the list and the array (Arrays.toString(array)
) results in:
[a+b, b+c, c+d, d+e]
As of Java 8, you might be tempted to use the advantage of Stream API, however, it was made for procesing the individual elements from a source collection. There is no such method for processing 2 or more sibling nodes at once.
The only way is to use Stream API to process the indices instead and map them to the real value. As long as you start with a primitive Stream called IntStream
you need to use IntStream::mapToObj
method to get boxed Stream<T>
:
String[] array = IntStream.range(0, elements.length-1)
.mapToObj(i -> elements[i] + "+" + elements[i + 1])
.toArray(String[]::new); // [a+b, b+c, c+d, d+e]
List<String> list = IntStream.range(0, elements.length-1)
.mapToObj(i -> elements[i] + "+" + elements[i + 1])
.collect(Collectors.toList()); // [a+b, b+c, c+d, d+e]
Use a simple background image for the textarea suffice.
Or
<div onselectstart="return false">your text</div>
Using FileShare fixed my issue of opening file even if it is opened by another process.
using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
{
}
We can manage it by hiding the icon as i did:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Spinner android:id="@+id/fragment_filter_sp_users"
android:layout_width="match_parent"
android:background="@color/colorTransparent"
android:layout_height="wrap_content"/>
<ImageView
android:layout_gravity="end|bottom"
android:contentDescription="@null"
android:layout_marginBottom="@dimen/_5sdp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_arrow_bottom"
/>
</FrameLayout>
I know this might be redundant but I use this script to batch convert files.
old_extension=$1
new_extension=$2
for i in *."$old_extension";
do ffmpeg -i "$i" "${i%.*}.$new_extension";
done
It takes 2 arguments to make it more flexible :
I create an alias for it but you can also use it manually like this:
sh batch_convert.sh mkv mp4
This would convert all the mkv
files into mp4
files.
As you can see it slightly more versatile. As long as ffmpeg
can convert it you can specify any two extensions.
Putting -p as the first option worked for me on Windows Server 2012R2 (in cmd.exe as Admin).
mysqldump.exe –p --user=root --databases DBname --result-file=C:\DBname.sql
I know it's an old thread I worked with above answer and had to add:
header('Access-Control-Allow-Methods: GET, POST, PUT');
So my header looks like:
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');
And the problem was fixed.
Hopefully this helps someone else.
My issue was that I had commented HTML in a PHP callback function via AJAX that was parsing the comments and return invalid JSON.
Once I removed the commented HTML, all was good and the JSON was parsed with no issues.
You can try like:
var path="~/Image/test.png"; System.Web.Hosting.HostingEnvironment.MapPath( @ + path)
I think you want to lowercase the checked value? Try:
var jIsHasKids = $('#chkIsHasKids:checked').val().toLowerCase();
or you want to check it, then get its value as lowercase:
var jIsHasKids = $('#chkIsHasKids').attr("checked", true).val().toLowerCase();
With Git 2.23 (August 2019), that would be, using git switch -f
:
git switch -f master
That avoids the confusion with git checkout
(which deals with files or branches).
And that will proceeds, even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.
If --recurse-submodules
is specified, submodule content is also restored to match the switching target.
This is used to throw away local changes.
The following script catenates several (relative/absolute) paths (BASEPATH) with a relative path (SUBDIR):
shopt -s extglob
SUBDIR="subdir"
for BASEPATH in '' / base base/ base// /base /base/ /base//; do
echo "BASEPATH = \"$BASEPATH\" --> ${BASEPATH%%+(/)}${BASEPATH:+/}$SUBDIR"
done
The output of which is:
BASEPATH = "" --> subdir
BASEPATH = "/" --> /subdir
BASEPATH = "base" --> base/subdir
BASEPATH = "base/" --> base/subdir
BASEPATH = "base//" --> base/subdir
BASEPATH = "/base" --> /base/subdir
BASEPATH = "/base/" --> /base/subdir
BASEPATH = "/base//" --> /base/subdir
The shopt -s extglob
is only necessary to allow BASEPATH to end on multiple slashes (which is probably nonsense). Without extended globing you can just use:
echo ${BASEPATH%%/}${BASEPATH:+/}$SUBDIR
which would result in the less neat but still working:
BASEPATH = "" --> subdir
BASEPATH = "/" --> /subdir
BASEPATH = "base" --> base/subdir
BASEPATH = "base/" --> base/subdir
BASEPATH = "base//" --> base//subdir
BASEPATH = "/base" --> /base/subdir
BASEPATH = "/base/" --> /base/subdir
BASEPATH = "/base//" --> /base//subdir
maps.google.com has a navigation service which can provide you route information in KML format.
To get kml file we need to form url with start and destination locations:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon) {// connect to map web service
StringBuffer urlString = new StringBuffer();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");// from
urlString.append(Double.toString(fromLat));
urlString.append(",");
urlString.append(Double.toString(fromLon));
urlString.append("&daddr=");// to
urlString.append(Double.toString(toLat));
urlString.append(",");
urlString.append(Double.toString(toLon));
urlString.append("&ie=UTF8&0&om=0&output=kml");
return urlString.toString();
}
Next you will need to parse xml (implemented with SAXParser) and fill data structures:
public class Point {
String mName;
String mDescription;
String mIconUrl;
double mLatitude;
double mLongitude;
}
public class Road {
public String mName;
public String mDescription;
public int mColor;
public int mWidth;
public double[][] mRoute = new double[][] {};
public Point[] mPoints = new Point[] {};
}
Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:
public static String getUrl(double fromLat, double fromLon,
double toLat, double toLon)
then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:
public static Road getRoute(InputStream is)
Full source code RoadProvider.java
class MapPathScreen extends MainScreen {
MapControl map;
Road mRoad = new Road();
public MapPathScreen() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
map = new MapControl();
add(new LabelField(mRoad.mName));
add(new LabelField(mRoad.mDescription));
add(map);
}
protected void onUiEngineAttached(boolean attached) {
super.onUiEngineAttached(attached);
if (attached) {
map.drawPath(mRoad);
}
}
private InputStream getConnection(String url) {
HttpConnection urlConnection = null;
InputStream is = null;
try {
urlConnection = (HttpConnection) Connector.open(url);
urlConnection.setRequestMethod("GET");
is = urlConnection.openInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
}
See full code on J2MEMapRouteBlackBerryEx on Google Code
public class MapRouteActivity extends MapActivity {
LinearLayout linearLayout;
MapView mapView;
private Road mRoad;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
new Thread() {
@Override
public void run() {
double fromLat = 49.85, fromLon = 24.016667;
double toLat = 50.45, toLon = 30.523333;
String url = RoadProvider
.getUrl(fromLat, fromLon, toLat, toLon);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
mHandler.sendEmptyMessage(0);
}
}.start();
}
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
TextView textView = (TextView) findViewById(R.id.description);
textView.setText(mRoad.mName + " " + mRoad.mDescription);
MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
};
};
private InputStream getConnection(String url) {
InputStream is = null;
try {
URLConnection conn = new URL(url).openConnection();
is = conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
}
See full code on J2MEMapRouteAndroidEx on Google Code
There's a strong chance that the privileges to select from table1 have been granted to a role, and the role has been granted to you. Privileges granted to a role are not available to PL/SQL written by a user, even if the user has been granted the role.
You see this a lot for users that have been granted the dba role on objects owned by sys. A user with dba role will be able to, say, SELECT * from V$SESSION
, but will not be able to write a function that includes SELECT * FROM V$SESSION
.
The fix is to grant explicit permissions on the object in question to the user directly, for example, in the case above, the SYS user has to GRANT SELECT ON V_$SESSION TO MyUser;
angular.module('formComponents', [])
.directive('formInput', function() {
return {
restrict: 'E',
compile: function(element, attrs) {
var type = attrs.type || 'text';
var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
var htmlText = '<div class="control-group">' +
'<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
'<div class="controls">' +
'<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
'</div>' +
'</div>';
element.replaceWith(htmlText);
}
};
})
You can use Excel Automation (it is basically a COM Base stuff) e.g:
Excel.Application xlApp ;
Excel.Workbook xlWorkBook ;
Excel.Worksheet xlWorkSheet ;
xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open("1.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
A)
Object* o;
o = new Object();
`` B)
Object* o = new Object();
I think A and B has no difference. In both the cases o is a pointer to class Object. statement new Object() creates an object of class Object from heap memory. Assignment statement assigns the address of allocated memory to pointer o.
One thing I would like to mention that size of allocated memory from heap is always the sizeof(Object) not sizeof(Object) + sizeof(void *).
You can use the semver package to determine if a version satisfies a semantic version requirement. This is not the same as comparing two actual versions, but is a type of comparison.
For example, version 3.6.0+1234 should be the same as 3.6.0.
import semver
semver.match('3.6.0+1234', '==3.6.0')
# True
from packaging import version
version.parse('3.6.0+1234') == version.parse('3.6.0')
# False
from distutils.version import LooseVersion
LooseVersion('3.6.0+1234') == LooseVersion('3.6.0')
# False
sometimes if a new header file is added, and this error starts coming due to that, you need to add library as well to get rid of unresolved external symbol
.
for example:
#include WtsApi32.h
will need:
#pragma comment(lib, "Wtsapi32.lib")
It looks like your Spring component scan Base is missing UserServiceImpl
<context:component-scan base-package="org.assessme.com.controller." />
Your output is correct. Denote the white characters of " Hello" and " This" at the beginning.
Another issue is with your methodology. Use the Arrays.sort()
method:
String[] strings = { " Hello ", " This ", "Is ", "Sorting ", "Example" };
Arrays.sort(strings);
Output:
Hello
This
Example
Is
Sorting
Here the third element of the array "is" should be "Is", otherwise it will come in last after sorting. Because the sort method internally uses the ASCII value to sort elements.
Since July 2017 you can use cmp.Equal
with cmpopts.IgnoreFields
option.
func TestPerson(t *testing.T) {
type person struct {
ID int
Name string
}
p1 := person{ID: 1, Name: "john doe"}
p2 := person{ID: 2, Name: "john doe"}
println(cmp.Equal(p1, p2))
println(cmp.Equal(p1, p2, cmpopts.IgnoreFields(person{}, "ID")))
// Prints:
// false
// true
}
I think based on the documentation of the @Before
and @After
the right conclusion is to give the methods unique names. I use the following pattern in my tests:
public abstract class AbstractBaseTest {
@Before
public final void baseSetUp() { // or any other meaningful name
System.out.println("AbstractBaseTest.setUp");
}
@After
public final void baseTearDown() { // or any other meaningful name
System.out.println("AbstractBaseTest.tearDown");
}
}
and
public class Test extends AbstractBaseTest {
@Before
public void setUp() {
System.out.println("Test.setUp");
}
@After
public void tearDown() {
System.out.println("Test.tearDown");
}
@Test
public void test1() throws Exception {
System.out.println("test1");
}
@Test
public void test2() throws Exception {
System.out.println("test2");
}
}
give as a result
AbstractBaseTest.setUp
Test.setUp
test1
Test.tearDown
AbstractBaseTest.tearDown
AbstractBaseTest.setUp
Test.setUp
test2
Test.tearDown
AbstractBaseTest.tearDown
Advantage of this approach: Users of the AbstractBaseTest class cannot override the setUp/tearDown methods by accident. If they want to, they need to know the exact name and can do it.
(Minor) disadvantage of this approach: Users cannot see that there are things happening before or after their setUp/tearDown. They need to know that these things are provided by the abstract class. But I assume that's the reason why they use the abstract class
Since I first saw break
in C a couple of decades back, this problem has vexed me. I was hoping some language enhancement would have an extension to break which would work thus:
break; // our trusty friend, breaks out of current looping construct.
break 2; // breaks out of the current and it's parent looping construct.
break 3; // breaks out of 3 looping constructs.
break all; // totally decimates any looping constructs in force.
<location path="ControllerName/ActionName">
<system.web>
<httpRuntime executionTimeout="1000"/>
</system.web>
</location>
Probably it is better to set such values in web.config instead of controller. Hardcoding of configurable options is considered harmful.
What do you want to do with the attribute? Is it an html attribute or something of your own?
Most of the time you can simply address it as a property: want to set a title on an element? element.title = "foo"
will do it.
For your own custom JS attributes the DOM is naturally extensible (aka expando=true), the simple upshot of which is that you can do element.myCustomFlag = foo
and subsequently read it without issue.
localStorage
is something that is kept on the client side. There is no data transmitted to the server side.
You can only get the data with JavaScript and you can send it to the server side with Ajax.
SQL injection: when user has the chance to input something that could be part of the sql statement
For example:
String query = “INSERT INTO students VALUES(‘” + user + “‘)”
when user input “Robert’); DROP TABLE students; –” as the input, it causes SQL injection
How prepared statement prevents this?
String query = “INSERT INTO students VALUES(‘” + “:name” + “‘)”
parameters.addValue(“name”, user);
=> when user input again “Robert’); DROP TABLE students; –“, the input string is precompiled on the driver as literal values and I guess it may be casted like:
CAST(‘Robert’); DROP TABLE students; –‘ AS varchar(30))
So at the end, the string will be literally inserted as the name to the table.
http://blog.linguiming.com/index.php/2018/01/10/why-prepared-statement-avoids-sql-injection/
Netbeans has great C and C++ support. Some people complain that it's bloated and slow, but I've been using it almost exclusively for personal projects and love it. The code assistance feature is one of the best I've seen.
In this jsfiddle you'll find a solution I deviced. The idea is to have a selector pair in html and use (plain) javascript to filter the options in the dependent selector, based on the selected option of the first. For example:
<select id="continents">
<option value = 0>All</option>
<option value = 1>Asia</option>
<option value = 2>Europe</option>
<option value = 3>Africa</option>
</select>
<select id="selectcountries"></select>
Uses (in the jsFiddle)
MAIN.createRelatedSelector
( document.querySelector('#continents') // from select element
,document.querySelector('#selectcountries') // to select element
,{ // values object
Asia: ['China','Japan','North Korea',
'South Korea','India','Malaysia',
'Uzbekistan'],
Europe: ['France','Belgium','Spain','Netherlands','Sweden','Germany'],
Africa: ['Mali','Namibia','Botswana','Zimbabwe','Burkina Faso','Burundi']
}
,function(a,b){return a>b ? 1 : a<b ? -1 : 0;} // sort method
);
[Edit 2021] or use data-attributes, something like:
document.addEventListener("change", checkSelect);
function checkSelect(evt) {
const origin = evt.target;
if (origin.dataset.dependentSelector) {
const selectedOptFrom = origin.querySelector("option:checked")
.dataset.dependentOpt || "n/a";
const addRemove = optData => (optData || "") === selectedOptFrom
? "add" : "remove";
document.querySelectorAll(`${origin.dataset.dependentSelector} option`)
.forEach( opt =>
opt.classList[addRemove(opt.dataset.fromDependent)]("display") );
}
}
_x000D_
[data-from-dependent] {
display: none;
}
[data-from-dependent].display {
display: initial;
}
_x000D_
<select id="source" name="source" data-dependent-selector="#status">
<option>MANUAL</option>
<option data-dependent-opt="ONLINE">ONLINE</option>
<option data-dependent-opt="UNKNOWN">UNKNOWN</option>
</select>
<select id="status" name="status">
<option>OPEN</option>
<option>DELIVERED</option>
<option data-from-dependent="ONLINE">SHIPPED</option>
<option data-from-dependent="UNKNOWN">SHOULD SELECT</option>
<option data-from-dependent="UNKNOWN">MAYBE IN TRANSIT</option>
</select>
_x000D_
Taking above answers and some fine-tuning (and for whatever it's worth), here is a way of achieving two scales via sec_axis
:
Assume a simple (and purely fictional) data set dt
: for five days, it tracks the number of interruptions VS productivity:
when numinter prod
1 2018-03-20 1 0.95
2 2018-03-21 5 0.50
3 2018-03-23 4 0.70
4 2018-03-24 3 0.75
5 2018-03-25 4 0.60
(the ranges of both columns differ by about factor 5).
The following code will draw both series that they use up the whole y axis:
ggplot() +
geom_bar(mapping = aes(x = dt$when, y = dt$numinter), stat = "identity", fill = "grey") +
geom_line(mapping = aes(x = dt$when, y = dt$prod*5), size = 2, color = "blue") +
scale_x_date(name = "Day", labels = NULL) +
scale_y_continuous(name = "Interruptions/day",
sec.axis = sec_axis(~./5, name = "Productivity % of best",
labels = function(b) { paste0(round(b * 100, 0), "%")})) +
theme(
axis.title.y = element_text(color = "grey"),
axis.title.y.right = element_text(color = "blue"))
Here's the result (above code + some color tweaking):
The point (aside from using sec_axis
when specifying the y_scale is to multiply each value the 2nd data series with 5 when specifying the series. In order to get the labels right in the sec_axis definition, it then needs dividing by 5 (and formatting). So a crucial part in above code is really *5
in the geom_line and ~./5
in sec_axis (a formula dividing the current value .
by 5).
In comparison (I don't want to judge the approaches here), this is how two charts on top of one another look like:
You can judge for yourself which one better transports the message (“Don’t disrupt people at work!”). Guess that's a fair way to decide.
The full code for both images (it's not really more than what's above, just complete and ready to run) is here: https://gist.github.com/sebastianrothbucher/de847063f32fdff02c83b75f59c36a7d a more detailed explanation here: https://sebastianrothbucher.github.io/datascience/r/visualization/ggplot/2018/03/24/two-scales-ggplot-r.html
From MYSQL I solved the problem like this:
SUM(CASE WHEN used = 1 THEN 1 ELSE 0 END) as amount_one,
Hope this helps :D
Maybe the solution someone is looking for is this:
Response.Redirect("/Sucesso")
This work when used in the View as well.
Dijkstra's algorithm assumes paths can only become 'heavier', so that if you have a path from A to B with a weight of 3, and a path from A to C with a weight of 3, there's no way you can add an edge and get from A to B through C with a weight of less than 3.
This assumption makes the algorithm faster than algorithms that have to take negative weights into account.
In addition to Brad's excellent answer, I have found out that (on iOS 4.2.1 at least) when opening custom files from the Mail app, your app is not fired or notified if the attachment has been opened before. The "open with…" popup appears, but just does nothing.
This seems to be fixed by (re)moving the file from the Inbox directory. A safe approach seems to be to both (re)move the file as it is opened (in -(BOOL)application:openURL:sourceApplication:annotation:
) as well as going through the Documents/Inbox directory, removing all items, e.g. in applicationDidBecomeActive:
. That last catch-all may be needed to get the app in a clean state again, in case a previous import causes a crash or is interrupted.
To save others a few seconds, and to save them from having to read the manual, here's the short answer. Add this to the top of your make file:
.DEFAULT_GOAL := mytarget
mytarget will now be the target that is run if "make" is executed and no target is specified.
If you have an older version of make (<= 3.80), this won't work. If this is the case, then you can do what anon mentions, simply add this to the top of your make file:
.PHONY: default
default: mytarget ;
References: https://www.gnu.org/software/make/manual/html_node/How-Make-Works.html
You can reference those remote tracking branches ~(listed with git branch -r
) with the name of their remote.
You need to fetch the remote branch:
git fetch origin aRemoteBranch
If you want to merge one of those remote branches on your local branch:
git checkout master
git merge origin/aRemoteBranch
Note 1: For a large repo with a long history, you will want to add the --depth=1
option when you use git fetch
.
Note 2: These commands also work with other remote repos so you can setup an origin
and an upstream
if you are working on a fork.
Note 3: user3265569 suggests the following alias in the comments:
From
aLocalBranch
, rungit combine remoteBranch
Alias:combine = !git fetch origin ${1} && git merge origin/${1}
Opposite scenario: If you want to merge one of your local branch on a remote branch (as opposed to a remote branch to a local one, as shown above), you need to create a new local branch on top of said remote branch first:
git checkout -b myBranch origin/aBranch
git merge anotherLocalBranch
The idea here, is to merge "one of your local branch" (here anotherLocalBranch
) to a remote branch (origin/aBranch
).
For that, you create first "myBranch
" as representing that remote branch: that is the git checkout -b myBranch origin/aBranch
part.
And then you can merge anotherLocalBranch
to it (to myBranch
).
If you want to go with the add-open option, here's a command to find which module provides which package ->
java --list-modules | tr @ " " | awk '{ print $1 }' | xargs -n1 java -d
the name of the module will be shown with the @ while the name of the packages without it
NOTE: tested with JDK 11
IMPORTANT: obviously is better than the provider of the package does not do the illegal access
I had to change git-rm to git rm in the above to get it to work:
find . -depth -name '.DS_Store' -exec git rm --cached '{}' \; -print
I know it's a relative old post but, I would like to share what worked for me: I've simply input "http://" before "localhost" in the url. Hope it helps somebody.
As per the syntax
function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
statements
}
you can define the default value of formal parameters. and also check undefined value by using typeof function.
One of the biggest problems with delivering live events on Internet is 'scale', and TCP doesn’t scale well. For example when you are beaming a live football match -as opposed to an on demand movie playback- the number of people watching can easily be 1000 times more. In such a scenario using TCP is a death sentence for the CDNs (content delivery networks).
There are a couple of main reasons why TCP doesn't scale well:
One of the largest tradeoffs of TCP is the variability of throughput achievable between the sender and the receiver. When streaming video over the Internet the video packets must traverse multiple routers over the Internet, each of these routers is connected with different speed connections. The TCP algorithm starts with TCP window off small, then grows until packet loss is detected, the packet loss is considered a sign of congestion and TCP responds to it by drastically reducing the window size to avoid congestion. Thus in turn reducing the effective throughput immediately. Now imagine a network with TCP transmission using 6-7 router hops to the client (a very normal scenario), if any of the intermediate router looses any packet, the TCP for that link will reduce the transmission rate. In-fact The traffic flow between routers follow an hourglass kind of a shape; always gong up and down in-between one of the intermediate routers. Rendering the effective through put much lower compared to best-effort UDP.
As you may already know TCP is an acknowledgement-based protocol. Lets for example say a sender is 50ms away (i.e. latency btw two points). This would mean time it takes for a packet to be sent to a receiver and receiver to send an acknowledgement would be 100ms; thus maximum throughput possible as compared to UDP based transmission is already halved.
The TCP doesn’t support multicasting or the new emerging standard of multicasting AMT. Which means the CDNs don’t have the opportunity to reduce network traffic by replicating the packets -when many clients are watching the same content. That itself is a big enough reason for CDNs (like Akamai or Level3) to not go with TCP for live streams.
<input type="text" value="3" class="field left" readonly>
You could see in https://www.w3schools.com/tags/att_input_readonly.asp
The method to set "readonly":
$("input").attr("readonly", true)
to cancel "readonly"(work in jQuery):
$("input").attr("readonly", false)
Try this:
package example.spin.spinnerexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener{
String[] bankNames={"BOI","SBI","HDFC","PNB","OBC"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.simpleSpinner);
spin.setOnItemSelectedListener(this);
//Creating the ArrayAdapter instance having the bank name list
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,bankNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
}
//Performing action onItemSelected and onNothing selected
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(), bankNames[position], Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
activity_main.xml:-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Spinner
android:id="@+id/simpleSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp" />
</RelativeLayout>
How about making the <div id="mainWrapperDivWithBGImage">
as three divs, where the two outside divs hold the rounded corners images, and the middle div simply has a background-color to match the rounded corner images. Then you could simply place the other elements inside the middle div, or:
#outside_left{width:10px; float:left;}
#outside_right{width:10px; float:right;}
#middle{background-color:#color of rnd_crnrs_foo.gif; float:left;}
Then
HTML:
<div id="mainWrapperDivWithBGImage">
<div id="outside_left><img src="rnd_crnrs_left.gif" /></div>
<div id="middle">
<div id="another_div"><img src="foo.gif" /></div>
<div id="outside_right><img src="rnd_crnrs_right.gif" /></div>
</div>
You may have to do position:relative; and such.
This is a pretty old question, but I thought I'd add my 2 cents. I've tried the above solutions, including the ghost css, which I will definitely be saving for future use. But none of these worked in my situation. Here's how I fixed my issue. Hopefully this will help someone else.
Open inspector (or whatever your preference) and starting with the first div in body tag, add display: none;
to just that element. If the scroll bar disappears, you know that element contains the element that's causing the issue. Then, remove the first css rule and go down one level into the containing element. Add the css to that div, and if the scroll bar goes away, you know that element is either causing, or containing the offending element. If adding the CSS does nothing, you know it was not that div that caused the issue, and either another div in the container is causing it, or the container itself is causing it.
This may be too time consuming for some. Lucky for me, my issue was in the header, but I can imagine this taking a bit of time if your issue was say, in the footer or something.
As an alternative to using UsedRange or providing an explicit range address, the AutoFilter.Range property can also specify the affected range.
ActiveSheet.AutoFilter.Range.Offset(1,0).Rows.SpecialCells(xlCellTypeVisible).Delete(xlShiftUp)
As used here, Offset causes the first row after the AutoFilter range to also be deleted. In order to avoid that, I would try using .Resize() after .Offset().
It's called a Favicon, have a read.
<link rel="shortcut icon" href="http://www.example.com/myicon.ico"/>
You can use this neat tool to generate cross-browser compatible Favicons.
It sets the default collation for the table; if you create a new column, that should be collated with latin_general_ci -- I think. Try specifying the collation for the individual column and see if that works. MySQL has some really bizarre behavior in regards to the way it handles this.
Adding Entityframework.dll and Entityframework.sqlserver.dll to the reference project solved the issue.
Hope this help(in onResume):
Locale locale = new Locale("ru");
Locale.setDefault(locale);
Configuration config = getBaseContext().getResources().getConfiguration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
Below is what worked for me -
QUOTE="'"
hive -e "alter table TBL_NAME set location $QUOTE$TBL_HDFS_DIR_PATH$QUOTE"
I am using MySQL 5.5.40. This version has the option --all-databases
mysqldump -u<username> -p<password> --all-databases --events > /tmp/all_databases__`date +%d_%b_%Y_%H_%M_%S`.sql
This command will create a complete backup of all databases in MySQL server to file named to current date-time.
Check out this question / answer. It's more concise than @Geoff's, and also uses the builtin fputcsv function.
$result = $db_con->query('SELECT * FROM `some_table`');
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, $headers);
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
In my case this got the job done:
const chbx = document.getElementsByName("input_name");
for(let i=0; i < chbx.length; i++) {
chbx[i].checked = false;
}
In Visual Studio:
Tools -> Nuget Package Manager -> Package Manager Console.
In PM:
Install-Package NuGet.CommandLine
Close Visual Studio and open it again.
Set in RecyclerView
initialization
recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
I used the VS Project Reference menu and browsed to: C:\windows\assembly\GAC_MSIL\System.Management.Automation and added a reference for the dll and the Runspaces dll.
I did not need to hack the .csprj file and add the reference line mentioned above. I do not have the Windows SDK installed.
I did do the Powershell copy mentioned above: Copy ([PSObject].Assembly.Location) C:\
My test with a Get-Process Powershell command then worked. I used examples from Powershell for developers Chapter 5.
There is also read_csv
in Pandas, which is fast and supports non-comma column separators and automatic typing by column:
import pandas as pd
df = pd.read_csv('your_file',sep='\t')
It can be converted to a NumPy array if you prefer that type with:
import numpy as np
arr = np.array(df)
This is by far the easiest and most mature text import approach I've come across.
>>> a='2010-01-31'
>>> a.split('-')
['2010', '01', '31']
>>> year,month,date=a.split('-')
>>> year
'2010'
>>> month
'01'
>>> date
'31'
There is no built-in way that I know of to do this so you will need to come up with a custom solution depending on how complicated your form is. You should read this post:
Convert HTML forms to read-only (Update: broken post link, archived link)
EDIT: Based on your update, why are you so worried about having it read-only? You can do it via client-side but if not you will have to add the required tag to each control or convert the data and display it as raw text with no controls. If you are trying to make it read-only so that the next post will be unmodified then you have a problem because anyone can mess with the post to produce whatever they want so when you do in fact finally receive the data you better be checking it again to make sure it is valid.
In my opinion the best choice is to put __ init __.py in the folder and call the file with
from dirBar.Bar import *
It is not recommended to use sys.path.append() because something might gone wrong if you use the same file name as the existing python package. I haven't test that but that will be ambiguous.
You may also used foreach loop for display category image and etc from parent category given by parent id.
for example, i am giving 74 id of parent category, then i will display the image from child category and its slug also.
**<?php
$catTerms = get_terms('product_cat', array('hide_empty' => 0, 'orderby' => 'ASC', 'child_of'=>'74'));
foreach($catTerms as $catTerm) : ?>
<?php $thumbnail_id = get_woocommerce_term_meta( $catTerm->term_id, 'thumbnail_id', true );
// get the image URL
$image = wp_get_attachment_url( $thumbnail_id ); ?>
<li><img src="<?php echo $image; ?>" width="152" height="245"/><span><?php echo $catTerm->name; ?></span></li>
<?php endforeach; ?>**
yum -y remove php*
to remove all php packages then you can install the 5.6 ones.
Just in case anyone was looking for the Kotlin version of this, it is as follows:
alertDialog.setPositiveButton(resources.getString(R.string.split_okay)) {
dialog, _ ->
dialog.dismiss()
}
SELECT E.CaseNum, E.FileNum, E.ActivityNum, E.Grade, V.Score
FROM Evaluation E
INNER JOIN Value V
ON E.CaseNum = V.CaseNum AND E.FileNum = V.FileNum AND E.ActivityNum = V.ActivityNum
Some people are saying it's not possible of downloading files with a batch script without using any JScript or VBScript, etc... But they are definitely wrong!
Here is a simple method that seems to work pretty well for downloading files in your batch scripts. It should be working on almost any file's URL. It is even possible to use a proxy server if you need it.
For downloading files, we can use BITSADMIN.EXE from the Windows system. There is no need for downloading/installing anything or using any JScript or VBScript, etc. Bitsadmin.exe is present on most Windows versions, probably from XP to Windows 10.
Enjoy!
USAGE:
You can use the BITSADMIN command directly, like this:
bitsadmin /transfer mydownloadjob /download /priority FOREGROUND "http://example.com/File.zip" "C:\Downloads\File.zip"
Proxy Server:
For connecting using a proxy, use this command before downloading.
bitsadmin /setproxysettings mydownloadjob OVERRIDE "proxy-server.com:8080"
Click this LINK if you want more info about BITSadmin.exe
TROUBLESHOOTING:
If you get this error: "Unable to connect to BITS - 0x80070422"
Make sure the windows service "Background Intelligent Transfer Service (BITS)" is enabled and try again. (It should be enabled by default.)
CUSTOM FUNCTIONS
Call :DOWNLOAD_FILE "URL"
Call :DOWNLOAD_PROXY_ON "SERVER:PORT"
Call :DOWNLOAD_PROXY_OFF
I made these 3 functions for simplifying the bitsadmin commands. It's easier to use and remember. It can be particularly useful if you are using it multiple times in your scripts.
PLEASE NOTE...
Before using these functions, you will first need to copy them from CUSTOM_FUNCTIONS.CMD to the end of your script. There is also a complete example: DOWNLOAD-EXAMPLE.CMD
:DOWNLOAD_FILE "URL"
The main function, will download files from URL.
:DOWNLOAD_PROXY_ON "SERVER:PORT"
(Optional) You can use this function if you need to use a proxy server.
Calling the :DOWNLOAD_PROXY_OFF function will disable the proxy server.
EXAMPLE:
CALL :DOWNLOAD_PROXY_ON "proxy-server.com:8080"
CALL :DOWNLOAD_FILE "http://example.com/File.zip" "C:\Downloads\File.zip"
CALL :DOWNLOAD_PROXY_OFF
CUSTOM_FUNCTIONS.CMD
:DOWNLOAD_FILE
rem BITSADMIN COMMAND FOR DOWNLOADING FILES:
bitsadmin /transfer mydownloadjob /download /priority FOREGROUND %1 %2
GOTO :EOF
:DOWNLOAD_PROXY_ON
rem FUNCTION FOR USING A PROXY SERVER:
bitsadmin /setproxysettings mydownloadjob OVERRIDE %1
GOTO :EOF
:DOWNLOAD_PROXY_OFF
rem FUNCTION FOR STOP USING A PROXY SERVER:
bitsadmin /setproxysettings mydownloadjob NO_PROXY
GOTO :EOF
DOWNLOAD-EXAMPLE.CMD
@ECHO OFF
SETLOCAL
rem FOR DOWNLOADING FILES, THIS SCRIPT IS USING THE "BITSADMIN.EXE" SYSTEM FILE.
rem IT IS PRESENT ON MOST WINDOWS VERSION, PROBABLY FROM WINDOWS XP TO WINDOWS 10.
:SETUP
rem URL (5MB TEST FILE):
SET "FILE_URL=http://ipv4.download.thinkbroadband.com/5MB.zip"
rem SAVE IN CUSTOM LOCATION:
rem SET "SAVING_TO=C:\Folder\5MB.zip"
rem SAVE IN THE CURRENT DIRECTORY
SET "SAVING_TO=5MB.zip"
SET "SAVING_TO=%~dp0%SAVING_TO%"
:MAIN
ECHO.
ECHO DOWNLOAD SCRIPT EXAMPLE
ECHO.
ECHO FILE URL: "%FILE_URL%"
ECHO SAVING TO: "%SAVING_TO%"
ECHO.
rem UNCOMENT AND MODIFY THE NEXT LINE IF YOU NEED TO USE A PROXY SERVER:
rem CALL :DOWNLOAD_PROXY_ON "PROXY-SERVER.COM:8080"
rem THE MAIN DOWNLOAD COMMAND:
CALL :DOWNLOAD_FILE "%FILE_URL%" "%SAVING_TO%"
rem UNCOMMENT NEXT LINE FOR DISABLING THE PROXY (IF YOU USED IT):
rem CALL :DOWNLOAD_PROXY_OFF
:RESULT
ECHO.
IF EXIST "%SAVING_TO%" ECHO YOUR FILE HAS BEEN SUCCESSFULLY DOWNLOADED.
IF NOT EXIST "%SAVING_TO%" ECHO ERROR, YOUR FILE COULDN'T BE DOWNLOADED.
ECHO.
:EXIT_SCRIPT
PAUSE
EXIT /B
rem FUNCTIONS SECTION
:DOWNLOAD_FILE
rem BITSADMIN COMMAND FOR DOWNLOADING FILES:
bitsadmin /transfer mydownloadjob /download /priority FOREGROUND %1 %2
GOTO :EOF
:DOWNLOAD_PROXY_ON
rem FUNCTION FOR USING A PROXY SERVER:
bitsadmin /setproxysettings mydownloadjob OVERRIDE %1
GOTO :EOF
:DOWNLOAD_PROXY_OFF
rem FUNCTION FOR STOP USING A PROXY SERVER:
bitsadmin /setproxysettings mydownloadjob NO_PROXY
GOTO :EOF
steps to install maven :
ZoomLib Link: https://drive.google.com/uc?export=download&id=0B34PUThnUsjVaHpkaGk0Z1hSRU0
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dummy_layout_for_zooming);// Activity layout
mZoomLinearLayout = (LinearLayout) findViewById(R.id.mZoomLinearLayout);// LinearLayout inside Activity layout
View v = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.layout_for_zoom, null, false);// View wants to zoom
v.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
ZoomView zoomView = new ZoomView(this);// intialize lib
zoomView.addView(v);
mZoomLinearLayout.addView(zoomView);
}
I have used Newtonsoft JSON.NET (Documentation) It allows you to create a class / object, populate the fields, and serialize as JSON.
public class ReturnData
{
public int totalCount { get; set; }
public List<ExceptionReport> reports { get; set; }
}
public class ExceptionReport
{
public int reportId { get; set; }
public string message { get; set; }
}
string json = JsonConvert.SerializeObject(myReturnData);
I just had this issue and tried setting it to a different port, but the only thing I needed to do was to delete my [app_directory]/tmp/pids/server.pid
and everything was good to go.
sp_executesql
is more likely to promote query plan reuse. When using sp_executesql
, parameters are explicitly identified in the calling signature. This excellent article descibes this process.
The oft cited reference for many aspects of dynamic sql is Erland Sommarskog's must read: "The Curse and Blessings of Dynamic SQL".
**podria ser algo asi en react y electron**
xslToJson = workbook => {
//var data = [];
var sheet_name_list = workbook.SheetNames[0];
return XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list], {
raw: false,
dateNF: "DD-MMM-YYYY",
header:1,
defval: ""
});
};
handleFile = (file /*:File*/) => {
/* Boilerplate to set up FileReader */
const reader = new FileReader();
const rABS = !!reader.readAsBinaryString;
reader.onload = e => {
/* Parse data */
const bstr = e.target.result;
const wb = XLSX.read(bstr, { type: rABS ? "binary" : "array" });
/* Get first worksheet */
let arr = this.xslToJson(wb);
console.log("arr ", arr)
var dataNueva = []
arr.forEach(data => {
console.log("data renaes ", data)
})
// this.setState({ DataEESSsend: dataNueva })
console.log("dataNueva ", dataNueva)
};
if (rABS) reader.readAsBinaryString(file);
else reader.readAsArrayBuffer(file);
};
handleChange = e => {
const files = e.target.files;
if (files && files[0]) {
this.handleFile(files[0]);
}
};
I'm writing this answer because it's the only approach that doesn't give you optionals back from NSDateComponent
variables and/or force unwrapping those variables (also for Swift 3).
Swift 3
let date = Date()
let cal = Calendar.current
let year = cal.component(.year, from: date)
let month = cal.component(.month, from: date)
let day = cal.component(.day, from: date)
Swift 2
let date = NSDate()
let cal = NSCalendar.currentCalendar()
let year = cal.component(.Year, fromDate: date)
let month = cal.component(.Month, fromDate: date)
let day = cal.component(.Day, fromDate: date)
Bonus Swift 3 fun version
let date = Date()
let component = { (unit) in return Calendar.current().component(unit, from: date) }
let year = component(.year)
let month = component(.month)
let day = component(.day)
You should create a background thread to to create and populate the form. This will allow your foreground thread to show the loading message.
solution: On the server you are trying to clone to or push from cat ~/.ssh/id_rsa.pub Go to GitHub, settings, SSH and GPG Keys , New SSH key paste key.
in my case, datas
is an objects of Array for more information please Click Here
<% for(let [index,data] of datas.entries() || []){ %>
Index : <%=index%>
Data : <%=data%>
<%} %>
According to the jQuery documentation of select()
:
Trigger the select event of each matched element. This causes all of the functions that have been bound to that select event to be executed, and calls the browser's default select action on the matching element(s).
There is your explanation why the jQuery select()
won't work in this case.
Use it in this way:
buttonOBJ.getBackground().setColorFilter(Color.parseColor("#YOUR_HEX_COLOR_CODE"), PorterDuff.Mode.MULTIPLY);
This is not "auto-completion", this is automation. One common tool for these things is called Expect.
You might also get away with just piping input from yes
.
As some of my servers are on an old Ubuntu LTS versions, I can't easily upgrade git to the latest version (which supports the -C option as described in some answers).
This trick works well for me, especially because it does not have the side effect of some other answers that leave you in a different directory from where you started.
pushd /X/Y
git pull
popd
Or, doing it as a one-liner:
pushd /X/Y; git pull; popd
Both Linux and Windows have pushd and popd commands.
It is just a selector that helps you select specific tag <p id = 'demo'></p>
elements which help you change the behavior, in any event (either mouse or keyboard).
if you know sql, please write a query to get the code's value,for example sql query equivalent and elasticsearch query
POST /_sql/translate
{
"query": "select name,surname from users"
}
result is ,be carefull look at the includes key
{
"size" : 1000,
"_source" : {
"includes" : [
"name",
"surname"
],
"excludes" : [ ]
},
"sort" : [
{
"_doc" : {
"order" : "asc"
}
}
]
}
I am running laravel 5.8 and i experienced the same problem. The solution that worked for me is as follows :
I used unsignedBigInteger('user_id') to define the foreign referenced key.
Schema::create('generals', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('general_name');
$table->string('status');
$table->timestamps();
});
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('general_id');
$table->foreign('general_id')->references('id')->on('generals');
$table->string('category_name');
$table->string('status');
$table->timestamps();
});
I hope this helps out.
The way I do this is to hold Alt then press Space, then E and finally P.
On Windows Alt jumps to the window menu, Space opens it, E selects Edit and P executes the Paste command.
Get these correct in succession and you can paste a snippet in under 2 seconds.
Attribute is a synonym of field
for array.length
Simple declaration of the StringHttpMessageConverter
bean is not enough, you need to inject it into AnnotationMethodHandlerAdapter
:
<bean class = "org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<array>
<bean class = "org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value = "text/plain;charset=UTF-8" />
</bean>
</array>
</property>
</bean>
However, using this method you have to redefine all HttpMessageConverter
s, and also it doesn't work with <mvc:annotation-driven />
.
So, perhaps the most convenient but ugly method is to intercept instantiation of the AnnotationMethodHandlerAdapter
with BeanPostProcessor
:
public class EncodingPostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String name)
throws BeansException {
if (bean instanceof AnnotationMethodHandlerAdapter) {
HttpMessageConverter<?>[] convs = ((AnnotationMethodHandlerAdapter) bean).getMessageConverters();
for (HttpMessageConverter<?> conv: convs) {
if (conv instanceof StringHttpMessageConverter) {
((StringHttpMessageConverter) conv).setSupportedMediaTypes(
Arrays.asList(new MediaType("text", "html",
Charset.forName("UTF-8"))));
}
}
}
return bean;
}
public Object postProcessAfterInitialization(Object bean, String name)
throws BeansException {
return bean;
}
}
-
<bean class = "EncodingPostProcessor " />
In iOS 6, tintColor tinted the background of navigation bars, tab bars, toolbars, search bars, and scope bars. To tint a bar background in iOS 7, use the barTintColor property instead.
In case you're using git, use the right email address you used for github registration and then your computer name. this worked for me.
In some version of numpy there is another imporant difference that you must be aware:
average
do not take in account masks, so compute the average over the whole set of data.
mean
takes in account masks, so compute the mean only over unmasked values.
g = [1,2,3,55,66,77]
f = np.ma.masked_greater(g,5)
np.average(f)
Out: 34.0
np.mean(f)
Out: 2.0
Code Camp Server, Jeffrey Palermo's sample code for the book ASP.NET MVC in Action. While the book is focused on the presentation layer, the application is modeled using DDD.
Not so much an answer as a cautionary tale: this was bugging me as well - and I thought I had a solution by pre-pending a zero and using the @(...)
syntax. i.e your code would have been:
var nonID = 0@(nonProID);
var proID = 0@(proID);
Getting output like:
var nonId = 0123;
What I didn't realise was that this is how JavaScript (version 3) represents octal/base-8 numbers and is actually altering the value. Additionally, if you are using the "use strict";
command then it will break your code entirely as octal numbers have been removed.
I'm still looking for a proper solution to this.
check this image link for all steps https://drive.google.com/open?id=0B0-Ll2y6vo_sQ29hYndnbGZVZms
STEP1: I created a field of type varbinary in table
STEP2: I created a stored procedure to accept a parameter of type sql_variant
STEP3: In my front end asp.net page, I created a sql data source parameter of object type
<tr>
<td>
UPLOAD DOCUMENT</td>
<td>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" />
<asp:SqlDataSource ID="sqldsFileUploadConn" runat="server"
ConnectionString="<%$ ConnectionStrings: %>"
InsertCommand="ph_SaveDocument"
InsertCommandType="StoredProcedure">
<InsertParameters>
<asp:Parameter Name="DocBinaryForm" Type="Object" />
</InsertParameters>
</asp:SqlDataSource>
</td>
<td>
</td>
</tr>
STEP 4: In my code behind, I try to upload the FileBytes from FileUpload Control via this stored procedure call using a sql data source control
Dim filebytes As Object
filebytes = FileUpload1.FileBytes()
sqldsFileUploadConn.InsertParameters("DocBinaryForm").DefaultValue = filebytes.ToString
Dim uploadstatus As Int16 = sqldsFileUploadConn.Insert()
' ... code continues ... '
You can forcibly close sockets with ss
command; the ss
command is a tool used to dump socket statistics and displays information in similar fashion (although simpler and faster) to netstat.
To kill any socket in CLOSE_WAIT state, run this (as root)
$ ss --tcp state CLOSE-WAIT --kill
if you want filename only :
for file in /home/user/*; do
f=$(echo "${file##*/}");
filename=$(echo $f| cut -d'.' -f 1); #file has extension, it return only filename
echo $filename
done
for more information about cut
command see here.
A simpler way to do this would be:
Sub populateB()
For Each Cel in Range("A1:A100")
If Cel.value <> "" Then Cel.Offset(0, 1).value = "Your Text"
Next
End Sub
First if the object you're dealing with is a string then you need to parse it then figure out the length of the keys :
obj = JSON.parse(jsonString);
shareInfoLen = Object.keys(obj.shareInfo[0]).length;
Here is SurlyDre's stored procedure modified so that foreign keys are ignored:
DROP PROCEDURE IF EXISTS `drop_all_tables`;
DELIMITER $$
CREATE PROCEDURE `drop_all_tables`()
BEGIN
DECLARE _done INT DEFAULT FALSE;
DECLARE _tableName VARCHAR(255);
DECLARE _cursor CURSOR FOR
SELECT table_name
FROM information_schema.TABLES
WHERE table_schema = SCHEMA();
DECLARE CONTINUE HANDLER FOR NOT FOUND SET _done = TRUE;
SET FOREIGN_KEY_CHECKS = 0;
OPEN _cursor;
REPEAT FETCH _cursor INTO _tableName;
IF NOT _done THEN
SET @stmt_sql = CONCAT('DROP TABLE ', _tableName);
PREPARE stmt1 FROM @stmt_sql;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
END IF;
UNTIL _done END REPEAT;
CLOSE _cursor;
SET FOREIGN_KEY_CHECKS = 1;
END$$
DELIMITER ;
call drop_all_tables();
DROP PROCEDURE IF EXISTS `drop_all_tables`;
The query either returned no rows or is erroneus, thus FALSE
is returned. Change it to
if (!$dbc || mysqli_num_rows($dbc) == 0)
mysqli_num_rows
:
Return Values
Returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.
The --no-ff
option is useful when you want to have a clear notion of your feature branch. So even if in the meantime no commits were made, FF is possible - you still want sometimes to have each commit in the mainline correspond to one feature. So you treat a feature branch with a bunch of commits as a single unit, and merge them as a single unit. It is clear from your history when you do feature branch merging with --no-ff
.
If you do not care about such thing - you could probably get away with FF whenever it is possible. Thus you will have more svn-like feeling of workflow.
For example, the author of this article thinks that --no-ff
option should be default and his reasoning is close to that I outlined above:
Consider the situation where a series of minor commits on the "feature" branch collectively make up one new feature: If you just do "git merge feature_branch" without --no-ff
, "it is impossible to see from the Git history which of the commit objects together have implemented a feature—you would have to manually read all the log messages. Reverting a whole feature (i.e. a group of commits), is a true headache [if --no-ff
is not used], whereas it is easily done if the --no-ff
flag was used [because it's just one commit]."
If it's always the third column, you can use this (assuming table class of "products"). It's kinda hacky though, and not robust if you add a new column.
table.products td+td+td {
text-align: right;
}
table.products td,
table.products td+td+td+td {
text-align: left;
}
But honestly, the best idea is to use a class on each cell. You can use the col
element to set the width, border, background or visibility of a column, but not any other properties. Reasons discussed here.
UPDATE 2018: C++20 will come with templated and conceptualized lambdas. The feature has already been integrated into the standard draft.
UPDATE 2014: C++14 has been released this year and now provides Polymorphic lambdas with the same syntax as in this example. Some major compilers already implement it.
At it stands (in C++11), sadly no. Polymorphic lambdas would be excellent in terms of flexibility and power.
The original reason they ended up being monomorphic was because of concepts. Concepts made this code situation difficult:
template <Constraint T>
void foo(T x)
{
auto bar = [](auto x){}; // imaginary syntax
}
In a constrained template you can only call other constrained templates. (Otherwise the constraints couldn't be checked.) Can foo
invoke bar(x)
? What constraints does the lambda have (the parameter for it is just a template, after all)?
Concepts weren't ready to tackle this sort of thing; it'd require more stuff like late_check
(where the concept wasn't checked until invoked) and stuff. Simpler was just to drop it all and stick to monomorphic lambdas.
However, with the removal of concepts from C++0x, polymorphic lambdas become a simple proposition again. However, I can't find any proposals for it. :(
Yes, they have deprecated the previous buildSessionFactory API, and it's quite easy to do well.. you can do something like this..
EDIT : ServiceRegistryBuilder is deprecated. you must use StandardServiceRegistryBuilder
public void testConnection() throws Exception {
logger.info("Trying to create a test connection with the database.");
Configuration configuration = new Configuration();
configuration.configure("hibernate_sp.cfg.xml");
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(ssrb.build());
Session session = sessionFactory.openSession();
logger.info("Test connection with the database created successfuly.");
}
For more reference and in depth detail, you can check the hibernate's official test case at https://github.com/hibernate/hibernate-orm/blob/master/hibernate-testing/src/main/java/org/hibernate/testing/junit4/BaseCoreFunctionalTestCase.java function (buildSessionFactory()).
// Array of doubles
double[] array_doubles = {2.5, 6.2, 8.2, 4846.354, 9.6};
// First position
double firstNum = array_doubles[0]; // 2.5
// Last position
double lastNum = array_doubles[array_doubles.length - 1]; // 9.6
This is the same in any array.
If like me you recently moved certain classes to different packages ect. and you use android navigation. Make sure to change the argType to you match you new package address. from:
app:argType="com.example.app.old.Item"
to:
app:argType="com.example.app.new.Item"
Cloud: is simply an aggregate of computing power. You can think of the entire "cloud" as single server, for your purposes. It's conceptually much like an old school mainframe where you could submit your jobs to and have it return the result, except that nowadays the concept is applied more widely. (I.e. not just raw computing, also entire services, or storage ...)
Grid: a grid is simply many computers which together might solve a given problem/crunch data. The fundamental difference between a grid and a cluster is that in a grid each node is relatively independent of others; problems are solved in a divide and conquer fashion.
Cluster: conceptually it is essentially smashing up many machines to make a really big & powerful one. This is a much more difficult architecture than cloud or grid to get right because you have to orchestrate all nodes to work together, and provide consistency of things such as cache, memory, and not to mention clocks. Of course clouds have much the same problem, but unlike clusters clouds are not conceptually one big machine, so the entire architecture doesn't have to treat it as such. You can for instance not allocate the full capacity of your data center to a single request, whereas that is kind of the point of a cluster: to be able to throw 100% of the oomph at a single problem.
With props to Rick (second comment down in the blog post mentioned), here's the MSDN article on httpOnlyCookies.
Bottom line is that you just add the following section in your system.web section in your web.config:
<httpCookies domain="" httpOnlyCookies="true|false" requireSSL="true|false" />
You can use a custom serializer at your money field. Here's an example with a MoneyBean. The field amount gets annotated with @JsonSerialize(using=...).
public class MoneyBean {
//...
@JsonProperty("amountOfMoney")
@JsonSerialize(using = MoneySerializer.class)
private BigDecimal amount;
//getters/setters...
}
public class MoneySerializer extends JsonSerializer<BigDecimal> {
@Override
public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
JsonProcessingException {
// put your desired money style here
jgen.writeString(value.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
}
}
That's it. A BigDecimal is now printed in the right way. I used a simple testcase to show it:
@Test
public void jsonSerializationTest() throws Exception {
MoneyBean m = new MoneyBean();
m.setAmount(new BigDecimal("20.3"));
ObjectMapper mapper = new ObjectMapper();
assertEquals("{\"amountOfMoney\":\"20.30\"}", mapper.writeValueAsString(m));
}
Working gradle dependency
Try this:
compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
You can just import
the css file wherever you want. Webpack will take care to bundle the css if you configured the loader as required.
Something like,
import 'bootstrap/dist/css/bootstrap.css';
And the webpack config like,
loaders: [{ test: /\.css$/, loader: 'style-loader!css-loader' }]
Note: You have to add font loaders as well, else you would be getting error.
Allowing all certificates is very powerful but it could also be dangerous. If you would like to only allow valid certificates plus some certain certificates it could be done like this.
.Net core:
using (var httpClientHandler = new HttpClientHandler())
{
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => {
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true; //Is valid
}
if (cert.GetCertHashString() == "99E92D8447AEF30483B1D7527812C9B7B3A915A7")
{
return true;
}
return false;
};
using (var httpClient = new HttpClient(httpClientHandler))
{
var httpResponse = httpClient.GetAsync("https://example.com").Result;
}
}
.Net framework:
System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate (
object sender,
X509Certificate cert,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true; //Is valid
}
if (cert.GetCertHashString() == "99E92D8447AEF30483B1D7527812C9B7B3A915A7")
{
return true;
}
return false;
};
Update:
How to get cert.GetCertHashString()
value in Chrome:
Click on Secure
or Not Secure
in the address bar.
Then click on Certificate -> Details -> Thumbprint and copy the value. Remember to do cert.GetCertHashString().ToLower()
.
Ubuntu 18.04 LTS
Configuration with bridged to see the server ip, and connect without "port forwarding"
VirtualBox > right click in server > settings > Network > enable adapter 2 > select "bridged" > Promiscuous mode: allow all > Check the cable connected > start server
On ubuntu server, edit sudo nano /etc/netplan/*init.yaml
file,
My sample file:
network:
ethernets:
enp0s3:
addresses: []
dhcp4: true
enp0s8:
addresses: [192.168.0.200/24]
dhcp4: no
dhcp6: no
nameservers:
addresses: [8.8.8.8, 8.8.4.4]
version: 2
Commands that will help you
nano /etc/netplan/file.yaml # file to specify the rules of network
reboot now # restart ubuntu server right now
netplan apply # do after edited *.yaml, to apply changes
ifconfig -a # show interfaces with ip, netmask, broadcast, etc...
ping google.com # to see if there is internet
Configure Static IP Addresses On Ubuntu 18.04 LTS Server - with NetPlan
What you are trying to do is an extension of string slicing in Python:
Say all strings are of length 10, last char to be removed:
>>> st[:9]
'abcdefghi'
To remove last N
characters:
>>> N = 3
>>> st[:-N]
'abcdefg'
Not to High-Jack this question but the note needs to be made that you need to use (N)VARCHAR instead of (N)CHAR data-type.
RIGHT('000' + CAST(@number1 AS NCHAR(3)), 3 )
Above segment, will not produce the correct response from SQL 2005
RIGHT('000' + CAST(@number1 AS NVARCHAR(3)), 3 )
Above segment, will produce the desired response from SQL 2005
The the varchar will provide you with the desired prefix length on the fly. Where as the fixed length data type will require length designation and adjustments.
You can use
$objWorksheet->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
$objWorksheet->getActiveSheet()->getColumnDimension('A')->setWidth(100);
or define auto-size:
$objWorksheet->getRowDimension('1')->setRowHeight(-1);
I want to propose a solution where both flavors of a many-to-many configuration can be achieved.
The "catch" is we need to create a view that targets the Join Table, since EF validates that a schema's table may be mapped at most once per EntitySet
.
This answer adds to what's already been said in previous answers and doesn't override any of those approaches, it builds upon them.
The model:
public class Member
{
public int MemberID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
public virtual ICollection<MemberCommentView> MemberComments { get; set; }
}
public class Comment
{
public int CommentID { get; set; }
public string Message { get; set; }
public virtual ICollection<Member> Members { get; set; }
public virtual ICollection<MemberCommentView> MemberComments { get; set; }
}
public class MemberCommentView
{
public int MemberID { get; set; }
public int CommentID { get; set; }
public int Something { get; set; }
public string SomethingElse { get; set; }
public virtual Member Member { get; set; }
public virtual Comment Comment { get; set; }
}
The configuration:
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
public class MemberConfiguration : EntityTypeConfiguration<Member>
{
public MemberConfiguration()
{
HasKey(x => x.MemberID);
Property(x => x.MemberID).HasColumnType("int").IsRequired();
Property(x => x.FirstName).HasColumnType("varchar(512)");
Property(x => x.LastName).HasColumnType("varchar(512)")
// configure many-to-many through internal EF EntitySet
HasMany(s => s.Comments)
.WithMany(c => c.Members)
.Map(cs =>
{
cs.ToTable("MemberComment");
cs.MapLeftKey("MemberID");
cs.MapRightKey("CommentID");
});
}
}
public class CommentConfiguration : EntityTypeConfiguration<Comment>
{
public CommentConfiguration()
{
HasKey(x => x.CommentID);
Property(x => x.CommentID).HasColumnType("int").IsRequired();
Property(x => x.Message).HasColumnType("varchar(max)");
}
}
public class MemberCommentViewConfiguration : EntityTypeConfiguration<MemberCommentView>
{
public MemberCommentViewConfiguration()
{
ToTable("MemberCommentView");
HasKey(x => new { x.MemberID, x.CommentID });
Property(x => x.MemberID).HasColumnType("int").IsRequired();
Property(x => x.CommentID).HasColumnType("int").IsRequired();
Property(x => x.Something).HasColumnType("int");
Property(x => x.SomethingElse).HasColumnType("varchar(max)");
// configure one-to-many targeting the Join Table view
// making all of its properties available
HasRequired(a => a.Member).WithMany(b => b.MemberComments);
HasRequired(a => a.Comment).WithMany(b => b.MemberComments);
}
}
The context:
using System.Data.Entity;
public class MyContext : DbContext
{
public DbSet<Member> Members { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<MemberCommentView> MemberComments { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new MemberConfiguration());
modelBuilder.Configurations.Add(new CommentConfiguration());
modelBuilder.Configurations.Add(new MemberCommentViewConfiguration());
OnModelCreatingPartial(modelBuilder);
}
}
From Saluma's (@Saluma) answer
If you now want to find all comments of members with LastName = "Smith" for example you can write a query like this:
This still works...
var commentsOfMembers = context.Members
.Where(m => m.LastName == "Smith")
.SelectMany(m => m.MemberComments.Select(mc => mc.Comment))
.ToList();
...but could now also be...
var commentsOfMembers = context.Members
.Where(m => m.LastName == "Smith")
.SelectMany(m => m.Comments)
.ToList();
Or to create a list of members with name "Smith" (we assume there is more than one) along with their comments you can use a projection:
This still works...
var membersWithComments = context.Members
.Where(m => m.LastName == "Smith")
.Select(m => new
{
Member = m,
Comments = m.MemberComments.Select(mc => mc.Comment)
})
.ToList();
...but could now also be...
var membersWithComments = context.Members
.Where(m => m.LastName == "Smith")
.Select(m => new
{
Member = m,
m.Comments
})
.ToList();
If you want to remove a comment from a member
var comment = ... // assume comment from member John Smith
var member = ... // assume member John Smith
member.Comments.Remove(comment);
If you want to Include()
a member's comments
var member = context.Members
.Where(m => m.FirstName == "John", m.LastName == "Smith")
.Include(m => m.Comments);
This all feels like syntactic sugar, however it does get you a few perks if you're willing to go through the additional configuration. Either way you seem to be able to get the best of both approaches.
Script for loading of custom .env
file:
Add the following lines to /config/environment.rb
, between the require
line, and the Application.initialize
line:
# Load the app's custom environment variables here, so that they are loaded before environments/*.rb
app_environment_variables = File.join(Rails.root, 'config', 'local_environment.env')
if File.exists?(app_environment_variables)
lines = File.readlines(app_environment_variables)
lines.each do |line|
line.chomp!
next if line.empty? or line[0] == '#'
parts = line.partition '='
raise "Wrong line: #{line} in #{app_environment_variables}" if parts.last.empty?
ENV[parts.first] = parts.last
end
end
And config/local_environment.env
(you will want to .gitignore
it) will look like:
# This is ignored comment
DATABASE_URL=mysql2://user:[email protected]:3307/database
RACK_ENV=development
(Based on solution of @user664833)
Tensorflow includes also a sigmoid
function:
https://www.tensorflow.org/versions/r1.2/api_docs/python/tf/sigmoid
import tensorflow as tf
sess = tf.InteractiveSession()
x = 0.458
y = tf.sigmoid(x)
u = y.eval()
print(u)
# 0.6125396
Country is a categorical variable and I want to see how many occurences of country exist in the data set. In other words, how many records/attendees are from each Country
barplot(summary(df$Country))
Rob's solution is very nice, only thing that in his -(void)adjustHeightOfTableview
method the calling of
[self.view needsUpdateConstraints]
does nothing, it just returns a flag, instead calling
[self.view setNeedsUpdateConstraints]
will make the desired effect.
You should goto the Layout folder and issue the following command:
F:\vs2017c>vs_community.exe /finalizeInstall
Then it will auto pickup cache components bypass downloading.
This could be leveraged to act like a "global variable", plus you can refer to the value from VBA and in a worksheet cell, and the assigned value will even persist after closing & re-opening the workbook!
To "declare" the name myVariable
and assign it a value of 123
:
ThisWorkbook.Names.Add "myVariable", 123
To retrieve the value (for example to display the value in a MsgBox
):
MsgBox [myVariable]
Alternatively, you could refer to the name with a string: (identical result as square brackets)
MsgBox Evaluate("myVariable")
To use the value on a worksheet just use it's name in your formula as-is:
=myVariable
In fact, you could even store function expressions: (sort of like in JavaScript)
(Admittedly, I can't actually think of a situation where this would be beneficial - but I don't use them in JS either.)
ThisWorkbook.Names.Add "myDay", "=if(isodd(day(today())),""on day"",""off day"")"
Square brackets are just a shortcut for the Evaluate method. I've heard that using them is considered messy or "hacky", but I've had no issues and their use in Excel is supported by Microsoft.
There is probably also a way use the Range
function to refer to these names, but I don't see any advantage so I didn't look very deeply into it.
Names.Add
method (Excel)Application.Evaluate
method (Excel)In my case, I didnt have the Apple Root certificate. It can be found here:
You can use
root.setBackgroundColor(0xFFFFFFFF);
or
root.setBackgroundColor(Color.parseColor("#ffffff"));
The following worked for me.
.back-ground {
background-image: url("../assets/background.png");
background-size: 100vw 100vh;
}
that worked to cover the entire background on different dimensions
Following Query works for me. Database Tabel t_sonde_results has domain d_date (datatype DATE) and d_time (datatype TIME) The intention is to query for last entry in t_sonde_results sorted by Date and Time
select * from
(select * from
(SELECT * FROM t_sonde_results
WHERE d_user_name = 'kenis' and d_smartbox_id = 6 order by d_time asc) AS tmp
order by d_date and d_time limit 1) as tmp1
Yarn supports this feature:
# .yarnrc file in project root
--modules-folder /node_modules
But your experience can vary depending on which packages you use. I'm not sure you'd want to go into that rabbit hole.
contents = open(filename).read()
You would think that simply authenticating a user in Active Directory would be a pretty simple process using LDAP in PHP without the need for a library. But there are a lot of things that can complicate it pretty fast:
It's actually easier in most cases to use a LDAP library supporting the above. I ultimately ended up rolling my own library which handles all the above points: LdapTools (Well, not just for authentication, it can do much more). It can be used like the following:
use LdapTools\Configuration;
use LdapTools\DomainConfiguration;
use LdapTools\LdapManager;
$domain = (new DomainConfiguration('example.com'))
->setUsername('username') # A separate AD service account used by your app
->setPassword('password')
->setServers(['dc1', 'dc2', 'dc3'])
->setUseTls(true);
$config = new Configuration($domain);
$ldap = new LdapManager($config);
if (!$ldap->authenticate($username, $password, $message)) {
echo "Error: $message";
} else {
// Do something...
}
The authenticate call above will:
There are other libraries to do this too (Such as Adldap2). However, I felt compelled enough to provide some additional information as the most up-voted answer is actually a security risk to rely on with no input validation done and not using TLS.
As a Python lover and Android programmer, I'm sad to say this is not a good way to go. There are two problems:
One problem is that there is a lot more than just a programming language to the Android development tools. A lot of the Android graphics involve XML files to configure the display, similar to HTML. The built-in java objects are integrated with this XML layout, and it's a lot easier than writing your code to go from logic to bitmap.
The other problem is that the G1 (and probably other Android devices for the near future) are not that fast. 200 MHz processors and RAM is very limited. Even in Java, you have to do a decent amount of rewriting-to-avoid-more-object-creation if you want to make your app perfectly smooth. Python is going to be too slow for a while still on mobile devices.
based on accepted answer
$output = some_function();
echo $output;
if it results array then use json_encode it will result json array which is supportable by javascript
$output = some_function();
echo json_encode($output);
If someone wants to stop execution after you echo some result use exit method of php. It will work like return keyword
$output = some_function();
echo $output;
exit;
%d
is for integers use %f
instead, it works for both float
and double
types:
double d = 1.2;
float f = 1.2f;
System.out.printf("%f %f",d,f); // prints 1.200000 1.200000
I have had a similar scenario where I needed to set the focus on a text box within a panel when the panel was shown. The panel was loaded on application startup, so I couldn't set the focus in the constructor. As the panel wasn't being loaded or being given focus on show, this meant that I had no event to fire the focus request from.
To solve this, I added a global method to my main that called a method in the panel that invoked requestFocusInWindow()
on the text area. I put the call to the global method in the button that showed the panel, after the call to show. This meant that the panel would be shown and then the text area assigned the focus after showing the panel. Hope that makes sense and helps!
Also, you can edit most of the auto-generated code by right clicking on the object in design view and selecting customize code, however I don't think that it allows you to edit panels.
$url='Your url'; // Specify your url
$data= array('parameterkey1'=>value,'parameterkey2'=>value); // Add parameters in key value
$ch = curl_init(); // Initialize cURL
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
public static void ClearLine(int lines = 1)
{
for (int i = 1; i <= lines; i++)
{
Console.SetCursorPosition(0, Console.CursorTop - 1);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, Console.CursorTop - 1);
}
}
If you do know the maximal length of a line, you can do
def getLastLine(fname, maxLineLength=80):
fp=file(fname, "rb")
fp.seek(-maxLineLength-1, 2) # 2 means "from the end of the file"
return fp.readlines()[-1]
This works on my windows machine. But I do not know what happens on other platforms if you open a text file in binary mode. The binary mode is needed if you want to use seek().
Add ID current
for active/current page:
<div class="menuBar">
<ul>
<li id="current"><a href="index.php">HOME</a></li>
<li><a href="two.php">PORTFOLIO</a></li>
<li><a href="three.php">ABOUT</a></li>
<li><a href="four.php">CONTACT</a></li>
<li><a href="five.php">SHOP</a></li>
</ul>
#current a { color: #ff0000; }
I think you can find it usefull
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-two-datasources
It shows how to define multiple datasources & assign one of them as primary.
Here is a rather full example, also contains distributes transactions - if you need it.
What you need is to create 2 configuration classes, separate the model/repository packages etc to make the config easy.
Also, in above example, it creates the data sources manually. You can avoid this using the method on spring doc, with @ConfigurationProperties annotation. Here is an example of this:
http://xantorohara.blogspot.com.tr/2013/11/spring-boot-jdbc-with-multiple.html
Hope these helps.
Dashes (-
) have no significance other than making the number more readable, so you might as well include them.
Since we never know where our website visitors are coming from, we need to make phone numbers callable from anywhere in the world. For this reason the +
sign is always necessary. The +
sign is automatically converted by your mobile carrier to your international dialing prefix, also known as "exit code". This code varies by region, country, and sometimes a single country can use multiple codes, depending on the carrier. Fortunately, when it is a local call, dialing it with the international format will still work.
Using your example number, when calling from China, people would need to dial:
00-1-555-555-1212
And from Russia, they would dial
810-1-555-555-1212
The +
sign solves this issue by allowing you to omit the international dialing prefix.
After the international dialing prefix comes the country code(pdf), followed by the geographic code (area code), finally the local phone number.
Therefore either of the last two of your examples would work, but my recommendation is to use this format for readability:
<a href="tel:+1-555-555-1212">+1-555-555-1212</a>
Note: For numbers that contain a trunk prefix different from the country code (e.g. if you write it locally with brackets around a 0
), you need to omit it because the number must be in international format.
if you are add jre and jkd path, remove jre install path, keep jdk path is work
You have to bind your event handlers to correct context (this
):
onChange={this.setAuthorState.bind(this)}