text:
Q: Stuck with the CSV file reading in javascript Hi I am trying to read the csv file (just on front end not want to store it on back end ). The error I am getting is attached with the image below.
enter image description here
The code I am trying is.
function file(){
       var fullPath = document.getElementById('upload').value;

       if (fullPath) {
            var startIndex = (fullPath.indexOf('\\') >= 0 ? fullPath.lastIndexOf('\\') : fullPath.lastIndexOf('/'));
            var filename = fullPath.substring(startIndex);

       if (filename.indexOf('\\') === 0 || filename.indexOf('/') === 0) {
        filename = filename.substring(1);
       }

    alert(filename);
   // passFile(filename);
    d3.csv(filename, function(error, data) {
        if (error) throw error;
           console.log(data); // [{"Hello": "world"}, …]
    });
  }
}

I just want to read the data from file but getting this error.
I have tried other ways too like This method I tried first but does not work for me. Can anyone help me out?

A: d3.csv() function is for fetching csv file from a remote location. If you want to read a local file by <input type="file"> element, you should use FileReader to read the file by yourself and parse it with d3.csvParse() function.
For example:

function file(){
 var uploadFileEl = document.getElementById('upload');

 if(uploadFileEl.files.length > 0){
  var reader = new FileReader();
  reader.onload = function(e) {
   console.log(d3.csvParse(reader.result));
  }
  reader.readAsText(uploadFileEl.files[0]);
 }
}
<input type="file" id="upload" />
<button id="upload" onclick="file()">Read CSV</button>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.9.1/d3.min.js"></script>


text:
Q: RegSetValueEx silently fails to write to HKLM I'm trying to write in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run from my C++ application like this:
HKEY key;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"), NULL, KEY_ALL_ACCESS, &key) == ERROR_SUCCESS){
    if (RegSetValueEx(key, TEXT("lcr"), 0, REG_SZ, (const BYTE*)runcmd.c_str(), (runcmd.size()+1)*sizeof(wchar_t)) != ERROR_SUCCESS){
        cout << "ERROR" ;
    }else{
        cout << "OK" << endl;
    }
    RegCloseKey(key);
}else{
    cout << "ERROR" ;
}

But it silently fails and nothing happens!
I tried both running as normal user & running as administrator.
What is the problem?

A: The problem is that your application is subject to UAC registry virtualization. Because you did not include a manifest in your application, the system drops into an XP (!) compatibility mode. When you write to restricted parts of the registry under HKLM, the system re-directs them to what is known as the virtual store under HKCU.
You should add a manifest to your application so that you are no longer virtualized. If you really do need to write to HKLM then you will need to specify the requireAdministrator option in the manifest so that your application is executed with elevated rights.
Probably your next move is to take some time to read the documentation that I linked to above and be sure that you fully understand all the implications of UAC.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to add order by into statement Does anybody know how to insert order by into the statement below
SELECT ctr_num,
       scn
FROM   user_convoy
WHERE  ctr_num LIKE '%" + str_convoy + "%'"

A: Not really sure about your question, but from my understanding, it should be:
select ctr_num , scn from user_convoy where ctr_num like '%" + str_convoy + "%'" ORDER BY your_column

A: Add ORDER BY at the end. The general format of your SELECT statements is generally SELECT FROM WHERE ORDER BY (assuming no grouping, of course).  Note that it is not case-sensitive.
select ctr_num , scn from user_convoy where ctr_num like '%' + str_convoy + '%' ORDER BY ctr_num

A: The ORDER BY keyword is used to sort the result-set by one or more columns.
Try below if you want to use Order By.
SELECT ctr_num,
       scn
FROM   user_convoy
WHERE  ctr_num LIKE '%' + str_convoy + '%'
ORDER BY
       ctr_num,scn

For more details:
Please refer w3schools Example and to learn in more depth this


text:
Q: why MySQL query is taking long time to execute and what is filtered means? I have a query that taking a long time to execute and what is filtered means in explain plan.
Below is the MySQL query, explain plan and Structure of a table and Version is MySQL V8.0
SELECT  `responses`.*
FROM `responses`
WHERE `responses`.`survey_id` = 196690 AND (responses.time >=  '2017-01-01 08:00:00') AND (responses.time <=  '2020-10-13 13:00:58')
ORDER BY `responses`.`id` ASC
LIMIT 500 OFFSET 0;

CREATE TABLE `responses` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `survey_id` int(10) NOT NULL,
  `token` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '',
  `time` datetime NOT NULL,
  `ip_address` int(15) unsigned NOT NULL,
  `identity` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
  `user_agent` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
  `completed` tinyint(1) DEFAULT NULL,
  `completed_time` datetime DEFAULT NULL,
  `referrer` tinytext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci,
  `page` tinytext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci,
  `visible` tinyint(1) DEFAULT '0',
  `mail_sent` tinyint(1) DEFAULT '0',
  `anonuuid` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT '',
  `metadata` json DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `survey_id` (`survey_id`),
  KEY `time` (`time`),
  KEY `index_responses_on_survey_id_and_time` (`survey_id`,`time`),
  KEY `survey_id_2` (`survey_id`,`token`),
  KEY `survey_id_3` (`survey_id`,`mail_sent`)
)ENGINE=InnoDB AUTO_INCREMENT=204788658 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC

explain
SELECT `responses`.*
FROM `responses`
WHERE `responses`.`survey_id` = 196690 AND (responses.time >= '2017-01-01 08:00:00') AND (responses.time <= '2020-10-19 13:01:00')
ORDER BY `responses`.`id` ASC
LIMIT 500 OFFSET 0\G

*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: responses
   partitions: NULL
         type: index
possible_keys: survey_id,time,index_responses_on_survey_id_and_time,survey_id_2,survey_id_3
          key: PRIMARY
      key_len: 4
          ref: NULL
         rows: 144663
     filtered: 0.19
        Extra: Using where
1 row in set, 1 warning (0.00 sec)

A: *

*Replace TINYTEXT by VARCHAR(...).  TEXT columns, though essentially the same as VARCHAR have some subtle extra overhead.

*Shrink the VARCHAR sizes to 'reasonable' sizes.

*When you have both INDEX(survey_id) and INDEX(survey_id, ...), get rid of the former.  Not only is it unnecessary, the Optimizer sometimes picks the former when the latter would be better.

*Change ORDER BY id to ORDER BY time (if it does not mess with the desired result too much).  Probably the Optimizer decided that ORDER BY id would be a better way to run the query than using INDEX(survey_id, time).  This change to ORDER BY would prevent that.  I suspect that most of the table is included in that time range, and that helped confuse the Optimizer.

Here is a bigger change that will probably speed things up more:
  PRIMARY KEY (`id`),
  KEY `survey_id` (`survey_id`),
  KEY `time` (`time`),
  KEY `index_responses_on_survey_id_and_time` (`survey_id`,`time`),
  KEY `survey_id_2` (`survey_id`,`token`),
  KEY `survey_id_3` (`survey_id`,`mail_sent`)

-->
  PRIMARY KEY (`survey_id`,`time`, `id`),  -- 'cluster' primarily on survey_id
  KEY(id),   -- to keep AUTO_INCREMENT happy
  KEY `time` (`time`),

That would essentially force the Optimizer to use the best index, and avoid bouncing between the index's BTree and the data's BTree 500 times.
(Also change the ORDER BY as noted above)
I don't know whether it would be worth keeping these two indexes:  (survey_id, token) and (survey_id, mail_sent).
"Filtered" is a crude estimate of what percentage of the rows will be kept.  I rarely find it to be of any use.
I see that you are using OFFSET.  Does this mean you will be "paginating"?  If so, there are further issues to discuss.


text:
Q: Angular 4: using the methods of feature module in it's components I'm now thinking about creating feature module for User and this module has components like:

*

*authorization;

*registration;

*profile;

*restore-password.

I want to create methods like:

*

*createUser();

*deleteUser();

*updateUserProfile().
in UserModule and then use it in the components listed above.
how can I use methods of UserModule in registrationComponent and ect. ?

A: When you want to use some methods in more than one component you build a so called service. It is a typescript class with the @Injectable() decorator:
import { Injectable } from '@angular/core';

@Injectable()
export class UserService {
  createUser(user) {
    // reach out to backend via http
  }

  // some other functions that have to be shared and used by components
}

This service can be injected like this:
import { UserService } from 'services/user.service.ts'

@Component({
  selector: 'user-create'
})
export class CreateUserComponent {
  constructor(private userService: UserService) {}

  createUser(user) {
    this.userService.createUser(user); // now you can call your method from the service like this
  }
}


text:
Q: Fatal error when moving pimcore from a server to local I moved all my pimcore files plus the database from a server to my localhost and made the necessary changes in website/var/config/system.xml.
Admin is working but the frond end is showing an error:
Fatal error: Call to a member function getFielddefinitions() on a non-object in /var/www/html/pimcore/pimcore/models/Object/Localizedfield/Resource.php on line 179

This line of code produces the error:
$this->model->getClass()->getFielddefinition("localizedfields")->getFielddefinitions()

The system requirements and file permissions are correct.
For testing purpose I installed a new pimcore project on my local system and it's working perfectly.
Can I make any changes in my Database?
How can I run my project successfully on local?

A: The error is happen when there are already objects present using the class.
Solution

*

*Login to backend as Admin.

*Go to Settings > Object > Classes

*For each of the classes in the left tree, click on them and then hit Save in the bottom right. (If unable to save just create a new class by hit the button Add new class )

Now try to load the frondend. It will work.

A: Pimcore uses database views for storing objects data. When exporting database, in views definitions there will be also SECURITY DEFINER.

/*!50013 DEFINER=`prod-user`@`%` SQL SECURITY DEFINER */

*

*OPTION: Vinot VT solution should work
You can acchive same with running command:

php pimcore/cli/console.php deployment:classes-rebuild

*OPTION: Use same database username on your local env 'prod-user', which is  useful if you will import prod database a lot

*OPTION: replace  DEFINER=prod-user@% with DEFINER=local-user@% before importing database

A: You can:

*

*set <debug>1</debug> in config.xml - this should show error

*if it wasn't helped, check apache and/or php error log.

A: We need to see the actual error (as Vinod has already pointed out).
I could speculate, though:
Are the database credentials (aka the DB username) identical?
If not you might need to remove the SECURITY DEFINER from the DB Dump.
See: Remove DEFINER clause from MySQL Dumps for hints on how to do that.
Another source of error might be the cache. Are you using the default file-based Pimcore cache?
If this is the case, try removing all files from website/var/cache and website/var/tmp
Let us know how that turned out.


text:
Q: How to add interial sound permission in Android Manifest I want to make the interial sound recording in that game, but i can't, i tried but i don't know what I'm doing wrong,  this is not my code, and my game but the developer doesn't makeing updates soo I'm trying to do what i can...
Soo please, if you know how to add, send me the code, thank you
(It looks like your post is mostly code; please add some more details
It looks like your post is mostly code; please add some more details) i dont know what i can add XD
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:hardwareAccelerated="true" android:versionCode="10502" android:versionName="1.5.2" package="com.altero.minidayz" platformBuildVersionCode="28" platformBuildVersionName="9">
    <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="28" />
    <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.AUDIO_USAGE" /> //there i tried to add audio usage but it doesn't works
    <uses-permission android:name="android.permission.RECORD_AUDIO" /> // there Record audio permission , and it's doesn't work too...
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="com.amazon.device.messaging.permission.RECEIVE" />
    <permission android:name="com.altero.minidayz.permission.RECEIVE_ADM_MESSAGE" android:protectionLevel="signature" />
    <uses-permission android:name="com.altero.minidayz.permission.RECEIVE_ADM_MESSAGE" />
    <permission android:name="com.altero.minidayz.permission.C2D_MESSAGE" android:protectionLevel="signature" />
    <uses-permission android:name="com.altero.minidayz.permission.C2D_MESSAGE" />
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="com.sec.android.provider.badge.permission.READ" />
    <uses-permission android:name="com.sec.android.provider.badge.permission.WRITE" />
    <uses-permission android:name="com.htc.launcher.permission.READ_SETTINGS" />
    <uses-permission android:name="com.htc.launcher.permission.UPDATE_SHORTCUT" />
    <uses-permission android:name="com.sonyericsson.home.permission.BROADCAST_BADGE" />
    <uses-permission android:name="com.sonymobile.home.permission.PROVIDER_INSERT_BADGE" />
    <uses-permission android:name="com.anddoes.launcher.permission.UPDATE_COUNT" />
    <uses-permission android:name="com.majeur.launcher.permission.UPDATE_BADGE" />
    <uses-permission android:name="com.huawei.android.launcher.permission.CHANGE_BADGE" />
    <uses-permission android:name="com.huawei.android.launcher.permission.READ_SETTINGS" />
    <uses-permission android:name="com.huawei.android.launcher.permission.WRITE_SETTINGS" />
    <uses-permission android:name="android.permission.READ_APP_BADGE" />
    <uses-permission android:name="com.oppo.launcher.permission.READ_SETTINGS" />
    <uses-permission android:name="com.oppo.launcher.permission.WRITE_SETTINGS" />
    <uses-permission android:name="me.everything.badger.permission.BADGE_COUNT_READ" />
    <uses-permission android:name="me.everything.badger.permission.BADGE_COUNT_WRITE" />
    <application android:hardwareAccelerated="true" android:icon="@mipmap/icon" android:label="@string/app_name" android:supportsRtl="true">
        <activity android:configChanges="keyboard|keyboardHidden|locale|orientation|screenSize" android:label="@string/activity_name" android:launchMode="singleTop" android:name="com.altero.minidayz.MainActivity" android:screenOrientation="landscape" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">
            <intent-filter android:label="@string/launcher_name">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode" android:exported="false" android:name="com.google.android.gms.ads.AdActivity" android:theme="@android:style/Theme.Translucent" />
        <meta-data android:name="com.google.android.gms.games.APP_ID" android:value="@string/app_id" />
        <enable-feature xmlns:amazon="http://schemas.amazon.com/apk/res/android" android:name="com.amazon.device.messaging" android:required="false" />
        <service android:exported="false" android:name="com.onesignal.ADMMessageHandler" />
        <receiver android:name="com.onesignal.ADMMessageHandler$Receiver" android:permission="com.amazon.device.messaging.permission.SEND">
            <intent-filter>
                <action android:name="com.amazon.device.messaging.intent.REGISTRATION" />
                <action android:name="com.amazon.device.messaging.intent.RECEIVE" />
                <category android:name="com.altero.minidayz" />
            </intent-filter>
        </receiver>
        <meta-data android:name="onesignal_app_id" android:value="" />
        <meta-data android:name="onesignal_google_project_number" android:value="str:REMOTE" />
        <receiver android:name="com.onesignal.GcmBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter android:priority="999">
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="com.altero.minidayz" />
            </intent-filter>
        </receiver>
        <receiver android:name="com.onesignal.NotificationOpenedReceiver" />
        <service android:name="com.onesignal.GcmIntentService" />
        <service android:name="com.onesignal.GcmIntentJobService" android:permission="android.permission.BIND_JOB_SERVICE" />
        <service android:name="com.onesignal.SyncJobService" android:permission="android.permission.BIND_JOB_SERVICE" />
        <service android:name="com.onesignal.RestoreJobService" android:permission="android.permission.BIND_JOB_SERVICE" />
        <service android:name="com.onesignal.RestoreKickoffJobService" android:permission="android.permission.BIND_JOB_SERVICE" />
        <service android:name="com.onesignal.SyncService" />
        <activity android:name="com.onesignal.PermissionsActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar" />
        <service android:name="com.onesignal.NotificationRestoreService" />
        <receiver android:name="com.onesignal.BootUpReceiver">
            <intent-filter>
                <action android:name="android.intent.action.ACTION_BOOT_COMPLETED" />
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            </intent-filter>
        </receiver>
        <receiver android:name="com.onesignal.UpgradeReceiver">
            <intent-filter>
                <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
            </intent-filter>
        </receiver>
        <activity android:exported="false" android:name="com.google.android.gms.common.api.GoogleApiActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar" />
        <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" />
        <meta-data android:name="android.support.VERSION" android:value="26.1.0" />
        <meta-data android:name="android.arch.lifecycle.VERSION" android:value="27.0.0-SNAPSHOT" />
    </application>
</manifest>```


text:
Q: Read json data from url using java i haved read some answers like
Simplest way to read json from a URL in java
but it can not work.
ok,here is my code
package day1;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class MainGet {

    public static void main(String[] args) {
        try {

            URL url = new URL("https://api.covid19api.com/summary");

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.connect();

            //Getting the response code
            int responsecode = conn.getResponseCode();

            if (responsecode != 200) {
                throw new RuntimeException("HttpResponseCode: " + responsecode);
            } else {

                String inline = "";
                Scanner scanner = new Scanner(url.openStream());

                //Write all the JSON data into a string using a scanner
                while (scanner.hasNext()) {
                    inline += scanner.nextLine();
                }

                //Close the scanner
                scanner.close();

                //Using the JSON simple library parse the string into a json object
                JSONParser parse = new JSONParser();
                JSONObject data_obj = (JSONObject) parse.parse(inline);

                //Get the required object from the above created object
                JSONObject obj = (JSONObject) data_obj.get("Global");

                //Get the required data using its key
                System.out.println(obj.get("TotalRecovered"));

                JSONArray arr = (JSONArray) data_obj.get("Countries");

                for (int i = 0; i < arr.size(); i++) {

                    JSONObject new_obj = (JSONObject) arr.get(i);

                    if (new_obj.get("Slug").equals("albania")) {
                        System.out.println("Total Recovered: " + new_obj.get("TotalRecovered"));
                        break;
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

i want a example that can run in eclipse.
i haved install gson and i use jdk11.
here is my url :https://ws.yunlin.gov.tw/001/Upload/539/opendata/15369/1096/61b84dbc-5fe5-4569-8b94-4eebf1deef71.json
i want read it into java
thanks so much

i think i have added org.json into path,but still haved error

A: You have not provided error description.
Assuming it's JSON parsing error.
That URL does not return JSONObject but a JSONArray.
This is almost copy and paste solution.
https://mkyong.com/java/gson-how-to-parse-json-arrays-an-array-of-arrays/


text:
Q: django-redis-cache creates random keys with integer values I am using the following in my Django project:
django-redis-cache==2.1.1
redis==3.5.5
Django==2.2.13
Python 3.7.5

In my settings.py I specified the following cache:
CACHES = {
    "default": {
        "BACKEND": "redis_cache.RedisCache",
        "LOCATION": "xxxxx.cloud.redislabs.com:10790",
        "OPTIONS": {
            "DB": 0,
            "PASSWORD": "xxxxx",
            "CONNECTION_POOL_CLASS": "redis.BlockingConnectionPool",
            "CONNECTION_POOL_CLASS_KWARGS": {"max_connections": 20, "timeout": 3,},
        },
        "KEY_PREFIX": "django_backend_2",
    }
}

Nowhere in any of my django apps am I actually using this redis cache, and I also have never_cache enabled in all my apps.
The session_engine is set to use files:
SESSION_ENGINE = 'django.contrib.sessions.backends.file'

But, when I check the keys in my redis, I see random keys get created and removed all the time:
(My prefix was django_backend then I changed it to django_backend_2 that is why you will see some prefixes as django_backend and some as django_backend_2.)
The values in these keys are also just integers.
b'django_backend_:1:rl:5409e278e64a68dc9647a76efdb1ebc6'
b'3'
b'django_backend_2:1:rl:7782bafff6e59026ab9128fcc171e742'
b'1'
b'django_backend_2:1:rl:8e35c29a5fcaea902eecb25b1eee5819'
b'4'
b'django_backend_:1:rl:8e35c29a5fcaea902eecb25b1eee5819'
b'2'
b'django_backend_2:1:rl:3d985fa28195dd6b27e8daa27d7a5b9c'
b'3'
b'django_backend_2:1:rl:97dbbf58e1f6191742336f77d6a0ee3f'
b'4'
b'django_backend_2:1:rl:d910a2d3f55adfcf17800e1be0a29ccc'
b'1'
b'django_backend_2:1:rl:a441f5cb14e949fd09ba967eb46df4a3'
b'2'
b'django_backend_2:1:rl:bd0ea6a16e224fd4dc7d00ee4923d502'
b'1'
b'django_backend_2:1:rl:db9c27edb5144791755378ed13691895'
b'1'
b'django_backend_2:1:rl:ddd02c9082d5203419fcd111f5d99b4a'
b'2'
b'django_backend_:1:rl:645c9769365940fa54818e0a99b5f7c6'
b'1'
b'django_backend_2:1:rl:9451df4e327529d0a9280c0cb3a76bbf'
b'1'
b'django_backend_2:1:rl:5409e278e64a68dc9647a76efdb1ebc6'
b'6'
b'django_backend_2:1:rl:b00a484f84287df2318b18ac6c3831aa'
b'2'
b'django_backend_2:1:rl:ee4f17e6c6fa1004811335ba199b5514'
b'1'
b'django_backend_:1:rl:ddd02c9082d5203419fcd111f5d99b4a'
b'1'
b'django_backend_2:1:rl:ec0959c9a1fb66a639fa4335b674cd1b'
b'1'
b'django_backend_:1:rl:3d985fa28195dd6b27e8daa27d7a5b9c'
b'1'
b'django_backend_2:1:rl:645c9769365940fa54818e0a99b5f7c6'
b'4'
b'django_backend_2:1:rl:13c420622b99b075ac456310ce353ef9'
b'1'
b'django_backend_2:1:rl:527977de6f4097bc2e9479f1d395e94f'
b'1'
b'django_backend_2:1:rl:3200f5f1ed135d5875a48cb2abc16a1a'
b'1'
b'django_backend_2:1:rl:9a069775ac907715dd5d35e32d622070'
b'1'

Why is this happening as the number of keys just seem to keep on growing and growing.
Thank you


text:
Q: CheckBox validation and QueryString URL I have some problem from my website validation.
I have two columns eg.[id],[name] and checkbox for validation. I need automation fill textbox from URL. but it have some trouble.
For example, I insert @Context.Request.Query["Name/"id"] for [Name] textbox and [id] to submit but no tick checkbox validation. It will cause all the textbox data disappear.
If no insert Context.Request.Query["Name/"id"] for [Name] textbox and [id] to submit but no tick checkbox validation.it will save data in textbox.
Gif for reference - this is insert Context.Request.Query["Name/"id"]:  https://i.stack.imgur.com/qGrwz.gif
Here is my target. when no tick and pop the error. the column still have data save.
GIF2 https://i.stack.imgur.com/vGmHU.gif
Controller
public class CheckBoxRequired : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // get the entered value
        var student = (UserViewModel)validationContext.ObjectInstance;

        // Check whether the IsAccepted is selected or not.
        if (student.IsAccepted == false)
        {
            return new ValidationResult(ErrorMessage == null ? "Please checked the checkbox" ErrorMessage);
        }

        return  ValidationResult.Success;
    }
}

public IActionResult CreateUser()
{
    return View();
}

[HttpPost]
public IActionResult CreateUser(UserViewModel user)
{
    if (ModelState.IsValid)
    {
        // after validation success, create a UserClass instance based on the ViewModel, and insert the "newuser" into database.
        var newuser = new UserClass();
        newuser.ID = user.ID;
        newuser.Name = user.Name;

        // save the newuser into the database via dbcontext
        _dbcontext.UserClass.Add(newuser);
        _dbcontext.SaveChanges();

        return RedirectToAction(nameof(Index));
    }

    return View();
}

View:
@model WebApplication2.Models.UserViewModel

@{
    ViewData["Title"] = "CreateUser";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

        <form asp-action="CreateUser">

                <input asp-for="ID" class="form-control"value="@Context.Request.Query["ID"]" />

                <input asp-for="Name" class="form-control" value="@Context.Request.Query["Name"]"/>

                    <input class="form-check-input" asp-for="IsAccepted" />

                <input type="submit" value="Create" class="btn btn-primary" />

        </form>

Models
public class UserViewModel
{
     [Required(ErrorMessage = "Entry ID")]
     public int ID { get; set; }
     [Required(ErrorMessage = "Entry Name")]
     public string Name { get; set; }
     //use custom validation method
     [CheckBoxRequired(ErrorMessage ="Please checked the items")]
     public bool IsAccepted { get; set; }
}

Can anybody help and give advise? Thanks


text:
Q: Excel VBA to copy -> muliple paste and rename a windows file from an excel column I'm not that smart when it comes to programming. Please bear with me.
I have an image.pdf file in a source location c:\Source. I want to create a copy of this file and rename it in a different location under a different name. But the question is not over it.
I want to perform this paste operation for let's say hundred times and rename all the files based on an Excel column. Every day the range expands or shrinks.
For Example

Source File Name - Image.Jpg
  Source Location - C:\Source\
  Destination File Name - D:\Destination\
  Destination File Names -
Alpha.Jpg
  Beta.Jpg
  .
  .
  .
  .
  Zebra.Jpg

Could you please provide me with a code and sample Excel file to perform this by just entering the source and destination file names and locations?
Please help me out as I've been spending a lot of time in doing this every day. Please let me know if you need a sample Excel sheet for reference.

A: Try this. You will have to add the reference Microsoft Scripting Runtime. You do it under "Tools" -> "References"
Option Explicit

Sub CreateCopies(ByVal destPath As String, ByVal templateFullPathName As String)

Dim fso As Scripting.FileSystemObject
Dim aName As Variant
Dim wks As Worksheet
Dim myDest As String
Dim lastRow As Long, iCell As Long

Set fso = New Scripting.FileSystemObject

Set wks = ThisWorkbook.Sheets("Sheet1")

' Find last row in column A
lastRow = wks.Range("A" & wks.Rows.Count).End(xlUp).Row

' Loop through cells from last row to 2nd row (if 1st row is header)
For iCell = lastRow To 2 Step -1

    aName = Cells(iCell, 2).Value

    myDest = destPath & "\" & "Copy of " & aName & ".pdf"

    fso.CopyFile _
       Source:=templateFullPathName, _
       Destination:=myDest

Next iCell

If Not (fso Is Nothing) Then Set fso = Nothing
End Sub

Sub UseThisToCallProcedure()
Call CreateCopies("D:\Destination\", "C:\Source\FILETOCOPY.pdf")
End Sub


text:
Q: What is the deeper meaning of renormalizability and how is it related to gauge invariance? I ask myself if the demand of local gauge invariance - say $U(1)$ invariance in free Dirac theory -$$L_D=\bar{\Psi}(i\gamma^\mu\partial_\mu-m)\Psi$$
is enough to define the full Maxwell-Dirac-Lagrangian UNIQUELY? I read that adding the Maxwell term $-\frac{1}{4}F_{\mu\nu}F^{\mu\nu} $ demands for other requirements like 1) simplicity, 2) Lorentz invariance and 3) renormalizability. Similarly you need those other requirements for the interaction term $L_{int}=-j_\mu A^\mu$. While simplicity is clearly a metaphysical requirement Lorentz invariance is a genuinely physical one. But I am not sure about the role of renormalizability here?
What is the deeper physical meaning of it and why is the demand for renormalizability physically like the demand for Lorentz invariance?

A: When you do naive calculations based on your Lagrangian (perturbation theory and thus Feynman diagrams, setting e.g. the parameter $m$ to the mass of the particle) you will at some point run into infinite results.
This is due to the fact, that $m$ in your Lagrangian (and other coupling constants) is not physical. The physical mass could for example be defined as the pole of the propagator, which will change with the order in perturbation theory.
Now these infinities can be erased by carefully defining what the physical parameters are and it then turns out, that the parameters of the Lagrangian (e.g. $m$)  cancel the infinities of your naive calculation.
At least this is so in a renormalizable theory. In a non-renormalizable theory it can happen, that at some point in your perturbation theory you would get infinities you could not get rid of, without introducing new terms in the Lagrangian.
However, their are certainly people who believe that renormalizability is not a fundamental requirement for a theory which we only use in perturbation theory and which we know to break down at some high energy. In that sense I would not say that you can compare the demand for renormalizability with the demand for Lorentz invariance in its physical inevitability. But it produces "nicer" theories, which could also be argued to be simpler.


text:
Q: How to update regex to allow empty value or alphanumeric only I'm trying to modify a regex so it will allow an empty value or alphanumeric only.
I currently have this, but it only validates the alphanumeric
if (ruletype eq "alphanumeric") {
    bMatch = true;
    variables.fieldName = listGetAt(arguments.rules[nRow],2,",");
    if (structKeyExists(arguments.form, "#variables.fieldName#")){
        if (NOT RefindNoCase("[[:alnum:]]",arguments.form[variables.fieldName])) {
            lstError = listAppend(lstError,nRow,",");
        }
    } else {
        lstError = listAppend(lstError,nRow,",");
    }
}

I tried converting to rematch to find the empty value, but that also accepts the value 1234^%^&& which contains special characters. I'm not sure how to fix that.

A: Do I understand correctly, from the value you mention, that arguments.form[variables.fieldName] is a comma-delimited list? If so, then what is to be matched is each list-item.(Incidentally, the # in sdkfk364563!@#$% has to be delimited).
A possible answer is then:
if (structKeyExists(arguments.form, variables.fieldName)){
    // Assuming arguments.form[variables.fieldName] is a comma-delimited list
    fieldNameArray=listToArray(arguments.form[variables.fieldName], ',', true);

    for (fieldValue in fieldNameArray) {
        fieldValue=trim(fieldValue);
        if (fieldValue eq "" or REfindNoCase("^[a-zA-Z0-9]*$",fieldValue) eq 0) {
            lstError = listAppend(lstError,nRow);
        }
    }
}

A: [[:alnum:]] is POSIX syntax, which may not be supported. Use the universal ASCII syntax, [a-zA-Z0-9]. Also modify your code to account for the presence of an integer and to rule out any possible space character.
 if (structKeyExists(arguments.form, variables.fieldName)){
        if (REfindNoCase("^[a-zA-Z0-9]*$",trim(arguments.form[variables.fieldName])) eq 0) {
            lstError = listAppend(lstError,nRow);
        }
 }


text:
Q: Outer corner round design balloon I'm trying to figure out how to make outer corner round design for chat bubble, to get desired result:

I've to use bubble as component over different background without same and solid color, but with some design element, so space around bubble must be transparent:

I've tried add element as separate part, but it seems like incorrect way to fix it in right position with change of screen size as separate part and hide lower end of form behind bubble square corner:

.balloon {
  margin: 40px;
  display: inline-block;
  position: relative;
  width: 200px;
  height: auto;
  background-color: rgb(114, 238, 110);
}

.txt {
  padding: 10px;
}

.right:after {
  content: " ";
  position: absolute;
  right: 0px;
  bottom: -20px;
  border: 12px solid;
  border-color: rgb(114, 238, 110) rgb(114, 238, 110) transparent transparent;
}

.left:after {
  content: " ";
  position: absolute;
  bottom: -20px;
  border: 22px solid;
  border-color: transparent transparent transparent rgb(114, 238, 110);
}

div.selectable div.active:after {
  content: "";
  position: absolute;
  margin-right: -8px;
  width: 37px;
  height: 15px;
  border-right: 8px solid rgb(114, 238, 110);
  border-top: 8px solid rgb(114, 238, 110);
  border-top-right-radius: 39px;
}

Hello world right side

Hello world left side

Hello world

A: gradient background can do it:

.box {
  width:200px;
  height:100px;
  display:inline-block;
  margin:10px;
  background:
    linear-gradient(green 0 0) top/100% calc(100% - 34px),
    radial-gradient(105% 100% at bottom left,transparent 97%,green) bottom right/40% 35px;
  background-repeat:no-repeat;
}
.left {
  background:
    linear-gradient(green 0 0) top/100% calc(100% - 34px),
    radial-gradient(105% 100% at bottom right,transparent 97%,green) bottom left/40% 35px;
  background-repeat:no-repeat;
}

body {
  background:linear-gradient(to right,lightblue,#f2f2f2);
}

A: EDIT:
You can use :left and :right with a clip-path and polygon shape to create the clip over the psuedo element.

#chatbox {
  height: 600px;
  width: 600px;
  background: url('https://allhdwallpapers.com/wp-content/uploads/2015/05/circle-8.jpg') no-repeat;
}

.balloon {
  margin: 40px;
  display: inline-block;
  position: relative;
  width: 200px;
  height: auto;
  background-color: rgb(114, 238, 110);
}

.txt {
  padding: 10px;
}

.right:before {
  content: ' ';
  position: absolute;
  right: 0px;
  bottom: -20px;
  height: 20px;
  width: 60px;
  background-color: rgb(114, 238, 110);
  clip-path: polygon(0 0, 100% 0, 100% 100%, 96% 80%, 91% 63%, 83% 45%, 72% 28%, 56% 15%, 39% 7%, 21% 3%);
  -webkit-clip-path: polygon(0 0, 100% 0, 100% 100%, 96% 80%, 91% 63%, 83% 45%, 72% 28%, 56% 15%, 39% 7%, 21% 3%);
}

.left:before {
  content: ' ';
  position: absolute;
  height: 20px;
  bottom: -20px;
  width: 60px;
  left: 0px;
  bottom: -20px;
  background-color: rgb(114, 238, 110);
  clip-path: polygon(0 0, 100% 0, 77% 2%, 59% 6%, 42% 13%, 26% 25%, 14% 41%, 8% 59%, 4% 78%, 0 100%);
  -webkit-clip-path: polygon(0 0, 100% 0, 77% 2%, 59% 6%, 42% 13%, 26% 25%, 14% 41%, 8% 59%, 4% 78%, 0 100%);
}

div.selectable div.active:after {
  content: "";
  position: absolute;
  margin-right: -8px;
  width: 37px;
  height: 15px;
  border-right: 8px solid rgb(114, 238, 110);
  border-top: 8px solid rgb(114, 238, 110);
  border-top-right-radius: 39px;
}

Hello world right side

Hello world left side

A: Hey I didn't use the :after implementation. Instead I used separate div elements and just giving them appropriate height and right-top/left-top border-radius like so :-

.balloon {
      margin: 40px;
      display: inline-block;
      position: relative;
      width: 200px;
      height: auto;
      background-color: rgb(114, 238, 110) ;
    }

    .txt{
      padding: 10px;
    }

.bubble-right{
height:50px;
background:white;
border-top-right-radius:50%;
}

.bubble-left{
height:50px;
background:white;
border-top-left-radius:50%;
}

Hello world right side

Hello world left side


text:
Q: Storing data structure (set) as a file but not loading it into memory I have a 2gb text file for filtering out values used by a python program i access infrequently. I do this by loading every line into a set and doing fast contains checks. This was a good idea at first when the file was only a few megabytes in size, but after a year the file has grown, and the initial loading time has become unmanageable even though i have basically unlimited RAM.
Before i replace my existing code with a file-based binary search, i wanted to ask if there's any way to use set functionality directly as a file on disk? I know there are tools to store data structures and load them into memory, but the loading part is the problem here.

A: Your best bet is to store it to a database. MongoDB handles sets well. Then you can just query the database like you do a set.
you have to install
sudo apt install mongodb-server-core
pip3 install pymongo
And create a /data/db directory on your drive with the right permissions then run
mongod &
before this code will work:

from pymongo import MongoClient
client = MongoClient()

client = MongoClient('localhost', 27017)

#client = MongoClient('mongodb://localhost:27017')

db = client.pymongo_test

posts = db.posts
post_data = {
    'title': 'Python and MongoDB',
    'content': 'PyMongo is fun, you guys',
    'author': 'Bill'
}
result = posts.insert_one(post_data)
print('One post: {0}'.format(result.inserted_id))

bills_post = posts.find_one({'author': 'Bill'})
print(bills_post)

One post: 5dc61c0cc2b75ebc458da31f
{'_id': ObjectId('5dc61bf76071bde943ca262b'), 'title': 'Python and MongoDB', 'content': 'PyMongo is fun, you guys', 'author': 'Bill'}
``

A: How about this as an interim approach until you find a DB or indexed file solution.

*

*Divide the keyword file into multiple files(37), based on the character the keyword starts with. e.g.

*

*keys_startwith_a.txt /contains all values starting with 'A' or 'a'
...

*keys_startwith_z.txt /contains all values starting with 'Z' or 'z'

*keys_startwith_0.txt /contains all values starting with '0'
...

*keys_startwith_9.txt /contains all values starting with '9'

*keys_startwith_others.txt /contains all values starting with any other char

*change the read mechanism for each file as stream. e.g.
io.read(file, buffer=1)
Now if you want to compare values, you just have to check the char the key starts with and compare against the values in corresponding file.
With this

*

*Your file loading is faster(each file footprint should be significantly reduced) and on demand(stream) i.e. only when required

*comparison is faster since check is against less no of values.

*since you have unlimited memory, even if all the files are loaded during comparison, it . won't create issues.

*Finally, you can perhaps use threads for even faster loading of files and can pass on the comparison tasks to multiple threads(if required)


text:
Q: gcc 6.2.0 thread is not a member of std Program:
#include <thread>

int main(void)
{
    std::thread t;
    return 0;
}

test.cpp: In function 'int main()':
test.cpp:6:5: error: 'thread' is not a member of 'std'
    std::thread t;
    ^~~

GCC info:
$ g++ test.cpp -H
. /home/nathan/development/toolchain/gnu/x86_64-unknown-linux-gnu/include/c++/6.2.0/thread

$ gcc -v
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/home/nathan/development/toolchain/gnu/x86_64-unknown-linux-gnu/libexec/gcc/x86_64-pc-linux-gnu/6.2.0/lto-wrapper
Target: x86_64-pc-linux-gnu
Configured with: ../gcc/configure --prefix=/home/nathan/development/toolchain/gnu/x86_64-unknown-linux-gnu --enable-languages=c,c++,fortran --disable-multilib --enable-threads=posix --enable-libstdcxx-threads
Thread model: posix
gcc version 6.2.0 (GCC)

Using other parts of STL work just fine, it is only thread that fails. Am I
missing something? When configured, GCC picks up the threading model.
Edit 1
Recompiled GCC with --enable-threads. Still produces same error.
Edit 2
Recompiled GCC with --enable-libstdcxx-threads. Still produces same error.
Edit 3
Recompiled GCC with --enable-threads=posix. Still produces same error.
Edit 4
Wanted to make clear that I was building using the repo on branch gcc-6_2_0-release.

A: After trying multiple times to build using the repo source, I eventually gave up, and compiled using the released tarballs from a GNU mirror. Not sure what options would have made the difference from what is in the repo vs what is released, but I simply used:
--enable-languages=c,c++ --disable-multilib
and everything worked as expected.


text:
Q: "bad value for range" is raised in rspec/turnip I'm using turnip for testing.
I wrote the following test:
session = ActionDispatch::Integration::Session.new(Rails.application)
str = "Basic " + Base64.strict_encode64("#{@token}:#{@secret}")
session.get "/api/v1/recommend/#{n}", nil, {"Authorization" => str}

I used ActionDispatch::Integration::Session.new(Rails.application) because turnip don't support get.
@token and @secret are values for token and token_secret, and I confirmed these values are valid.
n is given at arguments.
Next, I run it and these errors occurred:
Failures:

  1) test
     Failure/Error: test1
     ArgumentError:
       bad value for range
     # ./spec/features/recommendation.feature:13:in `test1'
     # ./app/models/user.rb:682:in `recommendation'
     # ./app/controllers/api/v1/users_controller.rb:209:in `recommendation'
     # spec/steps/recommendation_steps.rb:32:in `block (2 levels) in <top (required)>'
     # ./spec/features/recommendation.feature:14:in `block (6 levels) in run'
     # ./spec/features/recommendation.feature:13:in `each'
     # ./spec/features/recommendation.feature:13:in `block (5 levels) in run'
     # -e:1:in `<main>'

I tried the following cases and confirmed they are successful.

*

*Do same things in rails console

*Make a dummy encoded string and use it (of course authentication was failing, but no error)

Why did such errors occur?
(Added)
./app/models/user.rb:682:in recommendation:
  def recommendation limit = 10
    result = Hash.new{0.0}
    unused_recipe_ids = Recipe.where.not(id: self.made_recipes.pluck(:id)).pluck(:id)
    self.made_activities.includes(:recipe).each do |activity|
      c = coefficient(activity)
      similarities = RecipeSimilarity.where(from_recipe_id:           activity.recipe.id).where(to_recipe_id: unused_recipe_ids)
      similarities.each { |s| result[s.to_recipe_id] += s.score * c }
    end
    Recipe.where(id: result.sort{|a, b| b[1] <=> a[1]}[0...limit].map{|r| r[0]})
  end

  def coefficient activity
    return 1.5 if activity.type_code == 301
    return 0.5 if activity.type_code == 302
    if activity.type_code == 100
      return 1.0 if activity.evaluation == 0
      return 0.1 if activity.evaluation == 1
      return 0.6 if activity.evaluation == 2
      return 1.1 if activity.evaluation == 3
      return 1.6 if activity.evaluation == 4
      return 2.5 if activity.evaluation == 5
    end
    return 1.0
  end

./app/controllers/api/v1/users_controller.rb:209:in recommendation:
  def recommendation
    @recipes = @current_user.recommendation(params[:limit])
    render text: @recipes.to_json
  end

Recipe.count is 50.
RecipeSimilarity.count is 2500.


text:
Q: Нарисовать круг в svg Кто может нарисовать круг под размеры viewBox="0 0 36 36", простой круг. Ни эллипсом, а под тег path.

<svg  xmlns="http://www.w3.org/2000/svg"  xmlns:xlink="http://www.w3.org/1999/xlink"
         width="36" height="36" viewBox="0 0 36 36" >
 <circle cx="18" cy="18" r="15" fill="none" stroke="black" />
</svg>

Вообще не понимаю как в Inkscape, выполнить это. Одни эллипсы...

A: Задача понятна - перевод окружности из тега circle в идентичную окружность с помощью тега path.
Это действительно важно, так как анимации, например animateMotion - движение объекта вдоль пути, работают только с path

Вообще не понимаю как в Inkscape, выполнить это. Одни эллипсы.

#1. Установить в <ellipse cx="18" cy="18" rx="15" ry="15"> и эллипс превращается при равенстве радиусов - в окружность.  (Но это комментарий для общего понятия)
#2. С помощью векторного редактора
Чтобы получить идеальную окружность по форме нужно выполнить следующие шаги

*

*Написать svg с требуемыми параметрами, в частности viewBox="0 0 36 36"

<svg  xmlns="http://www.w3.org/2000/svg"  xmlns:xlink="http://www.w3.org/1999/xlink"
         width="36" height="36" viewBox="0 0 36 36" >
 <circle cx="18" cy="18" r="15" fill="none" stroke="black" />
</svg>

*

*Загрузить этот файл в векторный редактор

*

*В верхнем меню выбрать: контур / оконтурить объект Shift+Ctrl+C

*Сохранить файл в формате - *.svg и скопировать path
d="M 33,18 A 15,15 0 0 1 18,33 15,15 0 0 1 3,18 15,15 0 0 1 18,3 15,15 0 0 1 33,18 Z"
Ниже готовый результат:

.container {
width:30vw;
heigh:30vh;
}

<svg  xmlns="http://www.w3.org/2000/svg"  xmlns:xlink="http://www.w3.org/1999/xlink"
          viewBox="0 0 36 36" >
 <path fill="none" stroke="black" d="M 33,18 A 15,15 0 0 1 18,33 15,15 0 0 1 3,18 15,15 0 0 1 18,3 15,15 0 0 1 33,18 Z" />
</svg>

UPDATE

Это действительно важно, так как анимации, например animateMotion -
движение объекта вдоль пути, работают только с path

Решил в качестве бонуса добавить пример анимации движения шарика вдоль круговой трассы id="trace"

.container {
width:30vw;
heigh:30vh;
}

<svg  xmlns="http://www.w3.org/2000/svg"  xmlns:xlink="http://www.w3.org/1999/xlink"
          viewBox="0 0 36 36" >
 <path id="trace" fill="none" stroke="black" d="M 33,18 A 15,15 0 0 1 18,33 15,15 0 0 1 3,18 15,15 0 0 1 18,3 15,15 0 0 1 33,18 Z" />
 <circle cx="" cy="" r="2" fill="red">

        <animateMotion id="myanim" dur="6s" begin="0; myanim.end+1s" fill="freeze">
           <mpath xlink:href="#trace"/>
        </animateMotion>
    </circle>
</svg>


text:
Q: Querying an array in Firebase I am sure this has been asked before but I am struggling to find a correct answer. I'm using Swift 3. Here's the problem:
I have a list of postID's in an array. I now want to query Firebase and if the postID exists, then retrieve the data and display it in my tableview.
What's the recommended way to do this ? Any code examples would be of great help. Ideally I would want to get all the posts and then update the table view in one shot. Thanks.
To be clear I am looking for the Firebase Query here that will help me achieve this.
Firebase structure

A: Try this
first create database reference till post
let mainRef = Database.database().reference().child("Posts")

Now suppose you have post id in myPostID variable
 mainRef.child(myPostID).observeSingleEvent(of: .value) { (snapshot) in
            print(snapshot)
            if let  value = snapshot.value {
               // Value FOUND UPDATE YOUR TABLE HERE
            } else {
              // No ID found for this post
            }
  }

Hope it is helpful


text:
Q: Adding constraints to subview leading/trailing/top/bottom not working I'm trying to add a subview which is pinned to the leading/trailing/top/bottom of its superview, but neither view is drawn when I try and activate the constraints.
When I comment out the constraints code, I see the blue view, activating them I just get a black view in the playground.
To help debug this issue I created a playground, but still can't figure out why this is happening:
//: A UIKit based Playground for presenting user interface

import UIKit
import PlaygroundSupport

class MyView: UIView
{
    override init(frame: CGRect)
    {
        super.init(frame: frame)

        translatesAutoresizingMaskIntoConstraints = false
        backgroundColor = .blue
    }

    required init?(coder aDecoder: NSCoder)
    {
        fatalError()
    }
}

// Present the view controller in the Live View window
let myView = MyView(frame: CGRect(x: 0, y: 0, width: 300, height: 200))

PlaygroundPage.current.liveView = myView

let subview = UIView()
subview.translatesAutoresizingMaskIntoConstraints = false
subview.backgroundColor = .red

myView.addSubview(subview)

subview.leadingAnchor.constraint(equalTo: myView.leadingAnchor).isActive = true
subview.trailingAnchor.constraint(equalTo: myView.trailingAnchor).isActive = true
subview.topAnchor.constraint(equalTo: myView.topAnchor).isActive = true
subview.bottomAnchor.constraint(equalTo: myView.bottomAnchor).isActive = true

A: So setting the frame alone is not enough, the superview must have width and height constraints set to it.


text:
Q: How to use org.scalatest.Suite I'm trying to use scalatest suite using intellij idea like this :
class SampleTest extends org.scalatest.Suite {
    def myTest() {
       assert(true)
    }
}
(new SampleTest).execute()

I have added scalactic_2.11 and scalactic_2.11 to my pom file.The problem is that the SDK still cant resolve it.

A: Well it seems the problem is due to versioning. using the following version resolved the issue :
<dependency>
    <groupId>org.scalatest</groupId>
    <artifactId>scalatest</artifactId>
    <version>0.9.5</version>
</dependency>


text:
Q: Is it possible to /manipulate/ functions as it is strings? var myString = '';
myString += 'foo';
myString += 'bar';
myString = myString.replace(/oba/, 'qux');

console.log(myString) // produces "foquxr"

Is there any way to likewise tinker around with functions, like, say, turning function(a) { a += 'b'; return a; } info function(a) { a += 'b'; console.log(a); return a + 'c'; }?

A: You can compose functions thus
// (compose(f, g))(x, y, ...) is the same as f(g(x, y, ...))
function compose(f, g) {
  return function (var_args) {
    return f.call(this, g.apply(this, arguments));
  };
}

so
var f = compose(
  function (x) { console.log(x); return x + 'c'; },
  function (a) { a += 'b'; return a; });

lets you combine two small functions to get a function that behaves like

function(a) { a += 'b'; console.log(a); return a + 'c'; }

A: You could achieve this (without using eval) by getting the function's body from its declaration, manipulating it as needed, and redefining it by means of the Function() constructor:
function myFunction(a) { a += 'b'; return a; }

function changeFunction(){
    var func = window['myFunction'].toString();
    var body = func.substring(func.indexOf("{")+1, func.lastIndexOf("}"));
    body = body.replace("return a;", "console.log(a); return a + 'c';");
    window.myFunction = Function("a", body);
}

Here's a JSFiddle


text:
Q: How close can I place two squad members together before I'm guaranteed to eat a grenade? If I'm fighting Mutons, Heavy Floaters, or Cyberdiscs, they will tend to eschew their primary attack in favor of hucking a grenade in my general direction if my squad is spaced together too tight.
I know that there's a non-zero chance that they will just grenade one of my squad members anyway, but is there a good rule of thumb for how far apart my squad members should be in order to avoid a guaranteed grenade?  I assume it must be related to the radius of the grenade's blast, but I rarely use grenades myself so I don't have this info committed to memory already.

A: Visually, it looks like the effect radius of a grenade is a little larger than 2.5 tiles. It easily encompasses 5 tiles in a row (so if your soldiers are standing on tile #1 and tile #5 - 3 tiles in between - a grenade will easily include both soldiers' tiles completely. If your soldiers are standing on tile #1 and tile #6 - 4 tiles in between - it looks like it is still not that hard to hit them both with the grenade (but it's right at that edge where if you were trying, you'd be spending some time fiddling with the exact right placement). Soldiers at #1 and #7 (5 tiles in between) are safe.
I tested this by placing two soldiers 3,4, and 5 squares apart and seeing if I could fit the grenade indicator in between them without the "friendly fire" indicator (blue grenade indicator turns orange) turning on.

A: Alien grenades have the same AoE radius as regular ones (but better damage); if two of your people are close enough together that a single grenade could blast them both, chances are a muton or floater that manages to get into chucking range will toss one -- especially if they're both behind cover and its regular hit chance would be low.
The AI is reasonably clever; ask yourself "If I saw two enemies this close together, and behind cover where I'd have a poor chance of hitting them with regular fire, would I chuck a grenade?" If the answer is yes, then assume that the AI will do so if given the chance.
Also bear in mind that the grenade blast will injure your people and strip their cover and give any other alien units in the area a free shot. The AI will factor that into its consideration as well -- and remember that it isn't interested in keeping as much of your equipment intact as possible.


text:
Q: Noise from laptop I hope everybody is doing well. I have had this noise from my computer every `0 - 20 minutes for 2 days. it happened 1 time 1 month ago and sometimes it stops when I tap on the cooling fan side. Here's the sound I recorded:
https://drive.google.com/file/d/1V1k8ocZ_ohbIIbRtcy6p280N34BheYbP/view?usp=sharing
I opened my laptop case and the cooling fan seems clean from the outside.
Any idea why this could happen?
Model: Dell latitude e7450
Thank you

A: It's difficult to be certain from the sound, but it sounds a lot like the lubrication of the fan bearing has dried up. The possible fixes for this are:

*

*Replace the fan assembly

*Remove the fan assembly and relubricate the bearing

If you're not confident in your ability to do either of these, then you'll need to take it to a computer repair shop. In particular, the difficulty of the second option will depend on the design of the fan and how easy it is to gain access to the bearing. Some fans just have a sticker that can be peeled back and some drops of oil put into the hole, others require the impeller to be removed which can require some force and care needs to be taken not to break the fan blades.


text:
Q: Find Maclaurin series of $ y(t)=(t^2+t-2)e^{t^2+1} $
Find Maclaurin series of
$$
y(t)=(t^2+t-2)e^{t^2+1}
$$

I acted as usual:
$$
y(t)=e(t^2+t-2)\sum_{k=0}^\infty\frac{t^{2k}}{k!}=\sum_{k=0}^\infty\frac{et^{2k+2}}{k!}+\sum_{k=0}^\infty\frac{et^{2k+1}}{k!}-\sum_{k=0}^\infty\frac{2et^{2k}}{k!}
$$
And then I got stuck, since I don't understand how to combine even and odd powers together.

A: Now you do\begin{align}\sum_{k=0}^\infty\frac{et^{2k+2}}{k!}+\sum_{k=0}^\infty\frac{et^{2k+1}}{k!}-\sum_{k=0}^\infty\frac{2et^{2k}}{k!}&=\sum_{k=1}^\infty\frac{et^{2k}}{(k-1)!}+\sum_{k=0}^\infty\frac{et^{2k+1}}{k!}-\sum_{k=0}^\infty\frac{2et^{2k}}{k!}\\&=-2e+\sum_{k=1}^\infty\left(\frac e{(k-1)!}-\frac e{k!}\right)t^{2k}+\\&\phantom=+\sum_{k=0}^\infty\frac{et^{2k+1}}{k!}.\end{align}In other words, the MacLaurin series is $\sum_{k=0}^\infty a_kt^k$ with$$a_k=\begin{cases}-2e&\text{ if }k=0\\\frac e{\left(\frac{k-1}2\right)!}&\text{ if $k$ is odd}\\\frac e{\left(\frac k2-1\right)!}-\frac e{\left(\frac k2\right)!}&\text{ if $k$ is even and }k>0.\end{cases}$$


text:
Q: Ruby vs. Ruby On Rails What is the difference between Ruby on Rails and Ruby? I have asked four people but none can come up with a definitive answer. Is Rails a library of sorts for Ruby, a la Django to Python or Cocoa to Objective C, or is it a totally different language with different capabilities?
What can one do on Rails that cannot be done just with ruby?

A: Rails is a framework for building web applications with Ruby.  Ruby is a general purpose programming language.  Yes, Rails is analogous to Django.

A: Ruby is a programming lang like python and obj C. Rails is not a programming lang. It is a web framework for creating web apps and uses Ruby programming lang. :)

A: RoR is Web application framework on Ruby. Read more in Official Rails Documentation here


text:
Q: Create a variable with n bytes I'm writing an application that works with big-data applications. One of my processes is failing and debugging is taking a while because some of the files that needed to be loaded in memory are 50+ gb.
I want to be able to create an object with 2GB and another with 41GB of memory space. (It doesn't matter what is in the object, the object just needs to take some memory). I would read from a file, but its is taking a while.
Is there a programmatic way of creating a object with 2GB of memory size in python3.7?

A: import sys

a = 'a' * 3000000000
sys.getsizeof(a) / 1024 / 1024 / 1024

The output is 2.7939677694812417 = 2.8GB.

A: Thanks to @Quang Hoang in the comments. I'm just adding this answer here if someone is looking for an answer
some_var = 'x' * (1<<32)


text:
Q: How can I use an array in str_replace() function? All I'm trying to do is removing all <space> (spaces), - (dashes), , (commas). Here is my code:-
$str = "fwepoki3-4,32de e34d";
$res = str_replace(",", "", str_replace("-", "", str_replace(" ", "", $str)));

Is another function in php or any better idea for doing that?

A: You can do that by passing an array as first argument:
$res = str_replace(array(' ', '-', ','), '', $str);

You can test it here at phpfiddle.org.

str_replace() PHP's function let you choose if the three
  parameters will be a single value or an array.


text:
Q: MySQL shutdown unexpectedly in XAMPP XAMPP's control panel displays error as

Error: MySQL shutdown unexpectedly.
  14:09:43  [mysql]   This may be due to a blocked port, missing dependencies,
  improper privileges, a crash, or a shutdown by another method.

Text in mysql_error.log is
3812 [Note] Plugin 'FEDERATED' is disabled.
 1604 InnoDB: Warning: Using innodb_additional_mem_pool_size is        DEPRECATED. This option may be removed in future releases, together with the option innodb_use_sys_malloc and with the InnoDB's internal memory allocator.
[Note] InnoDB: Using atomics to ref count buffer pool pages
[Note] InnoDB: The InnoDB memory heap is disabled
 [Note] InnoDB: Mutexes and rw_locks use Windows interlocked functions
 [Note] InnoDB: Memory barrier is not used
 [Note] InnoDB: Compressed tables use zlib 1.2.3
 [Note] InnoDB: Not using CPU crc32 instructions
 [Note] InnoDB: Initializing buffer pool, size = 16.0M
 [Note] InnoDB: Completed initialization of buffer pool
 [Note] InnoDB: Restoring page 0 of tablespace 0
 [Warning] InnoDB: Doublewrite does not have page_no=0 of space: 0
 [ERROR] InnoDB: space header page consists of zero bytes in data file C:\xampp\mysql\data\ibdata1
 [ERROR] InnoDB: Could not open or create the system tablespace. If you tried to add new data files to the system tablespace, and it failed here, you should now edit innodb_data_file_path in my.cnf back to what it was, and remove the new ibdata files InnoDB created in this failed attempt. InnoDB only wrote those files full of zeros, but did not yet use them in any way. But be careful: do not remove old data files which contain your precious data!
       [ERROR] Plugin 'InnoDB' init function returned error.
 2015-04-15 14:09:43 3812 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
  [ERROR] Unknown/unsupported storage engine: InnoDB
   [ERROR] Aborting

2015-04-15 14:09:43 3812 [Note] Binlog end
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'partition'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'PERFORMANCE_SCHEMA'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_SYS_DATAFILES'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_SYS_TABLESPACES'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN_COLS'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_SYS_FIELDS'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_SYS_COLUMNS'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_SYS_INDEXES'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_SYS_TABLESTATS'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_SYS_TABLES'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_FT_INDEX_TABLE'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_FT_INDEX_CACHE'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_FT_CONFIG'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_FT_BEING_DELETED'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_FT_DELETED'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_FT_DEFAULT_STOPWORD'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_METRICS'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_BUFFER_POOL_STATS'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE_LRU'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX_RESET'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX'
2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_CMPMEM_RESET'
  2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_CMPMEM'
  2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_CMP_RESET'
  2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_CMP'
  2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_LOCK_WAITS'
  2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_LOCKS'
  2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'INNODB_TRX'
  2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'BLACKHOLE'
  2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'ARCHIVE'
  2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'MRG_MYISAM'
  2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'MyISAM'
  2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'MEMORY'
  2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'CSV'
  2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'sha256_password'
  2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'mysql_old_password'
  2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'mysql_native_password'
  2015-04-15 14:09:43 3812 [Note] Shutting down plugin 'binlog'
  2015-04-15 14:09:43 3812 [Note] c:\xampp\mysql\bin\mysqld.exe: Shutdown complete

A: if you want to fix the problem without losing your data you need to restore your database from backup just follow below steps carefuly and it will works !!

*

*Rename the folder xampp/mysql/data to xampp/mysql/data_backup

*Create a new folder xampp/mysql/data

*Copy the content that resides in xampp/mysql/backup to the new
xampp/mysql/data folder

*Copy all your database folders that are in xampp/mysql/data_backup to xampp/mysql/data
Important: Do not copy the mysql, performance_schema, and phpmyadmin folders from xampp/mysql/data_bk
5.Copy the ibdata1 file from xampp/mysql/data_backup and replace
it inside xampp/mysql/data folder
5.FINALLY!! Start MySQL from XAMPP control panel again

A: For avoiding this problem,
you can follow some steps which are given below:

*

*At first you should stop "Apache" and "MySQL" in your "xampp
control panel".

*Go to the path: C:\xampp\mysql\backup
Copy here everything

*Go to the path: C:\xampp\mysql\data
And paste it here everything

*Here you will see a pop-up: Replace or Skip Files
Click Replace the files in the destination

*Now you can start "Apache" and "MySQL" without any hassle.
Hopefully, it will work properly.


text:
Q: Knockout.js Tabindex in a foreach I am applying tabindex to multiple rows of textareas in a foreach list. There is a button at the end of each row. I need the tabbing sequence to go from left to right for each row proceeding to the next row, etc.
How can it make the preceeding rows start at a higher number than the proceeding rows?
eg: I expect:
row 1: tabindex 1,2,3
row 2: tabindex 4,5,6
but I am getting (2nd row starting 1 less than expected):
row 1: tabindex 1,2,3
row 2: tabindex 3,4,5

        <textarea rows="3" data-bind="attr: {  tabindex: ($index() + 1) }"></textarea>

        <textarea rows="3" data-bind="attr: {  tabindex: ($index() + 2) }"></textarea>

      delete row

A: You should multiply the index by 3:
data-bind="attr: { tabindex: ($index() * 3 + [index]) }"

The complete code:

            <textarea rows="3" data-bind="attr: { tabindex: ($index() * 3 + 1) }"></textarea>

            <textarea rows="3" data-bind="attr: { tabindex: ($index() * 3 + 2) }"></textarea>

        delete row


text:
Q: What event will fire if the textarea not being focus? Is there any event will fire if the textarea is not focus anymore?

A: onblur i think fires on an element that loses focus.  Check this out
http://www.w3schools.com/jsref/event_onblur.asp

A: That would be the blur, which is the opposite of focus.


text:
Q: Gradle/ivy use cached repos? I would like Grade/Ivy to use cached versions of my jars, as it takes ~20 seconds to check every time for updates.
Is this possible?
Thank you
Misha

A: Depending on the required speed it may be sufficient to setup a local repository proxy (you can do this for multiple repositories not only maven central) with Artifactory or Nexus. This way checking for updates should be much faster since it no longer goes over the internet but only over the local network. Only the first time you use a dependency will the proxy download it from the upstream repository.

A: Here, as always, is my hack-ey solution:
deps.sh
#!/bin/bash
if [ -d lib ]; then
   rm -rf lib
fi
mkdir lib

cd lib
NAMES=`find ~/.gradle/cache -name \*.jar`
for NAME in $NAMES; do
   ln -s $NAME .
done

and my build.gradle becomes
apply plugin: 'groovy'

/*
repositories {
   mavenCentral()
}
*/

dependencies {
  /*
  groovy group: 'org.codehaus.groovy', name: 'groovy', version: '1.7.0'
  groovy group: 'org.hibernate', name: 'hibernate-core', version: '3.3.2.GA'
  groovy group: 'org.hibernate', name: 'hibernate-annotations', version: '3.4.0.GA'
  groovy group: 'org.slf4j', name: 'slf4j-jdk14', version: '1.6.0'
  groovy group: 'org.jasypt', name: 'jasypt', version: '1.6'
  groovy group: 'org.codehaus.groovy.modules.http-builder', name: 'http-builder', version:     '0.5.0'
  groovy group: 'net.sourceforge.htmlunit', name: 'htmlunit', version: '2.7'
  testCompile group: 'junit', name: 'junit', version: '4.7'
  */
  groovy fileTree(dir: 'lib', include: '*.jar')
}


text:
Q: Horizontal slide menu calling Activity and caused NullPointerException after resume My ActivityA has a horizontal slide menu that contains one button.
Here is the behaviour:
1) During onClick, it will call ActivityB via startActivityForResult() for users to select a category group.
2) Then, it will call another activity, ActivityC for users to select a sub-category.
3) After that, it will return back to the ActivityA. (Both ActivityB and ActivityC call finish(), after they are done.)
Right after resume to ActivityA, the app is crashed and here is what I saw in Logcat. None of them are pointing to my code. Any suggestion please?
** And, I just found out that the NullPointer happens in CustomHorizontalScrollView.onLayout()
Is that because the scroll menu losing focus after resume? Or, it's confused with which TargetFragment should it display?? I tried putting in try-catch for that NullPointer inside onLayout() so that my app doesn't FC. The scroll menu and the main layout are displayed just fine. But only the search result didn't get displayed.
Activity A: source code
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LayoutInflater inflater = LayoutInflater.from(this);
    scrollView = (CustomHorizontalScrollView) inflater.inflate(R.layout.slide_menu, null);
    setContentView(scrollView);

    menu = inflater.inflate(R.layout.horz_scroll_menu, null);
    app = inflater.inflate(R.layout.main_list, null);

    btnSlide = (ImageView) app.findViewById(R.id.ib_slide_menu);
    btnSlide.setOnClickListener(new ClickListenerForScrolling(scrollView, menu));

    fAdsSearch = (AdsSearchFragment)getSupportFragmentManager().findFragmentById(R.id.f_search);
    fActionbar = (ActionBarFragment) getSupportFragmentManager().findFragmentById(R.id.f_actionbar);
    fAdsSearch.setTargetFragment(getSupportFragmentManager().findFragmentById(R.id.f_main), 0);
scrollView.initViews(new View[] {menu, app}, 1, new SizeCallbackForMenu(btnSlide));
}

slide_menu.xml: source code
<?xml version="1.0" encoding="utf-8"?>
<CustomHorizontalScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#00ffffff"
android:padding="0px"
android:layout_margin="0px"
android:fadingEdge="none"
android:fadingEdgeLength="0px"
android:scrollbars="none">
<LinearLayout
    android:id="@+id/top"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:orientation="horizontal"
    android:background="#ffffffff"
    android:padding="0px"
    android:layout_margin="0px">
</LinearLayout>
</CustomHorizontalScrollView>

horz_scroll_menu.xml: source code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<fragment
    android:id="@+id/f_filter_menu"
    android:name="MenuFragment"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
</fragment>
</LinearLayout>

main_list.xml: source code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<fragment
    android:id="@+id/f_actionbar"
    android:name="ActionBarFragment"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />
<fragment
    android:id="@+id/f_search"
    android:name="SearchFragment"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />
<fragment
    android:id="@+id/f_main"
    android:name="MainFragment"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />
</LinearLayout>

Logcat error:
02-08 15:57:12.959: E/AndroidRuntime(19322): FATAL EXCEPTION: main
02-08 15:57:12.959: E/AndroidRuntime(19322): java.lang.NullPointerException
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.Spinner.makeAndAddView(Spinner.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.Spinner.layout(Spinner.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.Spinner.onLayout(Spinner.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.view.View.layout(View.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.view.ViewGroup.layout(ViewGroup.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.LinearLayout.layoutHorizontal(LinearLayout.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.LinearLayout.onLayout(LinearLayout.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.view.View.layout(View.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.view.ViewGroup.layout(ViewGroup.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.LinearLayout.onLayout(LinearLayout.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.view.View.layout(View.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.view.ViewGroup.layout(ViewGroup.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.FrameLayout.onLayout(FrameLayout.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.view.View.layout(View.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.view.ViewGroup.layout(ViewGroup.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.LinearLayout.onLayout(LinearLayout.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.view.View.layout(View.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.view.ViewGroup.layout(ViewGroup.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.LinearLayout.layoutHorizontal(LinearLayout.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.LinearLayout.onLayout(LinearLayout.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.view.View.layout(View.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.view.ViewGroup.layout(ViewGroup.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.FrameLayout.onLayout(FrameLayout.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.HorizontalScrollView.onLayout(HorizontalScrollView.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.view.View.layout(View.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.view.ViewGroup.layout(ViewGroup.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.FrameLayout.onLayout(FrameLayout.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.view.View.layout(View.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.view.ViewGroup.layout(ViewGroup.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.LinearLayout.setChildFrame(LinearLayout.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.LinearLayout.layoutVertical(LinearLayout.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.LinearLayout.onLayout(LinearLayout.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.view.View.layout(View.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.view.ViewGroup.layout(ViewGroup.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.widget.FrameLayout.onLayout(FrameLayout.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.view.View.layout(View.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.view.ViewGroup.layout(ViewGroup.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.os.Handler.dispatchMessage(Handler.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.os.Looper.loop(Looper.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at android.app.ActivityThread.main(ActivityThread.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at java.lang.reflect.Method.invokeNative(Native Method)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at java.lang.reflect.Method.invoke(Method.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
02-08 15:57:12.959: E/AndroidRuntime(19322):    at dalvik.system.NativeStart.main(Native Method)

A: It turns out to be that this NullPointerException has nothing to do with the slide menu. It's because I clean up the list data by setting adapter to null. Thanks for all your help.


text:
Q: Javascript convert string to base64 and back again not correct I noticed that when I convert a javascript string to base64 with atob and then
back to text with btoa it returns a string different than where I started. I am wondering why?
Example:
btoa(atob('hello world'));

The result of this in Chrome dev tools is:
"helloworlQ=="
Any ideas why?

A: You are using the functions the wrong way around. "hello world" is a valid base64 string, but what you want is atob(btoa())

A: To convert ASCII to Base64, you need to do
btoa("hello world"); // "aGVsbG8gd29ybGQ="

To convert Base64 to ASCII, you do
atob("aGVsbG8gd29ybGQ="); // "hello world"

The names of the atob and btoa functions are very confusing.


text:
Q: Request a popular name for this or its solution algorithm Here is the problem together with the kind of result I am expecting.
I already have a routine that does this, I would like to research other solutions though so need any popular names for either a solutions or the problem itself.
If name1 and name2 are aliases or equivalent and name3 and name2 are aliases then
name1, name2, and name3 are all aliases of each other.

>>> aliases = [('name1', 'name2'), ('name3', 'name2')]
>>> consolidate_aliases(aliases)
[('name2', 'name3', 'name1')]
>>> aliases = [('A', 'X'), ('B', 'Y'), ('C', 'Z'), ('S', 'L'), ('T', 'M'), ('U', 'N'), ('Y', 'T'),  ('B', 'L')]
>>> consolidate_aliases(aliases)
[('S', 'B', 'T', 'Y', 'M', 'L'), ('U', 'N'), ('C', 'Z'), ('A', 'X')]
>>>

A: It's called transitive closure.

A: It looks like Union-Find algorithm

A: It is a variant of the "Connected components of a graph" problem. Google for it to see answers  like this and this.


text:
Q: error implementing passport-facebook authentication with the error code as "FacebookTokenError": redirect_uri isn't an absolute URI. Check RFC 3986 i'm using a localhost to test the passport-facebook authentication, i've been trying to implement the Auth and im getting the error mentioned above i've reviewed similar questions but none seem to help me, i've changed my dns address but to no avail,
this is my passport.js code for facebook authentication
const  mongoose  = require("mongoose");
const FacebookStrategy = require('passport-facebook').Strategy;
const passport = require('passport');
const User = module.exports = mongoose.model('User', facebookSchema)

var facebookSchema = mongoose.Schema

module.exports = function (_passport) {}
//serialize the user for the session
passport.serializeUser(function (user, done) {
done(null, user.id);
});

//deserialize the user
passport.deserializeUser(function (id, done) {
User.findById(id, function (err, user) {
done(err, user);
});
});

passport.use('facebook', new FacebookStrategy({
   clientID: 'XXXXXXXXXX',
   clientSecret: 'YYYYYYYYYYYYYYY',
   callbackURL: " http://localhost:3000/auth/facebook/callback",
   enableProof: true,
   profileFields: ['id', 'displayName', 'photos', 'email']
   },
   function (accessToken, refreshToken, profile, done)

  { let newUser = new User();
   // set the user's facebook credentials
   newUser.facebook.email = profile.emails[0].value,
   newUser.facebook.fullName = profile.displayName,

   User.findOne({email:newUser.facebook.email }, function(err, user) {
   if(!user) {
   newUser.save(function(err, newUser) {
   if(err) return done(err);
   done(null,newUser);
   });
   } else {
   done(null, user);
   }
   });
   }
  ));

this is my index.js code for initiallizing app
const rfc = require('rfc-3986');
const express = require('express');
const bodyParser = require('body-parser');
var routes = require('./routes/routes'); //importing route
require('./models/userModel')

app = express();
port = 3000;

require("./config/db"); app.get('/success', (req, res) => res.send("You have successfully logged in"));
app.get('/error', (req, res) => res.send("error logging in"));

const passport = require("passport");
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport);
app.set(rfc)
routes(app, passport);
app.set('view engine', 'ejs')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended:true}))

app.listen(port,()=>{
    console.log('server listening on localhost:' + port)
});

and this is my routes.js for app routing
app.get('/auth/facebook',
  passport.authenticate('facebook',  {scope:"email"}));

app.get('/auth/facebook/callback',
  passport.authenticate('facebook', { failureRedirect: '/login' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/success');`module.exports = function(app, passport) {
app.get('/auth/facebook',
  passport.authenticate('facebook',  {scope:"email"}));

app.get('/auth/facebook/callback',
  passport.authenticate('facebook', { failureRedirect: '/login' }),
  function(req, res) {
    // Successful authentication, redirect home.
    res.redirect('/success');
  });
}

  });
}

this is the error i get on browser
this is the same error on terminal


text:
Q: How to detect if JavaScript (ES6) class has a non-default constructor? I would like to know by some form of reflection or other means if a given ES6 class has a user-written non-default constructor, or not.

A: Assuming that user-provided constructor has one argument or more, you can do that by checking the length property of the function(class). But if the constructor takes no argument, there is simply no way as far as I know

function Person(fName, lName) {
    this.firstName = fName;
    this.lastName = lName
}
console.log(Person.length);

function Person2() {}
console.log(Person2.length);

class Person3 {
    constructor(f,l) {}
}
console.log(Person3.length);

class Person4 {
}
console.log(Person4.length);

A: You can invoke the Classname.prototype.constructor.toString() (where Classname is the inspected class name) and get the source string for the class. Which you can then parse and see if it was a constructor declared or not.
Presumably, you need a decent parser for that, but it's another story.
References:

*

*http://www.ecma-international.org/ecma-262/6.0/#sec-function.prototype.tostring


text:
Q: Error While opening PDFand Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH)) After i convert code from word to PDf if i input the same word document to convet to PDf the PDF File is damaged. Can you tel me whether this error is because of inputting same word PDf many times or other error.
 Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();
            object _MissingValue = System.Reflection.Missing.Value;

              public void WordtoPdf_Input()
 {
string filename_doc=System.IO.Path.GetFileName(LblFleip.Text);
string wordFileName = LblFleip.Text;
      string pdfFileName=string.Empty;
     appWord.Visible = false;
     appWord.ScreenUpdating = false;

  // Cast as Object for word Open method
  object filename = (object)wordFileName;

  // Use the dummy value as a placeholder for optional arguments
  Microsoft.Office.Interop.Word.Document doc = appWord.Documents.Open(ref filename, ref _MissingValue,
   ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue,
   ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue,
   ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue);
  doc.Activate();

   InputFilename = pdfFileName = Path.ChangeExtension(wordFileName, "pdf");
  object fileFormat = WdSaveFormat.wdFormatPDF;

  // Save document into PDF Format
  doc.SaveAs(ref outputFileName,
   ref fileFormat, ref _MissingValue, ref _MissingValue,
   ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue,
   ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue,
   ref _MissingValue, ref _MissingValue, ref _MissingValue, ref _MissingValue);

  // Close the Word document, but leave the Word application open.
  // doc has to be cast to type _Document so that it will find the
  // correct Close method.
  object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
  ((_Document)doc).Close(ref saveChanges, ref _MissingValue, ref _MissingValue);
  doc = null;

  // word has to be cast to type _Application so that it will find
  // the correct Quit method.
  ((_Application)appWord).Quit(ref _MissingValue, ref _MissingValue, ref _MissingValue);
  appWord = null;
    }

i am getting error. this is how i converted word to pdf and read Pages using itextsharp.

A: Try this code:
        string tEmpName= Path.GetTempFileName();
        File.Delete(tmpName.ToString());
        File.Delete(Filename);
        File.Move(tEmpName, Filename);


text:
Q: How can I simulate a double-tap event on a Scene View Background: I have an app presenting a 3D model with SceneKit. By default SceneKit has a function that once the user makes a double-tap, the 3D model returns into its original position. I want to use this feature programmatically. When the user hits a certain button, the 3D model shall return to its original position. Therefore, I would like to fire a double-tap event if possible and hope that the 3D model will react accordingly.
How can this be done?
This question relates to another case How to retrieve information about the camera position in a sceneKit project when the 3D model is zoomed? in which I try to resolve this task by setting the cameranode positions to their original value. But obviously this is not possible. The fake of the double-click would be a kind of work around in order to achieve the requirement for my application.

A: As mentioned in https://stackoverflow.com/a/24768474/2997825 and https://stackoverflow.com/a/70779030/2997825 SceneKit will create a new node and set it as the point of view when an interaction starts.
To revert to the original camera, you can simply set the pointOfView property back to the original, untouched, camera node.


text:
Q: onScroll() method is not called in fragment I make gallery and try to download new images during scrolling it, but onScroll() is not called! onScroll() is called one time when I start a fragment, but when I scroll listView, onScroll doesn't work
public class FotoActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_filter);

    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.container, new FotoFragment())
                .commit();
    }
}

public static class FotoFragment extends AbsListViewBaseFragment implements AbsListView.OnScrollListener {

    private static final String CLIENT_ID = "7f38ead5152e46f1a42284c2d84b0862";
    private static final String API_REQUEST = "cat";
    private static final String API_URL = "https://api.instagram.com/v1";

    static String downloadJsonUrl = API_URL + "/tags/" + API_REQUEST + "/media/recent?client_id=" + CLIENT_ID;

    private ImageAdapter picAdapter;

    ArrayList<String> picUrls = new ArrayList<String>();

    GetImages getInstagramImages;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        picAdapter = new ImageAdapter();

        getInstagramImages = new GetImages();
        getInstagramImages.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fr_image_grid, container, false);
        listView = (GridView) rootView.findViewById(R.id.grid);
        ((GridView) listView).setAdapter(picAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            }
        });

        listView.setOnScrollListener(this);

        return rootView;
    }

    @Override
    public void onScrollStateChanged(AbsListView absListView, int i) {

    }

    @Override
    public void onScroll(AbsListView absListView, int firstVisible, int visibleCount, int totalCount) {
        boolean loadMore = firstVisible + visibleCount >= totalCount;

        if (loadMore == true && getInstagramImages.getStatus() == AsyncTask.Status.FINISHED) {
            getInstagramImages = new GetImages();
            getInstagramImages.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
    }

    protected class GetImages extends AsyncTask<Void, Void, ArrayList> {

        @Override
        protected ArrayList doInBackground(Void... voids) {
            try {
                picUrls = parseJson();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return picUrls;
        }

        @Override
        protected void onPostExecute(ArrayList result) {
            super.onPostExecute(result);
            picAdapter.notifyDataSetChanged();
        }
    }

    private InputStream downloadJSON(String stringUrl) throws IOException {
        URL url = new URL(stringUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        connection.connect();
        return connection.getInputStream();
    }

    private ArrayList parseJson() throws IOException, JSONException {
        InputStream inputStream = downloadJSON(downloadJsonUrl);
        JSONObject jsonObject = (JSONObject) new JSONTokener(responseJSON).nextValue();
        JSONArray jsonArray = jsonObject.getJSONArray("data");
        for(int i = 0; i < jsonArray.length(); i ++){
            JSONObject imageJsonObject = jsonArray.getJSONObject(i).getJSONObject("images").getJSONObject("standard_resolution");
            picUrls.add(imageJsonObject.getString("url"));
        }
        downloadJsonUrl = jsonObject.getJSONObject("pagination").getString("next_url");

        return picUrls;
    }

}

A: The code looks fine some pieces were missing on filling in those, it works..you could refer to code here
FotoActivity.java


text:
Q: No known class method for selector 'labelColor' - react-native-image-crop-picker - for react-native iOS I am using react-native-image-crop-picker library within react-native application
Version details
react-native version: 59.10
 react-native-image-crop-picker: 0.25.3
 xcode: 10.1

While execution of code I am getting the error QBImagePicker/QBAssetsViewController.m:198:31: No known class method for selector 'labelColor'
195    // Info label
196    UIColor *labelColor = [UIColor blackColor];
197    if (@available(iOS 13.0, *)) {
198        labelColor = [UIColor labelColor];
199    }

I have tried to upgrade library version but issue is still there. can anyone please help
Thank you in advance

A: @property (class, nonatomic, readonly) UIColor *labelColor
        API_AVAILABLE(ios(13.0), tvos(13.0)) API_UNAVAILABLE(watchos);

I'm using XCode, and tripped over this. Note from the UIInterface.h definition (above) that it is unavailable for watchOS. If your code is like mine, and being used by WatchOS, then you will encounter the above issue.


text:
Q: Regular expression to capture last occurrence of a pattern I tried several ways for last occurrence, but they are not working. The following is my case,
abc def = ghi
abc def ghi = jkl
abc def ghi=jkl mno

For the first line, my capture target is "def". For the second line, my capture target is "ghi", and for the 3rd line, my capture target is "ghi". The target can be verbally expressed as "the last occurrence of word before equal sign".
How does the regular expression of Perl should look like?

A: you could use this pattern
(\w+)(?=\s*=)

Demo
(               # Capturing Group (1)
  \w            # <ASCII letter, digit or underscore>
  +             # (one or more)(greedy)
)               # End of Capturing Group (1)
(?=             # Look-Ahead
  \s            # <whitespace character>
  *             # (zero or more)(greedy)
  =             # "="
)               # End of Look-Ahead

A: \b(\w+)\s*= would suffice for your examples. It matches a word optionally immediately followed by whitespace, immediately followed by =. The \b reduces backtracking.
\b(\w+)[^\w=]*= matches your "verbal expression" more precisely. For example, it will match abc in abc !@# = def.

*

*\b matches between a \w and \W.

*\w matches a non-word character.

*\W matches a character that's not a word character.

*\s matches a whitespace character.

*[^\w=] matches a non-word character other than =.

A: Jack's answer is probably the best, but I can't wrap my head around how it works. I like breaking things down into smaller chunks.
use warnings;
use strict;

my @strings = ( "abc def = ghi",
                "abc def ghi = jkl",
                "abc def ghi=jkl mno"
                );
#
foreach (@strings) {
    my $last = get_last($_);
    print "$last\n";
}

sub get_last {
    my $string = shift;
    # group things as left side or right side
    my $left_side;
    my $right_side;
    if ($string =~ /(.*)=(.*)/) {
        $left_side = $1;
        $right_side = $2;
    }

    # split things according to whitespace and store in an array
    my @left_side = split (/\s+/, $left_side);

    # return the last element of that array
    return $left_side[-1];
}

A: You don't really need a regex, either. You can:

*

*split the first string on /\s*=\s*/

*grab the first element of the resulting array (ie all the stuff before the equals sign (with whitespace stripped off of the right end))

*split the string from step 2 on /\s+/

*take the last element of the resulting array from step 3.

In other words:
use strict;
use warnings;

my $str1 = "abc def = ghi";
my $str2 = "abc def ghi = jkl";
my $str3 = "abc def ghi=jkl mno";

sub grab_target{
    my $str = shift;
    return (split(/\s+/, (split(/\s*=\s*/, $str))[0]))[-1];
}

foreach  my $str ($str1, $str2, $str3){
    print grab_target $str;
    print "\n";
}

The resulting output is:
def
ghi
ghi


text:
Q: Exception when using taglibs in Glassfish 3.1 I'm getting the following error while trying to deploy my app in Glasfish 3.1
org.apache.jasper.JasperException: PWC6033: Error in Javac compilation for JSP

PWC6197: An error occurred at line: 16 in the jsp file: /WEB-INF/jsp/signup/signup.jsp
PWC6199: Generated servlet error:
string:///signup_jsp.java:233: package org.springframework.web.servlet.tags.form does not exist

The spring jars are in the lib directory of my webapplication.
I'm using:
Spring 3.1.3
Glassfish 3.1.1 (started using the Maven embedded pluging)
Any ideas?

A: I stumbled onto the answer here
Basically you need this in glassfish-web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app error-url="">
  <class-loader delegate="true"/>
  <jsp-config>
    <property name="keepgenerated" value="true">
      <description>Keep a copy of the generated servlet class' java code.</description>
    </property>
    <property name="compilerSourceVM" value="7"/>
    <property name="compilerTargetVM" value="7"/>
  </jsp-config>
</glassfish-web-app>


text:
Q: Configure networking on debian live standard iso using usb tethering I just downloaded Debian standard live iso from here. I have an Android device capable of usb tethering. I live booted from the debian live iso and got into login tty and connected my phone and turned on usb tethering and mobile data, and ran apt update as sudo su from terminal. I got error, could not establish connection. I ran systemctl status NetworkMamager it said, no service with that name could be found. Then I ran /etc/init.d/networking start. But still couldn't get online.
Any help would be greatly appreciated.
note: This desktop does not have a wifi module, and I don't happen to have an ethernet cable

A: Get the name of the USB interface through ip a command (e,g: usb0).
Set the interface up:
sudo ip link set usb0 up

Then run :
sudo dhclient usb0.
Debian: Android_Tethering