To compare strings with wildcards use
if [[ "$stringA" == *$stringB* ]]; then
# Do something here
else
# Do Something here
fi
One method I've found pretty useful for testing asynchronous methods is injecting an Executor
instance in the object-to-test's constructor. In production, the executor instance is configured to run asynchronously while in test it can be mocked to run synchronously.
So suppose I'm trying to test the asynchronous method Foo#doAsync(Callback c)
,
class Foo {
private final Executor executor;
public Foo(Executor executor) {
this.executor = executor;
}
public void doAsync(Callback c) {
executor.execute(new Runnable() {
@Override public void run() {
// Do stuff here
c.onComplete(data);
}
});
}
}
In production, I would construct Foo
with an Executors.newSingleThreadExecutor()
Executor instance while in test I would probably construct it with a synchronous executor that does the following --
class SynchronousExecutor implements Executor {
@Override public void execute(Runnable r) {
r.run();
}
}
Now my JUnit test of the asynchronous method is pretty clean --
@Test public void testDoAsync() {
Executor executor = new SynchronousExecutor();
Foo objectToTest = new Foo(executor);
Callback callback = mock(Callback.class);
objectToTest.doAsync(callback);
// Verify that Callback#onComplete was called using Mockito.
verify(callback).onComplete(any(Data.class));
// Assert that we got back the data that we expected.
assertEquals(expectedData, callback.getData());
}
You can use int casting which allows the base specification.
int(b, 2) # Convert a binary string to a decimal int.
flush()
will synchronize your database with the current state of object/objects held in the memory but it does not commit the transaction. So, if you get any exception after flush()
is called, then the transaction will be rolled back.
You can synchronize your database with small chunks of data using flush()
instead of committing a large data at once using commit()
and face the risk of getting an OutOfMemoryException
.
commit()
will make data stored in the database permanent. There is no way you can rollback your transaction once the commit()
succeeds.
Yes, you could append ;Connection Timeout=30
to your connection string and specify the value you wish.
The timeout value set in the Connection Timeout
property is a time expressed in seconds. If this property isn't set, the timeout value for the connection is the default value (15 seconds).
Moreover, setting the timeout value to 0
, you are specifying that your attempt to connect waits an infinite time. As described in the documentation, this is something that you shouldn't set in your connection string:
A value of 0 indicates no limit, and should be avoided in a ConnectionString because an attempt to connect waits indefinitely.
You can still use the Screen class from a WPF app. You just need to reference the System.Windows.Forms assembly from your application. Once you've done that, (and referenced System.Drawing for the example below):
Rectangle workingArea = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea;
...works just fine.
Have you considered setting your main window property WindowStartupLocation to CenterScreen?
I had this problem on Windows.
My problem was that my %GOPATH%
environment variable was set to
C:\Users\john\src\goworkspace
instead of
C:\Users\john\src\goworkspace\
Adding the missing trailing slash at the end fixed it for me.
android:gravity
can be used on a Layout to align its children.
android:layout_gravity
can be used on any view to align itself in its parent.
NOTE: If self or children is not centering as expected, check if width/height is
match_parent
and change to something else
d = {1:2, 3:4, 5:6, 7:8}
l = (1,5)
{key: d[key] for key in l}
With HTTP v1 API it is different
Example:
{
"message":{
"topic":"news",
"notification":{
"body":"Very good news",
"title":"Good news"
},
"android":{
"notification":{
"body":"Very good news",
"title":"Good news",
"sound":"default"
}
}
}
}
Since mysql_connect This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. by default xampp does not load it automatically
in your php.ini file you should uncomment
;; extension=php_mysql.dll
to
extension=php_mysql.dll
Then restart your apache you should be fine
There are many questions about REST auth patterns here on SO. These are the most relevant for your question:
Basically you need to choose between using API keys (least secure as the key may be discovered by an unauthorized user), an app key and token combo (medium), or a full OAuth implementation (most secure).
I've had good experience using the International Components for Unicode libraries - they're extremely powerful, and provide methods for conversion, locale support, date and time rendering, case mapping (which you don't seem to want), and collation, which includes case- and accent-insensitive comparison (and more). I've only used the C++ version of the libraries, but they appear to have a Java version as well.
Methods exist to perform normalized compares as referred to by @Coincoin, and can even account for locale - for example (and this a sorting example, not strictly equality), traditionally in Spanish (in Spain), the letter combination "ll" sorts between "l" and "m", so "lz" < "ll" < "ma".
In order to get the values of your parameters, you can use RouteData
.
More context would be nice. Why do you need to "extract" them in the first place? You should have an Action like:
public ActionResult Edit(int id, bool allowed) {}
Here is a modified JSBin with a working sample:
http://jsbin.com/sezamuja/1/edit
Here is what I did with filters in the input:
<input ng-model="(results.subjects | filter:{grade:'C'})[0].title">
Have a look at the documentation. You made the following mistakes.
Firstly, ps.executeQuery()
doesn't have any parameters. Instead you passed the SQL query into it.
Secondly, regarding the prepared statement, you have to use the ?
symbol if want to pass any parameters. And later bind it using
setXXX(index, value)
Here xxx stands for the data type.
For child-parent communication you should pass a function setting the state from parent to child, like this
class Parent extends React.Component {_x000D_
constructor(props) {_x000D_
super(props)_x000D_
_x000D_
this.handler = this.handler.bind(this)_x000D_
}_x000D_
_x000D_
handler() {_x000D_
this.setState({_x000D_
someVar: 'some value'_x000D_
})_x000D_
}_x000D_
_x000D_
render() {_x000D_
return <Child handler = {this.handler} />_x000D_
}_x000D_
}_x000D_
_x000D_
class Child extends React.Component {_x000D_
render() {_x000D_
return <Button onClick = {this.props.handler}/ >_x000D_
}_x000D_
}
_x000D_
This way the child can update the parent's state with the call of a function passed with props.
But you will have to rethink your components' structure, because as I understand components 5 and 3 are not related.
One possible solution is to wrap them in a higher level component which will contain the state of both component 1 and 3. This component will set the lower level state through props.
Send XML requests with the raw
data type, then set the Content-Type to text/xml
.
After creating a request, use the dropdown to change the request type to POST.
Open the Body tab and check the data type for raw.
Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)
Enter your raw XML data into the input field below
Click Send to submit your XML Request to the specified server.
In your template, you have access to all the variables that are members of the current $scope
. So, tobedone
should be $scope.tobedone
, and then you can display it with {{tobedone}}
, or [[tobedone]]
in your case.
I have several projects in a solution. For some of the projects, I previously added the references manually. When I used NuGet to update the WebAPI package, those references were not updated automatically.
I found out that I can either manually update those reference so they point to the v5 DLL inside the Packages folder of my solution or do the following.
If you use
<select [ngModel]="object">
<option *ngFor="let object of objects" [ngValue]="object">{{object.name}}</option>
</select>
You need to set the property object
in you components class to the item from objects
that you want to have pre-selected.
class MyComponent {
object;
objects = [{name: 'a'}, {name: 'b'}, {name: 'c'}];
constructor() {
this.object = this.objects[1];
}
}
This isn't exactly what you asked for but you can use the "hex" function in python:
>>> hex(15)
'0xf'
This vbscript/batch hybrid "append_sys_path.vbs" is not intuitive but works perfectly:
If CreateObject("WScript.Shell").Run("%ComSpec% /C ""NET FILE""", 0, True) <> 0 Then
CreateObject("Shell.Application").ShellExecute WScript.FullName, """" & WScript.ScriptFullName & """", , "runas", 5
WScript.Quit
End If
Set Shell = CreateObject("WScript.Shell")
Cmd = Shell.Exec("%ComSpec% /C ""REG QUERY ""HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"" /v Path | FINDSTR /I /C:""REG_SZ"" /C:""REG_EXPAND_SZ""""").StdOut.ReadAll
Cmd = """" & Trim(Replace(Mid(Cmd, InStr(1, Cmd, "_SZ", VBTextCompare) + 3), vbCrLf, ""))
If Right(Cmd, 1) <> ";" Then Cmd = Cmd & ";"
Cmd = "%ComSpec% /C ""REG ADD ""HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"" /v Path /t REG_EXPAND_SZ /d " & Replace(Cmd & "%SystemDrive%\Python27;%SystemDrive%\Python27\Scripts"" /f""", "%", """%""")
Shell.Run Cmd, 0, True
Advantages of this approach:
1) It doesn't truncate the system path environment at 1024 characters.
2) It doesn't concatenate the system and user path environment.
3) It's automatically run as administrator.
4) Preserve the percentages in the system path environment.
5) Supports spaces, parentheses and special characters.
6) Works on Windows 7 and above.
git branch -a
will list the branches in your local and not the branches in your remote.
And the error error: unable to delete 'remotes/origin/test': remote ref does not exist
means you don't have a branch in that name in your remote but the branch exists in your local.
You can use 'onclick' attribute like this :
<a ... href="javascript: onclick();" ...>...</a>
The below code this will help you
public class TextProperty {
private int heigt; //???????
private String []context = new String[1024]; //???????
/*
*@parameter wordNum
*
*/
public TextProperty(int wordNum ,InputStreamReader in) throws Exception {
int i=0;
BufferedReader br = new BufferedReader(in);
String s;
while((s=br.readLine())!=null){
if(s.length()>wordNum){
int k=0;
while(k+wordNum<=s.length()){
context[i++] = s.substring(k, k+wordNum);
k=k+wordNum;
}
context[i++] = s.substring(k,s.length());
}
else{
context[i++]=s;
}
}
this.heigt = i;
in.close();
br.close();
}
public int getHeigt() {
return heigt;
}
public String[] getContext() {
return context;
}
}
public class MainActivity extends AppCompatActivity {
private Button btn;
private ImageView iv;
private final int WORDNUM = 35; //?????? ???????
private final int WIDTH = 450; //???????
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.imageView);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int x=5,y=10;
try {
TextProperty tp = new TextProperty(WORDNUM, new InputStreamReader(getResources().getAssets().open("1.txt")));
Bitmap bitmap = Bitmap.createBitmap(WIDTH, 20*tp.getHeigt(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setTextAlign(Paint.Align.LEFT);
paint.setTextSize(20f);
String [] ss = tp.getContext();
for(int i=0;i<tp.getHeigt();i++){
canvas.drawText(ss[i], x, y, paint);
y=y+20;
}
canvas.save(Canvas.ALL_SAVE_FLAG);
canvas.restore();
String path = Environment.getExternalStorageDirectory() + "/image.png";
System.out.println(path);
FileOutputStream os = new FileOutputStream(new File(path));
bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
//Display the image on ImageView.
iv.setImageBitmap(bitmap);
iv.setBackgroundColor(Color.BLUE);
os.flush();
os.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}```
Very Simple these days..
string json = JsonConvert.SerializeObject(YourDataTable, Formatting.Indented);
Now Convert your Json to a DataTable:
YourDataTable = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));
Works for DataSets as well..
Use display: inline-block
, though you need to wrap it inside a DIV to keep it from actually displaying inline. Tested in Safari.
<style type="text/css">
.fieldset-auto-width {
display: inline-block;
}
</style>
<div>
<fieldset class="fieldset-auto-width">
<legend>Blah</legend>
...
</fieldset>
</div>
Try inheriting from ConfigurationSection. This blog post by Phil Haack has an example.
Confirmed, per the documentation for IConfigurationSectionHandler:
In .NET Framework version 2.0 and above, you must instead derive from the ConfigurationSection class to implement the related configuration section handler.
Here's a way to do it in Python 3:
"""Given an int32 number, print it in English."""
def int_to_en(num):
d = { 0 : 'zero', 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four', 5 : 'five',
6 : 'six', 7 : 'seven', 8 : 'eight', 9 : 'nine', 10 : 'ten',
11 : 'eleven', 12 : 'twelve', 13 : 'thirteen', 14 : 'fourteen',
15 : 'fifteen', 16 : 'sixteen', 17 : 'seventeen', 18 : 'eighteen',
19 : 'nineteen', 20 : 'twenty',
30 : 'thirty', 40 : 'forty', 50 : 'fifty', 60 : 'sixty',
70 : 'seventy', 80 : 'eighty', 90 : 'ninety' }
k = 1000
m = k * 1000
b = m * 1000
t = b * 1000
assert(0 <= num)
if (num < 20):
return d[num]
if (num < 100):
if num % 10 == 0: return d[num]
else: return d[num // 10 * 10] + '-' + d[num % 10]
if (num < k):
if num % 100 == 0: return d[num // 100] + ' hundred'
else: return d[num // 100] + ' hundred and ' + int_to_en(num % 100)
if (num < m):
if num % k == 0: return int_to_en(num // k) + ' thousand'
else: return int_to_en(num // k) + ' thousand, ' + int_to_en(num % k)
if (num < b):
if (num % m) == 0: return int_to_en(num // m) + ' million'
else: return int_to_en(num // m) + ' million, ' + int_to_en(num % m)
if (num < t):
if (num % b) == 0: return int_to_en(num // b) + ' billion'
else: return int_to_en(num // b) + ' billion, ' + int_to_en(num % b)
if (num % t == 0): return int_to_en(num // t) + ' trillion'
else: return int_to_en(num // t) + ' trillion, ' + int_to_en(num % t)
raise AssertionError('num is too large: %s' % str(num))
And the result is:
0 zero
3 three
10 ten
11 eleven
19 nineteen
20 twenty
23 twenty-three
34 thirty-four
56 fifty-six
80 eighty
97 ninety-seven
99 ninety-nine
100 one hundred
101 one hundred and one
110 one hundred and ten
117 one hundred and seventeen
120 one hundred and twenty
123 one hundred and twenty-three
172 one hundred and seventy-two
199 one hundred and ninety-nine
200 two hundred
201 two hundred and one
211 two hundred and eleven
223 two hundred and twenty-three
376 three hundred and seventy-six
767 seven hundred and sixty-seven
982 nine hundred and eighty-two
999 nine hundred and ninety-nine
1000 one thousand
1001 one thousand, one
1017 one thousand, seventeen
1023 one thousand, twenty-three
1088 one thousand, eighty-eight
1100 one thousand, one hundred
1109 one thousand, one hundred and nine
1139 one thousand, one hundred and thirty-nine
1239 one thousand, two hundred and thirty-nine
1433 one thousand, four hundred and thirty-three
2000 two thousand
2010 two thousand, ten
7891 seven thousand, eight hundred and ninety-one
89321 eighty-nine thousand, three hundred and twenty-one
999999 nine hundred and ninety-nine thousand, nine hundred and ninety-nine
1000000 one million
2000000 two million
2000000000 two billion
You might want to add name for the unique key as many times the default unique_key name by rails can be too long for which the DB can throw the error.
To add name for your index just use the name:
option.
The migration query might look something like this -
add_index :table_name, [:column_name_a, :column_name_b, ... :column_name_n], unique: true, name: 'my_custom_index_name'
More info - http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_index
This may not be an exact solution for your issue, but in my case, I tracked the files that Eclipse was polling against with SysInternals Procmon, and found that Eclipse was constantly polling a fairly large snapshot file for one of my projects. Removed that, and everything started up fine (albeit with the workspace in the state it was at the previous launch).
The file removed was:
<workspace>\.metadata\.plugins\org.eclipse.core.resources\.projects\<project>\.markers.snap
What you're asking about is multiple inheritance, and it's very problematic for a number of reasons. Multiple inheritance was specifically avoided in Java; the choice was made to support multiple interface implementation, instead, which is the appropriate workaround.
just try this..
you need to open the connection using connection.open()
on the SqlCommand.Connection
object before executing ExecuteNonQuery()
With Swift 5, UIButton
has a setTitleColor(_:for:)
method. setTitleColor(_:for:)
has the following declaration:
Sets the color of the title to use for the specified state.
func setTitleColor(_ color: UIColor?, for state: UIControlState)
The following Playground sample code show how to create a UIbutton
in a UIViewController
and change it's title color using setTitleColor(_:for:)
:
import UIKit
import PlaygroundSupport
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
// Create button
let button = UIButton(type: UIButton.ButtonType.system)
// Set button's attributes
button.setTitle("Print 0", for: UIControl.State.normal)
button.setTitleColor(UIColor.orange, for: UIControl.State.normal)
// Set button's frame
button.frame.origin = CGPoint(x: 100, y: 100)
button.sizeToFit()
// Add action to button
button.addTarget(self, action: #selector(printZero(_:)), for: UIControl.Event.touchUpInside)
// Add button to subView
view.addSubview(button)
}
@objc func printZero(_ sender: UIButton) {
print("0")
}
}
let controller = ViewController()
PlaygroundPage.current.liveView = controller
After this question was asked, Facebook launched HipHop for PHP which is probably the best-tested PHP compiler to date (seeing as it ran one of the world’s 10 biggest websites). However, Facebook discontinued it in favour of HHVM, which is a virtual machine, not a compiler.
Beyond that, googling PHP compiler
turns up a number of 3rd party solutions.
bcompiler_write_exe_footer()
manual)You can still use <hr>
as a horizontal line, and you probably should. In HTML5 it defines a thematic break in content, without making any promises about how it is displayed. The attributes that aren't supported in the HTML5 spec are all related to the tag's appearance. The appearance should be set in CSS, not in the HTML itself.
So use the <hr>
tag without attributes, then style it in CSS to appear the way you want.
Particularly when using something like Twitter's Bootstrap, white-space: nowrap;
doesn't always work in CSS when applying padding or margin to a child div
. Instead however, adding an equivalent border: 20px solid transparent;
style in place of padding/margin works more consistently.
Use the backslash before db on the header and you can use it then typically as you wrote it before.
Here is the example:
Use \DB;
Then inside your controller class you can use as you did before, like that ie :
$item = DB::table('items')->get();
datepicker in Finnish (Käännös suomeksi)
$.datepicker.regional['fi'] = {
closeText: "Valmis", // Display text for close link
prevText: "Edel", // Display text for previous month link
nextText: "Seur", // Display text for next month link
currentText: "Tänään", // Display text for current month link
monthNames: [ "Tammikuu","Helmikuu","Maaliskuu","Huhtikuu","Toukokuu","Kesäkuu",
"Heinäkuu","Elokuu","Syyskuu","Lokakuu","Marraskuu","Joulukuu" ], // Names of months for drop-down and formatting
monthNamesShort: [ "Tam", "Hel", "Maa", "Huh", "Tou", "Kes", "Hei", "Elo", "Syy", "Lok", "Mar", "Jou" ], // For formatting
dayNames: [ "Sunnuntai", "Maanantai", "Tiistai", "Keskiviikko", "Torstai", "Perjantai", "Lauantai" ], // For formatting
dayNamesShort: [ "Sun", "Maa", "Tii", "Kes", "Tor", "Per", "Lau" ], // For formatting
dayNamesMin: [ "Su","Ma","Ti","Ke","To","Pe","La" ], // Column headings for days starting at Sunday
weekHeader: "Vk", // Column header for week of the year
dateFormat: "mm/dd/yy", // See format options on parseDate
firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
isRTL: false, // True if right-to-left language, false if left-to-right
showMonthAfterYear: false, // True if the year select precedes month, false for month then year
yearSuffix: "" // Additional text to append to the year in the month headers
};
You can not add an element to an array, since arrays, in Java, are fixed-length. However, you could build a new array from the existing one using Arrays.copyOf(array, size)
:
public static void main(String[] args) {
int[] array = new int[] {1, 2, 3};
System.out.println(Arrays.toString(array));
array = Arrays.copyOf(array, array.length + 1); //create new array from old array and allocate one more element
array[array.length - 1] = 4;
System.out.println(Arrays.toString(array));
}
I would still recommend to drop working with an array and use a List
.
Let us see the difference between the two HTTP authentication using Wireshark
(Tool to analyse packets sent or received) .
1. Http Basic Authentication
As soon as the client types in the correct username:password,as requested by the Web-server, the Web-Server checks in the Database if the credentials are correct and gives the access to the resource .
Here is how the packets are sent and received :
In the first packet the Client fill the credentials using the POST method at the resource - lab/webapp/basicauth
.In return the server replies back with http response code 200 ok ,i.e, the username:password were correct .
Now , In the Authorization
header it shows that it is Basic Authorization followed by some random string .This String is the encoded (Base64) version of the credentials admin:aadd
(including colon ) .
2 . Http Digest Authentication(rfc 2069)
So far we have seen that the Basic Authentication sends username:password in plaintext over the network .But the Digest Auth sends a HASH of the Password using Hash algorithm.
Here are packets showing the requests made by the client and response from the server .
As soon as the client types the credentials requested by the server , the Password is converted to a response
using an algorithm and then is sent to the server , If the server Database has same response as given by the client the server gives the access to the resource , otherwise a 401 error .
In the above Authorization
, the response
string is calculated using the values of Username
,Realm
,Password
,http-method
,URI
and Nonce
as shown in the image :
Hence , we can see that the Digest Authentication is more Secure as it involve Hashing (MD5 encryption) , So the packet sniffer tools cannot sniff the Password although in Basic Auth the exact Password was shown on Wireshark.
You can use:
cout << "size of datatype = " << sizeof(datatype) << endl;
datatype = int
, long int
etc.
You will be able to see the size for whichever datatype you type.
Why the map
/lambda
magic? Doesn't this work?
>>> foo = ['a', 'b', 'c']
>>> print(','.join(foo))
a,b,c
>>> print(','.join([]))
>>> print(','.join(['a']))
a
In case if there are numbers in the list, you could use list comprehension:
>>> ','.join([str(x) for x in foo])
or a generator expression:
>>> ','.join(str(x) for x in foo)
Try this
a = int(input("Enter Limit"))
val = []
for z in range(0,a):
b = int(input("Enter Number in List"))
val.append(b)
for y in range(0,len(val)):
for x in range(0,len(val)-1):
if val[x]>val[x+1]:
t = val[x]
val[x] = val[x+1]
val[x+1] = t
print(val)
FacebookConnect or OpenID are two great options.
Basically, your users login to other sites they are already members of (Facebook, or Google), and then you get confirmation from that site telling you the user is trustworthy - start a session, and they're logged in. No database needed (unless you want to associate more data to their account).
Sometimes we know in advance that the value stored in a given integer variable will always be positive-when it is being used to only count things, for example. In such a case we can declare the variable to be unsigned, as in, unsigned int num student;
. With such a declaration, the range of permissible integer values (for a 32-bit compiler) will shift from the range -2147483648 to +2147483647 to range 0 to 4294967295. Thus, declaring an integer as unsigned almost doubles the size of the largest possible value that it can otherwise hold.
You need to escape backslash with a \
$str = str_replace ("\\", "/", $str);
You don't need to go level up and use ..
since all buttons are on the same level:
//button[contains(.,'Arcade Reader')]/preceding-sibling::button[@name='settings']
Only View File Adjust like this. You may try this.
@Html.FormatValue( (object)Convert.ChangeType(item.transdate, typeof(object)),
"{0: yyyy-MM-dd}")
item.transdate
it is your DateTime
type data.
Setting the icon
property when creating the BrowserWindow
only has an effect on Windows and Linux.
To set the icon on OS X, you can use electron-packager and set the icon using the --icon
switch.
It will need to be in .icns format for OS X. There is an online icon converter which can create this file from your .png.
Here I have written a few steps for How to Get RegID and Notification starting from scratch
You can find a complete tutorial here:
Code snippet to get Registration ID (Device Token for Push Notification).
Configure project for GCM
To enable GCM in our project we need to add a few permissions to our manifest file. Go to AndroidManifest.xml
and add this code:
Add Permissions
<uses-permission android:name="android.permission.INTERNET”/>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name=“.permission.RECEIVE" />
<uses-permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE" />
<permission android:name=“<your_package_name_here>.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
Add GCM Broadcast Receiver declaration in your application tag:
<application
<receiver
android:name=".GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" ]]>
<intent-filter]]>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="" />
</intent-filter]]>
</receiver]]>
<application/>
Add GCM Service declaration
<application
<service android:name=".GcmIntentService" />
<application/>
Now Go to your Launch/Splash Activity
Add Constants and Class Variables
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static String TAG = "LaunchActivity";
protected String SENDER_ID = "Your_sender_id";
private GoogleCloudMessaging gcm =null;
private String regid = null;
private Context context= null;
Update OnCreate and OnResume methods
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launch);
context = getApplicationContext();
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (regid.isEmpty()) {
registerInBackground();
} else {
Log.d(TAG, "No valid Google Play Services APK found.");
}
}
}
@Override
protected void onResume() {
super.onResume();
checkPlayServices();
}
// # Implement GCM Required methods(Add below methods in LaunchActivity)
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.d(TAG, "This device is not supported - Google Play Services.");
finish();
}
return false;
}
return true;
}
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.d(TAG, "Registration ID not found.");
return "";
}
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.d(TAG, "App version changed.");
return "";
}
return registrationId;
}
private SharedPreferences getGCMPreferences(Context context) {
return getSharedPreferences(LaunchActivity.class.getSimpleName(),
Context.MODE_PRIVATE);
}
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
throw new RuntimeException("Could not get package name: " + e);
}
}
private void registerInBackground() {
new AsyncTask() {
@Override
protected Object doInBackground(Object...params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
Log.d(TAG, "########################################");
Log.d(TAG, "Current Device's Registration ID is: " + msg);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return null;
}
protected void onPostExecute(Object result) {
//to do here
};
}.execute(null, null, null);
}
Note : please store REGISTRATION_KEY
, it is important for sending PN Message to GCM. Also keep in mind: this key will be unique for all devices and GCM will send Push Notifications by REGISTRATION_KEY
only.
Minimal runnable multi-file scope example
Here I illustrate how static
affects the scope of function definitions across multiple files.
a.c
#include <stdio.h>
/* Undefined behavior: already defined in main.
* Binutils 2.24 gives an error and refuses to link.
* https://stackoverflow.com/questions/27667277/why-does-borland-compile-with-multiple-definitions-of-same-object-in-different-c
*/
/*void f() { puts("a f"); }*/
/* OK: only declared, not defined. Will use the one in main. */
void f(void);
/* OK: only visible to this file. */
static void sf() { puts("a sf"); }
void a() {
f();
sf();
}
main.c
#include <stdio.h>
void a(void);
void f() { puts("main f"); }
static void sf() { puts("main sf"); }
void m() {
f();
sf();
}
int main() {
m();
a();
return 0;
}
Compile and run:
gcc -c a.c -o a.o
gcc -c main.c -o main.o
gcc -o main main.o a.o
./main
Output:
main f
main sf
main f
a sf
Interpretation
sf
, one for each filef
As usual, the smaller the scope, the better, so always declare functions static
if you can.
In C programming, files are often used to represent "classes", and static
functions represent "private" methods of the class.
A common C pattern is to pass a this
struct around as the first "method" argument, which is basically what C++ does under the hood.
What standards say about it
C99 N1256 draft 6.7.1 "Storage-class specifiers" says that static
is a "storage-class specifier".
6.2.2/3 "Linkages of identifiers" says static
implies internal linkage
:
If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage.
and 6.2.2/2 says that internal linkage
behaves like in our example:
In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function.
where "translation unit" is a source file after preprocessing.
How GCC implements it for ELF (Linux)?
With the STB_LOCAL
binding.
If we compile:
int f() { return 0; }
static int sf() { return 0; }
and disassemble the symbol table with:
readelf -s main.o
the output contains:
Num: Value Size Type Bind Vis Ndx Name
5: 000000000000000b 11 FUNC LOCAL DEFAULT 1 sf
9: 0000000000000000 11 FUNC GLOBAL DEFAULT 1 f
so the binding is the only significant difference between them. Value
is just their offset into the .bss
section, so we expect it to differ.
STB_LOCAL
is documented on the ELF spec at http://www.sco.com/developers/gabi/2003-12-17/ch4.symtab.html:
STB_LOCAL Local symbols are not visible outside the object file containing their definition. Local symbols of the same name may exist in multiple files without interfering with each other
which makes it a perfect choice to represent static
.
Functions without static are STB_GLOBAL
, and the spec says:
When the link editor combines several relocatable object files, it does not allow multiple definitions of STB_GLOBAL symbols with the same name.
which is coherent with the link errors on multiple non static definitions.
If we crank up the optimization with -O3
, the sf
symbol is removed entirely from the symbol table: it cannot be used from outside anyways. TODO why keep static functions on the symbol table at all when there is no optimization? Can they be used for anything?
See also
extern
is the opposite of static
, and functions are already extern
by default: How do I use extern to share variables between source files?C++ anonymous namespaces
In C++, you might want to use anonymous namespaces instead of static, which achieves a similar effect, but further hides type definitions: Unnamed/anonymous namespaces vs. static functions
Using Vue 1.x, use the special variable $index
like so:
<li v-for="catalog in catalogs">this index : {{$index + 1}}</li>
alternatively, you can specify an alias as a first argument for v-for
directive like so:
<li v-for="(itemObjKey, catalog) in catalogs">
this index : {{itemObjKey + 1}}
</li>
See : Vue 1.x guide
Using Vue 2.x, v-for
provides a second optional argument referencing the index of the current item, you can add 1 to it in your mustache template as seen before:
<li v-for="(catalog, itemObjKey) in catalogs">
this index : {{itemObjKey + 1}}
</li>
See: Vue 2.x guide
Eliminating the parentheses in the v-for
syntax also works fine hence:
<li v-for="catalog, itemObjKey in catalogs">
this index : {{itemObjKey + 1}}
</li>
Hope that helps.
If it's a direct child you can do as below if it could be nested deeper remove the >
$("#text-field").keydown(function(event) {
if($('#popup>p.filled-text').length !== 0) {
console.log("Found");
}
});
Here is the answer to your question
SELECT c.name AS ColumnName, t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%myName%';
Adapting from https://stackoverflow.com/a/49428678/1527469 (to add indexes):
System.out.print(" ");
for (int row = 0; row < array[0].length; row++) {
System.out.print("\t" + row );
}
System.out.println();
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length; col++) {
if (col < 1) {
System.out.print(row);
System.out.print("\t" + array[row][col]);
} else {
System.out.print("\t" + array[row][col]);
}
}
System.out.println();
}
Another option would be use a dictionary instead of an array:
Dim oNames As Object
Set oNames = CreateObject("Scripting.Dictionary")
'You could if need be create this automatically from an existing Array
'The 1 is just a dummy value, we just want the names as keys
oNames.Add "JOHN", 1
oNames.Add "BOB", 1
oNames.Add "JAMES", 1
oNames.Add "PHILIP", 1
As this would then get you a one-liner of
oNames.Exists("JOHN")
The advantage a dictionary provides is exact matching over partial matching from Filter
. Say if you have the original list of names in an Array, but were looking for "JO" or "PHIL" who were actually two new people in addition to the four we started with. In this case, Filter(oNAMES, "JO")
will match "JOHN" which may not be desired. With a dictionary, it won't.
Please see this link for more information on setting the text size in code. Basically it says:
public void setTextSize (int unit, float size)
Since: API Level 1 Set the default text size to a given unit and value. See TypedValue for the possible dimension units. Related XML Attributes
android:textSize Parameters
unit The desired dimension unit.
size The desired size in the given units.
See my answer to this question: Detect support for background-attachment: fixed?
Have facing same problem and found the solution by doing this, using SSMS 2014
- Just select the Option Overwrite the existing database(WITH REPLACE)
I agree with pez and some here.
It seems obvious to me that "new" is self descriptive object creation, where the YUI pattern Greg Dean describes is completely obscured.
The possibility someone could write var bar = foo;
or var bar = baz();
where baz isn't an object creating method seems far more dangerous.
You have a JSON object of the exception thrown, in the xhr object. Just use
alert(xhr.responseJSON.Message);
The JSON object expose two other properties: 'ExceptionType' and 'StackTrace'
SQL Plus will format the columns to hold the maximum possible value, which in this case is 255 characters.
To confirm that your output does not actually contain those extra spaces, try this:
SELECT
'/' || TRIM(A) || '/' AS COLUMN_A
,'/' || TRIM(B) || '/' AS COLUMN_B
FROM
MY_TABLE;
If the '/' characters are separated from your output, then that indicates that it's not spaces, but some other whitespace character that got in there (tabs, for example). If that is the case, then it is probably an input validation issue somewhere in your application.
However, the most likely scenario is that the '/' characters will in fact touch the rest of your strings, thus proving that the whitespace is actually trimmed.
If you wish to output them together, then the answer given by Quassnoi should do it.
If it is purely a display issue, then the answer given by Tony Andrews should work fine.
Another option I would recommend is to create a separate application that is stateless that would take the large file. On your main app open a new window or iframe that will accept the file and send it through that window then hide the window or iframe once the upload has started using Javascript.
I don't think this is possible with AD. The distinguishedName attribute is the only thing I know of that contains the OU piece on which you're trying to search, so you'd need a wildcard to get results for objects under those OUs. Unfortunately, the wildcard character isn't supported on DNs.
If at all possible, I'd really look at doing this in 2 queries using OU=Staff... and OU=Vendors... as the base DNs.
Assuming you are calling activity two from activity one using an Intent.
You can pass the data with the intent.putExtra(),
Take this for your reference. Sending arrays with Intent.putExtra
Hope that's what you want.
The most concise and intuitive way would be:
var selectElement = document.getElementById('ageselect');_x000D_
_x000D_
for (var age = 12; age <= 100; age++) {_x000D_
selectElement.add(new Option(age));_x000D_
}
_x000D_
Your age: <select id="ageselect"><option value="">Please select</option></select>
_x000D_
You can also differentiate the name and the value or add items at the start of the list with additional parameters to the used functions:
HTMLSelect?Element?.add(item[, before]);
new Option(text, value, defaultSelected, selected);
One way using angular service:
var app = angular.module("home", []);
app.controller('one', function($scope, ser1){
$scope.inputText = ser1;
});
app.controller('two',function($scope, ser1){
$scope.inputTextTwo = ser1;
});
app.factory('ser1', function(){
return {o: ''};
});
<div ng-app='home'>
<div ng-controller='one'>
Type in text:
<input type='text' ng-model="inputText.o"/>
</div>
<br />
<div ng-controller='two'>
Type in text:
<input type='text' ng-model="inputTextTwo.o"/>
</div>
</div>
Thanks to @EdChum I was struggling with same problem especially when indexes do not match. Unfortunatly in pandas guide this case is missed (when you for example delete some rows)
import pandas as pd
t=pd.DataFrame()
t['a']=[1,2,3,4]
t=t.loc[t['a']>1] #now index starts from 1
u=pd.DataFrame()
u['b']=[1,2,3] #index starts from 0
#option 1
#keep index of t
u.index = t.index
#option 2
#index of t starts from 0
t.reset_index(drop=True, inplace=True)
#now concat will keep number of rows
r=pd.concat([t,u], axis=1)
As David and Remou pointed out, vbCrLf
if you want a carriage-return-linefeed combination. Otherwise, Chr(13)
and Chr(10)
(although some VB-derivatives have vbCr
and vbLf
; VBScript may well have those, worth checking before using Chr
).
Here is a very slight improvement to user1387483's answer using an immediate function:
(function() {
$("*").on( 'touchstart', function() {
$(this).trigger('hover') ;
} ).on('touchend', function() {
$(this).trigger('hover') ;
} ) ;
})() ;
Also, I agree with Boz that this appears to be the "neatest, most compliant solution".
This is for Mac users:
first of all you have to clarify where the class file is... so for example, in 'Terminal' (A Mac Application) you would type:
cd
then wherever you file is e.g:
cd /Users/CollarBlast/Desktop/JavaFiles/
then you would hit enter. After that you would do the command. e.g:
cd /Users/CollarBlast/Desktop/JavaFiles/
(then i would press enter...)
Then i would type the command:
javap -c JavaTestClassFile.class
(then i would press enter again...)
and hopefully it should work!
or you could just write the power function, with recursion as a added bonus
int power(int x, int y){
if(y == 0)
return 1;
return (x * power(x,y-1) );
}
yes,yes i know this is less effecient space and time complexity but recursion is just more fun!!
Hmm, I would suggest that you use Flyweight to implement the states. Purpose: Avoid the memory overhead of a large number of small objects. State machines can get very, very big.
http://en.wikipedia.org/wiki/Flyweight_pattern
I'm not sure that I see the need to use design pattern State to implement the nodes. The nodes in a state machine are stateless. They just match the current input symbol to the available transitions from the current state. That is, unless I have entirely forgotten how they work (which is a definite possiblilty).
If I were coding it, I would do something like this:
interface FsmNode {
public boolean canConsume(Symbol sym);
public FsmNode consume(Symbol sym);
// Other methods here to identify the state we are in
}
List<Symbol> input = getSymbols();
FsmNode current = getStartState();
for (final Symbol sym : input) {
if (!current.canConsume(sym)) {
throw new RuntimeException("FSM node " + current + " can't consume symbol " + sym);
}
current = current.consume(sym);
}
System.out.println("FSM consumed all input, end state is " + current);
What would Flyweight do in this case? Well, underneath the FsmNode there would probably be something like this:
Map<Integer, Map<Symbol, Integer>> fsm; // A state is an Integer, the transitions are from symbol to state number
FsmState makeState(int stateNum) {
return new FsmState() {
public FsmState consume(final Symbol sym) {
final Map<Symbol, Integer> transitions = fsm.get(stateNum);
if (transisions == null) {
throw new RuntimeException("Illegal state number " + stateNum);
}
final Integer nextState = transitions.get(sym); // May be null if no transition
return nextState;
}
public boolean canConsume(final Symbol sym) {
return consume(sym) != null;
}
}
}
This creates the State objects on a need-to-use basis, It allows you to use a much more efficient underlying mechanism to store the actual state machine. The one I use here (Map(Integer, Map(Symbol, Integer))) is not particulary efficient.
Note that the Wikipedia page focuses on the cases where many somewhat similar objects share the similar data, as is the case in the String implementation in Java. In my opinion, Flyweight is a tad more general, and covers any on-demand creation of objects with a short life span (use more CPU to save on a more efficient underlying data structure).
export class Car {
id: number;
make: string;
model: string;
color: string;
year: Date;
constructor(car) {
{
this.id = car.id;
this.make = car.make || '';
this.model = car.model || '';
this.color = car.color || '';
this.year = new Date(car.year).getYear();
}
}
}
The || can become super useful for very complex data objects to default data that doesn't exist.
. .
In your component.ts or service.ts file you can deserialize response data into the model:
// Import the car model
import { Car } from './car.model.ts';
// If single object
car = new Car(someObject);
// If array of cars
cars = someDataToDeserialize.map(c => new Car(c));
Googling gives me this:
Command A & Command B
Execute Command A, then execute Command B (no evaluation of anything)
Command A | Command B
Execute Command A, and redirect all its output into the input of Command B
Command A && Command B
Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B
Command A || Command B
Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B
Although this question is pretty old and it has already a-lot answers, I think it is worth to provide an alternative. Using native java classes makes it very verbose to just use pem files and almost forces you wanting to convert the pem files into p12 or jks files as using p12 or jks files are much easier. I want to give anyone who wants an alternative for the already provided answers.
var keyManager = PemUtils.loadIdentityMaterial("certificate-chain.pem", "private-key.pem");
var trustManager = PemUtils.loadTrustMaterial("some-trusted-certificate.pem");
var sslFactory = SSLFactory.builder()
.withIdentityMaterial(keyManager)
.withTrustMaterial(trustManager)
.build();
var sslContext = sslFactory.getSslContext();
I need to provide some disclaimer here, I am the library maintainer
You could be using the 32 bit version, so you should prob try at the command line from the Framework (not Framework64) folder.
IE Did you try it from C:\Windows\Microsoft.NET\Framework\v4.0.30319 rather than the 64 version? If you ref 32 bit libs you can be forced to 32 bit version (some other reasons as well if I recall)
Is your site a child of another site in IIS?
For more details on this (since it applies to various types of apps running on .NET) see Scott's post at:
32-bit and 64-bit confusion around x86 and x64 and the .NET Framework and CLR
Check Enable Live Templates and leave the cursor at the position desired and click Apply then OK
You got an extra }
to many as seen below:
var nav = document.getElementsByClassName('nav-coll');
for (var i = 0; i < button.length; i++) {
nav[i].addEventListener('click',function(){
console.log('haha');
} // <-- REMOVE THIS :)
}, false);
};
A very good tool for those things is jsFiddle. I have created a fiddle with your invalid code and when clicking the TidyUp
button it formats your code which makes it clearer if there are any possible mistakes with missing braces.
DEMO - Your code in a fiddle, have a play :)
These two terms differentiate between two different ways of walking a tree.
It is probably easiest just to exhibit the difference. Consider the tree:
A
/ \
B C
/ / \
D E F
A depth first traversal would visit the nodes in this order
A, B, D, C, E, F
Notice that you go all the way down one leg before moving on.
A breadth first traversal would visit the node in this order
A, B, C, D, E, F
Here we work all the way across each level before going down.
(Note that there is some ambiguity in the traversal orders, and I've cheated to maintain the "reading" order at each level of the tree. In either case I could get to B before or after C, and likewise I could get to E before or after F. This may or may not matter, depends on you application...)
Both kinds of traversal can be achieved with the pseudocode:
Store the root node in Container
While (there are nodes in Container)
N = Get the "next" node from Container
Store all the children of N in Container
Do some work on N
The difference between the two traversal orders lies in the choice of Container
.
The recursive implementation looks like
ProcessNode(Node)
Work on the payload Node
Foreach child of Node
ProcessNode(child)
/* Alternate time to work on the payload Node (see below) */
The recursion ends when you reach a node that has no children, so it is guaranteed to end for finite, acyclic graphs.
At this point, I've still cheated a little. With a little cleverness you can also work-on the nodes in this order:
D, B, E, F, C, A
which is a variation of depth-first, where I don't do the work at each node until I'm walking back up the tree. I have however visited the higher nodes on the way down to find their children.
This traversal is fairly natural in the recursive implementation (use the "Alternate time" line above instead of the first "Work" line), and not too hard if you use a explicit stack, but I'll leave it as an exercise.
You can setup SSH key authorization like described here - https://confluence.atlassian.com/bitbucket/add-an-ssh-key-to-an-account-302811853.html.
Use the below css
input[type="submit"] {_x000D_
font-size: 20px;_x000D_
background: pink;_x000D_
border: none;_x000D_
padding: 10px 20px;_x000D_
}_x000D_
.flat-btn {_x000D_
-webkit-appearance: none;_x000D_
-moz-appearance: none;_x000D_
appearance: none;_x000D_
border-radius: 0;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
margin: 25px 0 10px;_x000D_
font-size: 20px;_x000D_
}
_x000D_
<h2>iOS Styled Button!</h2>_x000D_
<input type="submit" value="iOS Styled Button!" />_x000D_
_x000D_
<h2>No More Style! Button!</h2>_x000D_
<input class="flat-btn" type="submit" value="No More Style! Button!" />
_x000D_
Often I get the error "logcat read: Invalid argument
". I had to clear the log, before reading from the log.
I do like this:
prompt> cd ~/Desktop
prompt> adb logcat -c
prompt> adb logcat | tee log.txt
Cascading Style Sheet are designed for inheritance. Inheritance is intrinsic to their existence. If it wasn't built to be cascading, they would only be called "Style Sheets".
That said, if an inherited style doesn't fit your needs, you'll have to override it with another style closer to the object. Forget about the notion of "blocking inheritance".
You can also choose the more granular solution by giving styles to every individual objects, and not giving styles to the general tags like div, p, pre, etc.
For example, you can use styles that start with # for objects with a specific ID:
<style>
#dividstyle{
font-family:MS Trebuchet;
}
</style>
<div id="dividstyle">Hello world</div>
You can define classes for objects:
<style>
.divclassstyle{
font-family: Calibri;
}
</style>
<div class="divclassstyle">Hello world</div>
Hope it helps.
The permanent space is where the classes, methods, internalized strings, and similar objects used by the VM are stored and never deallocated (hence the name).
This Oracle article succinctly presents the working and parameterization of the HotSpot GC and advises you to augment this space if you load many classes (this is typically the case for application servers and some IDE like Eclipse) :
The permanent generation does not have a noticeable impact on garbage collector performance for most applications. However, some applications dynamically generate and load many classes; for example, some implementations of JavaServer Pages (JSP) pages. These applications may need a larger permanent generation to hold the additional classes. If so, the maximum permanent generation size can be increased with the command-line option -XX:MaxPermSize=.
Note that this other Oracle documentation lists the other HotSpot arguments.
Update : Starting with Java 8, both the permgen space and this setting are gone. The memory model used for loaded classes and methods is different and isn't limited (with default settings). You should not see this error any more.
I was looking through all these options and started to wonder about their relative features and performances, so I did some tests. In case anyone else are curious about the same, I'm sharing my results here.
Not wanting to bother about all the functions posted here, I chose to focus on a sample based on a few criteria: the function should work on both character, factor, logical and numeric vectors, it should deal with NAs and other problematic values appropriately, and output should be 'sensible', i.e. no numerics as character or other such silliness.
I also added a function of my own, which is based on the same rle
idea as chrispy's, except adapted for more general use:
library(magrittr)
Aksel <- function(x, freq=FALSE) {
z <- 2
if (freq) z <- 1:2
run <- x %>% as.vector %>% sort %>% rle %>% unclass %>% data.frame
colnames(run) <- c("freq", "value")
run[which(run$freq==max(run$freq)), z] %>% as.vector
}
set.seed(2)
F <- sample(c("yes", "no", "maybe", NA), 10, replace=TRUE) %>% factor
Aksel(F)
# [1] maybe yes
C <- sample(c("Steve", "Jane", "Jonas", "Petra"), 20, replace=TRUE)
Aksel(C, freq=TRUE)
# freq value
# 7 Steve
I ended up running five functions, on two sets of test data, through microbenchmark
. The function names refer to their respective authors:
Chris' function was set to method="modes"
and na.rm=TRUE
by default to make it more comparable, but other than that the functions were used as presented here by their authors.
In matter of speed alone Kens version wins handily, but it is also the only one of these that will only report one mode, no matter how many there really are. As is often the case, there's a trade-off between speed and versatility. In method="mode"
, Chris' version will return a value iff there is one mode, else NA. I think that's a nice touch.
I also think it's interesting how some of the functions are affected by an increased number of unique values, while others aren't nearly as much. I haven't studied the code in detail to figure out why that is, apart from eliminating logical/numeric as a the cause.
I was having the same issue, but with Glide. When I was going to disconnect from wifi and reconnect (just like it was suggested here), I noticed that I was in Airplane mode ???
Much has changed since this question was asked. Visual Studio 2013 with update 4 and Visual Studio 2015 now have integrated tools for Apache Cordova and you can run them on a Visual Studio emulator for Android.
Here are two methods to get more than 1 column in a scalar subquery (or inline subquery) and querying the lookup table only once. This is a bit convoluted but can be the very efficient in some special cases.
You can use concatenation to get several columns at once:
SELECT x,
regexp_substr(yz, '[^^]+', 1, 1) y,
regexp_substr(yz, '[^^]+', 1, 2) z
FROM (SELECT a.x,
(SELECT b.y || '^' || b.z yz
FROM b
WHERE b.v = a.v)
yz
FROM a)
You would need to make sure that no column in the list contain the separator character.
You could also use SQL objects:
CREATE OR REPLACE TYPE b_obj AS OBJECT (y number, z number);
SELECT x,
v.yz.y y,
v.yz.z z
FROM (SELECT a.x,
(SELECT b_obj(y, z) yz
FROM b
WHERE b.v = a.v)
yz
FROM a) v
You can also specify the date format like stated earlier: https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html
import 'package:intl/intl.dart';
String formatDate(DateTime date) => new DateFormat("MMMM d").format(date);
Produces: March 4
Try clearing your .subversion
folder in your home directory and try to commit again. It should prompt you for your password and then ask you if you would like to save the password.
I prefer the oneliner:
print(sorted(df['Column Name'].unique()))
One way to format it is:
printf("%lld.%.9ld", (long long)ts.tv_sec, ts.tv_nsec);
It works, this is a problem with the tool used: normalized CSS by jsFiddle is causing the problem by hiding you the default of browsers...
See http://jsfiddle.net/XvdX9/5/
EDIT:
normalize.css stylesheet from jsFiddle adds the instruction border-collapse: collapse
to all tables and it renders them completely differently in CSS2.1:
Differences between the 2 models can be seen in this other fiddle: http://jsfiddle.net/XvdX9/11/ (with some transparencies on cells and an enormous border-radius on the top-left one, in order to see what happens on table vs its cells)
In the same CSS2.1 page about HTML tables, there are also explanations about what browsers should/could do with empty-cells in the separated borders model, the difference between border-style: none
and border-style: hidden
in the collapsing borders model, how width is calculated and which border should display if both table, row and cell elements define 3 different styles on the same border.
After your DataBind()
:
lstDepartment.SelectedIndex = 0; //first item
or
lstDepartment.SelectedValue = "Yourvalue"
or
//add error checking, just an example, FindByValue may return null
lstDepartment.Items.FindByValue("Yourvalue").Selected = true;
or
//add error checking, just an example, FindByText may return null
lstDepartment.Items.FindByText("Yourvalue").Selected = true;
run the below code in Terminal
makesure You are inside your project folder in terminal
ng g s servicename --module=app.module
Info on MySQL's full text search. This is restricted to MyISAM tables, so may not be suitable if you wantto use a different table type.
http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
Even if WHERE textcolumn LIKE "%SUBSTRING%"
is going to be slow, I think it is probably better to let the Database handle it rather than have PHP handle it. If it is possible to restrict searches by some other criteria (date range, user, etc) then you may find the substring search is OK (ish).
If you are searching for whole words, you could pull out all the individual words into a separate table and use that to restrict the substring search. (So when searching for "my search string" you look for the the longest word "search" only do the substring search on records containing the word "search")
Assume I have below array:
Skins[
{Id: 1, Name: "oily skin"},
{Id: 2, Name: "dry skin"}
];
If we want to get item with Id = 1
and Name = "oily skin"
, We'll try as below:
var skinName = skins.find(x=>x.Id == "1").Name;
The result will return the skinName is "Oily skin".
A null pointer is guaranteed to not compare equal to a pointer to any object. It's actual value is system dependent and may vary depending on the type. To get a null int
pointer you would do
int* p = 0;
A null pointer will be returned by malloc
on failure.
We can test if a pointer is null, i.e. if malloc
or some other function failed simply by testing its boolean value:
if (p) {
/* Pointer is not null */
} else {
/* Pointer is null */
}
A void pointer can point to any type and it is up to you to handle how much memory the referenced objects consume for the purpose of dereferencing and pointer arithmetic.
npm build
no longer exists. You must call npm run build
now. More info below.
npm install
: installs dependencies, then calls the install
from the package.json
scripts
field.
npm run build
: runs the build field from the package.json
scripts
field.
https://docs.npmjs.com/misc/scripts
There are many things you can put into the npm package.json
scripts field. Check out the documentation link above more above the lifecycle of the scripts - most have pre and post hooks that you can run scripts before/after install, publish, uninstall, test, start, stop, shrinkwrap, version.
npm install
is not the same as npm run install
npm install
installs package.json
dependencies, then runs the package.json
scripts.install
npm run install
after dependencies are installed.npm run install
only runs the package.json
scripts.install
, it will not install dependencies.npm build
used to be a valid command (used to be the same as npm run build
) but it no longer is; it is now an internal command. If you run it you'll get: npm WARN build npm build called with no arguments. Did you mean to npm run-script build?
You can read more on the documentation: https://docs.npmjs.com/cli/buildThere are still two top level commands that will run scripts, they are:
npm start
which is the same as npm run start
npm test
==> npm run test
you can write the function in a separate file (say common-functions.php) and include it wherever needed.
function getEmployeeFullName($employeeId) {
// Write code to return full name based on $employeeId
}
You can include common-functions.php in another file as below.
include('common-functions.php');
echo 'Name of first employee is ' . getEmployeeFullName(1);
You can include any number of files to another file. But including comes with a little performance cost. Therefore include only the files which are really required.
To print the content of Root store:
certutil -store Root
To output content to a file:
certutil -store Root > root_content.txt
To add certificate to Root store:
certutil -addstore -enterprise Root file.cer
Summary:
The curl_exec
command in PHP is a bridge to use curl
from console. curl_exec makes it easy to quickly and easily do GET/POST requests, receive responses from other servers like JSON and download files.
Warning, Danger:
curl
is evil and dangerous if used improperly because it is all about getting data from out there in the internet. Someone can get between your curl and the other server and inject a rm -rf /
into your response, and then why am I dropped to a console and ls -l
doesn't even work anymore? Because you mis underestimated the dangerous power of curl. Don't trust anything that comes back from curl to be safe, even if you are talking to your own servers. You could be pulling back malware to relieve fools of their wealth.
These were done on Ubuntu 12.10
Basic curl from the commandline:
el@apollo:/home/el$ curl http://i.imgur.com/4rBHtSm.gif > mycat.gif
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 492k 100 492k 0 0 1077k 0 --:--:-- --:--:-- --:--:-- 1240k
Then you can open up your gif in firefox:
firefox mycat.gif
Glorious cats evolving Toxoplasma gondii to cause women to keep cats around and men likewise to keep the women around.
cURL example get request to hit google.com, echo to the commandline:
This is done through the phpsh terminal:
php> $ch = curl_init();
php> curl_setopt($ch, CURLOPT_URL, 'http://www.google.com');
php> curl_exec($ch);
Which prints and dumps a mess of condensed html and javascript (from google) to the console.
cURL example put the response text into a variable:
This is done through the phpsh terminal:
php> $ch = curl_init();
php> curl_setopt($ch, CURLOPT_URL, 'http://i.imgur.com/wtQ6yZR.gif');
php> curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
php> $contents = curl_exec($ch);
php> echo $contents;
The variable now contains the binary which is an animated gif of a cat, possibilities are infinite.
Do a curl from within a PHP file:
Put this code in a file called myphp.php:
<?php
$curl_handle=curl_init();
curl_setopt($curl_handle,CURLOPT_URL,'http://www.google.com');
curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);
if (empty($buffer)){
print "Nothing returned from url.<p>";
}
else{
print $buffer;
}
?>
Then run it via commandline:
php < myphp.php
You ran myphp.php and executed those commands through the php interpreter and dumped a ton of messy html and javascript to screen.
You can do GET
and POST
requests with curl, all you do is specify the parameters as defined here: Using curl to automate HTTP jobs
Reminder of danger:
Be careful dumping curl output around, if any of it gets interpreted and executed, your box is owned and your credit card info will be sold to third parties and you'll get a mysterious $900 charge from an Alabama one-man flooring company that's a front for overseas credit card fraud crime ring.
The window is only displayed once the mainloop is entered. So you won't see any changes you make in your while True
block preceding the line root.mainloop()
.
GUI interfaces work by reacting to events while in the mainloop. Here's an example where the StringVar is also connected to an Entry widget. When you change the text in the Entry widget it automatically changes in the Label.
from tkinter import *
root = Tk()
var = StringVar()
var.set('hello')
l = Label(root, textvariable = var)
l.pack()
t = Entry(root, textvariable = var)
t.pack()
root.mainloop() # the window is now displayed
I like the following reference: tkinter 8.5 reference: a GUI for Python
Here is a working example of what you were trying to do:
from tkinter import *
from time import sleep
root = Tk()
var = StringVar()
var.set('hello')
l = Label(root, textvariable = var)
l.pack()
for i in range(6):
sleep(1) # Need this to slow the changes down
var.set('goodbye' if i%2 else 'hello')
root.update_idletasks()
root.update
Enter event loop until all pending events have been processed by Tcl
.
Maybe you'll be able to set the event handlers programmatically, using something like (pseudocode)
sub myhandler(eventsource)
process(eventsource.value)
end sub
for each cell
cell.setEventHandler(myHandler)
But i dont know the syntax for achieving this in VB/VBA, or if is even possible.
FASTER: Bitwise instead of modulus.
select * from MEN where (id&1)=0;
Random question: Do you actually use uppercase table names? Usually uppercase is reserved for keywords. (By convention)
Yes:
>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
Using the sorted keyword key and a lambda function:
>>> sorted(x.items(), key=lambda i: i[1])
[('b', 3), ('a', 5), ('c', 7)]
>>> sorted(x.items(), key=lambda i: i[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]
This works for all dictionaries. However Counter
has a special function which already gives you the sorted items (from most frequent, to least frequent). It's called most_common()
:
>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]
>>> list(reversed(x.most_common())) # in order of least to most
[('b', 3), ('a', 5), ('c', 7)]
You can also specify how many items you want to see:
>>> x.most_common(2) # specify number you want
[('c', 7), ('a', 5)]
Run the following command in terminal:
sudo ln -s /usr/share/phpmyadmin /var/www/html/
MiniDLNA uses inotify
, which is a functionality within the Linux kernel, used to discover changes in specific files and directories on the file system. To get it to work, you need inotify support enabled in your kernel.
The notify_interval
(notice the lack of a leading 'i'), as far as I can tell, is only used if you have inotify disabled. To use the notify_interval
(ie. get the server to 'poll' the file system for changes instead of automatically being notified of them), you have to disable the inotify
functionality.
This is how it looks in my /etc/minidlna.conf
:
# set this to no to disable inotify monitoring to automatically discover new files
# note: the default is yes
inotify=yes
Make sure that inotify is enabled in your kernel.
If it's not enabled, and you don't want to enable it, a forced rescan is the way to force MiniDLNA to re-scan the drive.
You can also use importlib
directly
import importlib
try:
importlib.import_module(module_name)
except ImportError:
# Handle error
FWIW, this BASH script will take a PEM- or DER-format X.509 certificate or OpenSSL public key file (also PEM format) as the first argument and disgorge an OpenSSH RSA public key. This expands upon @mkalkov's answer above. Requirements are cat
, grep
, tr
, dd
, xxd
, sed
, xargs
, file
, uuidgen
, base64
, openssl
(1.0+), and of course bash
. All except openssl
(contains base64
) are pretty much guaranteed to be part of the base install on any modern Linux system, except maybe xxd
(which Fedora shows in the vim-common
package). If anyone wants to clean it up and make it nicer, caveat lector.
#!/bin/bash
#
# Extract a valid SSH format public key from an X509 public certificate.
#
# Variables:
pubFile=$1
fileType="no"
pkEightTypeFile="$pubFile"
tmpFile="/tmp/`uuidgen`-pkEightTypeFile.pk8"
# See if a file was passed:
[ ! -f "$pubFile" ] && echo "Error, bad or no input file $pubFile." && exit 1
# If it is a PEM format X.509 public cert, set $fileType appropriately:
pemCertType="X$(file $pubFile | grep 'PEM certificate')"
[ "$pemCertType" != "X" ] && fileType="PEM"
# If it is an OpenSSL PEM-format PKCS#8-style public key, set $fileType appropriately:
pkEightType="X$(grep -e '-BEGIN PUBLIC KEY-' $pubFile)"
[ "$pkEightType" != "X" ] && fileType="PKCS"
# If this is a file we can't recognise, try to decode a (binary) DER-format X.509 cert:
if [ "$fileType" = "no" ]; then
openssl x509 -in $pubFile -inform DER -noout
derResult=$(echo $?)
[ "$derResult" = "0" ] && fileType="DER"
fi
# Exit if not detected as a file we can use:
[ "$fileType" = "no" ] && echo "Error, input file not of type X.509 public certificate or OpenSSL PKCS#8-style public key (not encrypted)." && exit 1
# Convert the X.509 public cert to an OpenSSL PEM-format PKCS#8-style public key:
if [ "$fileType" = "PEM" -o "$fileType" = "DER" ]; then
openssl x509 -in $pubFile -inform $fileType -noout -pubkey > $tmpFile
pkEightTypeFile="$tmpFile"
fi
# Build the string:
# Front matter:
frontString="$(echo -en 'ssh-rsa ')"
# Encoded modulus and exponent, with appropriate pointers:
encodedModulus="$(cat $pkEightTypeFile | grep -v -e "----" | tr -d '\n' | base64 -d | dd bs=1 skip=32 count=257 status=none | xxd -p -c257 | sed s/^/00000007\ 7373682d727361\ 00000003\ 010001\ 00000101\ / | xxd -p -r | base64 -w0 )"
# Add a comment string based on the filename, just to be nice:
commentString=" $(echo $pubFile | xargs basename | sed -e 's/\.crt\|\.cer\|\.pem\|\.pk8\|\.der//')"
# Give the user a string:
echo $frontString $encodedModulus $commentString
# cleanup:
rm -f $tmpFile
#div-name
{
background-image: url('../images/background-art-main.jpg');
background-position: top right 50px;
background-repeat: no-repeat;
}
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
EDIT From Your comments i have edited the onclick view in this the button1 and button2 functions will be executed separately.
public onClick(View v){
switch(v.getId()){
case R.id.button1:
//Your button 1 function
break;
case R.id. button2:
//Your button 2 function
break;
}
}
If you are using the GET request to actually SEND data...
check: http://techhelplist.com/index.php/tech-tutorials/37-windows-troubles/60-vbscript-sending-get-request
The problem with MSXML2.XMLHTTP is that there are several versions of it, with different names depending on the windows os version and patches.
this explains it: http://support.microsoft.com/kb/269238
i have had more luck using vbscript to call
set ID = CreateObject("InternetExplorer.Application")
IE.visible = 0
IE.navigate "http://example.com/parser.php?key=" & value & "key2=" & value2
do while IE.Busy....
....and more stuff but just to let the request go thru.
Error :
System : aws ec2 instance (t2 small)
issue : while installing opencv python via
pip3 install opencv-python
Problem with the CMake installation, aborting build. CMake executable is cmake
----------------------------------------
Failed building wheel for opencv-python
Running setup.py clean for opencv-python
What worked for me
pip3 install --upgrade pip setuptools wheel
After this you still might received fallowing error error
from .cv2 import *
ImportError: libGL.so.1: cannot open shared object file: No such file or directory
Installing libgl solved the error for me.
sudo apt update
sudo apt install libgl1-mesa-glx
Hope this helps
You cannot pass user/table name to pl/sql with a parameter. You can create a procedure and build sql and then execute immediately to achieve that.
BTW you can pass the error message directly to sys.exit:
if len(sys.argv) < 2:
sys.exit('Usage: %s database-name' % sys.argv[0])
if not os.path.exists(sys.argv[1]):
sys.exit('ERROR: Database %s was not found!' % sys.argv[1])
Try this.. very easy to understand & implementation...
You can download sample code directly here https://github.com/Tech-Dev-Mobile/Json-Sample
- (void)simpleJsonParsingPostMetod
{
#warning set webservice url and parse POST method in JSON
//-- Temp Initialized variables
NSString *first_name;
NSString *image_name;
NSData *imageData;
//-- Convert string into URL
NSString *urlString = [NSString stringWithFormat:@"demo.com/your_server_db_name/service/link"];
NSMutableURLRequest *request =[[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
//-- Append data into posr url using following method
NSMutableData *body = [NSMutableData data];
//-- For Sending text
//-- "firstname" is keyword form service
//-- "first_name" is the text which we have to send
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",@"firstname"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@",first_name] dataUsingEncoding:NSUTF8StringEncoding]];
//-- For sending image into service if needed (send image as imagedata)
//-- "image_name" is file name of the image (we can set custom name)
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition:form-data; name=\"file\"; filename=\"%@\"\r\n",image_name] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
//-- Sending data into server through URL
[request setHTTPBody:body];
//-- Getting response form server
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//-- JSON Parsing with response data
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSLog(@"Result = %@",result);
}
I got this problem recently. Here what I do:
sudo service mongod restart
pm2 restart [your-app-id]
. To get ID use pm2 list
Based on reading your answer and seeing how you likely came up with it, I believe you think an "exception-in-progress" has "precedence". Keep in mind:
When an new exception is thrown in a catch block or finally block that will propagate out of that block, then the current exception will be aborted (and forgotten) as the new exception is propagated outward. The new exception starts unwinding up the stack just like any other exception, aborting out of the current block (the catch or finally block) and subject to any applicable catch or finally blocks along the way.
Note that applicable catch or finally blocks includes:
When a new exception is thrown in a catch block, the new exception is still subject to that catch's finally block, if any.
Now retrace the execution remembering that, whenever you hit throw
, you should abort tracing the current exception and start tracing the new exception.
You could try this
=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),FALSE, TRUE)
-or-
=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),"FALSE", "File found in row " & MATCH(<single column I value>,<entire column E range>,0))
you could replace <single column I value>
and <entire column E range>
with named ranged. That'd probably be the easiest.
Just drag that formula all the way down the length of your I column in whatever column you want.
You could do an SQLDump
of the database (and its data) then search that file.
Here is my solution using SwiftyJSON
if let path : String = NSBundle.mainBundle().pathForResource("filename", ofType: "json") {
if let data = NSData(contentsOfFile: path) {
let json = JSON(data: data)
}
}
I would suggest using wire shark to trace packets. If you are using Ubuntu, sudo-apt get wireshark. Like Joni stated the only way to figure out whats going wrong is to follow the GET requests and their associated responses.
node.innerHTML = "";
Non-standard, but fast and well supported.
int[]
and int*
are represented the same way, except int[] allocates (IIRC).
ap
is a pointer, therefore giving it the value of an integer is dangerous, as you have no idea what's at address 45.
when you try to access it (x = *ap
), you try to access address 45, which causes the crash, as it probably is not a part of the memory you can access.
A turkish one. If someone is still interested.
$('input[type="text"]').keyup(function() {
$(this).val($(this).val().replace(/^([a-zA-Z\s\ö\ç\s\i\i\g\ü\Ö\Ç\S\I\G\Ü])|\s+([a-zA-Z\s\ö\ç\s\i\i\g\ü\Ö\Ç\S\I\G\Ü])/g, function ($1) {
if ($1 == "i")
return "I";
else if ($1 == " i")
return " I";
return $1.toUpperCase();
}));
});
Ubuntu 15.10, Kernel 4.2.0, x86-64, GCC 5.2.1 example
Enough standards, let's look at an implementation :-)
Local variable
Standards: undefined behavior.
Implementation: the program allocates stack space, and never moves anything to that address, so whatever was there previously is used.
#include <stdio.h>
int main() {
int i;
printf("%d\n", i);
}
compile with:
gcc -O0 -std=c99 a.c
outputs:
0
and decompiles with:
objdump -dr a.out
to:
0000000000400536 <main>:
400536: 55 push %rbp
400537: 48 89 e5 mov %rsp,%rbp
40053a: 48 83 ec 10 sub $0x10,%rsp
40053e: 8b 45 fc mov -0x4(%rbp),%eax
400541: 89 c6 mov %eax,%esi
400543: bf e4 05 40 00 mov $0x4005e4,%edi
400548: b8 00 00 00 00 mov $0x0,%eax
40054d: e8 be fe ff ff callq 400410 <printf@plt>
400552: b8 00 00 00 00 mov $0x0,%eax
400557: c9 leaveq
400558: c3 retq
From our knowledge of x86-64 calling conventions:
%rdi
is the first printf argument, thus the string "%d\n"
at address 0x4005e4
%rsi
is the second printf argument, thus i
.
It comes from -0x4(%rbp)
, which is the first 4-byte local variable.
At this point, rbp
is in the first page of the stack has been allocated by the kernel, so to understand that value we would to look into the kernel code and find out what it sets that to.
TODO does the kernel set that memory to something before reusing it for other processes when a process dies? If not, the new process would be able to read the memory of other finished programs, leaking data. See: Are uninitialized values ever a security risk?
We can then also play with our own stack modifications and write fun things like:
#include <assert.h>
int f() {
int i = 13;
return i;
}
int g() {
int i;
return i;
}
int main() {
f();
assert(g() == 13);
}
Local variable in -O3
Implementation analysis at: What does <value optimized out> mean in gdb?
Global variables
Standards: 0
Implementation: .bss
section.
#include <stdio.h>
int i;
int main() {
printf("%d\n", i);
}
gcc -00 -std=c99 a.c
compiles to:
0000000000400536 <main>:
400536: 55 push %rbp
400537: 48 89 e5 mov %rsp,%rbp
40053a: 8b 05 04 0b 20 00 mov 0x200b04(%rip),%eax # 601044 <i>
400540: 89 c6 mov %eax,%esi
400542: bf e4 05 40 00 mov $0x4005e4,%edi
400547: b8 00 00 00 00 mov $0x0,%eax
40054c: e8 bf fe ff ff callq 400410 <printf@plt>
400551: b8 00 00 00 00 mov $0x0,%eax
400556: 5d pop %rbp
400557: c3 retq
400558: 0f 1f 84 00 00 00 00 nopl 0x0(%rax,%rax,1)
40055f: 00
# 601044 <i>
says that i
is at address 0x601044
and:
readelf -SW a.out
contains:
[25] .bss NOBITS 0000000000601040 001040 000008 00 WA 0 0 4
which says 0x601044
is right in the middle of the .bss
section, which starts at 0x601040
and is 8 bytes long.
The ELF standard then guarantees that the section named .bss
is completely filled with of zeros:
.bss
This section holds uninitialized data that contribute to the program’s memory image. By definition, the system initializes the data with zeros when the program begins to run. The section occu- pies no file space, as indicated by the section type,SHT_NOBITS
.
Furthermore, the type SHT_NOBITS
is efficient and occupies no space on the executable file:
sh_size
This member gives the section’s size in bytes. Unless the sec- tion type isSHT_NOBITS
, the section occupiessh_size
bytes in the file. A section of typeSHT_NOBITS
may have a non-zero size, but it occupies no space in the file.
Then it is up to the Linux kernel to zero out that memory region when loading the program into memory when it gets started.
AJAX requests are asynchronous. Your doSomething function is being exectued, the AJAX request is being made but it happens asynchronously; so the remainder of doSomething is executed and the value of status
is undefined when it is returned.
Effectively, your code works as follows:
function doSomething(someargums) {
return status;
}
var response = doSomething();
And then some time later, your AJAX request is completing; but it's already too late
You need to alter your code, and populate the "response" variable in the "success" callback of your AJAX request. You're going to have to delay using the response until the AJAX call has completed.
Where you previously may have had
var response = doSomething();
alert(response);
You should do:
function doSomething() {
$.ajax({
url:'action.php',
type: "POST",
data: dataString,
success: function (txtBack) {
alert(txtBack);
})
});
};
What you need to do is configure Fiddler to work as a "reverse proxy"
There are instructions on 2 different ways you can do this on Fiddler's website. Here is a copy of the steps:
Step #0
Before either of the following options will work, you must enable other computers to connect to Fiddler. To do so, click Tools > Fiddler Options > Connections and tick the "Allow remote computers to connect" checkbox. Then close Fiddler.
Option #1: Configure Fiddler as a Reverse-Proxy
Fiddler can be configured so that any traffic sent to http://127.0.0.1:8888
is automatically sent to a different port on the same machine. To set this configuration:
http://127.0.0.1:8888
Option #2: Write a FiddlerScript rule
Alternatively, you can write a rule that does the same thing.
Say you're running a website on port 80 of a machine named WEBSERVER. You're connecting to the website using Internet Explorer Mobile Edition on a Windows SmartPhone device for which you cannot configure the web proxy. You want to capture the traffic from the phone and the server's response.
http://webserver:8888
Requests from the SmartPhone will appear in Fiddler. The requests are forwarded from port 8888 to port 80 where the webserver is running. The responses are sent back through Fiddler to the SmartPhone, which has no idea that the content originally came from port 80.
The pseudo-elements generated by ::before and ::after are contained by the element's formatting box, and thus don't apply to replaced elements such as img, or to br elements.
Error:
[error] [client 127.0.0.1] (13)Permission denied: Could not open password file: /home/XXX/svn/svn_password
Info:
##SELinux Security Context File Labels #httpd_sys_content_t The type used by regular static web pages with .html and .htm extensions. #httpd_sys_script_ro_t Required for CGI scripts to read files and directories. #httpd_sys_script_ra_t Same as the httpd_sys_script_ro_t type but also allows appending data to files by the CGI script. #httpd_sys_script_rw_t Files with this type may be changed by a CGI script in any way, including deletion. #httpd_sys_script_exec_t The type required for the execution of CGI scripts
Solution:
[root@localhost]# perror 13 OS error code 13: Permission denied [root@localhost]# chown apache.apache /home/XXX/svn/ -R [root@localhost]# semanage fcontext -a -t httpd_sys_script_rw_t "/home/XXX/svn(/.*)?" [root@localhost]# restorecon -R -v /home/XXX/svn/ [root@localhost]# restorecon reset /home/XXX/svn/ context [root@localhost]# ls -dZ /home/XXX/svn/ drwxr-xr-x. apache apache system_u:object_r:httpd_sys_rw_content_t:s0 /home/XXX/svn/ [root@localhost]# ls -dZ /home/XXX/svn/svn_password -rwxr-xr-x. apache apache system_u:object_r:httpd_sys_rw_content_t:s0 /home/XXX/svn/svn_password [root@localhost]#
Use eclipse with the plugins shelled & basheclipse.
https://sourceforge.net/projects/shelled/?source=directory https://sourceforge.net/projects/basheclipse/?source=directory
For shelled: Download the zip and import it into eclipse via help -> install new software : local archive For basheclipse: Copy the jars into dropins directory of eclipse
Follow the steps provides https://sourceforge.net/projects/basheclipse/files/?source=navbar
I wrote a tutorial with many screenshots at http://dietrichschroff.blogspot.de/2017/07/bash-enabling-eclipse-for-bash.html
Just another alternative solution for those who want to pass variables to a script which is sourced using flask, I only managed to get this working by defining the variables outside and then calling the script as follows:
<script>
var myfileuri = "/static/my_csv.csv"
var mytableid = 'mytable';
</script>
<script type="text/javascript" src="/static/test123.js"></script>
If I input jinja variables in test123.js
it doesn't work and you will get an error.
If you say that it works with accessing directly manageproducts.do?option=1
in the browser then it should work with:
$.get('manageproducts.do', { option: '1' }, function(data) {
...
});
as it would send the same GET request.
Everyone is right. You can't print an int[] object out directly, but there's also no need to not use an ArrayList of integer arrays.
Using,
Arrays.toString(arl.get(0))
means splitting the String object into a substring if you want to insert anything in between, such as commas.
Here's what I think amv was looking for from an int array viewpoint.
System.out.println("Arraylist contains: "
+ arl.get(0)[0] + ", "
+ arl.get(0)[1] + ", "
+ arl.get(0)[2]);
This answer is a little late for amv but still may be useful to others.
In my opinion, this is the most readable:
for i in reversed(xrange(101)):
print i,
Remove the quotes here:
is:
ORDER BY = 'post_datetime DESC' AND LIMIT = '3'
Should be:
ORDER BY post_datetime DESC LIMIT 3
Default migration generator does not handle default values (column modifiers are supported but do not include default
or null
), but you could create your own generator.
You can also manually update the migration file prior to running rake db:migrate
by adding the options to add_column
:
add_column :tweet, :retweets_count, :integer, :null => false, :default => 0
... and read Rails API
It sounds like the data you're really looking for can be accessed via secondary URL called by some javascript on the primary page.
While you could try running javascript on the server to handle this, a simpler approach to might be to load up the page using Firefox and use a tool like Charles or Firebug to identify exactly what that secondary URL is. Then you can just query that URL directly for the data you are interested in.
Try using list.AddRange(VTSWeb.GetDailyWorktimeViolations(VehicleID2));
I try mimetypes library first. If it's not working, I use python-magic libary instead.
import mimetypes
def guess_type(filename, buffer=None):
mimetype, encoding = mimetypes.guess_type(filename)
if mimetype is None:
try:
import magic
if buffer:
mimetype = magic.from_buffer(buffer, mime=True)
else:
mimetype = magic.from_file(filename, mime=True)
except ImportError:
pass
return mimetype
To everyone who said that this is a bad idea I want to say it is not always a bad one. Sometimes it is very boring to have to zoom out to see all the content. For example when you type on an input on iOS it zooms to get it in the center of the screen. You have to zoom out after that cause closing the keyboard does not do the work. Also I agree that when you put many I hours in making a great layout and user experience you don't want it to be messed up by a zoom.
But the other argument is valuable as well for people with vision issues. However In my opinion if you have issues with your eyes you are already using the zooming features of the system so there is no need to disturb the content.
Another option would be to simply copy & drop the column:
df = pd.DataFrame(d)
df['new_name'] = df['two']
df = df.drop('two', axis=1)
df.head()
After that you get the result:
one three new_name
0 1 a 9
1 2 b 8
2 3 c 7
3 4 d 6
4 5 e 5
Or a nested List (okay, the OP was for a single column and this is for multiple columns..):
//Base list is a list of fields, ie a data record
//Enclosing list is then a list of those records, ie the Result set
List<List<String>> ResultSet = new List<List<String>>();
using (SqlConnection connection =
new SqlConnection(connectionString))
{
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand(qString, connection);
// Create and execute the DataReader..
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var rec = new List<string>();
for (int i = 0; i <= reader.FieldCount-1; i++) //The mathematical formula for reading the next fields must be <=
{
rec.Add(reader.GetString(i));
}
ResultSet.Add(rec);
}
}
Maybe you could do
SELECT * FROM table LIMIT 10000 OFFSET FLOOR(RAND() * 190000)
If your protocol is http and you are using Subversion 1.7, you can switch the user at anytime by simply using the global --username option on any command.
When Ingo's method didn't work for me, this was what I found that worked.
Another way, There is check box Page Layout tab with Gridlines [ ] View which should be checked.
Based in this implementation with Node.js of JWT with refresh token:
1) In this case they use a uid and it's not a JWT. When they refresh the token they send the refresh token and the user. If you implement it as a JWT, you don't need to send the user, because it would inside the JWT.
2) They implement this in a separated document (table). It has sense to me because a user can be logged in in different client applications and it could have a refresh token by app. If the user lose a device with one app installed, the refresh token of that device could be invalidated without affecting the other logged in devices.
3) In this implementation it response to the log in method with both, access token and refresh token. It seams correct to me.
Make sure that you really need it. Do a google search for "singleton anti-pattern" to see some arguments against it.
There's nothing inherently wrong with it I suppose, but it's just a mechanism for exposing some global resource/data so make sure that this is the best way. In particular, I've found dependency injection (DI) more useful particularly if you are also using unit tests, because DI allows you to use mocked resources for testing purposes.
find
has a -delete
action:
find . -maxdepth 1 -name '*.pdf' -delete
Simple idea: get the lenght of the longest row, iterate over each column printing the content of a row if it has elements. The below code might have some off-by-one errors as it was coded in a simple text editor.
int longestRow = 0;
for (int i = 0; i < array.length; i++) {
if (array[i].length > longestRow) {
longestRow = array[i].length;
}
}
for (int j = 0; j < longestRow; j++) {
for (int i = 0; i < array.length; i++) {
if(array[i].length > j) {
System.out.println(array[i][j]);
}
}
}
This is what I use to output parameter lists for a stored procedure into the debug console:
string query = (from SqlParameter p in sqlCmd.Parameters where p != null where p.Value != null select string.Format("Param: {0} = {1}, ", p.ParameterName, p.Value.ToString())).Aggregate(sqlCmd.CommandText, (current, parameter) => current + parameter);
Debug.WriteLine(query);
This will generate a console outputt simlar to this:
Customer.prGetCustomerDetails: @Offset = 1, Param: @Fetch = 10, Param: @CategoryLevel1ID = 3, Param: @VehicleLineID = 9, Param: @SalesCode1 = bce,
I place this code directly below any procedure I wish to debug and is similar to a sql profiler session but in C#.
Sweet Persist is another one.
It is possible to serialize to and from streams in XML, JSON, Lua, and binary formats.
In C, static
means the function or variable you define can be only used in this file(i.e. the compile unit)
So, static inline
means the inline function which can be used in this file only.
EDIT:
The compile unit should be The Translation Unit
Another option: define your variable out of the Jasper object and then just call a variable.
Spread operator: ES6
this.state = { jasper: { name: 'jasper', age: 28 } }
let foo = "something that needs to be saved into state"
this.setState(prevState => ({
jasper: {
...jasper.entity,
foo
}
})
Here's a variation on the first answer given in this thread which doesn't require any extra packages, libraries or special functions.
state = {
someProperty: {
flag: 'string'
}
}
handleChange = (value) => {
const newState = {...this.state.someProperty, flag: value}
this.setState({ someProperty: newState })
}
In order to set the state of a specific nested field, you have set the whole object. I did this by creating a variable, newState
and spreading the contents of the current state into it first using the ES2015 spread operator. Then, I replaced the value of this.state.flag
with the new value (since I set flag: value
after I spread the current state into the object, the flag
field in the current state is overridden). Then, I simply set the state of someProperty
to my newState
object.
Try the code mentioned below
public static void main(String[] args) {
int smallest=0; int large=0; int num;
System.out.println("enter the number");
Scanner input=new Scanner(System.in);
int n=input.nextInt();
num=input.nextInt();
smallest = num;
for(int i=0;i<n-1;i++)
{
num=input.nextInt();
if(num<smallest)
{
smallest=num;
}
}
System.out.println("the smallest is:"+smallest);
}
you can make use of the below code for sorting in descending order and storing to a dictionary:
listname = []
for key, value in sorted(dictionaryName.iteritems(), key=lambda (k,v): (v,k),reverse=True):
diction= {"value":value, "key":key}
listname.append(diction)
I finally write this function that should cover all the possible situations, adding a char prefix and suffix to the input. this char is evaluated to be different to any of the char conteined in the search parameter, so it can't affect the result.
CREATE FUNCTION [dbo].[CountOccurrency]
(
@Input nvarchar(max),
@Search nvarchar(max)
)
RETURNS int AS
BEGIN
declare @SearhLength as int = len('-' + @Search + '-') -2;
declare @conteinerIndex as int = 255;
declare @conteiner as char(1) = char(@conteinerIndex);
WHILE ((CHARINDEX(@conteiner, @Search)>0) and (@conteinerIndex>0))
BEGIN
set @conteinerIndex = @conteinerIndex-1;
set @conteiner = char(@conteinerIndex);
END;
set @Input = @conteiner + @Input + @conteiner
RETURN (len(@Input) - len(replace(@Input, @Search, ''))) / @SearhLength
END
usage
select dbo.CountOccurrency('a,b,c,d ,', ',')
I guess this is probably a non issue for most but I tried to solve it. I think I have a pretty decent solution. In case anyone else stumbles upon this issue.
function randomNums($gen, $trim, $low, $high)
{
$results_to_gen = $gen;
$low_range = $low;
$high_range = $high;
$trim_results_to= $trim;
$items = array();
$results = range( 1, $results_to_gen);
$i = 1;
foreach($results as $result)
{
$result = mt_rand( $low_range, $high_range);
$items[] = $result;
}
$unique = array_unique( $items, SORT_NUMERIC);
$countem = count( $unique);
$unique_counted = $countem -$trim_results_to;
$sum = array_slice($unique, $unique_counted);
foreach ($sum as $key)
{
$output = $i++.' : '.$key.'<br>';
echo $output;
}
}
randomNums(1100, 1000 ,890000, 899999);
An abstract method is a method signature declaration with no body. For instance:
public abstract class Shape {
. . .
public abstract double getArea();
public abstract double getPerimeter();
}
The methods getArea()
and getPerimeter()
are abstract. Because the Shape
class has an abstract method, it must be declared abstract
as well. A class may also be declared abstract
without any abstract methods. When a class is abstract, an instance of it cannot be created; one can only create instances of (concrete) subclasses. A concrete class is a class that is not declared abstract (and therefore has no abstract methods and implements all inherited abstract methods). For instance:
public class Circle extends Shape {
public double radius;
. . .
public double getArea() {
return Math.PI * radius * radius;
}
public double getPerimeter() {
return 2.0 * Math.PI * radius;
}
}
There are many reasons to do this. One would be to write a method that would be the same for all shapes but that depends on shape-specific behavior that is unknown at the Shape
level. For instance, one could write the method:
public abstract class Shape {
. . .
public void printArea(PrintStream out) {
out.println("The area is " + getArea());
}
}
Admittedly, this is a contrived example, but it shows the basic idea: define concrete behavior in terms of unspecified behavior.
Another reason for having an abstract class is so you can partially implement an interface. All methods declared in an interface are inherited as abstract methods by any class that implements the interface. Sometimes you want to provide a partial implementation of an interface in a class and leave the details to subclasses; the partial implementation must be declared abstract.
This does exist, but it's actually a feature of git log
:
git log -p [--follow] [-1] <path>
Note that -p
can also be used to show the inline diff from a single commit:
git log -p -1 <commit>
Options used:
-p
(also -u
or --patch
) is hidden deeeeeeeep in the git-log
man page, and is actually a display option for git-diff
. When used with log
, it shows the patch that would be generated for each commit, along with the commit information—and hides commits that do not touch the specified <path>
. (This behavior is described in the paragraph on --full-diff
, which causes the full diff of each commit to be shown.)-1
shows just the most recent change to the specified file (-n 1
can be used instead of -1
); otherwise, all non-zero diffs of that file are shown.--follow
is required to see changes that occurred prior to a rename.As far as I can tell, this is the only way to immediately see the last set of changes made to a file without using git log
(or similar) to either count the number of intervening revisions or determine the hash of the commit.
To see older revisions changes, just scroll through the log, or specify a commit or tag from which to start the log. (Of course, specifying a commit or tag returns you to the original problem of figuring out what the correct commit or tag is.)
Credit where credit is due:
log -p
thanks to this answer.--follow
option.-n 1
option and atatko for mentioning the -1
variant.-p
"means" semantically.Normal multiplication like you showed:
>>> import numpy as np
>>> m = np.array([[1,2,3],[4,5,6],[7,8,9]])
>>> c = np.array([0,1,2])
>>> m * c
array([[ 0, 2, 6],
[ 0, 5, 12],
[ 0, 8, 18]])
If you add an axis, it will multiply the way you want:
>>> m * c[:, np.newaxis]
array([[ 0, 0, 0],
[ 4, 5, 6],
[14, 16, 18]])
You could also transpose twice:
>>> (m.T * c).T
array([[ 0, 0, 0],
[ 4, 5, 6],
[14, 16, 18]])
ipython
is an interactive shell built with python.
From the project website:
IPython provides a rich toolkit to help you make the most out of using Python, with:
- Powerful Python shells (terminal and Qt-based).
- A web-based notebook with the same core features but support for code, text, mathematical expressions, inline plots and other rich media.
- Support for interactive data visualization and use of GUI toolkits.
- Flexible, embeddable interpreters to load into your own projects.
- Easy to use, high performance tools for parallel computing.
Note that the first 2 lines tell you it helps you make the most of using Python. Thus, you don't need to alter your code, the IPython shell runs your python code just like the normal python shell does, only with more features.
I recommend reading the IPython tutorial to get a sense of what features you gain when using IPython.
Firstly run this query
SHOW VARIABLES LIKE '%char%';
You have character_set_server='latin1'
for eg if CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
replace it to CHARSET=latin1
and remove the collate
You are good to go
TRY THIS CODE
// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;
// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
// Initialize the flag to false.
nonNumberEntered = false;
// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
// Determine whether the keystroke is a backspace.
if (e.KeyCode != Keys.Back)
{
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
nonNumberEntered = true;
}
}
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (nonNumberEntered == true)
{
MessageBox.Show("Please enter number only...");
e.Handled = true;
}
}
Source is http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=VS.90).aspx
Use reqclient: not designed for scripting purpose
like request
or many other libraries. Reqclient allows in the constructor
specify many configurations useful when you need to reuse the same
configuration again and again: base URL, headers, auth options,
logging options, caching, etc. Also has useful features like
query and URL parsing, automatic query encoding and JSON parsing, etc.
The best way to use the library is create a module to export the object pointing to the API and the necessary configurations to connect with:
Module client.js
:
let RequestClient = require("reqclient").RequestClient
let client = new RequestClient({
baseUrl: "https://myapp.com/api/v1",
cache: true,
auth: {user: "admin", pass: "secret"}
})
module.exports = client
And in the controllers where you need to consume the API use like this:
let client = require('client')
//let router = ...
router.get('/dashboard', (req, res) => {
// Simple GET with Promise handling to https://myapp.com/api/v1/reports/clients
client.get("reports/clients")
.then(response => {
console.log("Report for client", response.userId) // REST responses are parsed as JSON objects
res.render('clients/dashboard', {title: 'Customer Report', report: response})
})
.catch(err => {
console.error("Ups!", err)
res.status(400).render('error', {error: err})
})
})
router.get('/orders', (req, res, next) => {
// GET with query (https://myapp.com/api/v1/orders?state=open&limit=10)
client.get({"uri": "orders", "query": {"state": "open", "limit": 10}})
.then(orders => {
res.render('clients/orders', {title: 'Customer Orders', orders: orders})
})
.catch(err => someErrorHandler(req, res, next))
})
router.delete('/orders', (req, res, next) => {
// DELETE with params (https://myapp.com/api/v1/orders/1234/A987)
client.delete({
"uri": "orders/{client}/{id}",
"params": {"client": "A987", "id": 1234}
})
.then(resp => res.status(204))
.catch(err => someErrorHandler(req, res, next))
})
reqclient
supports many features, but it has some that are not supported by other
libraries: OAuth2 integration and logger integration
with cURL syntax, and always returns native Promise objects.
Your can do it like this in short hands.
int[,] values=new int[2,3]{{2,4,5},{4,5,2}};
for (int i = 0; i < values.GetLength(0); i++)
{
for (int k = 0; k < values.GetLength(1); k++) {
Console.Write(values[i,k]);
}
Console.WriteLine();
}
I had the same problem when my network config was incorrect and DNS was not resolving. In other words the issue could arise when there is no Network Access.
If you only need to replace
then you can use a far simpler regex:
var textWithNBSpaceReplaced = originalText.replace(/ /g, ' ');
Also, there is a typo in your div example, it says &nnbsp;
instead of
.
Spring Docs explain that
In proxy mode (which is the default), only external method calls coming in through the proxy are intercepted. This means that self-invocation, in effect, a method within the target object calling another method of the target object, will not lead to an actual transaction at runtime even if the invoked method is marked with @Transactional.
Consider the use of AspectJ mode (see mode attribute in table below) if you expect self-invocations to be wrapped with transactions as well. In this case, there will not be a proxy in the first place; instead, the target class will be weaved (that is, its byte code will be modified) in order to turn @Transactional into runtime behavior on any kind of method.
Another way is user BeanSelfAware
For the accepted answer when you try to hide any view inside stack view, the constraint works not correct.
Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<NSLayoutConstraint:0x618000086e50 UIView:0x7fc11c4051c0.height == 120 (active)>",
"<NSLayoutConstraint:0x610000084fb0 'UISV-hiding' UIView:0x7fc11c4051c0.height == 0 (active)>"
)
Reason is when hide the view
in stackView
it will set the height to 0 to animate it.
Solution change the constraint priority
as below.
import UIKit
class ViewController: UIViewController {
let stackView = UIStackView()
let a = UIView()
let b = UIView()
override func viewDidLoad() {
super.viewDidLoad()
a.backgroundColor = UIColor.red
a.widthAnchor.constraint(equalToConstant: 200).isActive = true
let aHeight = a.heightAnchor.constraint(equalToConstant: 120)
aHeight.isActive = true
aHeight.priority = 999
let bHeight = b.heightAnchor.constraint(equalToConstant: 120)
bHeight.isActive = true
bHeight.priority = 999
b.backgroundColor = UIColor.green
b.widthAnchor.constraint(equalToConstant: 200).isActive = true
view.addSubview(stackView)
stackView.backgroundColor = UIColor.blue
stackView.addArrangedSubview(a)
stackView.addArrangedSubview(b)
stackView.axis = .vertical
stackView.distribution = .equalSpacing
stackView.translatesAutoresizingMaskIntoConstraints = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// Just add a button in xib file or storyboard and add connect this action.
@IBAction func test(_ sender: Any) {
a.isHidden = !a.isHidden
}
}
Like others suggested you are better off using collection. If you however for some reason must stick to array then Apache Commons ArrayUtils may help:
int[] series = {4,2};
series = ArrayUtils.add(series, 3); // series is now {4,2,3}
series = ArrayUtils.add(series, 4); // series is now {4,2,3,4};
Note that the add
method creates a new array, copies the given array and appends the new element at the end, which may have impact on performance.
It works too :
<form>
<label for="male"><input type="checkbox" name="male" id="male" />Male</label><br />
<label for="female"><input type="checkbox" name="female" id="female" />Female</label>
</form>
use state is not always needed you can just simply do this
let paymentList = [
{"id":249,"txnid":"2","fname":"Rigoberto"}, {"id":249,"txnid":"33","fname":"manuel"},]
then use your data in a map loop like this in my case it was just a table and im sure many of you are looking for the same. here is how you use it.
<div className="card-body">
<div className="table-responsive">
<table className="table table-striped">
<thead>
<tr>
<th>Transaction ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
{
paymentList.map((payment, key) => (
<tr key={key}>
<td>{payment.txnid}</td>
<td>{payment.fname}</td>
</tr>
))
}
</tbody>
</table>
</div>
</div>
Using the chronic gem:
class MyModel < ActiveRecord::Base
validate :valid_date?
def valid_date?
unless Chronic.parse(from_date)
errors.add(:from_date, "is missing or invalid")
end
end
end
You should be able to do this like (as you're using the query api):
Entrant.where("pincode").ne(null)
... which will result in a mongo query resembling:
entrants.find({ pincode: { $ne: null } })
A few links that might help:
If you don't want to expand or collapse all the way - here is a simple HeightAnimation -
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;
public class HeightAnimation extends Animation {
protected final int originalHeight;
protected final View view;
protected float perValue;
public HeightAnimation(View view, int fromHeight, int toHeight) {
this.view = view;
this.originalHeight = fromHeight;
this.perValue = (toHeight - fromHeight);
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
view.getLayoutParams().height = (int) (originalHeight + perValue * interpolatedTime);
view.requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
}
Usage:
HeightAnimation heightAnim = new HeightAnimation(view, view.getHeight(), viewPager.getHeight() - otherView.getHeight());
heightAnim.setDuration(1000);
view.startAnimation(heightAnim);
[[UITabBar appearance] setTintColor:[UIColor redColor]];
[[UITabBar appearance] setBarTintColor:[UIColor yellowColor]];
Try this:
jQuery('#myInput').keypress(function(e) {
code = e.keyCode ? e.keyCode : e.which;
if(code.toString() == 13) {
alert('You pressed enter!');
}
});
You can do this with "just the regular expression" as you asked for in a comment:
(?<=sentence).*
(?<=sentence)
is a positive lookbehind assertion. This matches at a certain position in the string, namely at a position right after the text sentence
without making that text itself part of the match. Consequently, (?<=sentence).*
will match any text after sentence
.
This is quite a nice feature of regex. However, in Java this will only work for finite-length subexpressions, i. e. (?<=sentence|word|(foo){1,4})
is legal, but (?<=sentence\s*)
isn't.
Can you try the following?
psexec \\server cmd /c "echo . | powershell script.ps1"
YOu can also try the following
do {
try {
System.out.println("Enter first num: ");
n1 = Integer.parseInt(input.next());
System.out.println("Enter second num: ");
n2 = Integer.parseInt(input.next());
nQuotient = n1/n2;
bError = false;
}
catch (Exception e) {
System.out.println("Error!");
input.reset();
}
} while (bError);
The simplest technique is to use NSString *uuid = [[NSProcessInfo processInfo] globallyUniqueString]
. See the NSProcessInfo class reference.
parent()
method returns the direct parent element of the selected one. This method only traverse a single level up the DOM tree.
parents()
method allows us to search through the ancestors of these elements in the DOM tree. Begin from given selector and move up.
The **.parents()** and **.parent()** methods are almost similar, except that the latter only travels a single level up the DOM tree. Also, **$( "html" ).parent()** method returns a set containing document whereas **$( "html" ).parents()** returns an empty set.
[closest()][3]method returns the first ancestor of the selected element.An ancestor is a parent, grandparent, great-grandparent, and so on.
This method traverse upwards from the current element, all the way up to the document's root element (<html>), to find the first ancestor of DOM elements.
According to docs:
**closest()** method is similar to **parents()**, in that they both traverse up the DOM tree. The differences are as follows:
**closest()**
Begins with the current element
Travels up the DOM tree and returns the first (single) ancestor that matches the passed expression
The returned jQuery object contains zero or one element
**parents()**
Begins with the parent element
Travels up the DOM tree and returns all ancestors that matches the passed expression
The returned jQuery object contains zero or more than one element
To add some info that helped me today, a jQuery object/this
can also be passed in to the .not() selector.
$(document).ready(function(){_x000D_
$(".navitem").click(function(){_x000D_
$(".navitem").removeClass("active");_x000D_
$(".navitem").not($(this)).addClass("active");_x000D_
});_x000D_
});
_x000D_
.navitem_x000D_
{_x000D_
width: 100px;_x000D_
background: red;_x000D_
color: white;_x000D_
display: inline-block;_x000D_
position: relative;_x000D_
text-align: center;_x000D_
}_x000D_
.navitem.active_x000D_
{_x000D_
background:green;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="navitem">Home</div>_x000D_
<div class="navitem">About</div>_x000D_
<div class="navitem">Pricing</div>
_x000D_
The above example can be simplified, but wanted to show the usage of this
in the not()
selector.
SEVERE: Error listenerStart
This boils down to that a ServletContextListener
which is registered by either @WebListener
annotation on the class, or by a <listener>
declaration in web.xml
, has thrown an unhandled exception inside the contextInitialized()
method. This is usually caused by a developer's mistake (a bug) and needs to be fixed. For example, a NullPointerException
.
The full exception should be visible in webapp-specific startup log as well as the IDE console, before the particular line which you've copypasted. If there is none and you still can't figure the cause of the exception by just looking at the code, put the entire contextInitialized()
code in a try-catch
wherein you log the exception to a reliable output and then interpret and fix it accordingly.
You can use []
to extract values from a QueryDict
object like you would any ordinary dictionary.
# HTTP POST variables
request.POST['section'] # => [39]
request.POST['MAINS'] # => [137]
# HTTP GET variables
request.GET['section'] # => [39]
request.GET['MAINS'] # => [137]
# HTTP POST and HTTP GET variables (Deprecated since Django 1.7)
request.REQUEST['section'] # => [39]
request.REQUEST['MAINS'] # => [137]
An iframe
has another scope, so you can't access it to style or to change its content with javascript.
It's basically "another page".
The only thing you can do is to edit its own CSS, because with your global CSS you can't do anything.
moment startOf() and endOf() is the answer you are searching for.. For Example:-
moment().startOf('year'); // set to January 1st, 12:00 am this year
moment().startOf('month'); // set to the first of this month, 12:00 am
moment().startOf('week'); // set to the first day of this week, 12:00 am
moment().startOf('day'); // set to 12:00 am today
In case the host
part is omitted it defaults to the wildcard symbol %
, allowing all hosts.
CREATE USER 'service-api';
GRANT ALL PRIVILEGES ON the_db.* TO 'service-api' IDENTIFIED BY 'the_password'
SELECT * FROM mysql.user;
SHOW GRANTS FOR 'service-api'
According to the matplotlib legend documentation:
The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored).
Thus, one could use:
plt.legend(loc=(x, y))
to set the legend's lower left corner to the specified (x, y)
position.
Do not use passwords. Use peer authentication instead:
postgres://myuser@%2Fvar%2Frun%2Fpostgresql/mydb
The value 1382086394000 is probably a time value, which is the number of milliseconds since 1970-01-01T00:00:00Z. You can use it to create an ECMAScript Date object using the Date constructor:
var d = new Date(1382086394000);
How you convert that into something readable is up to you. Simply sending it to output should call the internal (and entirely implementation dependent) toString method* that usually prints the equivalent system time in a human readable form, e.g.
Fri Oct 18 2013 18:53:14 GMT+1000 (EST)
In ES5 there are some other built-in formatting options:
and so on. Note that most are implementation dependent and will be different in different browsers. If you want the same format across all browsers, you'll need to format the date yourself, e.g.:
alert(d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear());
* The format of Date.prototype.toString has been standardised in ECMAScript 2018. It might be a while before it's ubiquitous across all implementations, but at least the more common browsers support it now.