text:
Q: Cant get `get_image_tag` hook working Im so confussed, can some one tell me why this isnt doing anything ? I've put this in the functions.php file but no matter what hook i try, it doesnt work. I've spent almost 2 days now on this and im left with no ideas.
function lightbox_image( $html, $id, $alt, $title, $align, $size ) {
    return $html."The function is working";
}
add_filter('get_image_tag', 'lightbox_image', 10, 6);

Any help would be greatly appreciated!
Thank you!

A: I found the problem, it was working fine, but this function is ran when you include an image in the text editor. Its not called as the page loads.


text:
Q: Tomcat Performance with Spring Boot API for File Upload I have a Spring boot API and one of the endpoints allows users to upload video's. Now My controller basically takes the file as a MultiPart file and then I store it in a temp folder accessible to tomcat. Once I have it stored on Disk, I then push the video to an S3 bucket.
Now to me anyway, this seems to be less than optimal, Like if I wanted to have a 100 or a 1000 users upload at once it seems really non performant to write the files to disk first.
As a little background I'm storing it on disk with the intention that if there is a issue pushing to S3 I can retry
The below code might show what I'm doing better than the above:
public Video addVideo(@RequestParam("title") String title,
    @RequestParam("Description") String Description,
    @RequestParam(value = "file", required = true) MultipartFile file) {
           this.amazonS3ClientService.uploadFileToS3Bucket(file, title, description));
}

Method for storing Video file:
String fileNameWithExtenstion = awsS3FileName + "." + FilenameUtils.getExtension(multipartFile.getOriginalFilename());

//creating the file in the server (temporarily)
File file = new File(tomcatTempDir + fileNameWithExtenstion);FileOutputStream fos = new FileOutputStream(file);

fos.write(multipartFile.getBytes());

fos.close();PutObjectRequest putObjectRequest = new PutObjectRequest(this.awsS3Bucket, awsS3BucketFolder + UnigueId + "/" + fileNameWithExtenstion, file);

if (enablePublicReadAccess) {
    putObjectRequest.withCannedAcl(CannedAccessControlList.PublicRead);
}

// Upload a file as a new object with ContentType and title

specified.amazonS3.putObject(putObjectRequest);
//removing the file created in the server
file.delete();

So my question is....is there a better way in Tomcat to:
A) Take in a file via a controllerB) Push to S3

A: There is no other way to do it with multipart. The problem with multipart that to properly segement parts from the requst they need sometimes skipped or be repeatable. That is impossible within memory w/o having memory to explode. Therefore, Commons FileUpload caches them on disk after a certain threshold is reached.
Multipart requests are the worst way for that. I highly recommend to use either PUT or POST with content type application/octet-stream. You can take the bare request input stream and pass to HttpClient to stream to your backend server. I did this already 5 years ago and it works for gigabytes. I have posted the solution in the Apache HttpClient mailing list.
There is one possibility how this could work under specific conditions:

*

*All parts are in the correct physical order you want to read

*Your write to a backend is fast enough to sustain the read from the front

Consume the root part and then go over to the next physical one, process the request body lazily. JAX-WS RI (Metro) has a very nice handling of multipart requests for XOP/MTOM. Learn from that because you won't be able to make it any better.

A: Perhaps you can try to direct stream the input stream from your MultipartFile to S3.
Consider the following uploadFileToS3Bucket method:
public PutObjectResult uploadFileToS3Bucket(InputStream input, long size, String title, String description) {
  // Indicate the length of the information to avoid the need to compute it by the AWS SDK
  // See: https://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/s3/model/PutObjectRequest.html#PutObjectRequest-java.lang.String-java.lang.String-java.io.InputStream-com.amazonaws.services.s3.model.ObjectMetadata-
  ObjectMetadata objectMetadata = new ObjectMetadata();
  objectMetadata.setContentLength(size); // rely on Spring implementation. Maybe you probably also can use input.available()
  // compute the object name as appropriate
  String key = "...";
  PutObjectRequest putObjectRequest = new PutObjectRequest(
    this.awsS3Bucket, key, input, objectMetadata
  );

  // The rest of your code
  if (enablePublicReadAccess) {
    putObjectRequest.withCannedAcl(CannedAccessControlList.PublicRead);
  }

  // Upload a file as a new object with ContentType and title

  return specified.amazonS3.putObject(putObjectRequest);
}

Of course, you need to provide the service the input stream obtained from the client request associated with the MutipartFile object:
public Video addVideo(
  @RequestParam("title") String title,
  @RequestParam("Description") String Description,
  @RequestParam(value = "file", required = true) MultipartFile file) {

  try (InputStream input = file.getInputStream()) {
    this.amazonS3ClientService.uploadFileToS3Bucket(input, file.getSize(), title, description));
  }
}

Probably you can also play with the getBytes method of MultipartFile and create a ByteArrayInputStream to perform the operation.
In addVideo:
byte[] bytes = file.getBytes();

In uploadFileToS3Bucket:
ObjectMetadata objectMetadata = new ObjectMetadata();
  objectMetadata.setContentLength(bytes.length);
PutObjectRequest putObjectRequest = new PutObjectRequest(
  this.awsS3Bucket, key, new ByteArrayInputStream(bytes), objectMetadata
);

I would prefer the first solution, but try to determine which option offers you the best performance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: send emails from MY gmail account with OAuth2 and nodemailer I want to send emails from my gmail address through my own server. I'm using nodemailer and using account credentials is flaky, and often times doesn't work and leads to this thread
I've implemented everything on that thread many times, and still it's flaky, and also I know OAuth2 is the way to go.
I have a project with cliendID and clientSecret in google developer console, as you can see:

But how do I get an access token WITHOUT any browser interaction?
I seem to be missing something trivial here ...
I've went through all google tutorials and docs I could find about OAuth2, tokens, and APIs, but all guides go through the browser in one point.

A: Go to the OAuth Playground, click the cog on the top right, check the Use your own OAuth credentials and insert your clientID and clientSecret.
Then select the Gmail API v1 scopes you want in the list to the left and follow the outlined steps and you will get an access_token and a refresh_token.

A: Google Oauth2 actually all Oauth2 implementations I am aware of require that a user grant an application access via a web browser.
There is an alternative type called service accounts this is more like oauth1 service accounts are preauthorized.  You can grant a service account access to your google drive by sharing folders and files with the service account like you would any other user.   Because they are preauthorized there is no browser window pop up with service accounts.
You can only user service accounts with Gmail if you have a Google domains account Gsuite.  The admin can go in and grant the service account access to the Gmail account in question. Perform G Suite Domain-Wide Delegation of Authority
If this is a normal user Gmail account you cant use a service account.   You will have to use Oauth2 popup the request and save the refresh token so that you can gain access at a later date.


text:
Q: How to solve the djongo.exceptions.SQLDecodeError: while trying to run the migrate command I am creating a DjangoRestful app that uses SimpleJWT for authentication. When I try to add the Blacklist app and make migrations. i.e: py manage.py migrate as suggested in the documentation, I get the error below:
Operations to perform:
  Apply all migrations: accounts, admin, auth, contenttypes, main, sessions, token_blacklist
Running migrations:
  Applying token_blacklist.0008_migrate_to_bigautofield...Not implemented alter command for SQL ALTER TABLE "token_blacklist_blacklistedtoken" ALTER COLUMN "id" TYPE long
Traceback (most recent call last):
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\cursor.py", line 51, in execute
    self.result = Query(
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 784, in __init__
    self._query = self.parse()
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 876, in parse
    raise e
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 857, in parse
    return handler(self, statement)
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 889, in _alter
    query = AlterQuery(self.db, self.connection_properties, sm, self._params)
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 425, in __init__
    super().__init__(*args)
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 84, in __init__
    super().__init__(*args)
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 62, in __init__
    self.parse()
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 441, in parse
    self._alter(statement)
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\sql2mongo\query.py", line 500, in _alter
    raise SQLDecodeError(f'Unknown token: {tok}')
djongo.exceptions.SQLDecodeError:

        Keyword: Unknown token: TYPE
        Sub SQL: None
        FAILED SQL: ('ALTER TABLE "token_blacklist_blacklistedtoken" ALTER COLUMN "id" TYPE long',)
        Params: ([],)
        Version: 1.3.6

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\cursor.py", line 59, in execute
    raise db_exe from e
djongo.database.DatabaseError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\core\management\__init__.py", line 425, in execute_from_command_line
    utility.execute()
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\core\management\__init__.py", line 419, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\core\management\base.py", line 373, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\core\management\base.py", line 417, in execute
    output = self.handle(*args, **options)
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\core\management\base.py", line 90, in wrapped
    res = handle_func(*args, **kwargs)
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\core\management\commands\migrate.py", line 253, in handle
    post_migrate_state = executor.migrate(
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\db\migrations\executor.py", line 126, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\db\migrations\executor.py", line 156, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\db\migrations\executor.py", line 236, in apply_migration
    state = migration.apply(state, schema_editor)
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\db\migrations\migration.py", line 125, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\db\migrations\operations\fields.py", line 225, in database_forwards
    schema_editor.alter_field(from_model, from_field, to_field)
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\db\backends\base\schema.py", line 620, in alter_field
    self._alter_field(model, old_field, new_field, old_type, new_type,
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\db\backends\base\schema.py", line 777, in _alter_field
    self.execute(
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\db\backends\base\schema.py", line 153, in execute
    cursor.execute(sql, params)
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\db\backends\utils.py", line 99, in execute
    return super().execute(sql, params)
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\db\backends\utils.py", line 67, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\MR.Robot\.virtualenvs\fsm-GjGxZg3c\lib\site-packages\djongo\cursor.py", line 59, in execute
    raise db_exe from e
django.db.utils.DatabaseError

I should also mention I am using MongoDB as my database.
Here is my installed apps list:
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework_simplejwt.token_blacklist',
    'drf_yasg',
    'main',
    'accounts',
]

When I remove the app from the installed apps and run the command, there is no error.
My package versions:
anyio==3.5.0
asgiref==3.5.0
backports.zoneinfo==0.2.1
certifi==2021.10.8
charset-normalizer==2.0.12
coreapi==2.3.3
coreschema==0.0.4
Django==4.0.2
djangorestframework==3.13.1
djangorestframework-simplejwt==5.0.0
djongo==1.3.6
drf-yasg==1.20.0
idna==3.3
inflection==0.5.1
itypes==1.2.0
Jinja2==3.0.3
MarkupSafe==2.0.1
packaging==21.3
PyJWT==2.3.0
pymongo==3.12.1
pyparsing==3.0.7
pytz==2021.3
requests==2.27.1
ruamel.yaml==0.17.21
ruamel.yaml.clib==0.2.6
sniffio==1.2.0
sqlparse==0.2.4
tk==0.1.0
tzdata==2022.1
uritemplate==4.1.1
urllib3==1.26.8

Does anyone know how to fix this?

A: I've got the same error and I tried one of solutions suggested here:
https://github.com/doableware/djongo/issues/505#issuecomment-841308612, after which everything looks OK but of course there are probably hidden effects (Django migrate --fake and --fake-initial explained).
So in your case you could try smth. like this:
python manage.py migrate --fake token_blacklist 0008

Update:
I also found out that if I remove all old migrations and create them again from scratch there is no such error. It is again probably NOT a safe approach but it worked for me for my test project as my database is empty anyway:
cd your_app_name/migrations/
rm -rf *
cd ../..
python manage.py makemigrations your_app_name
python manage.py migrate

if python manage.py makemigrations your_app_name does not result in creating an initial migration file, then you can try to initiate first empty migration file with python manage.py makemigrations --empty your_app_name and then do the rest.

A: Make AlterField operations no-op.
Add this in manage.py before execute_from_command_line(sys.argv):
if sys.argv[1] == 'migrate':
    from django.conf import settings
    from django.db.migrations import AlterField
    if settings.DATABASES['default']['ENGINE'] == 'djongo':
        AlterField.database_forwards = lambda *_: None
        AlterField.database_backwards = lambda *_: None

References:

*

*Not implemented alter command (doableware/djongo#433)

*delete blacklist migrations (jazzband/djangorestframework-simplejwt#282)
Similar issue reported at django migrate is throwing error after configuring mongodb (doableware/djongo#567).


text:
Q: Ubuntu 22.04 Failed to start: Failure handling of the snapd snap I am just starting to switch to Linux from Windows and just installed Ubuntu 22.04. I managed to install the gnome extension for hiding the top panel and flatpak support, following the instructions in their site and switched my laptop off. After I booted I get a black screen with ext4-fs errors and this:errors screenshot
Note that I have one Sata SSD with Windows 11 on it and Ubuntu is installed on an M2 Sata SSD, so the two operating systems are on different drives. I use a laptop Acer Aspire 3 A315-32, it has intel uhd graphics if it matters. How can I solve this, and if I have to reinstall the system, how to prevent it from happening? Thanks.


text:
Q: Android Layout - UI Objects with the same position How can I have two images stay on top of each other.
In other words, the position of image 1 is exactly the same as the position of the second image; one image is covering the other completely?

A: Use a FrameLayout and then put your two ImageViews inside it. Children of a FrameLayout stack on top of each vertically.

A: I think RelativeLayout is what you are looking for.

A: You should take a look at FrameLayout. Adroid have an example of using FrameLayout. Read up on this good example, and you'll have a better idea of how to tackle your problem.


text:
Q: Difficulty connecting data tables I want to bind these two (df1,df2) datasets:
df1f <- mtcars %>% filter(am == 1)
df1 <- cbind(n = table(df1f$carb),
      prop.table(with(df1f, table(carb, cyl)), margin = 1))

> df1
  n 4         6         8
1 4 1 0.0000000 0.0000000
2 4 1 0.0000000 0.0000000
4 3 0 0.6666667 0.3333333
6 1 0 1.0000000 0.0000000
8 1 0 0.0000000 1.0000000

df2f <- mtcars %>% filter(cyl == 4)
df2 <- prop.table(with(df2f, table(carb, gear)), margin = 1)

> df2
    gear
carb         3         4         5
   1 0.2000000 0.8000000 0.0000000
   2 0.0000000 0.6666667 0.3333333

I tried some functions like cbind(), merge() or list(df1,df2) %>% reduce(bind_rows) but they all resulted in an error message (usually due to the different number of rows)
Is there a way to bind these tables in a way that would result in a side-by-side output like this?
  n 4         6         8     carb         3         4         5
1 4 1 0.0000000 0.0000000        1 0.2000000 0.8000000 0.0000000
2 4 1 0.0000000 0.0000000        2 0.0000000 0.6666667 0.3333333
4 3 0 0.6666667 0.3333333
6 1 0 1.0000000 0.0000000
8 1 0 0.0000000 1.0000000

Thank you!

A: Update
If you have multiple dataframes, you can try Reduce
Reduce(
    function(x, y) {
        cbind(
            x,
            rbind(
                y,
                matrix(nrow = nrow(x) - nrow(y), ncol = ncol(y))
            )
        )
    },
    list(df1,df2,df3,df4,df5,df6)
)

Do you mean something like this?
cbind(
    df1,
    rbind(
        df2,
        matrix(nrow = nrow(df1) - nrow(df2), ncol = ncol(df2))
    )
)

which gives
  n 4         6         8   3         4         5
1 4 1 0.0000000 0.0000000 0.2 0.8000000 0.0000000
2 4 1 0.0000000 0.0000000 0.0 0.6666667 0.3333333
4 3 0 0.6666667 0.3333333  NA        NA        NA
6 1 0 1.0000000 0.0000000  NA        NA        NA
8 1 0 0.0000000 1.0000000  NA        NA        NA


text:
Q: JDBC Cannot connect to mysql I'm trying to connect to mysql db using jdbc,but an exception occurred.Can anyone help me? thx!
driver version is 6.0.6 and mysql db version is  5.7.18.
it seems the error is caused by ArrayIndexOutOfBoundsException,but I really can't figure it out!
code:
    package test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Test {

    @org.junit.jupiter.api.Test
    public void test(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "admin");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

stack
java.sql.SQLNonTransientConnectionException: Could not create connection to database server.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:526)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:513)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:505)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:479)
    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:1779)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:1596)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:633)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:347)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:219)
    at java.sql.DriverManager.getConnection(DriverManager.java:664)
    at java.sql.DriverManager.getConnection(DriverManager.java:247)
    at test.Test.test(Test.java:13)

Caused by: java.lang.ArrayIndexOutOfBoundsException: 39
    at com.mysql.cj.mysqla.io.Buffer.readInteger(Buffer.java:271)
    at com.mysql.cj.mysqla.io.MysqlaCapabilities.setInitialHandshakePacket(MysqlaCapabilities.java:62)
    at com.mysql.cj.mysqla.io.MysqlaProtocol.readServerCapabilities(MysqlaProtocol.java:482)
    at com.mysql.cj.mysqla.io.MysqlaProtocol.beforeHandshake(MysqlaProtocol.java:367)
    at com.mysql.cj.mysqla.io.MysqlaProtocol.connect(MysqlaProtocol.java:1412)
    at com.mysql.cj.mysqla.MysqlaSession.connect(MysqlaSession.java:132)
    at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:1726)
    ... 36 more

A: As Mark said you should downgrade to 5.1.42 driver first. It helped me to at least to see what real error is. In my case it was connection to root account from another host. In you case it might be something else. 6.0.6 really still under development.

A: Use com.mysql.cj.jdbc.Driver (deprecated), instead of com.mysql.jdbc.Driver
And make sure you are using latest version of mysql driver
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.15</version>
</dependency>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/testDB" />
    <property name="username" value="root" />
    <property name="password" value="password" />
</bean>

A: Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "admin");

so u need to check for the port no you have provided in mysql,and also the table name.


text:
Q: iPhone with external hard drive I see there have recently been several products released that offer to give an iOS device access to local mass storage on the order of terabytes via WiFi.  It appears that most if not all of these devices only allow access to the drive through a special (and very limited) iOS app for THAT product.
Via jailbreaking or otherwise, is there a way to use ANY iOS app (for example, photo, audio, and video editing apps) with local Wifi-connected storage?

A: No, it is not possible in iOS and I'll bet it won't be implemented in near future. To be this feature possible, you need at least very fast wifi everywhere.


text:
Q: How to disable past dates in Bootstrap datetimepicker after set check in date I know how to disable past days from current date.
its working with jsfiddle
but my problem is how can I disable previous dates after select check in date.
my jquery
$(function () {

        $('#datetimepicker1').datetimepicker({
            format: 'YYYY-MM-DD'
        });
        $('#datetimepicker2').datetimepicker({
            format: 'YYYY-MM-DD'
        });
        $('#from_date').datetimepicker({
            format: 'YYYY-MM-DD'
        });
        $('#to_date').datetimepicker({
            format: 'YYYY-MM-DD'
        });
    });

my view

            <input type='text' name="from_date" id="from_date" class="form-control" />

            <input type='text' name="to_date" id="to_date" class="form-control" />

    <button class="btn btn-info" id="search">SEARCH</button>

any help please.

A: Have you tried like this
$('#datetimepicker').datetimepicker({  minDate:new Date('2016-10-25')}); //set check in date here

EDIT
For Format date
$('#datetimepicker').datetimepicker({
    format: 'YYYY-MM-DD',
    minDate:new Date('2016-10-25')
});

EDIT
Set From and To Dynamically
Please see jsfiddle

A: In case of  https://tempusdominus.github.io/bootstrap-4/Options/
you can try set the range of allowed dates like
JS
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);

var yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);

$('#datetimepicker1').datetimepicker({
    minDate: yesterday,
    maxDate: tomorrow,
});

A: just override the minDate property in your datetimepicker
var checkin = '2016-10-24';
$('#datetimepicker1').data("DateTimePicker").minDate(checkin);

A: I believe you want to control the end date to be greater than start date, if this is the case below code might help you, it's checking if the start date is less than or equal end date, and if end date is greater than or equal start date, then it sets the minimum time period for bookings, you can set it as you would like, or just set the .minDate('#start').val() to the end date, console log sections are commented out as they are only for debugging purposes:
$('#Start').on("dp.change",
                  function(e)
                  {
                        if (dateSorter($('#End').val(), $(this).val()) === -1 || dateSorter($('#End').val(), $(this).val()) === 0)
                            // if ($('#End').val() < $(this).val())
                        {
                         //   console.log("End date "+$('#End').val()+ " is beofre start date: "+ $(this).val()+" Setting minimum booking period");
                            $('#End').data("DateTimePicker").date(e.date.add(30, 'minutes'));
                        }

                    });
$('#End').on("dp.change",
                 function(e)
                  {
                     if (dateSorter($('#Start').val(), $(this).val()) === 1 || dateSorter($('#Start').val(), $(this).val()) === 0)
                     // if ($('#Start').val() >= $(this).val())
                     {
                        //   console.log("Start date " + $('#Start').val() + " is after end date: " + $(this).val()+" Setting minimum booking period");
                        $(this).data("DateTimePicker").date(e.date.add(30, 'minutes'));
                     }
               });

If you want to add formatting (this is a date time picker), you can use this script:
 $(".datePickerTime").datetimepicker({
        defaultDate: false,
        useCurrent: false,
        showClear: true,
        showClose: true,
        locale: "en-au",
        format: "YYYY-MM-DD hh:mm A",
        sideBySide: true,
        toolbarPlacement: "bottom"

    });

For only a date picker use as:
 $(".datePicker").datetimepicker({
        defaultDate: false,
        useCurrent: false,
        showClear: true,
        showClose: true,

    locale: 'en-au',
    format: 'YYYY-MM-DD'
});


text:
Q: How can I pack up multiple functions in a single widget? I want to pack some func. in a single widget so that I can interact with that particular widget using bind func.
There's Frame widget which packs up widgets in it and canvas.create_window func. in Canvas widget which also does the same as Frame.
Following program generates sticman after every 3 sec. And when user click the stickman, it disappears.
I tried using Frame to pack functions ...
    from Tkinter import *
    root = Tk()

    hitbox = Frame(root, height = 100, width= 100)
    hitbox.pack()
    can = Canvas(hitbox, height= 450, width= 1000)   # Canvas inside hitbox
    can.pack()

    def stickman (a,b,c,d):
        # Code that makes stickman according to coordinates

    def HP(p,q):
        # Code that makes Progressbar widget inside hitbox which act as healthbar

    counter = 0
    def init():
        if counter == 10:
            pass
        else:
            counter +=1
            stickman(100,100,130,130)
            HP(90, 120)
            root.after(3000, init)    # Stickman respawns after 3 seconds

    def kill():
        hitbox.destroy()

    hitbox.bind('<Button-1>', kill)
    root.mainloop()

Stickman respawns after every 3 seconds but bind func. with frame does not seems to be working when running code. Stickman doesn't disappears when clicked.

A: I think what you are asking for is to destroy the Tkinter frame when Button 1 or the left button on the mouse is clicked. The stickman doesn't disappear because the frame isn't actively listening for the key click unlike a label or an entry field would do.
So, there are 2 easy fixes for this problem:
1. Binding to Root Window
Binding the keybind to the root window would solve the problem mostly because the root window is always actively listening for keybinds unlike the frame or an input field. The only problem with this approach is that the user can click anywhere on the window to destroy the frame.
2. Binding to the Stickman Itself
Binding the keybind to the stickman itself is the cleanest approach because it would be just the same as the first solution but this time the user can only click on the stickman to destroy the frame. This is probably the solution you were looking for. To implement this solution just replace the root.bind('<Button-1>', kill) with stickman.bind('<Button-1>', kill) (or whatever the name is of your stickman is) after defining the stickman but before packing it.

I atatched a modified version of your code down below for the first option:
from tkinter import *
root = Tk()

def kill(event=None):
    hitbox.destroy()

root.bind('<Button-1>', kill)
hitbox = Frame(root, height = 100, width= 100)
hitbox.pack()
can = Canvas(hitbox, height= 450, width= 1000)   # Canvas inside hitbox
can.pack()

def stickman (a,b,c,d):
    pass
    # Code that makes stickman according to coordinates

def HP(p,q):
    pass
    # Code that makes Progressbar widget inside hitbox which act as healthbar

counter = 0
def init():
    if counter == 10:
        pass
    else:
        counter +=1
        stickman(100,100,130,130)
        HP(90, 120)
        root.after(3000, init)    # Stickman respawns after 3 seconds

root.mainloop()


text:
Q: SQL Server, Converting a select mechanism from "and" into "or" I have a web based program which chooses some records from a database using a checkboxlist. (my check box list sends parameters to a stored procedure and I use the result of stored procedure).
Here how my check box list looks like
Overflow              [] (sends param1)
Open Records          [] (sends param2)
Records with 4 groups [] (sends param3)

Here how my stored procedure looks like,
SELECT * FROM myRecordsTable WHERE
        (Overflow LIKE '%O%' OR @param1= 'No')
        AND (OpenClose= 'Open' OR @param2= 'No')
        AND (4orMore = '4orMore' OR @param3 = 'No')

So as you can see, my check box lists works like "And" procedure, in other words, when I check Overflow and Open records in my checkboxlist, my stored procedure will return (Open records which has Overflow)
What I like to do is I want my check box list to work like "Or", in other words, I want to be able to get (Open records  "OR" records which has Overflow)
Important PS: I can't have two stored procedures (1 for OR and 1 for AND) since my procedures are not that short like the example above, because once I change something in one procedure I will have to do the exact same changes in the second one and that is not good coding.
Important PS2: I don't want to corrupt the structure of the stored procedure. I want to use my stored procedure as "AND" or "OR" whenever I want (using another parameter maybe), and the way I tried to do this was using dynamic sql as in the link below
SQL Server, Can a T-SQL operator be used like a variable ? Or something like that
but I couldn't manage to solve it.
Thanks for helps.
Edit: Here I will give an example to show the problem more clearly
Below code, nothing is selected in checkboxlist, returns 42703 (Remember this number) rows
declare @op varchar(3)
set @op = 'AND'

declare @query nvarchar(4000)
set @query =
'
SELECT ASIM, SonGrup, DortUzeri FROM CacheOPERASYONELRawKayitlar WHERE
'
set @query = @query + '(ASIM LIKE ''%S%'' OR ''No''=''No'') '+@op+' '

set @query = @query + '(SonGrup LIKE ''Son Grup'' OR ''No''=''No'') '+@op+' '

set @query = @query + '(DortUzeri LIKE ''Dört ve Üzeri'' OR ''No''=''No'') '
exec(@query)

Below code ASIM is selected, returns 9349 rows
declare @op varchar(3)
set @op = 'AND'

declare @query nvarchar(4000)
set @query =
'
SELECT ASIM, SonGrup, DortUzeri FROM CacheOPERASYONELRawKayitlar WHERE
'
set @query = @query + '(ASIM LIKE ''%S%'' OR ''Yes''=''No'') '+@op+' '

set @query = @query + '(SonGrup LIKE ''Son Grup'' OR ''No''=''No'') '+@op+' '

set @query = @query + '(DortUzeri LIKE ''Dört ve Üzeri'' OR ''No''=''No'') '
exec(@query)

I won't give the same code anymore, because the logic is same, the "No" turns into "Yes" when the checkbox list is selected, and this is the structure of the code.
ASIM and SonGrup is selected returns 5885 rows
ASIM and SonGrup and DortUzeri is selected returns 1385 rows
The above code works perfectly with AND, so when I wanted to use OR Operator I should get the result 37696 , which is the result of the below code
SELECT ASIM, SonGrup, DortUzeri FROM CacheOPERASYONELRawKayitlar WHERE
ASIM LIKE '%S%' OR SonGrup LIKE 'Son Grup' OR DortUzeri LIKE 'Dört ve Üzeri'

So I executed the code with OR operator where the three checkbox list components is selected, the code is below and it returns 37696 , which is correct.
declare @op varchar(3)
set @op = 'OR'

declare @query nvarchar(4000)
set @query =
'
SELECT ASIM, SonGrup, DortUzeri FROM CacheOPERASYONELRawKayitlar WHERE
'
set @query = @query + '(ASIM LIKE ''%S%'' OR ''Yes''=''No'') '+@op+' '

set @query = @query + '(SonGrup LIKE ''Son Grup'' OR ''Yes''=''No'') '+@op+' '

set @query = @query + '(DortUzeri LIKE ''Dört ve Üzeri'' OR ''Yes''=''No'') '
exec(@query)

The problem arises when one of the checklist components is not checked, here is the 3rd component is not checked version of the code,
declare @op varchar(3)
set @op = 'OR'

declare @query nvarchar(4000)
set @query =
'
SELECT ASIM, SonGrup, DortUzeri FROM CacheOPERASYONELRawKayitlar WHERE
'
set @query = @query + '(ASIM LIKE ''%S%'' OR ''Yes''=''No'') '+@op+' '

set @query = @query + '(SonGrup LIKE ''Son Grup'' OR ''Yes''=''No'') '+@op+' '

set @query = @query + '(DortUzeri LIKE ''Dört ve Üzeri'' OR ''No''=''No'') '
exec(@query)

The above code should have returned 34613 which I found using the following
SELECT ASIM, SonGrup, DortUzeri FROM CacheOPERASYONELRawKayitlar WHERE
ASIM LIKE '%S%' OR SonGrup LIKE 'Son Grup'

However it returns 42703 (The number which I wanted you to remember caused because of ''No''=''No'') , that is where my problem arises. Here I couldn't find the solution.

A: You should use dynamic sql - as well as the syntax being easier on the eye it will also give your query a better chance of performing.
If you can, then I would probably construct the dynamic sql in your application rather than in the stored procedure, however if you really have to call a stored procedure then that also works:
Disclaimer: I never usually write dynamic SQL inside a stored procedure, and I also don't have SQL server installed on this machine to make sure that the following works, however hopefully this should be of some help:
declare @op varchar(3)

IF @operator = "AND"
    set @op = "AND"
ELSE
    set @op = "OR"

declare @query varchar(max)
set @query = "select * from myRecordsTable WHERE" +

IF @param1 <> "No"
    set @query = @query + " Overflow LIKE '%O%' " + @op
IF @param2 <> ' No'
    set @query = " OpenClose = 'Open' " + @op

IF @operator = "AND"
    set @query = @query + " 1=1"
IF @operator = "OR"
    set @query = @query + " 1=0"

exec(@query)

Important parts to note:

*

*I test the value of @operator explicitly to avoid SQL injection (never trust your caller)

*I use 1=1 and 1=0 to avoid complicated logic with operators due to not knowing which of my conditions will be the first or the last.  SQL server optimiser will optimise this away as a tautology early in the optimisation process.


text:
Q: Vector adds element, but shortly after removes it First, my code (shortened):
import java.util.Vector;

public class GameField {

    private Vector rooms = new Vector();

    public void generateRooms() {
        for (int i = 0; i < 10; i++) {
            rooms.add(new Room(x, y, width, height));
        }
    }
}

I know the class Vector is generic, but we haven't learned those yet and we should use it like this.
When I call the method generateRooms() it doesn't add ten rooms as expected, but adds one room every loop and removes the room again if it comes to the beginning of the loop.
At the end, I only have one room in the Vector, instead of ten.
Why is this so? Is it because I don't use generic types or what else causes this behaviour?

A: I make the generateRooms function return the room vector  , and it works OK :
public class Room {

    int x;
    int y;
    int width;
    int height;

    public Room(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
}
class Main {

    private Vector rooms = new Vector();

    public Vector generateRooms() {
        for (int i = 0; i < 10; i++) {
            rooms.add(new Room(1 * i, 2, 3, 4));
        }
        return rooms;
    }

    public static void main(String[] args) {
        Main m = new Main();
        Vector r = m.generateRooms();
        for (int i = 0; i < 10; i++) {
            Room room = (Room) r.get(i);
            System.out.println(room.x + "   " + room.y + "   " + room.width + "    " + room.height);
        }
    }
}


text:
Q: Laravel can't change config value I found the problem, i'll try to use a homestead or docker.

if i restart php artisan serve the changed values are applied.

Same my post: Laravel can't change config value

I make route
Route::get('/config', function () {
    return dd(config('app'));
});

And cant change my config/app.php, for example i want to change
'url' => env('APP_URL', 'test'),
'client_url' => env('APP_CLIENT_URL', 'test'),

I set
APP_CLIENT_URL=str1
APP_URL=str2

and there is something inexplicable:
My "url" => "http://127.0.0.1:8000" !!! not default 'test' or from .env, I did not set such a value.
My client_url contains the old value, after I cached the config.
This is not production, i accidentally run config:cache, but after i remove all cache from bootsrap/cache, storage/framework/cache and running cache:clear, config:clear.
After running config:cache values from the .env were put in config, but I do not want to constantly change cache in development and it is not recommended in the documentation.
How can I easily change .env in in developing?


text:
Q: Few files upload from device to server out of pushed list I wrote two different code to try to upload selected files to server, but none of them is uploaded all the files available in list though both codes show uploading complete without any error.  pls help to fix it.
Thread up = new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            String content_type = getMimeType(filespath.get(ina));
                                            OkHttpClient okHttpClient = new OkHttpClient();
                                            RequestBody requestBody = RequestBody.create(MediaType.parse(content_type), new File(filespath.get(ina)));

                                            RequestBody requestBody1 = new MultipartBody.Builder()
                                                    .setType(MultipartBody.FORM)
                                                    .addFormDataPart("type", content_type)
                                                    .addFormDataPart("myFile", filespath.get(ina).substring(filespath.get(ina).lastIndexOf("/") + 1), requestBody)
                                                    .addFormDataPart("location", titlevalue + "/")
                                                    .build();

                                            Request request = new Request.Builder().url("MyPHP URL")
                                                    .post(requestBody1)
                                                    .build();
                                            try {
                                                Response response = okHttpClient.newCall(request).execute();

                                                if (!response.isSuccessful()) {
                                                    Log.i(TAG, "Error");
                                                }
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    });

                                    up.start();

filespath is String Arraylist with path of all files being uploaded and this Thread is called in Forloop of same.
Other method tried is as follows:
 HttpClient httpClient = new DefaultHttpClient();
                                            MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
                                            FileBody fileBody = new FileBody(new File(filespath.get(ina)));
                                            multipartEntity.addPart("myFile", fileBody);
                                            multipartEntity.addTextBody("location", titlevalue + "/");

                                            HttpEntity httpEntity = multipartEntity.build();

                                            HttpPost httpPost = new HttpPost("MyPHP URL");
                                            httpPost.setEntity(httpEntity);

                                            try {
                                                HttpResponse httpResponse = httpClient.execute(httpPost);
                                                Log.i(TAG, "Http Re" + httpResponse);
                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }

I did few trials to check like when I selected only 20 Images, all uploaded and I got ok response too. Where as when I tried with 40 images, I could upload only 32 with ok response, where as for remaining 8, there was no response.
pls guide, what I m missing.
See Logcat 9 files uploaded where as on server I found only 4. (numbered 1,2,3,4)


text:
Q: JPA get foreign key without loading related record I am trying to optomize some reports and am trying to remove the need to load some expensive related records(multiple cascade loads, on each of ~500+ records).
My entity's are something like this:
@Entity
@Table(name="foo")
public class Foo
{
    @Id
    @Type(type = "pg-uuid")
    private UUID id;
...
    public UUID getId(){
        return id;
    }

and:
@Entity
@Table(name="bar")
public class Bar
{
    @Id
    @Type(type = "pg-uuid")
    private UUID id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="FOO_ID")
    private Foo foo;
...

    public UUID getFooId(){
        return foo.getId();
    }

My issue is that when i make this call: return foo.getId(); hibernate goes and instantiates the Foo entity, and loads all related records even though i only want/need the id, which is a foreign key in my Bar table.
Is there any way to get Foo.Id from Bar without loading the Foo record?
Thanks in advance.

A: Try mapping the FOO_ID column as a basic mapping instead or in addition to the existing Foo reference mapping:
@Entity
@Table(name="bar")
public class Bar
{
    @Id
    @Type(type = "pg-uuid")
    private UUID id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="FOO_ID")
    private Foo foo;

    @Column(name="FOO_ID", insertable=false, updatable=false)
    private UUID fooId;
...

    public UUID getFooId(){
        return fooId;
    }

You can then decide to use fooId in queries to avoid joins. Because it is read-only, the FK value is still set from the foo reference - there may be some issues with a cache if you set the reference and not the fooId UUID; you can either set it yourself, or force a refresh to have JPA do it for you.

A: Hibernate thinks that getFooId() is a method that can potentially use any field of Bar. Hibernate can't check which fields exactly are used by the method, so it loads all lazy associations just in case.
You can use @Transient to avoid this
@Transient
public UUID getFooId(){
    return foo.getId();
}


text:
Q: How to write paginated controller that expose resource or list of resource in spring-data-hatoas Using spring-data, I want to write two method for my Person entity.
Person.java:
public class Person {
    @Id
    String id;
    String name;
    Integer age;
    // getters/setters omitted for clarity
}

I have written also a PersonResouce:
public class PersonResource extends Resource<Person> {

    public PersonResource(Person content, Link... links) {
        super(content, links);
    }

}

I have also added a PersonResourceAssembler:
public class PersonResourceAssembler extends ResourceAssemblerSupport<Person, PersonResource> {

    public PersonResourceAssembler() {
        super(PersonController.class, PersonResource.class);
    }

    public PersonResource createResource(Person person) {
        PersonResource personResource = new PersonResource(person);
        Link link = linkTo(PersonController.class).slash(person.getId()).withSelfRel();
        personResource.add(link);
        return personResource;
    }

    @Override
    public PersonResource toResource(Person person) {
        PersonResource resource = createResource(person);
        return resource;
    }
}

And this is my PersonController:
@RestController
@RequestMapping("persons")
public class PersonController {

  @Autowired
  private PersonService personService;

  @GetMapping
  public HttpEntity<List<PersonResource>> showAll(@PageableDefault(size = 20) Pageable pageable, PersonDTO condition) {
    Page<Person> page = personService.findAll(pageable, condition);
    Iterable<Person> personList = page.getContent();
    PersonResourceAssembler assembler = new PersonResourceAssembler();
    List<PersonResource> resources = assembler.toResources(personList);
    return new HttpEntity<>(resources);
  }

  @RequestMapping(name = "{id}", produces= MediaType.APPLICATION_JSON_VALUE)
  public HttpEntity<PersonResource> showOne(@PathVariable("id") Long id, PersonDTO condition) {
    condition.setId(id);
    Person person = personService.get(id);
    PersonResourceAssembler assembler = new PersonResourceAssembler();
    PersonResource resource  = assembler.toResource(person);
    return new HttpEntity<>(resource);
  }

}

This is the response for the list:
[
  {
    "createdById": 1,
    "createdDate": "2017-09-21T10:21:05.741Z",
    "deleted": false,
    "email": null,
    "firstName": "User49",
    "id": 52,
    "lastModifiedById": null,
    "lastName": "robot",
    "links": [
      {
        "href": "http://localhost:8080/users/52",
        "rel": "self"
      }
    ],
    "middleName": null,
    "mobile": "010101010001149",
    "roleList": [
      {
        "createdById": null,
        "createdDate": "2017-09-21T10:21:05.580Z",
        "deleted": false,
        "id": 2,
        "lastModifiedById": null,
        "name": "USER",
        "userList": null,
        "version": 0
      }
    ],
    "username": "user49",
    "version": 0
  }
]

This is the response for one resource :
{
  "_links": {
    "self": {
      "href": "http://localhost:8080/users/52"
    }
  },
  "createdById": 1,
  "createdDate": "2017-09-21T10:21:05.741Z",
  "deleted": false,
  "email": null,
  "firstName": "User49",
  "id": 52,
  "lastModifiedById": null,
  "lastName": "robot",
  "middleName": null,
  "mobile": "010101010001149",
  "roleList": [
    {
      "createdById": null,
      "createdDate": "2017-09-21T10:21:05.580Z",
      "deleted": false,
      "lastModifiedById": null,
      "name": "USER",
      "userList": null
    }
  ],
  "username": "user49"
}

I've looked at the documentation and it appear possible to use PagedResources to create pagination.
I also want my response to look like the RepositoryRestController response which means for the list reponse :

*

*put entities under key "_embedded"

*put links under key "_links"

*put page under key "page"

I have tried to play a bit with PagedResources but it appear to work differently than Resource and can't just replace it.
I would like to see a Controller/Assembler that use the PagedResource.
Solution
solution for me was to do like this
  @GetMapping
  public ResponseEntity<?> findAll(PagedResourcesAssembler<Person> pageAssembler, @PageableDefault(size = 20) Pageable pageable, UserDTO condition) {
    Page<User> userList = userService.findAll(pageable, condition);
    PagedResources<?> resources = pageAssembler.toResource(userList, new UserResourceAssembler());
    return ResponseEntity.ok(resources);
  }

A: Try to use PagedResourcesAssembler to build paged resources:
@RestController
@RequestMapping("persons")
public class PersonController {

    @Autowired private PersonService personService;
    @Autowired private PagedResourcesAssembler<Person> assembler;
    @Autowired private EntityLinks links;

    @GetMapping("/paged")
    public ResponseEntity<?> getPaged(Pageable pageable) {
        Page<Person> personsPage = personService.getPaged(pageable);

        Link pageSelfLink = links.linkFor(Person.class).slash("/paged").withSelfRel();
        PagedResources<?> resources = assembler.toResource(personPage, this::toResource, pageSelfLink);

        return ResponseEntity.ok(resources);
    }

    private ResourceSupport toResource(Person person) {
        Link pesonLink = links.linkForSingleResource(person).withRel("person");
        Link selfLink = links.linkForSingleResource(person).withSelfRel();
        return new Resource<>(person, personLink, selfLink);
    }
}

See my example.


text:
Q: Viewing the color (#xxxxxx) of the element under the cursor What would be the easiest way to view the color values (guifg and guibg) of the highlighting element that the cursor is currently on?

A: Figures, found it in help. In case anyone ever needs this ...
nmap <F11> :call <SID>SynColour()<CR>

function! <SID>SynColour()
echo "guibg = ".synIDattr(synIDtrans( synID(line("."), col("."), 1) ), "bg#").", guifg = ".synIDattr(synIDtrans( synID(line("."), col("."), 1) ), "fg#")
endfunction

A: For syntax script development (why else would you need the editor color?), you'll also need the syntax group and linked highlight group names. The SyntaxAttr plugin provides this in a nice mapping, e.g.:
group: vimUserFuncName guifg=DarkCyan(#008b8b) gui=bold


text:
Q: Redirect All Request from web server to another I have to make an application in tomcat which core responsibility is to redirect all request coming from browser application to API server. It works like proxy server between browser application and API application. Have to write it on tomcat. How can i achieve this, do i have write a REST API application on tomcat too?
Project Description
Requirement is like we have two application one is developed on React, its a web-portal and the other one is on spring-boot as a backend application (json apis).
spring-boot application is going to be deployed on secure zone and web-portal is in DMZ. web-portal in on internet, backend application is on intranet. As web-portal is a CSR application so the api's calls from web-portal contains backend application IP/URI but it cannot be accessible from internet.
So i am planning to write an application on DMZ zone and it will be deployed on apache tomcat, so like when request comes at tomcat it redirect it to backend application server which is on intranet with all headers/payload and redirect response from backend server to web-portal.

A: You want to set up a reverse proxy which is a standard pattern. Take a look at the answers at Reverse Proxy Java or just search the web for "reverse proxy java".
If you are not bound to implement it in java take a look at Nginx which we use in many projects to transfer the request from the web app to the REST backend.


text:
Q: Reference Color from Data Frame in ggplot2 MWE:
library(ggplot2)
library(dplyr)

df <- data.frame(GROUP = factor(c("AL", "AS", "B", "HI", "I", "P", "T", "W", "E", "NE", "EL", "EP", "SW", "SOD"), ordered = TRUE),
                 color.codes = c("#000000",
                                 "#b05cc6",
                                 "#afb045",
                                 "#7777c8",
                                 "#db8f47",
                                 "#4dacd0",
                                 "#cb5242",
                                 "#56b88f",
                                 "#c75a88",
                                 "#5db74e",
                                 "#4f7e3b",
                                 "#ff0000",
                                 "#8d7134",
                                 "#000080"),
                 Year = rep(paste0(2010:2025, "-", 2011:2026), each=14),
                 value = runif(224))

df$Year <- factor(df$Year,
                  levels=sort(unique(df$Year)),
                  ordered=TRUE)

ggplot(df,
               aes(x = Year, y = value, color = GROUP, group = GROUP)) +
  geom_point() +
  geom_line(linetype = "dotted") + # make all dotted by default
  geom_line(data = (df %>% filter(Year <= "2014-2015")),
            aes(x = Year, y = value, color = GROUP),
            lty = "solid") + # and then make all prior to 2015 solid
  scale_color_manual(values = df$color.codes) +
  xlab("School Year") +
  ylab("Proficiency Rate")

Let's examine the data frame:
> head(df)
  GROUP color.codes      Year     value
1    AL     #000000 2010-2011 0.5540173
2    AS     #b05cc6 2010-2011 0.0301139
3     B     #afb045 2010-2011 0.7469069
4    HI     #7777c8 2010-2011 0.4981707
5     I     #db8f47 2010-2011 0.9677573
6     P     #4dacd0 2010-2011 0.7777855

For example, #b05cc6, according to Google, is something of a purple shade. But it clearly looks red, despite that it's supposed to be purple.
It also doesn't make any sense that B has the same color as AL. How can this be fixed?

A: Make a palette of group names and colour code mappings:
pal = unique(df[,c("GROUP","color.codes")])

> head(pal)
  GROUP color.codes
1    AL     #000000
2    AS     #b05cc6
3     B     #afb045
4    HI     #7777c8
5     I     #db8f47
6     P     #4dacd0

Fixup color codes to be character and not factor, or else they get converted to numeric and looked up in the palette:
> pal$color.codes=as.character(pal$color.codes)

Now create a named vector from the palette columns:
> pval = pal$color.codes
> names(pval) = pal$GROUP
> pval
       AL        AS         B        HI         I         P         T         W
"#000000" "#b05cc6" "#afb045" "#7777c8" "#db8f47" "#4dacd0" "#cb5242" "#56b88f"
        E        NE        EL        EP        SW       SOD
"#c75a88" "#5db74e" "#4f7e3b" "#ff0000" "#8d7134" "#000080"

Then use that in scale_color_manual(values=pval).
Now AS looks purply, B looks like a sort of greeny vom colour.

EP looks red. etc.


text:
Q: Javascript OOP / Classes I'm sure this question has been asked before, but I can't seem to find the right and/or best format for it.  Basically, I am trying to develop some custom Javascript classes for use within my site.  I'd like to be able to call them as follows:
MasterClass.SubClass.function(params);

Any help would be greatly appreciated.  Thanks!

A: The easiest is to form this structure using object literals:
MasterClass = {
    SubClass: {
        fn: function(params) {
        }
    }
}

When you want to spread this across multiple source files, you could do this:
MasterClass = {}

Then, in each additional source file:
(function(ns) {
    ns.SubClass = {
        fn: function(param) { }
    }
}(MasterClass));

A: Based on your single line of pseudocode, this fits the bill:
var MasterClass = {
    SubClass: {
        myFunction: function(params) {
            // snip
        }
    }
};

A: just to do things differently you could use prototype as well and not have to type out MasterClass each time
 function MasterClass () {
     this.prop = "test"
 }

 function SubClass () {
    this.func = function () {
    return this.prop
   }
}

 SubClass.prototype = new MasterClass()

 var subclass = new SubClass()
 subclass.func() //return "test"


text:
Q: Add variable to existing string IF (@countryCode=="A") THEN
    @para1from = "America"
ELSEIF (@countryCode=="I") THEN
    @para1from = "India"
ENDIF

SET @paragraph1 = "I am from %%=(v(@para1from))=%%."

But when I send the email, its shown as "I am from %%=(v(@para1from))=%%."

A: You've misplaced the v function name - try without the additional parentheses:
IF (@countryCode=="A") THEN
    @para1from = "America"
ELSEIF (@countryCode=="I") THEN
    @para1from = "India"
ENDIF

SET @paragraph1 = "I am from %%=v(@para1from)=%%."

Alternatively, you can use a concat function to get the same result:
IF (@countryCode=="A") THEN
    @para1from = "America"
ELSEIF (@countryCode=="I") THEN
    @para1from = "India"
ENDIF

SET @paragraph1 = Concat("I am from ", @para1from)


text:
Q: Javascript: getElementbyID width issues following a javascript tutorial on youtube, learning the basics.
Have the following code here which line for line is the same as I see it (excluding maybe variable names).
Tried to debug and see that alert and console messages go through but the document.getElementByID.style.width seems to get me nothing.
width is a defined variable (yes should have named it differently to not clash with keyname width but did change name and same results anyway).
Having console.log as the outputs.
Outputs width fine and it does increment.
the actual image doesn't move an inch however.
Can't see any typos.
The code is exactly the same as the tutorial.
Looked it over for nearly an hour already.
Any help is appreciated.  It's not much, very basic, but I don't want to skip out on understanding why something doesn't work, thanks.

let width =200;
let diff = 2;

let intervalID = 0;

function increase() {
  intervalID = setInterval(zoomIn, 20);
}

function zoomIn() {
  if (width < 400) {
    width = width + diff;
    document.getElementById("img2").style.width = width;
    console.log(width);
    console.log(document.getElementById("img2").style.width);
  } else {
    clearInterval(intervalID);
  }
}
<img id="img2" onmouseover="increase()" onmouseout="decrease()" src="/Images/image.png" alt="img" width="200" />

A: width = 1;
function increase() {
  intervalID = setInterval(zoomIn, 20);
}

function zoomIn() {
  if (width < 400) {
    width++;
    document.getElementById("img2").style.width = width;
    console.log(width);
    console.log(document.getElementById("img2").style.width);
  } else {
    clearInterval(intervalID);
  }
}

increase();

Example is here

A: The object.style.width property gets an String composed by the number + the px word not only a number, also if you dont have the decrease method you have going to have an undefined exception:
let width =200;
let diff = 2;

let intervalID = 0;

function increase() {
  intervalID = setInterval(zoomIn, 20);
}

function zoomIn() {
  if (width < 400) {
    width = width + diff;
    document.getElementById("img2").style.width = width + "px"; // You assign for example 30px as String
    console.log(width);
    console.log(document.getElementById("img2").style.width);
  } else {
    clearInterval(intervalID);
  }
}

Example: Code on Jsffidle


text:
Q: ng-repeat doesn't fire the second time after $scope changes I'm new to Angular and trying to create a filtering mechanism that fires a  search when typing a letter, looking it up the db and returning results.
The results are returning ok from the DB, but the issue i'm having is when i'm filling the scope array with the results and ng-repeat doesn't fire.
my HTML and JS:

    app.controller("friendsController",function($scope,$http){
        $scope.results =[];
        $scope.onTextChange = function (){
            var results = [];
            var text = $scope.friendsLookupText;
            $http({
                url: 'utilities/getFriendsByValue.php',
                method: 'POST',
                data: {textValue: text}
            }).success(function(data) {
                if(data=="none")
                {
                    $scope.results = results;
                }
                else
                {
                    var stringResult = JSON.stringify(data);
                    var parsedResult = JSON.parse(stringResult);
                    $scope.results = parsedResult;
                }
            });

        };
    });

  <input type="text" id="friendsLookupText" ng-model="friendsLookupText" ng-change="onTextChange()">

{{result.username}}

I'll be glad if anyone could help.

A: Remove $scope from the repeat in the view, use only results

{{result.username}}


text:
Q: Prevent scrolling of parent container when scrolling in overflow:scroll container has reached its limits Simply put, i guess you all know the issue: you use your mousewheel (or trackpad gesture) to scroll inside a div that is set to overflow:scroll (or a setting to that effect). The moment you reach the end of the scrollable area, the scroll 'commands' are immediately sent to the parent container - the main window for instance.
This can be quite annoying and i wonder if there is a way to prevent it.
I created this jsFiddle to demonstrate the issue and provide a ground for experimentation.
The only idea that came to my mind was using preventDefault but since i am not a JS wizard, i don't see where or how i could apply that correctly.

A: This is not optimal but I bootstrap uses this for their modal windows.
FIDDLE
.overflowHidden {
    overflow:hidden !important;
}

$('#scrollable').hover(function () {
        console.log("hello");
        $('body').addClass('overflowHidden');
    }, function () {
        $('body').removeClass('overflowHidden');
    });

A: After extensive research and violent testing, i combined my results into a solution that serves my purpose perfectly.
The approach is simple
Instead of measuring scroll conditions (on scroll) from within a container, we simply replace the entire scroll functionality by writing our own scroll handler. That way we have complete control over what is happening, plus the scroll event cannot default (or bubble) to the outer container:
Meet greedyScroll v0.9b
$.fn.extend({
    greedyScroll: function(sensitivity) {
        return this.each(function() {
            $(this).bind('mousewheel DOMMouseScroll', function(evt) {
               var delta;
               if (evt.originalEvent) {
                  delta = -evt.originalEvent.wheelDelta || evt.originalEvent.detail;
               }
               if (delta !== null) {
                  evt.preventDefault();
                  if (evt.type === 'DOMMouseScroll') {
                     delta = delta * (sensitivity ? sensitivity : 20);
                  }
                  return $(this).scrollTop(delta + $(this).scrollTop());
               }
            });
        });
    }
});

Usage
HTML:

Javascript:
$('.scrollWrapper').greedyScroll(25);

I found a value of 20 works fine for sensitivity, but some may prefer higher or lower settings.
Disclaimer
I don't claim this works in anything other than Chrome, as this is what i exclusively made sure it works for.
Credits go almost entirely to the team who developed the plugin i linked to in one of the comments to Lokesh's answer.
Code improvements are always welcome.


text:
Q: Javascript/Jquery Pomodoro Clock: Display issue when clock is running I am trying to build a simple Podomoro Clock and I'm having an issue with the increment and decrement controls.I want the user to ONLY control the increment/decrement display when the timer is paused(stopped) but instead what happens is the timer display can be controlled no matter what even if the timer is running or stopped.
Here is my code:
HTML

FreeCodeCamp Podomoro

Break Time

      <button class="btn btn-danger" id="breakMinus">-</button>

5

      <button class="btn btn-success" id="breakPlus">+</button>

Pomodoro Time

      <button class="btn btn-danger" id="workMinus">-</button>

25

      <button class="btn btn-success" id="workPlus">+</button>

Work

      26

      <button class="btn btn-success" id="startBtn">Start</button>
      <button class="btn btn-danger" id="stopBtn">Stop</button>

JS
 $(document).ready(function() {
  var pomoTime = $('#pomodoroNum');
  var breakTime = $('#breakNum');
  var status = $('#timerStatus');
  var timerDisplay = $('#timer');
  var startButton = $('#startBtn');
  var stopButton = $('#stopBtn');
  var state = 1; // 1=stopped 2=running
  var pomoVal = 24;
  var breakVal = 4;
  var countDown;

  startButton.click(function() {
    if (state == 1) { // if timer is not running then start timer
      state = 2;
      startTimer(pomoVal);

    };
  });

  stopButton.on("click", function() {
    if (state == 2) {
      pauseTimer();
      state = 1;
    }
  });

  updateDisplay();

  function startTimer(time) {

    var minutes = time;
    var seconds = 60;

    countDown = setInterval(function() {

      seconds--;
      minutes = ("0" + minutes).slice(-2); // double digits conversion if <10
      seconds = ("0" + seconds).slice(-2);

      timerDisplay.html(minutes + ":" + seconds);

      if (seconds == 0) {
        minutes-- // decerement minutes when seconds 0...
        seconds = 60; // ..and reset seconds to 60
      }

      if (minutes < 0) {
        clearInterval(countdown);
      }

    }, 1000);

  };

  function pauseTimer() {

    clearInterval(countDown);
  };

  function updateDisplay() {
    if (status == 2) {
      return false;
    }
    $('#breakMinus').on("click", function() {
      status.html("Break");
      if (breakTime.html() > 1) {
        breakTime.html(parseInt(breakTime.html()) - 1);
      };
      timerDisplay.html(breakTime.html());
    });

    $('#breakPlus').on("click", function() {
      status.html("Break");
      breakTime.html(parseInt(breakTime.html()) + 1); // parseInt to covert string into number so it doesn't concatanate.
      timerDisplay.html(breakTime.html());
    });

    // work minus and plus
    $('#workMinus').on("click", function() {
      status.html("Work");
      if (pomoTime.html() > 1) {
        pomoTime.html(parseInt(pomoTime.html()) - 1);
      };
      timerDisplay.html(pomoTime.html());
    });

    $('#workPlus').on("click", function() {

      status.html("Work");
      pomoTime.html(parseInt(pomoTime.html()) + 1); // parseInt to covert string into number to prevent concatanation.
      timerDisplay.html(pomoTime.html());

    });
  };

});

I've tried to return the function updateDisplay() to stop it when status is 2(when timer is running). but it still doesn't work.
example : http://codepen.io/aliz16/pen/OXMwRJ?editors=1010

A: You need to check the state variable in your control event handlers:
  function updateDisplay() {
    /*
      Not Needed
      if (status == 2) {
         return false;
      }
    */
    $('#breakMinus').on("click", function() {
      // Check status here
      if (status == 2) {
         return false;
      }
      status.html("Break");
      if (breakTime.html() > 1) {
        breakTime.html(parseInt(breakTime.html()) - 1);
      };
      timerDisplay.html(breakTime.html());
    });

    $('#breakPlus').on("click", function() {
      // Check status here
      if (status == 2) {
         return false;
      }
      status.html("Break");
      breakTime.html(parseInt(breakTime.html()) + 1); // parseInt to covert string into number so it doesn't concatanate.
      timerDisplay.html(breakTime.html());
    });

    // work minus and plus
    $('#workMinus').on("click", function() {
      // Check status here
      if (status == 2) {
         return false;
      }
      status.html("Work");
      if (pomoTime.html() > 1) {
        pomoTime.html(parseInt(pomoTime.html()) - 1);
      };
      timerDisplay.html(pomoTime.html());
    });

    $('#workPlus').on("click", function() {

       // Check status here
      if (status == 2) {
         return false;
      }
      status.html("Work");
     pomoTime.html(parseInt(pomoTime.html()) + 1); // parseInt to covert string into number to prevent concatanation.
      timerDisplay.html(pomoTime.html());

    });
  };


text:
Q: Chrome extensions accessing GUM I'm working on a little sideproject in form of a chrome extension which displays the local stream via the getUserMedia API.
First I had issues requesting the gum (getUserMedia) since I tried to access it via the popup.js and the background.js. After some testing I got it working within the content.js, but now the issue was acutally displaying the stream in the popup.html. Further investigation suggested using the inbuild sendMessage from chrome (since the content script has no access to the popup).
So my workflow is now a onClick listener on my popup, on user click sending a notification to my content script, requesting the gum there and executing a callback function from the received message which sets the stream on my video element. The issue now my send stream is altered by transferring it via the sendMessage function, which results in an error setting the stream on my video element, since the stream is no longer a MediaStream object.
My approach is a trial and error approach since I'm neither a webdeveloper nor do I have any experience with chrome-extensions. Any suggestions or help on how I can achive this are highly appreciated
-- popup.js
let startStream = document.getElementById('gum');

function setStream(stream) {
  if(stream != null){
    video = document.getElementById('localStream');

    if("srcObject" in video) {
      console.log("videoelement supports scrObject.")
    }

    console.log('stream: ', stream)
    video.srcObject = stream;
  } else {
    console.log("popup: passed stream is not definded")
  }
}

startStream.onclick = function(element) {
  console.log("popup start stream clicked");
  chrome.tabs.query({
    active: true,
    currentWindow: true
  }, tabs => {
    chrome.tabs.sendMessage(
        tabs[0].id,
        {from: 'popup', action: 'startStream'},
        setStream);
  });
};

-- popup.html
<!DOCTYPE html>
<html>
  <head>
    <style>
      button {
        height: 30px;
        width: 30px;
        outline: none;
      }
    </style>
  </head>
  <body>
    <video controls id=localStream></video>
    <button id="gum">Start</button>
    <script src="popup.js"></script>
  </body>
</html>

-- content.js
console.log('content script init')

chrome.runtime.onMessage.addListener((msg, sender, response) => {
  console.log(sender.tab ?
              "message from a content script:" + sender.tab.url :
              "message from the extension");

  if (msg.from == "popup" && msg.action == "startStream"){
    console.log('content script start stream action')
    navigator.mediaDevices.getUserMedia({video:true, audio:true})
    .then((stream) => {
      console.log('content gum successfull: ', toString(stream));
      console.log('stream: ', stream);
      response(stream);
    })
    .catch((err) => {
      console.log('content gum error: ' + error);
      response(null);
    });
    return true;
  }
});

-- manifest.json
{
    "version": "1.0",
    "name": "Some test",
    "description": "Build an Extension!",
    "manifest_version": 2,
    "permissions": ["declarativeContent", "storage", "activeTab", "tabs"],

    "background": {
      "scripts": ["background.js"],
      "persistent": false
    },

    "content_scripts": [{
      "matches": ["<all_urls>"],
      "js": ["content.js"],
      "run_at": "document_idle",
      "all_frames": false
    }],

    "browser_action": {
      "default_popup": "popup.html",
      "default_icon": {
        "16": "images/icon-off-16.png",
        "32": "images/icon-off-32.png",
        "48": "images/icon-off-48.png",
        "64": "images/icon-off-64.png",
        "128": "images/icon-off-128.png"
      },
      "default_title": "World Domination"
    },

    "icons": {
      "16": "images/icon-off-16.png",
      "32": "images/icon-off-32.png",
      "48": "images/icon-off-48.png",
      "64": "images/icon-off-64.png",
      "128": "images/icon-off-128.png"
    }
  }


text:
Q: Dynamics 365 Portals - Employee Self-Service - 'Content Editor Tool' not appearing for 2nd Admin user I have a trial Dynamics 365 Portal for Employee Self-Service. I am also seeing this issue in my real Office 365/Dynamics 365 instance.
For my first Admin user I was able to log into the Portal, add them to the Administrator web role, log in again and see the 'Content Editor Tool' floating in the top right corner. All good.
For a second Admin user I do exactly the same thing... but no 'Content Editor Tool' appears. I have tried to match both the first Admin account and the second Admin account exactly the same but nothing happens.
I have also Restarted the Portal from the Admin center and have turned the Portal off and on again.
Is there anyway I can diagnose why this second Admin is not working?

A: I worked it out. Web Roles and Security Roles are not the same.
Security Roles are set at User level and provide access to Dynamics 365.
Web Roles are set at Contact level and provide access to the Portal.
For the other Portals you just send an Invitation Workflow, and I still had to do this step even though the User had been created already by virtue of logging into the Employee Self Service (ESS) portal. I created the invite for the Contact, saved it, added the Administrator Web Role, and then selected 'Other Activities' (in the ... button) and then 'Invite Redemption'.
In the 'Invite Redemption' dialog, select the Contact again, provide any username, and click the 'Save' button.
This will complete the workflow to add the Web Role. Next time you log in as that user the tool will be visible.


text:
Q: How to use QGIS field calculator in python? I would like to use QGIS Field Calculator in Python to update the existing column based on certain conditions?
How can I do this?

A: There is no prebuilt class to do the magic the field calculator does (I am planning on adding it at some stage) however it's quite simple:
expression = QgsExpression("1 + 1")
# This allows field lookup
index = layer.fieldNameIndex("UpdateField")
expression.prepare(layer.pendingFields())
layer.startEditing()
for feature in layer.getFeatures():
    value = expression.evaluate(feature)
    layer.changeAttributeValue(feature.id(), index, value)

layer.commitChanges()

A couple of notes: We are using changeAttributeValue because it's faster but does require use to use the feature id and field index, another way which might be as fast but is clearer to read is:
expression = QgsExpression("1 + 1")
# This allows field lookup
expression.prepare(layer.pendingFields())

layer.startEditing()
for feature in layer.getFeatures():
    value = expression.evaluate(feature)
    feature["UpdateField"] = value
    layer.updateFeature(feature)

layer.commitChanges()


text:
Q: mysqli_query gives empty value Im creating a login system for my website.
I got the problem that my mysqli_query is empty:
The code: $r = mysqli_query($dbc, $q); returns empty.
I think the problem is in the sql language that i pass it:
$q = "SELECT userid, fname, lname FROM User WHERE email='$e' AND pass=SHA1('$p')";

If i execute the sql above with the data that im actually is fetching from the form then i will get the result Im looking for. So i think its the php and sql combined that got an error.
if(empty($errors)){
    $q = "SELECT userid, fname, lname FROM User WHERE email='$e' AND pass=SHA1('$p')";

    $r = mysqli_query($dbc, $q);
    //Check for right data
    $errors[] = $e;
    $errors[] = $p;
    //Check if connection is up
    if($dbc != null){
        $errors[] = "Connection up";
    }
    //Check query
    if(is_null($r)){
        $errors[] = "Query is null";
    }
    //Check query for being empty
    if(empty($r)){
        $errors[] = "Its empty";
    }
    if( mysqli_num_rows($r) == 1){
        $row = mysqli_fetch_array($r, MYSQLI_ASSOC);
        return array(true, $row);
    }else{
        $errors[] = "Email address and password not found.";
    }
    return array(false, $errors);

}

A: You can try this
if(empty($errors)){
    $p = sha1($p);
    $q = "SELECT userid, fname, lname FROM User WHERE email = '$e' AND pass = '$p'";

    $r = mysqli_query($dbc, $q);
    if(!$r){
        die(mysqli_error($dbc));
    }

    //Check for right data
    $errors[] = $e;
    $errors[] = $p;
    //Check if connection is up
    if($dbc != null){
        $errors[] = "Connection up";
    }
    //Check query
    if(is_null($r)){
        $errors[] = "Query is null";
    }
    //Check query for being empty
    if(empty($r)){
        $errors[] = "Its empty";
    }
    if( mysqli_num_rows($r) > 0){
        $row = mysqli_fetch_assoc($r);
        return array(true, $row['userid'], $row['fname'], $row['lname']);
    }else{
        $errors[] = "Email address and password not found.";
    }
    return array_merge(array(true), $errors);
}


text:
Q: How to add stuff into existing base class in C#? Say I have a Father class to be inherited by Children classes, later I want to add more stuff into the Father class without modifying the original Father class, please teach me how could I do it.
Let me clarify my question. Any valuables and methods in Father will automatically accessible to all the Children classes, right? For example:
public class Father
{
    public int a;
    public int b;
    public int c()
    {
        return a+b;
    }
}

public class Child : Father
{
    private int d=a*b+c();
}

Now I want to add a boolean e and a method f() to Father so my Child could access it directly, without adding those lines directly in Father or make a new class in between Father and Child. Is that possible? How could I do it?

A: You are looking for Extension Methods. Refer this post for more information.

A: If you want to add more fields to your father model then maybe your inheritance structure should be changed.
For example you had model A and model B. Model B inherited fields from model A
public class A
{
    public string FieldA { get; set; }
}

public class B : A
{
    public string FieldB { get; set; }
}

This way the class B has fields FieldA and FieldB.
Now if you want your class B to inherit from a class that has the fields of A but more you could add another layer to your inheritance tree like this.
public class A
{
    public string FieldA { get; set; }
}

public class C : A
{
    public string FieldC { get; set; }
}

public class B : C
{
    public string FieldB { get; set; }
}

Now your class B has fields FieldA and FieldB and FieldC and you don't have to alter your original father class A.
Now if you want to extend methods for a class you could also go with static extensions like this:
Public static void DoSomething(this A a)
{
    ...
}

and then call A.DoSomething();


text:
Q: Spring data elasticsearch:throws MappingInstantiationException: Failed to instantiate java.util.Set using constructor NO_CONSTRUCTOR with arguments I am in process of migrating an application to the latest spring boot version (using gradle spring-boot-dependencies with version 2.5.4).
I have an entity called Customer which is annotated with @Document(indexName = "customer"); and another entity Address which is annotated with @Document(indexName = "address"). Customer class has private Set<Address> addresses = new HashSet<>().
Getting the below error, while calling List hits = elasticsearchTemplate
.search(nativeSearchQuery, Customer.class) from the repository.

org.springframework.data.mapping.model.MappingInstantiationException:
Failed to instantiate java.util.Set using constructor NO_CONSTRUCTOR with arguments.

It is working if I follow similar MONGO suggestion Failed to instantiate java.util.Set using constructor NO_CONSTRUCTOR with arguments and make the declaration private HashSet<Address> addresses = new HashSet<>(). I can't follow this as we have hundreds of entities and their JPA criteria mappings built with JPA Metamodel are failing.
please note that I have already reviewed the below 2  threads and feel it's different:

*

*Indexing problem with Spring Data Elastic migration from 3.x to 4.x

*Spring data elasticsearch: Using @Document annotation on POJO interface class not working
if you are looking for a sample repository: https://gitlab.com/mvallapuneni/spring-es-sample
Any help is appreciated...

A: java.util.Set is an interface not a class.
Interfaces do not have constructors, they are joined to a class that "implements" (has the operating code methods of) the interface.
All method signatures in an interface are abstract , they have no code, only the signature of methods supplied by the implementing class.
e.g. HashSet is a class that implements java.util.Set
See the API documentation at the top of its page for "all known implementing classes"
Your HashSet is private it must use private methods to call on it e.g. set or get e.t.c.
To hazard a guess the List must become a Set but List is instantiated and Set is a variable waiting.
Somewhere in the code in private methods this goes like (figuratively)...
private Set<Address> addresses = (Set<Address>)(Collection<Address>)elasticsearchTemplate.search(nativeSearchQuery, Customer.class);

Note that in that line they are all interfaces but to have an instantiated interface means there is a class attached that implements the interface List , however the class should also be able to use interface Set.
I just presume the List returned is actually in a HashSet and the instantiation is simply reserving space in memory like "C" language, just a helper that is not required to have any class instantiated at that time.
A HashSet takes a Collection in its constructor and a Collection can be either a Set or a List.


text:
Q: How does "setting object properties" work on derived objects (and how does this differ from setting primitives) I thought I mastered prototypal inheritance but now setting object properties on derived objects work.
Consider this code:
var com_mtag = {};
com_mtag.start = function(){
// creating myBase and setting a string property and an object-property
    // both have a "prop" property set to "Base"
com_mtag.myBase = {};
com_mtag.myBase.prop = "Base";
com_mtag.myBase.obj = {prop: "Base"};

// Now derive myObj from myBase...
com_mtag.myObj = Object.create(com_mtag.myBase);

    // modifying prop and obj.prop via the derived object
com_mtag.myObj.prop = "Derived";
com_mtag.myObj.obj.prop = "Derived";
};

The result is this:
1) both myBase and myObj have a property "prop" with the values "Base" and "Derived" respectively (as expected)
2) but myBase.obj and myObj.obj point to the same object which now has the value prop="Derived"
How does this work? I've learned that when setting object properties, the interpreter will not go down the prototype chain but create the property on the instance where the "set" was performed (it did this for the string property).
But how did the interpreter handle setting the object property? It must have gone down the chain in order to locate the object. And did it create a new reference to this object within the derived object?
Hoping that I made myself clear (which I doubt when I read this but I cannot explain better), I would very much appreciate anyone to shed some light on this.

A:
I've learned that when setting object properties, the interpreter will not go down the prototype chain but create the property on the instance where the "set" was performed

Yes, this is true, but every property in your access chain com_mtag.myObj.obj is reading property values, not setting them. Only the .prop at the end actually sets anything.
When you set a property on an object, you are setting the object's own property (we say "own" property to distinguish them from inherited prototype properties), which shadows any prototype property with the same name. This is why you can shadow the inherited com_mtag.myObj.prop with a new value: com_mtag.myObj gains its own prop property.
However, with com_mtag.myObj.obj.prop, you set the property of an object that exists as a propery of the myBase prototype. In this case, com_mtag.myObj does not gain its own obj propety, because you are not setting obj; you are merely reading it.
com_mtag.myObj doesn't have its own obj property, so com_mtag.myObj.obj must refer to the value stored in the propotype's obj property, i.e., com_mtag.myBase.obj. Therefore, com_mtag.myObj.obj.prop refers to the prop property on that object.
If you had given com_mtag.myObj its own obj property, then com_mtag.myObj.obj.prop would set prop on the value stored in that obj. Since com_mtag.myObj has no such property of its own, it must use the object stored at com_mtag.myBase.obj to find an object to set prop on.
Consider instead the possibility of creating a new object with a prop property, and storing that whole object in com_mtag.myObj.obj:
com_mtag.myObj.obj = { prop: "Derived" };

Without creating a new object like that, only the original prototype obj object exists. The JavaScript engine will not create a new object on myObj.obj; it will use the one on the prototype.


text:
Q: CSS to make anchor hovers look like highlighter text I've been struggling with this for days and just can't get it. Is it possible to get the hover state of a link to look like the attached picture? So it appears ilke a highlighter was used on the text and have the white space between the lines
http://krwilliams.com/lab/test/highlighterlinks.jpg
sorry it wouldn't let me attach the image.
Here is the closest I can get
http://krwilliams.com/lab/test/resources.html

A: In your example, turn off float:left on your A-tag.


text:
Q: Setting a dynamic value as header in subseqent request Gatling/Scala I have regex'ed a value that I want to use for subsequent requests in my Gatling script this way:
 .exec(http("request_test")
    .get("https://test/eai/bad")
    .check(regex("content=\"([0-9A-Z]*)\"").saveAs("bidkid")))

Now in the receeding request I want to add bidkid as a header to the request. How can I do that?

A: Have you tried:
.exec(http("request_test")
  .get("https://test/eai/bad")
  .check(regex("content=\"([0-9A-Z]*)\"").saveAs("bidkid")))
.pause(2)
.exec(http("Next Request")
  .get("https://test/eai/bad")
  .header("header_name", "${bidkid}")

It should work.


text:
Q: iOS - How can I create a custom transition between two views? I'm trying to create a custom transition between two views. The idea is to create the same kind of effect that the "Videos" app in the iPad and the twitter on iPhone have.
Anyway, I can't find out how to perform that.
I tried to use [UIView transitionWithView: ...] passing nil to options and trying to create layers in the animations block but it's not working at all.
I've seen all the videos of Apple at WWDC 2010 and 2011 dealing with the subject but they never explain how to do so !
I also tried to find an answer here but there's no real explanation.
Thanks for your help.
Edit : The effect I'm trying to achieve is the one you can see here http://www.youtube.com/watch?v=SGzL658OAx4 (0:44)

A: I don't know which effect you are talking about but here are some code to make Push transition inside a scrollView (You can make curl page transition with that code too).
-(void)performFadeTransitionTo:(GenericScreen*)newNextView
                     direction:(NSUInteger)direction {
    CATransition *transition = [CATransition animation];
    transition.duration = 0.75;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];

    transition.type = kCATransitionFade;

    transition.subtype = kCATransitionFromRight;

    transition.delegate = self;
    [innerScroll setContentSize:newNextView.frame.size];
    [innerScroll scrollRectToVisible:CGRectMake(0, 0, screenWidth, 10)
                            animated:NO];

    [innerScroll.layer addAnimation:transition
                             forKey:nil];

    currentView.hidden = YES;
    newNextView.hidden = NO;
    currentView = newNextView;
}

A: If you want a custom transition, create your own subclass of UIStoryboardSegue and override the -perform method. See the UIStoryboardSegue reference page, particularly Subclassing Notes.


text:
Q: Mongo DB chained query I am new to MongoDB and as I wonder if a chained query like the following is possible(somewhat like a join):
db.places.insert({
"_id": original_id
"place_name": "Broadway Center"
"url": "bc.example.net"})

db.people.insert({
"name": "Erin"
"places_id": original_id
"url":  "bc.example.net/Erin"})

So given a place name string, I want to select the people associated with that place.
But the people collection only reference the place id, not the place name.

A: You cannot use joins in MongoDB.
The idiomatic solution is retrieve all place_ids for that place_name from your places collection and then use the place_ids to query in your people collection.
Another option is keeping, for example, places in people collection (this makes more sense to me than people inside places collection but, of course, it depends on your domain). But then you have to take into account that in case that only one place changes, you have to change all people documents sharing a specific place. If people and places are in separate collections this doesn't happen so it depends on if we have static data or not and on if we want to optimize searches or updates.


text:
Q: Adobe DTM: Event Rule | Capture data attribute HTML Markup shown here
Hi, I would like to get data-target values using Adobe DTM event based Rule. As shown in image at top (Image name: HTML Markup), all menu items belongs to plan-home-navigation class. And each item have unique data-target attribute. How can I capture this using DTM event based Rule. I tried below shared combination but did not work.
Adobe DTM: Event based Rule

A: You are targeting the wrong element to trigger the event based rule. Instead of the div container of the navigation header, you will need to trigger the event based rule on the anchor elements themselves. So the Element Tag should be div.plan-home-navigation a[data-target]. You can further narrow down the selection by manually specifying data-target as the property and #plan- with regex option turned on.

Come to think of it, [data-target] might not even be required if these are the only anchor links in the container. Let alone manually specifying data-target.


text:
Q: WPF ItemsControl doesnt update when I add a new item in ItemsSource I want to make a PartialProgressBar for a multithreading downloader but I couldn't make it to work.
No change when I add element into the ItemsSource. How can I fix it?
MainWindow.
    public partial class MainWindow : Window
    {
        ObservableCollection<HttpRange> Ranges;
        public MainWindow()
        {
            InitializeComponent();
            DataContext = this;
            Ranges = new ObservableCollection<HttpRange>();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var range1 = new HttpRange(start: 0, end: 50, saveDir: "path", fileId: "1");
            var range2 = new HttpRange(start: 50, end: 100, saveDir: "path", fileId: "1");
            Ranges.Add(range1);
            Ranges.Add(range2);
        }
    }

MainWindow.xaml
<local:PartialProgressBar Background="Yellow"
                          HorizontalAlignment="Left"
                          VerticalAlignment="Top"
                          x:Name="prbar" Width="250" Height="20"
                          ContentSize="100"
                          Ranges="{Binding Ranges}" />

PartialProgressBar.xaml
<UserControl x:Class="Alto_Download_Manager.PartialProgressBar"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:Alto_Download_Manager"
         mc:Ignorable="d"
         d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
    <local:RangeToTotalWidthConverter x:Key="RangeToTotalWidthConverter"/>
    <local:RangeToProgressConverter x:Key="RangeToProgressConverter"/>
</UserControl.Resources>
<!---->
<ItemsControl x:Name="list"  ItemsSource="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}, Path=Ranges}">
    <ItemsPanelTemplate>
        <StackPanel  Orientation="Horizontal"></StackPanel>
    </ItemsPanelTemplate>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock>a</TextBlock>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

PartialProgressBar.xaml.cs
public partial class PartialProgressBar : UserControl
{
    public PartialProgressBar()
    {
        InitializeComponent();
    }

    public long ContentSize
    {
        get { return (long)GetValue(ContentSizeProperty); }
        set { SetValue(ContentSizeProperty, value); }
    }

    // Using a DependencyProperty as the backing store for ContentSize.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ContentSizeProperty =
        DependencyProperty.Register("ContentSize", typeof(long), typeof(PartialProgressBar), new PropertyMetadata(1L));

    public List<HttpRange> Ranges
    {
        get { return (List<HttpRange>)GetValue(RangesProperty); }
        set
        {
            SetValue(RangesProperty, value);
        }
    }

    // Using a DependencyProperty as the backing store for Ranges.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty RangesProperty =
        DependencyProperty.Register("Ranges", typeof(List<HttpRange>), typeof(PartialProgressBar), new PropertyMetadata(null));

}


text:
Q: Write a cpprestsdk json value object into a file I receive a JSON response body as part of a REST request. I would like to write the body of the JSON into a file. A quick way to do this would be to use the web::http::response object itself..
pplx::task<void> requestTask = fstream::open_ostream(U("testResults.json")).then([=](ostream outFile)
    {
        *fileStream = outFile;
//some work
    })
.then([=](http_response response)
    {
        printf("Received response status code:%u\n", response.status_code());

        // Write response body into the file.
        return response.body().read_to_end(fileStream->streambuf());
    })
    .then([=](size_t s)
    {
        return fileStream->close();
    });

However, after receiving the response body, I extract the JSON from it to calculate some values, after which, as documented, the json cannot be extracted or used again from the response body, so i have to use the web::json::value object.
http::json::value someValue = response.extract_json().get();

I'd like to write this json::value object, someValue, to a JSON file, but not sure how to get it done. Writing to an ostream object with serialize.c_cstr() on someValue gives weird output.
ostream o("someFile.json");
o << setw(4) << someValue.serialize().c_str() << std<<endl;

A: If your system typdef std::string as a wide string, then outputting via ostream would lead to weird output.
web::json::value::serialize() returns a utility::string_t
https://microsoft.github.io/cpprestsdk/classweb_1_1json_1_1value.html#a5bbd4bca7b13cd912ffe76af825b0c6c
utility::string_t is typedef as a std::string
https://microsoft.github.io/cpprestsdk/namespaceutility.html#typedef-members
So something like this would work:
std::filesystem::path filePath(L"c:\\someFile.json"); // Assuming wide chars here. Could be U instead of L depending on your setup
std::wofstream outputFile(filePath);
outputFile << someJSONValue.serialize().c_str();
outputFile.close();


text:
Q: Should I preserve
 in XML element strings I read XML files that sometimes contain elements like
<stringValue>text
text</stringValue>

XmlReader returns
text\ntext

for such strings.
So, when I rewrite the source XML later using XmlWriter I don't get the same strings (there is no
 in them).
Should I worry about all this or it's fine to allow string to be changed this way?

A: I would worry about it yes because your manipulating the data. This means if you do a round-trip to the XML document the text formatting wouldn't be the same.
You would need to make sure on saving back out to XML persist the same formatting.

A:
 is the xml encoding for a new line character (\n).  If your XML data has a new line in the text, then this notation is correct and the output from XMLWriter is correct.  If the new line was not in the original XML data, I've been seeing an issue with IE10/IE11 using the XMLHttpRequest object inserting \r\n in the XML data.